code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def label_to_node(self, selection=):
if not isinstance(selection,set) and not isinstance(selection,list) and (not isinstance(selection,str) or not (selection != or selection != or selection != )):
raise RuntimeError()
if isinstance(selection, str):
selection = selectio... | Return a dictionary mapping labels (strings) to ``Node`` objects
* If ``selection`` is ``"all"``, the dictionary will contain all nodes
* If ``selection`` is ``"leaves"``, the dictionary will only contain leaves
* If ``selection`` is ``"internal"``, the dictionary will only contain internal n... |
def remove_from_ptr_size(self, ptr_size):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
self.path_tbl_size -= ptr_size
new_extents = utils.ceiling_div(self.path_tbl_size, 4096) * 2
need_remove_extents = False
if n... | Remove the space for a path table record from the volume descriptor.
Parameters:
ptr_size - The length of the Path Table Record being removed from this Volume Descriptor.
Returns:
True if extents need to be removed from the Volume Descriptor, False otherwise. |
def validateBusName(n):
try:
if not in n:
raise Exception()
if in n:
raise Exception()
if len(n) > 255:
raise Exception()
if n[0] == :
raise Exception()
if n[0].isdigit():
raise Exception()
if bus_re.s... | Verifies that the supplied name is a valid DBus Bus name. Throws
an L{error.MarshallingError} if the format is invalid
@type n: C{string}
@param n: A DBus bus name |
def get_release_data(self, package_name: str, version: str) -> Tuple[str, str, str]:
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
release_id = self.registry._get_release_id(package_name, version)
return self.get_rele... | Returns ``(package_name, version, manifest_uri)`` associated with the given
package name and version, *if* they are published to the currently set registry.
* Parameters:
* ``name``: Must be a valid package name.
* ``version``: Must be a valid package version. |
def home_dir():
if os.name == :
from win32com.shell import shell, shellcon
return shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, 0, 0)
else:
return os.path.expanduser() | Returns:
str : Path to home directory (or ``Documents`` directory on Windows). |
def count_tokens(tokens, to_lower=False, counter=None):
r
if to_lower:
tokens = [t.lower() for t in tokens]
if counter is None:
return Counter(tokens)
else:
counter.update(tokens)
return counter | r"""Counts tokens in the specified string.
For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may
look like::
(td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)
Parameters
----------
tokens : list of str
A source list of tok... |
def get_assessments_offered_by_query(self, assessment_offered_query):
and_list = list()
or_list = list()
for term in assessment_offered_query._query_terms:
if in assessment_offered_query._query_terms[term] and in assessment_offered_query._query_terms[term... | Gets a list of ``AssessmentOffered`` elements matching the given assessment offered query.
arg: assessment_offered_query
(osid.assessment.AssessmentOfferedQuery): the assessment
offered query
return: (osid.assessment.AssessmentOfferedList) - the returned
... |
def handle_endtag(self, tag):
if tag in PARENT_ELEMENTS:
self.current_parent_element[] =
self.current_parent_element[] =
if tag == :
self.parsing_li = True
if tag != :
self.cleaned_html += .format(tag) | Called by HTMLParser.feed when an end tag is found. |
def catvl(z, ver, vnew, lamb, lambnew, br):
if ver is not None:
br = np.concatenate((br, np.trapz(vnew, z, axis=-2)), axis=-1)
ver = np.concatenate((ver, vnew), axis=-1)
lamb = np.concatenate((lamb, lambnew))
else:
ver = vnew.copy(order=)
lamb = lambnew.copy()
... | trapz integrates over altitude axis, axis = -2
concatenate over reaction dimension, axis = -1
br: column integrated brightness
lamb: wavelength [nm]
ver: volume emission rate [photons / cm^-3 s^-3 ...] |
def stop_process(self, pids, status=):
success
if status not in process_result_statuses:
raise OperetoClientError(%status)
pids = self._get_pids(pids)
for pid in pids:
self._call_rest_api(, +pid++status, error=) | stop_process(self, pids, status='success')
Stops a running process
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *result* (`string`) -- the value the process will be terminated with. Any of the following possible values: success , failure , error , warning , t... |
def detach(gandi, resource, background, force):
resource = sorted(tuple(set(resource)))
if not force:
proceed = click.confirm( %
.join(resource))
if not proceed:
return
result = gandi.disk.detach(resource, background)
if background:
... | Detach disks from currectly attached vm.
Resource can be a disk name, or ID |
def repeat_func_eof(func: Callable[[], Union[T, Awaitable[T]]], eof: Any, *, interval: float=0, use_is: bool=False) -> AsyncIterator[T]:
pred = (lambda item: item != eof) if not use_is else (lambda item: (item is not eof))
base = repeat_func.raw(func, interval=interval)
return cast(AsyncIterator[T], st... | Repeats the result of a 0-ary function until an `eof` item is reached.
The `eof` item itself is not part of the resulting stream; by setting `use_is` to true,
eof is checked by identity rather than equality.
`times` and `interval` behave exactly like with `aiostream.create.repeat`. |
def aes_decrypt(key, stdin, chunk_size=65536):
if not AES256CBC_Support:
raise Exception(
)
key = hashlib.sha256(key).digest()
chunk_size = max(16, chunk_size >> 4 << 4)
iv = stdin.read(16)
while len(iv) < 16:
chunk = stdin.read(16 - len(iv))
if not... | Generator that decrypts a content stream using AES 256 in CBC
mode.
:param key: Any string to use as the decryption key.
:param stdin: Where to read the encrypted data from.
:param chunk_size: Largest amount to read at once. |
def fetch_local_package(self, config):
self.update_paths_and_config(config=config,
pkg_dir_name=config[],
pkg_cache_dir=os.getcwd()) | Make a local path available to current stacker config.
Args:
config (dict): 'local' path config dictionary |
def _peg_pose_in_hole_frame(self):
peg_pos_in_world = self.sim.data.get_body_xpos("cylinder")
peg_rot_in_world = self.sim.data.get_body_xmat("cylinder").reshape((3, 3))
peg_pose_in_world = T.make_pose(peg_pos_in_world, peg_rot_in_world)
hole_pos_in_world = sel... | A helper function that takes in a named data field and returns the pose of that
object in the base frame. |
def create_question_pdfs(nb, pages_per_q, folder, zoom) -> list:
html_cells = nb_to_html_cells(nb)
q_nums = nb_to_q_nums(nb)
os.makedirs(folder, exist_ok=True)
pdf_options = PDF_OPTS.copy()
pdf_options[] = ZOOM_FACTOR * zoom
pdf_names = []
for question, cell in zip(q_nums, html_cells... | Converts each cells in tbe notebook to a PDF named something like
'q04c.pdf'. Places PDFs in the specified folder and returns the list of
created PDF locations. |
def reads_supporting_variants(variants, samfile, **kwargs):
for variant, allele_reads in reads_overlapping_variants(
variants=variants,
samfile=samfile,
**kwargs):
yield variant, filter_non_alt_reads_for_variant(variant, allele_reads) | Given a SAM/BAM file and a collection of variants, generates a sequence
of variants paired with reads which support each variant. |
def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs):
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get(,(10,7))
nsims = kwargs.get(, 200)
if self.latent_variables.estimated is False:
raise Ex... | Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many past observations to show on the forecast graph?
intervals : Boolean
... |
def _parse_rd(self, config):
match = RD_RE.search(config)
if match:
value = match.group()
else:
value = match
return dict(rd=value) | _parse_rd scans the provided configuration block and extracts
the vrf rd. The return dict is intended to be merged into the response
dict.
Args:
config (str): The vrf configuration block from the nodes running
configuration
Returns:
dict: resourc... |
def make_query(catalog):
query = {}
request = api.get_request()
index = get_search_index_for(catalog)
limit = request.form.get("limit")
q = request.form.get("q")
if len(q) > 0:
query[index] = q + "*"
else:
return None
portal_type = request.form.get("portal_type")
... | A function to prepare a query |
def gen_localdir(self, localdir):
directory = "{0}/{1}/".format(localdir, self.get("username"))
if not os.path.exists(directory):
os.makedirs(directory)
return directory | Generate local directory where track will be saved.
Create it if not exists. |
def _check_require_version(namespace, stacklevel):
repository = GIRepository()
was_loaded = repository.is_registered(namespace)
yield
if was_loaded:
return
if namespace in ("GLib", "GObject", "Gio"):
return
if get_required_version(namespace) i... | A context manager which tries to give helpful warnings
about missing gi.require_version() which could potentially
break code if only an older version than expected is installed
or a new version gets introduced.
::
with _check_require_version("Gtk", stacklevel):
load_namespace_and_o... |
def bfs_multi_edges(G, source, reverse=False, keys=True, data=False):
from collections import deque
from functools import partial
if reverse:
G = G.reverse()
edges_iter = partial(G.edges_iter, keys=keys, data=data)
list(G.edges_iter(, keys=True, data=True))
visited_nodes = set([so... | Produce edges in a breadth-first-search starting at source.
-----
Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
by D. Eppstein, July 2004. |
def get_templates():
injected = {}
for name, data in templates.items():
injected[name] = dict([(k, v % env) for k, v in data.items()])
return injected | Returns each of the templates with env vars injected. |
def get_statements(self):
edges = _get_dict_from_list(, self.cx)
for edge in edges:
edge_type = edge.get()
if not edge_type:
continue
stmt_type = _stmt_map.get(edge_type)
if stmt_type:
id = edge[]
so... | Convert network edges into Statements.
Returns
-------
list of Statements
Converted INDRA Statements. |
def destroy(ads):
for ad in ads:
try:
ad.services.stop_all()
except:
ad.log.exception() | Cleans up AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects. |
def apply_to_model(self, model):
t call this method directly. Instead, set the theme
on the :class:`~bokeh.document.Document` the model is a part of.
'
model.apply_theme(self._for_class(model.__class__))
if len(_empty_dict) > 0:
raise ... | Apply this theme to a model.
.. warning::
Typically, don't call this method directly. Instead, set the theme
on the :class:`~bokeh.document.Document` the model is a part of. |
def check_dashboard_cookie(self):
cookie_raw = self.request.get(DASHBOARD_FILTER_COOKIE, None)
return cookie_raw
return get_strings(json.loads(cookie_raw)) | Check if the dashboard cookie should exist through bikasetup
configuration.
If it should exist but doesn't exist yet, the function creates it
with all values as default.
If it should exist and already exists, it returns the value.
Otherwise, the function returns None.
:... |
def _parse_stop_words_file(self, path):
language = None
loaded = False
if os.path.isfile(path):
self._logger.debug(, path)
language = path.split()[-1]
if not language in self.__stop_words:
self.__stop_words[language] = set()
... | Load stop words from the given path.
Parse the stop words file, saving each word found in it in a set
for the language of the file. This language is obtained from
the file name. If the file doesn't exist, the method will have
no effect.
Args:
path: Path to the stop ... |
def split_input(img):
s = img.shape[0]
assert img.shape[1] == 2 * s
input, output = img[:, :s, :], img[:, s:, :]
if args.mode == :
input, output = output, input
if IN_CH == 1:
input = cv2.cvtColor(input, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis]
if OUT_CH == 1:
outp... | img: an RGB image of shape (s, 2s, 3).
:return: [input, output] |
def _CompositeMapByteStream(
self, byte_stream, byte_offset=0, context=None, **unused_kwargs):
context_state = getattr(context, , {})
attribute_index = context_state.get(, 0)
mapped_values = context_state.get(, None)
subcontext = context_state.get(, None)
if not mapped_values:
map... | Maps a sequence of composite data types on a byte stream.
Args:
byte_stream (bytes): byte stream.
byte_offset (Optional[int]): offset into the byte stream where to start.
context (Optional[DataTypeMapContext]): data type map context.
Returns:
object: mapped value.
Raises:
Ma... |
def get_default_config(self):
config = super(SmartCollector, self).get_default_config()
config.update({
: ,
: ,
: False,
: ,
: ,
})
return config | Returns default configuration options. |
def all(self, customer_id, data={}, **kwargs):
url = "{}/{}/tokens".format(self.base_url, customer_id)
return self.get_url(url, data, **kwargs) | Get all tokens for given customer Id
Args:
customer_id : Customer Id for which tokens have to be fetched
Returns:
Token dicts for given cutomer Id |
def delete(fun):
*network.interfaces
if __opts__[] == :
data = __salt__[]()
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__[](, data)
load = {
: ,
: __opts__[],
: fun,
}
return _mine_send(load, __opts__) | Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces' |
def optional(e, default=Ignore):
def match_optional(s, grm=None, pos=0):
try:
return e(s, grm, pos)
except PegreError:
return PegreResult(s, default, (pos, pos))
return match_optional | Create a PEG function to optionally match an expression. |
def removeAll(self):
before_len = len(self.model.db)
self.model.db = []
if not self._batch.enable.is_set():
self.model.save_db()
return before_len - len(self.model.db) | Remove all objects
Returns:
len(int): affected rows |
def PorodGuinier(q, a, alpha, Rg):
return PorodGuinierMulti(q, a, alpha, Rg) | Empirical Porod-Guinier scattering
Inputs:
-------
``q``: independent variable
``a``: factor of the power-law branch
``alpha``: power-law exponent
``Rg``: radius of gyration
Formula:
--------
``G * exp(-q^2*Rg^2/3)`` if ``q>q_sep`` and ``a*q^alpha`` otherwise.
... |
def remove_tags(self, tags, **kwargs):
dxpy.api.job_remove_tags(self._dxid, {"tags": tags}, **kwargs) | :param tags: Tags to remove from the job
:type tags: list of strings
Removes each of the specified tags from the job. Takes
no action for tags that the job does not currently have. |
def _prevNonCommentBlock(self, block):
block = self._prevNonEmptyBlock(block)
while block.isValid() and self._isCommentBlock(block):
block = self._prevNonEmptyBlock(block)
return block | Return the closest non-empty line, ignoring comments
(result <= line). Return -1 if the document |
def retrieve_loadbalancer_status(self, loadbalancer, **_params):
return self.get(self.lbaas_loadbalancer_path_status % (loadbalancer),
params=_params) | Retrieves status for a certain load balancer. |
def _execute(self, line):
output = self.app.output
if not in sys.path:
sys.path.insert(0, )
def compile_with_flags(code, mode):
" Compile code with the right compiler flags. "
return compile(code, , mode,
... | Evaluate the line and print the result. |
def coarsegrain(P, n):
M = pcca(P, n)
W = np.linalg.inv(np.dot(M.T, M))
A = np.dot(np.dot(M.T, P), M)
P_coarse = np.dot(W, A)
from msmtools.analysis import stationary_distribution
pi_coarse = np.dot(M.T, stationary_distribution(P))
X = np.dot(np.diag(pi_coarse), P_coarse)
... | Coarse-grains transition matrix P to n sets using PCCA
Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using:
..math:
\tilde{P} = M^T P M (M^T M)^{-1}
See [2]_ for the derivation of this form from the coarse-graining method first derived in [1]_.
Reference... |
def delete_resourcegroupitems(scenario_id, item_ids, **kwargs):
user_id = int(kwargs.get())
_get_scenario(scenario_id, user_id)
for item_id in item_ids:
rgi = db.DBSession.query(ResourceGroupItem).\
filter(ResourceGroupItem.id==item_id).one()
db.DBSession.delete(rgi... | Delete specified items in a group, in a scenario. |
def get_input_files(oqparam, hazard=False):
fnames = []
for key in oqparam.inputs:
fname = oqparam.inputs[key]
if hazard and key not in (, ,
, ):
continue
elif key == :
gsim_lt = get_gsim_lt(oqparam)
fo... | :param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: input path names in a specific order |
def on_message(self, msg=None):
if msg is None:
try:
msg = self.ws.recv()
except Exception as e:
self.subscriber.on_message_error(
% str(e))
self.disconnect()
return False
if not msg:
... | Poll the websocket for a new packet.
`Client.listen()` calls this.
:param msg (string(byte array)): Optional. Parse the specified message
instead of receiving a packet from the socket. |
def encode_username_password(
username: Union[str, bytes], password: Union[str, bytes]
) -> bytes:
if isinstance(username, unicode_type):
username = unicodedata.normalize("NFC", username)
if isinstance(password, unicode_type):
password = unicodedata.normalize("NFC", password)
return... | Encodes a username/password pair in the format used by HTTP auth.
The return value is a byte string in the form ``username:password``.
.. versionadded:: 5.1 |
def disconnect(self):
self._connected = False
if self._transport is not None:
try:
self._transport.disconnect()
except Exception:
self.logger.error(
"Failed to disconnect from %s", self._host, exc_info=True)
... | Disconnect from the current host, but do not update the closed state.
After the transport is disconnected, the closed state will be True if
this is called after a protocol shutdown, or False if the disconnect
was in error.
TODO: do we really need closed vs. connected states? this only a... |
def get_default_bios_settings(self, only_allowed_settings=True):
headers_bios, bios_uri, bios_settings = self._check_bios_resource()
try:
base_config_uri = bios_settings[][][]
except KeyError:
msg = ("BaseConfigs resource not found. CouldnBaseConfigsdefa... | Get default BIOS settings.
:param: only_allowed_settings: True when only allowed BIOS settings
are to be returned. If False, All the BIOS settings supported
by iLO are returned.
:return: a dictionary of default BIOS settings(factory settings).
Depending ... |
def hexists(self, key, field):
fut = self.execute(b, key, field)
return wait_convert(fut, bool) | Determine if hash field exists. |
def qualify(self):
defns = self.root.defaultNamespace()
if Namespace.none(defns):
defns = self.schema.tns
for a in self.autoqualified():
ref = getattr(self, a)
if ref is None:
continue
if isqref(ref):
contin... | Convert attribute values, that are references to other
objects, into I{qref}. Qualfied using default document namespace.
Since many wsdls are written improperly: when the document does
not define a default namespace, the schema target namespace is used
to qualify references. |
def log_rho_bg(trigs, bins, counts):
trigs = np.atleast_1d(trigs)
N = sum(counts)
assert np.all(trigs >= np.min(bins)), \
if np.any(trigs >= np.max(bins)):
N = N + 1
log_rhos = []
for t in trigs:
if t >= np.max(bins):
... | Calculate the log of background fall-off
Parameters
----------
trigs: array
SNR values of all the triggers
bins: string
bins for histogrammed triggers
path: string
counts for histogrammed triggers
Returns
-------
... |
def _set_with_metadata(self, name, value, layer=None, source=None):
if self._frozen:
raise TypeError()
if isinstance(value, dict):
if name not in self._children or not isinstance(self._children[name], ConfigTree):
self._children[name] = ConfigTree(layer... | Set a value in the named layer with the given source.
Parameters
----------
name : str
The name of the value
value
The value to store
layer : str, optional
The name of the layer to store the value in. If none is supplied
then the v... |
def get_mzid_specfile_ids(mzidfn, namespace):
sid_fn = {}
for specdata in mzid_specdata_generator(mzidfn, namespace):
sid_fn[specdata.attrib[]] = specdata.attrib[]
return sid_fn | Returns mzid spectra data filenames and their IDs used in the
mzIdentML file as a dict. Keys == IDs, values == fns |
def keys(self, remote=False):
if not remote:
return list(super(CouchDB, self).keys())
return self.all_dbs() | Returns the database names for this client. Default is
to return only the locally cached database names, specify
``remote=True`` to make a remote request to include all databases.
:param bool remote: Dictates whether the list of locally cached
database names are returned or a remote... |
def _parse_tags(tag_file):
tag_name = None
tag_value = None
for num, line in enumerate(tag_file):
if num == 0:
if line.startswith(BOM):
line = line.lstrip(BOM)
if len(line) == 0 or line.isspace():
continue
eli... | Parses a tag file, according to RFC 2822. This
includes line folding, permitting extra-long
field values.
See http://www.faqs.org/rfcs/rfc2822.html for
more information. |
def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False):
normalize_in_place(a_pyxb, ignore_timestamps)
normalize_in_place(b_pyxb, ignore_timestamps)
a_xml = d1_common.xml.serialize_to_xml_str(a_pyxb)
b_xml = d1_common.xml.serialize_to_xml_str(b_pyxb)
are_equivalent = d1_common.xml.are_... | Determine if SystemMetadata PyXB objects are semantically equivalent.
Normalize then compare SystemMetadata PyXB objects for equivalency.
Args:
a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare
reset_timestamps: bool
``True``: Timestamps in the SystemMetadata are set to a standard v... |
def md5_object(obj):
hasher = hashlib.md5()
if isinstance(obj, basestring) and PY3:
hasher.update(obj.encode())
else:
hasher.update(obj)
md5 = hasher.hexdigest()
return md5 | If an object is hashable, return the string of the MD5.
Parameters
-----------
obj: object
Returns
----------
md5: str, MD5 hash |
def _get_synonym(self, line):
mtch = self.attr2cmp[].match(line)
text, scope, typename, dbxrefs, _ = mtch.groups()
typename = typename.strip()
dbxrefs = set(dbxrefs.split()) if dbxrefs else set()
return self.attr2cmp[]._make([text, scope, typename, dbxrefs]) | Given line, return optional attribute synonym value in a namedtuple.
Example synonym and its storage in a namedtuple:
synonym: "The other white meat" EXACT MARKETING_SLOGAN [MEAT:00324, BACONBASE:03021]
text: "The other white meat"
scope: EXACT
typename: MARKETING_S... |
def send_produce_request(self, payloads=(), acks=1, timeout=1000,
fail_on_error=True, callback=None):
encoder = functools.partial(
KafkaProtocol.encode_produce_request,
acks=acks,
timeout=timeout)
if acks == 0:
decod... | Encode and send some ProduceRequests
ProduceRequests will be grouped by (topic, partition) and then
sent to a specific broker. Output is a list of responses in the
same order as the list of payloads specified
Arguments:
payloads (list of ProduceRequest): produce requests to... |
def set_quantity(self, twig=None, value=None, **kwargs):
return self.get_parameter(twig=twig, **kwargs).set_quantity(value=value, **kwargs) | TODO: add documentation |
def group(self, meta=None, meta_aggregates=None, regs=None,
regs_aggregates=None, meta_group_name="_group"):
if isinstance(meta, list) and \
all([isinstance(x, str) for x in meta]):
meta = Some(meta)
elif meta is None:
meta = none()
els... | *Wrapper of* ``GROUP``
The GROUP operator is used for grouping both regions and/or metadata of input
dataset samples according to distinct values of certain attributes (known as grouping
attributes); new grouping attributes are added to samples in the output dataset,
storing the results... |
def detokenize(self, inputs, delim=):
detok = delim.join([self.idx2tok[idx] for idx in inputs])
detok = detok.replace(self.separator + , )
detok = detok.replace(self.separator, )
detok = detok.replace(config.BOS_TOKEN, )
detok = detok.replace(config.EOS_TOKEN, )
... | Detokenizes single sentence and removes token separator characters.
:param inputs: sequence of tokens
:param delim: tokenization delimiter
returns: string representing detokenized sentence |
def main(args):
print("\nNote itt work correctly so take what it gives with a bucketload of salt\n")
if not len(sys.argv) > 1:
initialAnswers = askInitial()
inputPath = pathlib.Path(initialAnswers[])
year = int(initialAnswers[])
... | main entry point of app
Arguments:
args {namespace} -- arguments provided in cli |
def script(self, sql_script, split_algo=, prep_statements=True, dump_fails=True):
return Execute(sql_script, split_algo, prep_statements, dump_fails, self) | Wrapper method providing access to the SQLScript class's methods and properties. |
def add(self, service, workers=1, args=None, kwargs=None):
_utils.check_callable(service, )
_utils.check_workers(workers, 1)
service_id = uuid.uuid4()
self._services[service_id] = _service.ServiceConfig(
service_id, service, workers, args, kwargs)
return serv... | Add a new service to the ServiceManager
:param service: callable that return an instance of :py:class:`Service`
:type service: callable
:param workers: number of processes/workers for this service
:type workers: int
:param args: additional positional arguments for this service
... |
def setup_top(self):
self.top_grammar = SchemaNode("grammar")
self.top_grammar.attr = {
"xmlns": "http://relaxng.org/ns/structure/1.0",
"datatypeLibrary": "http://www.w3.org/2001/XMLSchema-datatypes"}
self.tree = SchemaNode("start") | Create top-level elements of the hybrid schema. |
def _ask_password():
password = "Foo"
password_trial = ""
while password != password_trial:
password = getpass.getpass()
password_trial = getpass.getpass(prompt="Repeat:")
if password != password_trial:
print("\nPasswords do not match!")
return password | Securely and interactively ask for a password |
def dynacRepresentation(self):
details = [
self.energyDefnFlag.val,
self.energy.val,
self.phase.val,
self.x.val,
self.y.val,
self.radius.val,
]
return [, [details]] | Return the Pynac representation of this Set4DAperture instance. |
def version_list(package):
team, owner, pkg = parse_package(package)
session = _get_session(team)
response = session.get(
"{url}/api/version/{owner}/{pkg}/".format(
url=get_registry_url(team),
owner=owner,
pkg=pkg
)
)
for version in response... | List the versions of a package. |
def get_root_path(self, name):
module = modules.get(name)
if module is not None and hasattr(module, ):
return dirname(abspath(module.__file__))
return None | Attempt to compute a root path for a (hopefully importable) name.
Based in part on Flask's `root_path` calculation. See:
https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L777 |
def scatter(self, *args, **kwargs):
if "color" not in kwargs:
kwargs["color"] = self.next_color()
series = ScatterSeries(*args, **kwargs)
self.add_series(series) | Adds a :py:class:`.ScatterSeries` to the chart.
:param \*data: The data for the series as either (x,y) values or two big\
tuples/lists of x and y values respectively.
:param str name: The name to be associated with the series.
:param str color: The hex colour of the line.
:param... |
def _read_footer(file_obj):
footer_size = _get_footer_size(file_obj)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Footer size in bytes: %s", footer_size)
file_obj.seek(-(8 + footer_size), 2)
tin = TFileTransport(file_obj)
pin = TCompactProtocolFactory().get_protocol(tin)
f... | Read the footer from the given file object and returns a FileMetaData object.
This method assumes that the fo references a valid parquet file. |
def p_kwl_kwl(self, p):
_LOGGER.debug("kwl -> kwl ; kwl")
if p[3] is not None:
p[0] = p[3]
elif p[1] is not None:
p[0] = p[1]
else:
p[0] = TypedClass(None, TypedClass.UNKNOWN) | kwl : kwl SEPARATOR kwl |
def auth(self):
if self._auth is None:
self._auth = AuthTypesList(
self._version,
account_sid=self._solution[],
domain_sid=self._solution[],
)
return self._auth | Access the auth
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList
:rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList |
def get_groups_from_category(self, category) -> typing.Iterator[]:
Mission.validator_group_category.validate(category, )
for group in self.groups:
if group.group_category == category:
yield group | Args:
category: group category
Returns: generator over all groups from a specific category in this coalition |
def run_cmd_unit(self, sentry_unit, cmd):
output, code = sentry_unit.run(cmd)
if code == 0:
self.log.debug(
.format(sentry_unit.info[],
cmd, code))
else:
msg = (
.format(sentry... | Run a command on a unit, return the output and exit code. |
def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"):
"Cargo el formato de campos a generar desde una planilla CSV"
if not os.path.exists(archivo):
archivo = os.path.join(self.InstallDir, "plantillas", os.path.basename(archivo))
if DEBUG: print "abriendo... | Cargo el formato de campos a generar desde una planilla CSV |
def download_handler(feed, placeholders):
import shlex
value = feed.retrieve_config(, )
if value == :
while os.path.isfile(placeholders.fullpath):
placeholders.fullpath = placeholders.fullpath +
placeholders.filename = placeholders.filename +
urlretrieve(placeh... | Parse and execute the download handler |
def print_response(self, input=, keep=False, *args, **kwargs):
cookie = kwargs.get()
if cookie is None:
cookie = self.cookie or
status = kwargs.get()
lines = input.splitlines()
if status and not lines:
lines = []
if cookie:
o... | print response, if cookie is set then print that each line
:param args:
:param keep: if True more output is to come
:param cookie: set a custom cookie,
if set to 'None' then self.cookie will be used.
if set to 'False' disables cookie output entirely
... |
def tempdir(cls, suffix=, prefix=None, dir=None):
if prefix is None:
prefix = tempfile.template
if dir is not None:
dir = str(Path(dir))
dirname = tempfile.mkdtemp(suffix, prefix, dir)
return cls(dirname).absolute() | Returns a new temporary directory.
Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the
`text` argument is not accepted.
The directory is readable, writable, and searchable only by the
creating user.
The caller is responsible for deleting the directory when done... |
def fit(self, order=3):
x = self.volumes**(-2./3.)
self.eos_params = np.polyfit(x, self.energies, order)
self._set_params() | Overriden since this eos works with volume**(2/3) instead of volume. |
def get(config, messages, freq, pidDir=None, reactor=None):
ret = taservice.MultiService()
args = ()
if reactor is not None:
args = reactor,
procmon = procmonlib.ProcessMonitor(*args)
if pidDir is not None:
protocols = TransportDirectoryDict(pidDir)
procmon.protocols = p... | Return a service which monitors processes based on directory contents
Construct and return a service that, when started, will run processes
based on the contents of the 'config' directory, restarting them
if file contents change and stopping them if the file is removed.
It also listens for restart and... |
def get_finder(import_path):
Finder = import_string(import_path)
if not issubclass(Finder, BaseFileSystemFinder):
raise ImproperlyConfigured(.format(import_path))
return Finder() | Get a finder class from an import path.
Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.
This function uses an lru cache.
:param import_path: string representing an import path
:return: An instance of the finder |
def flatten(sequence, levels = 1):
if levels == 0:
for x in sequence:
yield x
else:
for x in sequence:
for y in flatten(x, levels - 1):
yield y | Example:
>>> nested = [[1,2], [[3]]]
>>> list(flatten(nested))
[1, 2, [3]] |
def _writeStructureLink(self, link, fileObject, replaceParamFile):
fileObject.write( % link.type)
fileObject.write( % link.numElements)
weirs = link.weirs
culverts = link.culverts
for weir in weirs:
fileObject.write( % weir.type)
... | Write Structure Link to File Method |
def extern_store_dict(self, context_handle, vals_ptr, vals_len):
c = self._ffi.from_handle(context_handle)
tup = tuple(c.from_value(val[0]) for val in self._ffi.unpack(vals_ptr, vals_len))
d = dict()
for i in range(0, len(tup), 2):
d[tup[i]] = tup[i + 1]
return c.to_value(d) | Given storage and an array of Handles, return a new Handle to represent the dict.
Array of handles alternates keys and values (i.e. key0, value0, key1, value1, ...).
It is assumed that an even number of values were passed. |
def check_recommended_global_attributes(self, dataset):
recommended_ctx = TestCtx(BaseCheck.MEDIUM, )
variable_defined_platform = any((hasattr(var, ) for var in dataset.variables))
if not variable_defined_platform:
platform_name = getattr(dataset, , )
... | Check the global recommended attributes for 1.1 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
Basic "does it exist" checks are done in BaseNCEICheck:check_recommended
:title = "" ; //........................ |
def get_min_max_mag(self):
"Return the minimum and maximum magnitudes"
mag, num_bins = self._get_min_mag_and_num_bins()
return mag, mag + self. bin_width * (num_bins - 1) | Return the minimum and maximum magnitudes |
def normal_curve_single(obj, u, normalize):
ders = obj.derivatives(u, 2)
point = ders[0]
vector = linalg.vector_normalize(ders[2]) if normalize else ders[2]
return tuple(point), tuple(vector) | Evaluates the curve normal vector at the input parameter, u.
Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u.
The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself.
:param obj: input curve
:type obj: abstract... |
def get_app_guid(self, app_name):
summary = self.space.get_space_summary()
for app in summary[]:
if app[] == app_name:
return app[] | Returns the GUID for the app instance with
the given name. |
def unmount(self, client):
getattr(client, self.unmount_fun)(mount_point=self.path) | Unmounts a backend within Vault |
def map(self, fn, *seq):
"Perform a map operation distributed among the workers. Will "
"block until done."
results = Queue()
args = zip(*seq)
for seq in args:
j = SimpleJob(results, fn, seq)
self.put(j)
r = []
for i in range(len(... | Perform a map operation distributed among the workers. Will |
def broadcast_transaction(self, hex_tx):
resp = self.obj.sendrawtransaction(hex_tx)
if len(resp) > 0:
return {: resp, : True}
else:
return error_reply() | Dispatch a raw transaction to the network. |
def async_task(self, func):
def process_response(task):
try:
response = task.result()
except Exception as e:
self.loop.create_task(
self.errors_handlers.notify(types.Update.get_current(), e))
else:
... | Execute handler as task and return None.
Use this decorator for slow handlers (with timeouts)
.. code-block:: python3
@dp.message_handler(commands=['command'])
@dp.async_task
async def cmd_with_timeout(message: types.Message):
await asyncio.sleep(120... |
def create_parser():
description =
parser = argparse.ArgumentParser(
usage=,
description=description,
epilog=,
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
,
action=,
nargs=1,
help="Git SHA of the older commit... | Setup argument Parsing. |
def intersect(self, **kwargs):
ls = None
if "linestring" in kwargs:
ls = kwargs.pop()
spoint = Point(ls.coords[0])
epoint = Point(ls.coords[-1])
elif "start_point" and "end_point" in kwargs:
spoint = kwargs.get()
epoint = kwar... | Intersect a Line or Point Collection and the Shoreline
Returns the point of intersection along the coastline
Should also return a linestring buffer around the interseciton point
so we can calculate the direction to bounce a particle. |
def save_file(self, filename, text):
if not filename.endswith():
filename +=
path = os.path.join(self.currentpath, filename)
with open(path, , encoding="utf-8") as file_:
file_.write(text) | Save the given text under the given control filename and the
current path. |
def _set_configspec(self, section, copy):
configspec = section.configspec
many = configspec.get()
if isinstance(many, dict):
for entry in section.sections:
if entry not in configspec:
section[entry].configspec = many
for entry in ... | Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__ |
def create(self, datapath, tracker_urls, comment=None, root_name=None,
created_by=None, private=False, no_date=False, progress=None,
callback=None):
if datapath:
self.datapath = datapath
try:
tracker_urls = [ + tracker_urls]
... | Create a metafile with the path given on object creation.
Returns the last metafile dict that was written (as an object, not bencoded). |
def make_codon_list(protein_seq, template_dna=None, include_stop=True):
codon_list = []
if template_dna is None:
template_dna = []
for i, res in enumerate(protein_seq.upper()):
try: template_codon = template_dna[3*i:3*i+3]
except IndexError: template_codon =
... | Return a list of codons that would be translated to the given protein
sequence. Codons are picked first to minimize the mutations relative to a
template DNA sequence and second to prefer "optimal" codons. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.