text stringlengths 81 112k |
|---|
Find regexp in activitylog
find record as if type are in description.
def find(self, item, description='', event_type=''):
"""
Find regexp in activitylog
find record as if type are in description.
"""
# TODO: should be refactored, dumb logic
if ': ' in item:
... |
Currently a small stub to create an instance of Checker for the passed
``infile`` and run its test functions through linting.
Args:
infile
Returns:
int: Number of flake8 errors raised.
def do_command_line(infile: typing.IO[str]) -> int:
"""
Currently a small stub to create an inst... |
finds the appropriate properties (spec) of a module, and sets
its loader.
def find_spec(self, fullname, path, target=None):
'''finds the appropriate properties (spec) of a module, and sets
its loader.'''
if not path:
path = [os.getcwd()]
if "." in fullname:
... |
import the source code, transforma it before executing it so that
it is known to Python.
def exec_module(self, module):
'''import the source code, transforma it before executing it so that
it is known to Python.'''
global MAIN_MODULE_NAME
if module.__name__ == MAIN_MODULE_... |
Iterate through multiple lists or arrays of equal size
def _izip(*iterables):
""" Iterate through multiple lists or arrays of equal size """
# This izip routine is from itertools
# izip('ABCD', 'xy') --> Ax By
iterators = map(iter, iterables)
while iterators:
yield tuple(map(next, iterator... |
Check and convert any input scalar or array to numpy array
def _checkinput(zi, Mi, z=False, verbose=None):
""" Check and convert any input scalar or array to numpy array """
# How many halo redshifts provided?
zi = np.array(zi, ndmin=1, dtype=float)
# How many halo masses provided?
Mi = np.array(M... |
Find cosmological parameters for named cosmo in cosmology.py list
def getcosmo(cosmology):
""" Find cosmological parameters for named cosmo in cosmology.py list """
defaultcosmologies = {'dragons': cg.DRAGONS(), 'wmap1': cg.WMAP1_Mill(),
'wmap3': cg.WMAP3_ML(), 'wmap5': cg.WMAP5_mean... |
Output the cosmology to a string for writing to file
def _getcosmoheader(cosmo):
""" Output the cosmology to a string for writing to file """
cosmoheader = ("# Cosmology (flat) Om:{0:.3f}, Ol:{1:.3f}, h:{2:.2f}, "
"sigma8:{3:.3f}, ns:{4:.2f}".format(
cosmo['omega_M_0'... |
NFW conc from Duffy 08 Table 1 for halo mass and redshift
def cduffy(z, M, vir='200crit', relaxed=True):
""" NFW conc from Duffy 08 Table 1 for halo mass and redshift"""
if(vir == '200crit'):
if relaxed:
params = [6.71, -0.091, -0.44]
else:
params = [5.71, -0.084, -0.47... |
Perturb best-fit constant of proportionality Ascaling for
rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c)
Parameters
----------
cosmo : dict
Dictionary of cosmological parameters, similar in format to:
{'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0':... |
Returns the normalisation constant between
Rho_-2 and Rho_mean(z_formation) for a given cosmology
Parameters
----------
cosmology : str or dict
Can be named cosmology, default WMAP7 (aka DRAGONS), or
DRAGONS, WMAP1, WMAP3, WMAP5, WMAP7, WMAP9, Planck13, Planck15
or dictionar... |
Returns integral of the linear growth factor from z=200 to z=z
def _int_growth(z, **cosmo):
""" Returns integral of the linear growth factor from z=200 to z=z """
zmax = 200
if hasattr(z, "__len__"):
for zval in z:
assert(zval < zmax)
else:
assert(z < zmax)
y, yerr = ... |
Returns derivative of the linear growth factor at z
for a given cosmology **cosmo
def _deriv_growth(z, **cosmo):
""" Returns derivative of the linear growth factor at z
for a given cosmology **cosmo """
inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5)
fz = (1 + z) ... |
Returns linear growth factor at a given redshift, normalised to z=0
by default, for a given cosmology
Parameters
----------
z : float or numpy array
The redshift at which the growth factor should be calculated
norm : boolean, optional
If true then normalise the growth factor to... |
Trial function to solve 2 eqns (17 and 18) from Correa et al. (2015c)
for 1 unknown, i.e. concentration, returned by a minimisation call
def _minimize_c(c, z=0, a_tilde=1, b_tilde=-1,
Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75):
""" Trial function to solve 2 eqns (17 and 18) from Cor... |
Rearrange eqn 18 from Correa et al (2015c) to return
formation redshift for a concentration at a given redshift
Parameters
----------
c : float / numpy array
Concentration of halo
z : float / numpy array
Redshift of halo with concentration c
Ascaling : float
Cosmolog... |
Calculate growth rate indices a_tilde and b_tilde
Parameters
----------
zi : float
Redshift
Mi : float
Halo mass at redshift 'zi'
cosmo : dict
Dictionary of cosmological parameters, similar in format to:
{'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.... |
Calculate accretion rate and mass history of a halo at any
redshift 'z' with mass 'Mi' at a lower redshift 'z'
Parameters
----------
z : float
Redshift to solve acc_rate / mass history. Note zi<z
zi : float
Redshift
Mi : float
Halo mass at redshift 'zi'
cosmo : d... |
Calculate mass accretion history by looping function acc_rate
over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'
Parameters
----------
z : float / numpy array
Redshift to output MAH over. Note zi<z always
zi : float
Redshift
Mi : float
Halo mass at redshi... |
Calculate concentration for halo of mass 'M' at redshift 'z'
Parameters
----------
z : float / numpy array
Redshift to find concentration of halo
M : float / numpy array
Halo mass at redshift 'z'. Must be same size as 'z'
cosmo : dict
Dictionary of cosmological parameters, s... |
Run commah code on halo of mass 'Mi' at redshift 'zi' with
accretion and profile history at higher redshifts 'z'
This is based on Correa et al. (2015a,b,c)
Parameters
----------
cosmology : str or dict
Can be named cosmology, default WMAP7 (aka DRAGONS), or
DRAGONS, WMAP1, W... |
Load a configuration and keep it alive for the given context
:param config_path: path to a configuration file
def load(config_path: str):
"""
Load a configuration and keep it alive for the given context
:param config_path: path to a configuration file
"""
# we bind the config to _ to keep it ... |
Replaces instances of
repeat n:
by
for __VAR_i in range(n):
where __VAR_i is a string that does not appear elsewhere
in the code sample.
def transform_source(text):
'''Replaces instances of
repeat n:
by
for __VAR_i in range(n):
where __VAR_i is a string tha... |
returns a list of possible variables names that
are not found in the original text.
def get_unique_variable_names(text, nb):
'''returns a list of possible variables names that
are not found in the original text.'''
base_name = '__VAR_'
var_names = []
i = 0
j = 0
while j < nb:
... |
Get a release by tag
def tag(self, tag):
"""Get a release by tag
"""
url = '%s/tags/%s' % (self, tag)
response = self.http.get(url, auth=self.auth)
response.raise_for_status()
return response.json() |
Assets for a given release
def release_assets(self, release):
"""Assets for a given release
"""
release = self.as_id(release)
return self.get_list(url='%s/%s/assets' % (self, release)) |
Upload a file to a release
:param filename: filename to upload
:param content_type: optional content type
:return: json object from github
def upload(self, release, filename, content_type=None):
"""Upload a file to a release
:param filename: filename to upload
:param c... |
Validate ``tag_name`` with the latest tag from github
If ``tag_name`` is a valid candidate, return the latest tag from github
def validate_tag(self, tag_name, prefix=None):
"""Validate ``tag_name`` with the latest tag from github
If ``tag_name`` is a valid candidate, return the latest tag fro... |
Return the full reddit URL associated with the usernote.
Arguments:
subreddit: the subreddit name for the note (PRAW Subreddit object)
def full_url(self):
"""Return the full reddit URL associated with the usernote.
Arguments:
subreddit: the subreddit name for the note ... |
Convert a reddit URL into the short-hand used by usernotes.
Arguments:
link: a link to a comment, submission, or message (str)
Returns a String of the shorthand URL
def _compress_url(link):
"""Convert a reddit URL into the short-hand used by usernotes.
Arguments:
... |
Convert a usernote's URL short-hand into a full reddit URL.
Arguments:
subreddit: the subreddit the URL is for (PRAW Subreddit object or str)
short_link: the compressed link from a usernote (str)
Returns a String of the full URL.
def _expand_url(short_link, subreddit=None):
... |
Get the JSON stored on the usernotes wiki page.
Returns a dict representation of the usernotes (with the notes BLOB
decoded).
Raises:
RuntimeError if the usernotes version is incompatible with this
version of puni.
def get_json(self):
"""Get the JSON stored... |
Set up the UserNotes page with the initial JSON schema.
def _init_notes(self):
"""Set up the UserNotes page with the initial JSON schema."""
self.cached_json = {
'ver': self.schema,
'users': {},
'constants': {
'users': [x.name for x in self.subreddit.... |
Send the JSON from the cache to the usernotes wiki page.
Arguments:
reason: the change reason that will be posted to the wiki changelog
(str)
Raises:
OverflowError if the new JSON data is greater than max_page_size
def set_json(self, reason='', new_page=False):
... |
Return a list of Note objects for the given user.
Return an empty list if no notes are found.
Arguments:
user: the user to search for in the usernotes (str)
def get_notes(self, user):
"""Return a list of Note objects for the given user.
Return an empty list if no notes ar... |
Decompress the BLOB portion of the usernotes.
Arguments:
j: the JSON returned from the wiki page (dict)
Returns a Dict with the 'blob' key removed and a 'users' key added
def _expand_json(self, j):
"""Decompress the BLOB portion of the usernotes.
Arguments:
j:... |
Compress the BLOB data portion of the usernotes.
Arguments:
j: the JSON in Schema v5 format (dict)
Returns a dict with the 'users' key removed and 'blob' key added
def _compress_json(self, j):
"""Compress the BLOB data portion of the usernotes.
Arguments:
j: t... |
Add a note to the usernotes wiki page.
Arguments:
note: the note to be added (Note)
Returns the update message for the usernotes wiki
Raises:
ValueError when the warning type of the note can not be found in the
stored list of warnings.
def add_note(sel... |
Remove a single usernote from the usernotes.
Arguments:
username: the user that for whom you're removing a note (str)
index: the index of the note which is to be removed (int)
Returns the update message for the usernotes wiki
def remove_note(self, username, index):
"""... |
Function load
Get the list of all objects
@return RETURN: A ForemanItem list
def load(self):
""" Function load
Get the list of all objects
@return RETURN: A ForemanItem list
"""
cl_tmp = self.api.list(self.objName, limit=self.searchLimit).values()
cl = ... |
Return True if the item relates to the given app_id (and app_ver, if passed).
def is_related_to(item, app_id, app_ver=None):
"""Return True if the item relates to the given app_id (and app_ver, if passed)."""
versionRange = item.get('versionRange')
if not versionRange:
return True
for vR in ve... |
Return the first matching target application in this version range.
Returns None if there are no target applications or no matching ones.
def get_related_targetApplication(vR, app_id, app_ver):
"""Return the first matching target application in this version range.
Returns None if there are no target applic... |
Generate the addons blocklists.
<emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com">
<versionRange minVersion="0" maxVersion="*" severity="3">
<targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
<versionRange minVersion="39.0a1" maxVersion="*"/>
</targetApplication... |
Generate the plugin blocklists.
<pluginItem blockID="p422">
<match name="filename" exp="JavaAppletPlugin\\.plugin"/>
<versionRange minVersion="Java 7 Update 16"
maxVersion="Java 7 Update 24"
severity="0" vulnerabilitystatus="1">
<targetApplica... |
Generate the gfxBlacklistEntry.
<gfxBlacklistEntry blockID="g35">
<os>WINNT 6.1</os>
<vendor>0x10de</vendor>
<devices>
<device>0x0a6c</device>
</devices>
<feature>DIRECT2D</feature>
<featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
<driverVers... |
Generate the certificate blocklists.
<certItem issuerName="MIGQMQswCQYD...IENB">
<serialNumber>UoRGnb96CUDTxIqVry6LBg==</serialNumber>
</certItem>
or
<certItem subject='MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5'
pubKeyHash='VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8='>
... |
Create or update a label
def label(self, name, color, update=True):
"""Create or update a label
"""
url = '%s/labels' % self
data = dict(name=name, color=color)
response = self.http.post(
url, json=data, auth=self.auth, headers=self.headers
)
if respo... |
A dictionary with a one-to-one translation of keywords is used
to provide the transformation.
def translate(source, dictionary):
'''A dictionary with a one-to-one translation of keywords is used
to provide the transformation.
'''
toks = tokenize.generate_tokens(StringIO(source).readline)
result... |
Function enhance
Enhance the object with new item or enhanced items
def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'images':
SubDict(self.api, self.objName,
self.payloa... |
Async component of _run
async def _run_payloads(self):
"""Async component of _run"""
delay = 0.0
try:
while self.running.is_set():
await self._start_payloads()
await self._reap_payloads()
await asyncio.sleep(delay)
dela... |
Start all queued payloads
async def _start_payloads(self):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
task = self.event_loop.create_task(coroutine())
self._tasks.add(task)
self._payloads.clear()
await... |
Clean up all finished payloads
async def _reap_payloads(self):
"""Clean up all finished payloads"""
for task in self._tasks.copy():
if task.done():
self._tasks.remove(task)
if task.exception() is not None:
raise task.exception()
aw... |
Cancel all remaining payloads
async def _cancel_payloads(self):
"""Cancel all remaining payloads"""
for task in self._tasks:
task.cancel()
await asyncio.sleep(0)
for task in self._tasks:
while not task.done():
await asyncio.sleep(0.1)
... |
Check a plaintext password against a hashed password.
def check_password(password: str, encrypted: str) -> bool:
""" Check a plaintext password against a hashed password. """
# some old passwords have {crypt} in lower case, and passlib wants it to be
# in upper case.
if encrypted.startswith("{crypt}"):... |
Check if version of repository is semantic
def validate(ctx, sandbox):
"""Check if version of repository is semantic
"""
m = RepoManager(ctx.obj['agile'])
if not sandbox or m.can_release('sandbox'):
click.echo(m.validate_version()) |
Reset transaction back to original state, discarding all
uncompleted transactions.
def reset(self, force_flush_cache: bool = False) -> None:
"""
Reset transaction back to original state, discarding all
uncompleted transactions.
"""
super(LDAPwrapper, self).reset()
... |
Object state is cached. When an update is required the update will be
simulated on this cache, so that rollback information can be correct.
This function retrieves the cached data.
def _cache_get_for_dn(self, dn: str) -> Dict[str, bytes]:
"""
Object state is cached. When an update is re... |
Are there uncommitted changes?
def is_dirty(self) -> bool:
""" Are there uncommitted changes? """
if len(self._transactions) == 0:
raise RuntimeError("is_dirty called outside a transaction.")
if len(self._transactions[-1]) > 0:
return True
return False |
End a transaction. Must not be dirty when doing so. ie. commit() or
rollback() must be called if changes made. If dirty, changes will be
discarded.
def leave_transaction_management(self) -> None:
"""
End a transaction. Must not be dirty when doing so. ie. commit() or
rollback() ... |
Attempt to commit all changes to LDAP database. i.e. forget all
rollbacks. However stay inside transaction management.
def commit(self) -> None:
"""
Attempt to commit all changes to LDAP database. i.e. forget all
rollbacks. However stay inside transaction management.
"""
... |
Roll back to previous database state. However stay inside transaction
management.
def rollback(self) -> None:
"""
Roll back to previous database state. However stay inside transaction
management.
"""
if len(self._transactions) == 0:
raise RuntimeError("rollba... |
Process action. oncommit is a callback to execute action, onrollback is
a callback to execute if the oncommit() has been called and a rollback
is required
def _process(self, on_commit: UpdateCallable, on_rollback: UpdateCallable) -> Any:
"""
Process action. oncommit is a callback to exe... |
Add a DN to the LDAP database; See ldap module. Doesn't return a result
if transactions enabled.
def add(self, dn: str, mod_list: dict) -> None:
"""
Add a DN to the LDAP database; See ldap module. Doesn't return a result
if transactions enabled.
"""
_debug("add", self, ... |
Modify a DN in the LDAP database; See ldap module. Doesn't return a
result if transactions enabled.
def modify(self, dn: str, mod_list: dict) -> None:
"""
Modify a DN in the LDAP database; See ldap module. Doesn't return a
result if transactions enabled.
"""
_debug("mod... |
Modify a DN in the LDAP database; See ldap module. Doesn't return a
result if transactions enabled.
def modify_no_rollback(self, dn: str, mod_list: dict):
"""
Modify a DN in the LDAP database; See ldap module. Doesn't return a
result if transactions enabled.
"""
_debug(... |
delete a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
def delete(self, dn: str) -> None:
"""
delete a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
"""
_debug("delete", self)
... |
rename a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None:
"""
rename a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.... |
for testing purposes only. always fail in commit
def fail(self) -> None:
""" for testing purposes only. always fail in commit """
_debug("fail")
# on commit carry out action; on rollback reverse rename
def on_commit(_obj):
raise_testfailure("commit")
def on_rollba... |
Utility function made to reproduce range() with unit integer step
but with the added possibility of specifying a condition
on the looping variable (e.g. var % 2 == 0)
def __experimental_range(start, stop, var, cond, loc={}):
'''Utility function made to reproduce range() with unit integer step
... |
Create a new "for loop" line as a replacement for the original code.
def create_for(line, search_result):
'''Create a new "for loop" line as a replacement for the original code.
'''
try:
return line.format(search_result.group("indented_for"),
search_result.group("var"),
... |
Function __setitem__
Set a parameter of a foreman object as a dict
@param key: The key to modify
@param attribute: The data
@return RETURN: The API result
def setOverrideValue(self, attributes, hostName):
""" Function __setitem__
Set a parameter of a foreman object as a... |
Spits out the timedelta in days.
def get_interval_timedelta(self):
""" Spits out the timedelta in days. """
now_datetime = timezone.now()
current_month_days = monthrange(now_datetime.year, now_datetime.month)[1]
# Two weeks
if self.interval == reminders_choices.INTERVAL_2_WEEK... |
Execute a runner without blocking the event loop
async def awaitable_runner(runner: BaseRunner):
"""Execute a runner without blocking the event loop"""
runner_thread = CapturingThread(target=runner.run)
runner_thread.start()
delay = 0.0
while not runner_thread.join(timeout=0):
await asyncio... |
Create an ``asyncio`` event loop running in the main thread and watching runners
Using ``asyncio`` to handle suprocesses requires a specific loop type to run in the main thread.
This function sets up and runs the correct loop in a portable way.
In addition, it runs a single :py:class:`~.BaseRunner` until c... |
Function enhance
Enhance the object with new item or enhanced items
def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'os_default_templates':
SubDict(self.api, self.objName,
... |
Retry "tries" times, with initial "delay", increasing delay "delay*backoff" each time.
Without exception success means when function returns valid object.
With exception success when no exceptions
def retry(tries=10, delay=1, backoff=2, retry_exception=None):
"""
Retry "tries" times, with initial "dela... |
Dump initialized object structure to yaml
def dump(node):
""" Dump initialized object structure to yaml
"""
from qubell.api.private.platform import Auth, QubellPlatform
from qubell.api.private.organization import Organization
from qubell.api.private.application import Application
from qubell.a... |
Generate environment used for 'org.restore' method
:param file: env file
:return: env
def load_env(file):
"""
Generate environment used for 'org.restore' method
:param file: env file
:return: env
"""
env = yaml.load(open(file))
for org in env.get('organizations', []):
if n... |
Set specified value to yaml path.
Example:
patch('application/components/child/configuration/__locator.application-id','777')
Will change child app ID to 777
def patch_env(env, path, value):
""" Set specified value to yaml path.
Example:
patch('application/components/chi... |
Extract metadata link for starter kit from platform configs. Starter kit available on add component - starter kit menu.
Beware, config could be changed by deploy scripts during deploy.
:param name: Name of starter kit
:return: Link to metadata
def get_starter_kit_meta(name):
"""
Extract metadata li... |
Extact manifest url from metadata url
:param metaurl: Url to metadata
:param name: Name of application to extract
:return:
def get_manifest_from_meta(metaurl, name):
"""
Extact manifest url from metadata url
:param metaurl: Url to metadata
:param name: Name of application to extract
:re... |
Function getPayloadStruct
Get the payload structure to do a creation or a modification
@param key: The key to modify
@param attribute: The data
@param objType: NOT USED in this class
@return RETURN: The API result
def getPayloadStruct(self, attributes, objType=None):
""... |
Function log
Decorator to log lasts request before sending a new one
@return RETURN: None
def log(function):
""" Function log
Decorator to log lasts request before sending a new one
@return RETURN: None
"""
def _log(self, *args, **kwargs):
ret = fun... |
Function clearHistVars
Clear the variables used to get history of all vars
@return RETURN: None
def clearReqVars(self):
""" Function clearHistVars
Clear the variables used to get history of all vars
@return RETURN: None
"""
self.errorMsg = None
self.pay... |
Function list
Get the list of an object
@param obj: object name ('hosts', 'puppetclasses'...)
@param filter: filter for objects
@param only_id: boolean to only return dict with name/id
@return RETURN: the list of the object
def list(self, obj, filter=False, only_id=False, limit... |
Function get
Get an object by id
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@return RETURN: the targeted object
def get(self, obj, id, sub_object=None):
""" Function get
Get an object by id
@param obj: obj... |
Function get_id_by_name
Get the id of an object
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@return RETURN: the targeted object
def get_id_by_name(self, obj, name):
""" Function get_id_by_name
Get the id of an objec... |
Function set
Set an object by id
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@param action: specific action of an object ('power'...)
@param payload: the dict of the payload
@param async: should this request be async... |
Function create
Create an new object
@param obj: object name ('hosts', 'puppetclasses'...)
@param payload: the dict of the payload
@param async: should this request be async, if true use
return.result() to get the response
@return RETURN: the server respo... |
Function delete
Delete an object by id
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@return RETURN: the server response
def delete(self, obj, id):
""" Function delete
Delete an object by id
@param obj: objec... |
Modified ``run`` that captures return value and exceptions from ``target``
def run(self):
"""Modified ``run`` that captures return value and exceptions from ``target``"""
try:
if self._target:
return_value = self._target(*self._args, **self._kwargs)
if return... |
Start all queued payloads
def _start_payloads(self):
"""Start all queued payloads"""
with self._lock:
payloads = self._payloads.copy()
self._payloads.clear()
for subroutine in payloads:
thread = CapturingThread(target=subroutine)
thread.start()
... |
Clean up all finished payloads
def _reap_payloads(self):
"""Clean up all finished payloads"""
for thread in self._threads.copy():
# CapturingThread.join will throw
if thread.join(timeout=0):
self._threads.remove(thread)
self._logger.debug('reaped ... |
Decorate functions that modify the internally stored usernotes JSON.
Ensures that updates are mirrored onto reddit.
Arguments:
func: the function being decorated
def update_cache(func):
"""Decorate functions that modify the internally stored usernotes JSON.
Ensures that updates are mirrored ... |
Create an unbound prototype of this class, partially applying arguments
.. code:: python
controller = Controller.s(interval=20)
pipeline = controller(rate=10) >> pool
def s(cls: Type[C], *args, **kwargs) -> Partial[C]:
"""
Create an unbound prototype of this class, pa... |
Collect all bases and organize into parent/child mappings.
def _build_mappings(
self, classes: Sequence[type]
) -> Tuple[Mapping[type, Sequence[type]], Mapping[type, Sequence[type]]]:
"""
Collect all bases and organize into parent/child mappings.
"""
parents_to_children: Mut... |
Collect all classes defined in/under ``package_paths``.
def _collect_classes(
self, package_paths: Sequence[str], recurse_subpackages: bool = True
) -> Sequence[type]:
"""
Collect all classes defined in/under ``package_paths``.
"""
import uqbar.apis
classes = []
... |
Return a tuple for authenticating a user
If not successful raise ``AgileError``.
def get_auth():
"""Return a tuple for authenticating a user
If not successful raise ``AgileError``.
"""
auth = get_auth_from_env()
if auth[0] and auth[1]:
return auth
home = os.path.expanduser("~")
... |
Function checkAndCreate
Check if an architectures exists and create it if not
@param key: The targeted architectures
@param payload: The targeted architectures description
@param osIds: The list of os ids liked with this architecture
@return RETURN: The id of the object
def che... |
Get output (as a string) from pip command
:param pip_args: list o pip switches to pass
:return: string with results
def pip_command_output(pip_args):
"""
Get output (as a string) from pip command
:param pip_args: list o pip switches to pass
:return: string with results
"""
import sys
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.