Search is not available for this dataset
text stringlengths 75 104k |
|---|
def methods(self):
"""
Run the typing methods
"""
self.contamination_detection()
ReportImage(self, 'confindr')
self.run_genesippr()
ReportImage(self, 'genesippr')
self.run_sixteens()
self.run_mash()
self.run_gdcs()
ReportImage(self,... |
def contamination_detection(self):
"""
Calculate the levels of contamination in the reads
"""
self.qualityobject = quality.Quality(self)
self.qualityobject.contamination_finder(input_path=self.sequencepath,
report_path=self.reportpa... |
def run_genesippr(self):
"""
Run the genesippr analyses
"""
GeneSippr(args=self,
pipelinecommit=self.commit,
startingtime=self.starttime,
scriptpath=self.homepath,
analysistype='genesippr',
cutoff=0... |
def run_sixteens(self):
"""
Run the 16S analyses using the filtered database
"""
SixteensFull(args=self,
pipelinecommit=self.commit,
startingtime=self.starttime,
scriptpath=self.homepath,
analysistype='si... |
def run_mash(self):
"""
Run MASH to determine the closest refseq genomes
"""
self.pipeline = True
mash.Mash(inputobject=self,
analysistype='mash') |
def complete(self):
"""
Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the
sample.general.bestassemblyfile != 'NA'
"""
# Boolean to store the completeness of the analyses
allcomplete = True
# Clear the list of samp... |
def protected_operation(fn):
"""
Use this decorator to prevent an operation from being executed
when the related uri resource is still in use.
The parent_object must contain:
* a request
* with a registry.queryUtility(IReferencer)
:raises pyramid.httpexceptions.HTTPConflict: Sign... |
def protected_operation_with_request(fn):
"""
Use this decorator to prevent an operation from being executed
when the related uri resource is still in use.
The request must contain a registry.queryUtility(IReferencer)
:raises pyramid.httpexceptions.HTTPConflict: Signals that we don't want to
... |
def protected_view(view, info):
"""allows adding `protected=True` to a view_config`"""
if info.options.get('protected'):
def wrapper_view(context, request):
response = _advice(request)
if response is not None:
return response
else:
ret... |
def syncdb(pool=None):
"""
Create tables if they don't exist
"""
from flask_philo_sqlalchemy.schema import Base # noqa
from flask_philo_sqlalchemy.orm import BaseModel # noqa
from flask_philo_sqlalchemy.connection import create_pool
if pool is None:
pool = create_pool()
for c... |
def checkInstalledPip(package, speak=True, speakSimilar=True):
"""checks if a given package is installed on pip"""
packages = sorted([i.key for i in pip.get_installed_distributions()])
installed = package in packages
similar = None
if not installed:
similar = [pkg for pkg in packages if pac... |
def checkInstalledBrew(package, similar=True, speak=True, speakSimilar=True):
"""checks if a given package is installed on homebrew"""
packages = subprocess.check_output(['brew', 'list']).split()
installed = package in packages
similar = []
if not installed:
similar = [pkg for pkg in packag... |
def init_module(remote_credences=None,local_path=None):
"""Connnexion informations : remote_credences for remote acces OR local_path for local access"""
if remote_credences is not None:
RemoteConnexion.HOST = remote_credences["DB"]["host"]
RemoteConnexion.USER = remote_credences["DB"]["user"]
... |
def cree_local_DB(scheme):
"""Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]}
Usefull at installation of application (and for developement)
"""
conn = LocalConnexion()
req = ""
for table, fields in scheme.items():
req += f"DROP TABLE IF ... |
def execute(self, requete_SQL):
"""Execute one or many requests
requete_SQL may be a tuple(requete,args) or a list of such tuples
Return the result or a list of results
"""
try:
cursor = self.cursor()
if isinstance(requete_SQL,tuple):
res =... |
def placeholders(cls,dic):
"""Placeholders for fields names and value binds"""
keys = [str(x) for x in dic]
entete = ",".join(keys)
placeholders = ",".join(cls.named_style.format(x) for x in keys)
entete = f"({entete})"
placeholders = f"({placeholders})"
return en... |
def jsonise(dic):
"""Renvoie un dictionnaire dont les champs dont compatibles avec SQL
Utilise Json. Attention à None : il faut laisser None et non pas null"""
d = {}
for k, v in dic.items():
if type(v) in abstractRequetesSQL.TYPES_PERMIS:
d[k] = v
... |
def insert(table, datas, avoid_conflict=False):
""" Insert row from datas
:param table: Safe table name
:param datas: List of dicts.
:param avoid_conflict: Allows ignoring error if already exists (do nothing then)
:return:
"""
if avoid_conflict:
debut... |
def update(cls,table, dic, Id):
""" Update row with Id from table. Set fields given by dic."""
if dic:
req = "UPDATE {table} SET {SET} WHERE id = " + cls.named_style.format('__id') + " RETURNING * "
r = abstractRequetesSQL.formate(req, SET=dic, table=table, args=dict(dic, __id=I... |
def cree(table, dic, avoid_conflict=False):
""" Create ONE row from dic and returns the entry created """
if avoid_conflict:
req = """ INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} ON CONFLICT DO NOTHING RETURNING *"""
else:
req = """ INSERT INTO {table} {ENTET... |
def supprime(cls,table, **kwargs):
""" Remove entries matchin given condition
kwargs is a dict of column name : value , with length ONE.
"""
assert len(kwargs) == 1
field, value = kwargs.popitem()
req = f"""DELETE FROM {table} WHERE {field} = """ + cls.mark_style
... |
def trace(self, context, obj):
"""Enumerate the children of the given object, as would be visible and utilized by dispatch."""
root = obj
if isroutine(obj):
yield Crumb(self, root, endpoint=True, handler=obj, options=opts(obj))
return
for name, attr in getmembers(obj if isclass(obj) else obj.__cl... |
def main(argv=None):
'''
Main entry-point for calling layouts directly as a program.
'''
# Prep argparse
ap = argparse.ArgumentParser(
description='Basic query options for Python HID-IO Layouts repository',
)
ap.add_argument('--list', action='store_true', help='List available layout ... |
def retrieve_github_cache(self, github_path, version, cache_dir, token):
'''
Retrieves a cache of the layouts git repo from GitHub
@param github_path: Location of the git repo on GitHub (e.g. hid-io/layouts)
@param version: git reference for the version to download (e.g. master)
... |
def get_layout(self, name):
'''
Returns the layout with the given name
'''
layout_chain = []
# Retrieve initial layout file
try:
json_data = self.json_files[self.layout_names[name]]
except KeyError:
log.error('Could not find layout: %s', n... |
def dict_merge(self, merge_to, merge_in):
'''
Recursively merges two dicts
Overwrites any non-dictionary items
merge_to <- merge_in
Modifies merge_to dictionary
@param merge_to: Base dictionary to merge into
@param merge_in: Dictionary that may overwrite element... |
def squash_layouts(self, layouts):
'''
Returns a squashed layout
The first element takes precedence (i.e. left to right).
Dictionaries are recursively merged, overwrites only occur on non-dictionary entries.
[0,1]
0:
test: 'my data'
1:
test: 's... |
def dict(self, name, key_caps=False, value_caps=False):
'''
Returns a JSON dict
@key_caps: Converts all dictionary keys to uppercase
@value_caps: Converts all dictionary values to uppercase
@return: JSON item (may be a variable, list or dictionary)
'''
# Invalid... |
def locale(self):
'''
Do a lookup for the locale code that is set for this layout.
NOTE: USB HID specifies only 35 different locales. If your layout does not fit, it should be set to Undefined/0
@return: Tuple (<USB HID locale code>, <name>)
'''
name = self.json_data['h... |
def compose(self, text, minimal_clears=False, no_clears=False):
'''
Returns the sequence of combinations necessary to compose given text.
If the text expression is not possible with the given layout an ComposeException is thrown.
Iterate over the string, converting each character into ... |
def main(self):
"""
Run the necessary methods in the correct order
"""
logging.info('Starting {at} analysis pipeline'.format(at=self.analysistype))
# Create the objects to be used in the analyses
objects = Objectprep(self)
objects.objectprep()
self.runmeta... |
def genus_specific(self):
"""
For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S
analyses have been performed. Perform the analyses if required
"""
# Initialise a variable to store whether the necessary analyses have alre... |
def pause():
"""Tell iTunes to pause"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", PAUSE], stdout=subprocess.PIPE).communicate() |
def resume():
"""Tell iTunes to resume"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", RESUME], stdout=subprocess.PIPE).communicate() |
def skip():
"""Tell iTunes to skip a song"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", SKIP], stdout=subprocess.PIPE).communicate() |
def play(song, artist=None, album=None):
"""Tells iTunes to play a given song/artist/album - MACOSX ONLY"""
if not settings.platformCompatible():
return False
if song and not artist and not album:
(output, error) = subprocess.Popen(["osascript", "-e", DEFAULT_ITUNES_PLAY % (song, song, song)], stdout=subproces... |
def service_provider(*services):
"""
This is a class decorator that declares a class to provide a set of services.
It is expected that the class has a no-arg constructor and will be instantiated
as a singleton.
"""
def real_decorator(clazz):
instance = clazz()
for service in ser... |
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
compound = bool(re.search(r'(-| |=)', word))
syllabify = _syllabify_compound if compound else _syllabify_simplex
syllabifications = list(syllabify(word))
for word, rules in rank(syllabifications):
# post-proces... |
def apply_T2(word):
'''There is a syllable boundary within a VV sequence of two nonidentical
vowels that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].'''
WORD = word
offset = 0
for vv in vv_sequences(WORD):
seq = vv.group(2)
if not is_diphthong(seq) and not is_long(seq):
... |
def apply_T5(word):
'''If a (V)VVV sequence contains a VV sequence that could be an /i/-final
diphthong, there is a syllable boundary between it and the third vowel,
e.g., [raa.ois.sa], [huo.uim.me], [la.eis.sa], [sel.vi.äi.si], [tai.an],
[säi.e], [oi.om.me].'''
WORD = word
offset = 0
for v... |
def apply_T6(word):
'''If a VVV-sequence contains a long vowel, there is a syllable boundary
between it and the third vowel, e.g. [kor.ke.aa], [yh.ti.öön], [ruu.an],
[mää.yt.te].'''
WORD = word
offset = 0
for vvv in vvv_sequences(WORD):
seq = vvv.group(2)
j = 2 if is_long(seq[:2... |
def apply_T7(word):
'''If a VVV-sequence does not contain a potential /i/-final diphthong,
there is a syllable boundary between the second and third vowels, e.g.
[kau.an], [leu.an], [kiu.as].'''
WORD = word
offset = 0
for vvv in vvv_sequences(WORD):
i = vvv.start(2) + 2 + offset
... |
def apply_T8(word):
'''Split /ie/, /uo/, or /yö/ sequences in syllables that do not take
primary stress.'''
WORD = word
offset = 0
for vv in tail_diphthongs(WORD):
i = vv.start(1) + 1 + offset
WORD = WORD[:i] + '.' + WORD[i:]
offset += 1
RULE = ' T8' if word != WORD els... |
def wsp(word):
'''Return the number of unstressed heavy syllables.'''
HEAVY = r'[ieaAoO]{1}[\.]*(u|y)[^ieaAoO]+(\.|$)'
# # if the word is not monosyllabic, lop off the final syllable, which is
# # extrametrical
# if '.' in word:
# word = word[:word.rindex('.')]
# gather the indices of ... |
def pk_prom(word):
'''Return the number of stressed light syllables.'''
LIGHT = r'[ieaAoO]{1}[\.]*(u|y)(\.|$)'
# # if the word is not monosyllabic, lop off the final syllable, which is
# # extrametrical
# if '.' in word:
# word = word[:word.rindex('.')]
# gather the indices of syllable... |
def ext(self, extension):
"""
Match files with an extension - e.g. 'js', 'txt'
"""
new_pathq = copy(self)
new_pathq._pattern.ext = extension
return new_pathq |
def apply_T8(word):
'''Split /ie/ sequences in syllables that do not take primary stress.'''
WORD = word
offset = 0
for ie in ie_sequences(WORD):
i = ie.start(1) + 1 + offset
WORD = WORD[:i] + '.' + WORD[i:]
offset += 1
RULE = ' T8' if word != WORD else ''
return WORD,... |
def apply_T9(word):
'''Split /iu/ sequences that do not appear in the first, second, or final
syllables.'''
WORD = word
index = 0
offset = 0
for iu in iu_sequences(WORD):
if iu.start(1) != index:
i = iu.start(1) + 1 + offset
WORD = WORD[:i] + '.' + WORD[i:]
... |
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ValueError, AttributeError):
raise ImportError('Cla... |
def import_object_ns(name_space, import_str, *args, **kwargs):
"""Tries to import object from default namespace.
Imports a class and return an instance of it, first by trying
to find the class in a default namespace, then failing back to
a full path if not found in the default namespace.
"""
im... |
def install_virtualbox(distribution, force_setup=False):
""" install virtualbox """
if 'ubuntu' in distribution:
with hide('running', 'stdout'):
sudo('DEBIAN_FRONTEND=noninteractive apt-get update')
sudo("sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o "
"D... |
def install_vagrant_plugin(plugin, use_sudo=False):
""" install vagrant plugin """
cmd = 'vagrant plugin install %s' % plugin
with settings(hide('running', 'stdout')):
if use_sudo:
if plugin not in sudo('vagrant plugin list'):
sudo(cmd)
else:
if plug... |
def runner(self):
"""
Run the necessary methods in the correct order
"""
printtime('Starting mashsippr analysis pipeline', self.starttime)
if not self.pipeline:
# Create the objects to be used in the analyses
objects = Objectprep(self)
objects.... |
def cree_widgets(self):
"""Create widgets and store them in self.widgets"""
for t in self.FIELDS:
if type(t) is str:
attr, kwargs = t, {}
else:
attr, kwargs = t[0], t[1].copy()
self.champs.append(attr)
is_editable = kwargs.p... |
def cree_ws_lecture(self, champs_ligne):
"""Alternative to create read only widgets. They should be set after."""
for c in champs_ligne:
label = ASSOCIATION[c][0]
w = ASSOCIATION[c][3](self.acces[c], False)
w.setObjectName("champ-lecture-seule-details")
se... |
def preservesurrogates(s):
"""
Function for splitting a string into a list of characters, preserving surrogate pairs.
In python 2, unicode characters above 0x10000 are stored as surrogate pairs. For example, the Unicode character
u"\U0001e900" is stored as the surrogate pair u"\ud83a\udd00":
s = ... |
def _unichr(i):
"""
Helper function for taking a Unicode scalar value and returning a Unicode character.
:param s: Unicode scalar value to convert.
:return: Unicode character
"""
if not isinstance(i, int):
raise TypeError
try:
return six.unichr(i)
except ValueError:
... |
def _padded_hex(i, pad_width=4, uppercase=True):
"""
Helper function for taking an integer and returning a hex string. The string will be padded on the left with zeroes
until the string is of the specified width. For example:
_padded_hex(31, pad_width=4, uppercase=True) -> "001F"
:param i: integ... |
def _uax44lm2transform(s):
"""
Helper function for taking a string (i.e. a Unicode character name) and transforming it via UAX44-LM2 loose matching
rule. For more information, see <https://www.unicode.org/reports/tr44/#UAX44-LM2>.
The rule is defined as follows:
"UAX44-LM2. Ignore case, whitespac... |
def _to_unicode_scalar_value(s):
"""
Helper function for converting a character or surrogate pair into a Unicode scalar value e.g.
"\ud800\udc00" -> 0x10000
The algorithm can be found in older versions of the Unicode Standard.
https://unicode.org/versions/Unicode3.0.0/ch03.pdf, Section 3.7, D28
... |
def _get_nr_prefix(i):
"""
Helper function for looking up the derived name prefix associated with a Unicode scalar value.
:param i: Unicode scalar value.
:return: String with the derived name prefix.
"""
for lookup_range, prefix_string in _nr_prefix_strings.items():
if i in lookup_range... |
def casefold(s, fullcasefold=True, useturkicmapping=False):
"""
Function for performing case folding. This function will take the input
string s and return a copy of the string suitable for caseless comparisons.
The input string must be of type 'unicode', otherwise a TypeError will be
raised.
... |
def _build_unicode_character_database(self):
"""
Function for parsing the Unicode character data from the Unicode Character
Database (UCD) and generating a lookup table. For more info on the UCD,
see the following website: https://www.unicode.org/ucd/
"""
filename = "Uni... |
def lookup_by_name(self, name):
"""
Function for retrieving the UnicodeCharacter associated with a name. The name lookup uses the loose matching
rule UAX44-LM2 for loose matching. See the following for more info:
https://www.unicode.org/reports/tr44/#UAX44-LM2
For example:
... |
def lookup_by_partial_name(self, partial_name):
"""
Similar to lookup_by_name(name), this method uses loose matching rule UAX44-LM2 to attempt to find the
UnicodeCharacter associated with a name. However, it attempts to permit even looser matching by doing a
substring search instead of ... |
def _load_unicode_block_info(self):
"""
Function for parsing the Unicode block info from the Unicode Character
Database (UCD) and generating a lookup table. For more info on the UCD,
see the following website: https://www.unicode.org/ucd/
"""
filename = "Blocks.txt"
... |
def _build_casefold_map(self):
"""
Function for parsing the case folding data from the Unicode Character
Database (UCD) and generating a lookup table. For more info on the UCD,
see the following website: https://www.unicode.org/ucd/
"""
self._casefold_map = defaultdict(d... |
def lookup(self, c, lookup_order="CF"):
"""
Function to lookup a character in the casefold map.
The casefold map has four sub-tables, the 'C' or common table, the 'F' or
full table, the 'S' or simple table and the 'T' or the Turkic special
case table. These tables correspond to... |
def load_from_json(data):
"""
Load a :class:`RegistryReponse` from a dictionary or a string (that
will be parsed as json).
"""
if isinstance(data, str):
data = json.loads(data)
applications = [
ApplicationResponse.load_from_json(a) for a in data['a... |
def load_from_json(data):
"""
Load a :class:`ApplicationResponse` from a dictionary or string (that
will be parsed as json).
"""
if isinstance(data, str):
data = json.loads(data)
items = [Item.load_from_json(a) for a in data['items']] if data['items'] is not N... |
def load_from_json(data):
"""
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
"""
if isinstance(data, str):
data = json.loads(data)
return Item(data['title'], data['uri']) |
def apply_T11(word):
'''If a VVV sequence contains a /u, y/-final diphthong and the third vowel
is /i/, there is a syllable boundary between the diphthong and /i/.'''
WORD = word
offset = 0
for vvv in t11_vvv_sequences(WORD):
# i = vvv.start(1) + (1 if vvv.group(1).startswith('i') else 2) +... |
def apply_T12(word):
'''There is a syllable boundary within a VV sequence of two nonidentical
vowels that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].'''
WORD = word
offset = 0
for vv in new_vv(WORD):
# import pdb; pdb.set_trace()
seq = vv.group(1)
if not is_diph... |
def _syllabify_simplex(word):
'''Syllabify the given word.'''
word, rules = apply_T1(word)
if re.search(r'[^ieAyOauo]*([ieAyOauo]{2})[^ieAyOauo]*', word):
word, T2 = apply_T2(word)
word, T8 = apply_T8(word)
word, T9 = apply_T9(word)
rules += T2 + T8 + T9
# T4 produc... |
def apply_T9(word):
'''Split /iu/ sequences that do not appear in the first or second
syllables. Split /iu/ sequences in the final syllable iff the final
syllable would receive stress.'''
WORD = word
index = 0
offset = 0
for iu in iu_sequences(WORD):
if iu.start(1) != index:
... |
def apply_T10(word):
'''Any /iou/ sequence contains a syllable boundary between the first and
second vowel.'''
WORD = word
offset = 0
for iou in iou_sequences(WORD):
i = iou.start(1) + 1 + offset
WORD = WORD[:i] + '.' + WORD[i:]
offset += 1
RULE = ' T10' if word != WORD... |
def T1(word):
'''Insert a syllable boundary in front of every CV sequence.'''
# split consonants and vowels: 'balloon' -> ['b', 'a', 'll', 'oo', 'n']
WORD = [i for i in re.split(r'([ieaouäöy]+)', word, flags=FLAGS) if i]
# keep track of which sub-rules are applying
sub_rules = set()
# a count ... |
def T2(word, rules):
'''Split any VV sequence that is not a genuine diphthong or long vowel.
E.g., [ta.e], [ko.et.taa]. This rule can apply within VVV+ sequences.'''
WORD = word
offset = 0
for vv in vv_sequences(WORD):
seq = vv.group(1)
if not phon.is_diphthong(seq) and not phon.is... |
def T4(word, rules):
'''Optionally split /u,y/-final diphthongs that do not take primary stress.
E.g., [lau.ka.us], [va.ka.ut.taa].'''
WORD = re.split(
r'([ieaouäöy]+[^ieaouäöy]+\.*[ieaoäö]{1}(?:u|y)(?:\.*[^ieaouäöy]+|$))', # noqa
word, flags=re.I | re.U)
PARTS = [[] for part in range(... |
def T6(word, rules):
'''If a VVV-sequence contains a long vowel, insert a syllable boundary
between it and the third vowel. E.g. [kor.ke.aa], [yh.ti.öön], [ruu.an],
[mää.yt.te].'''
offset = 0
try:
WORD, rest = tuple(word.split('.', 1))
for vvv in long_vowel_sequences(rest):
... |
def T8(word, rules):
'''Join /ie/, /uo/, or /yö/ sequences in syllables that take primary
stress.'''
WORD = word
try:
vv = tail_diphthongs(WORD)
i = vv.start(1) + 1
WORD = WORD[:i] + word[i + 1:]
except AttributeError:
pass
rules += ' T8' if word != WORD else '... |
def T11(word, rules):
'''If a VVV sequence contains a /u,y/-final diphthong, insert a syllable
boundary between the diphthong and the third vowel.'''
WORD = word
offset = 0
for vvv in precedence_sequences(WORD):
i = vvv.start(1) + (1 if vvv.group(1)[-1] in 'uyUY' else 2) + offset
WO... |
def pk_prom(word):
'''Return the number of stressed light syllables.'''
violations = 0
stressed = []
for w in extract_words(word):
stressed += w.split('.')[2:-1:2] # odd syllables, excl. word-initial
# (CVV = light)
for syll in stressed:
if phon.is_vowel(syll[-1]):
... |
def rank(syllabifications):
'''Rank syllabifications.'''
# def key(s):
# word = s[0]
# w = wsp(word)
# p = pk_prom(word)
# n = nuc(word)
# t = w + p + n
# print('%s\twsp: %s\tpk: %s\tnuc: %s\ttotal: %s' % (word, w, p, n, t))
# return w + p + n
# syl... |
def ansi_format_iter( self, x_start=0, y_start=0, width=None, height=None, frame=0, columns=1, downsample=1 ):
"""Return the ANSI escape sequence to render the image.
x_start
Offset from the left of the image data to render from. Defaults to 0.
y_start
Offset from the t... |
def ansi_format_iter( self, x_start=0, y_start=0, width=None, height=None, frame=0, columns=1, downsample=1, frame_index=None, frame_flip_v=0, frame_flip_h=0 ):
"""Return the ANSI escape sequence to render the image.
x_start
Offset from the left of the image data to render from. Defaults to... |
def main():
"""
Purge a single fastly url
"""
parser = OptionParser(description=
"Purge a single url from fastly.")
parser.add_option("-k", "--key", dest="apikey",
default="", help="fastly api key")
parser.add_option("-H", "--host", dest="host",
... |
def set_callbacks(self, **dic_functions):
"""Register callbacks needed by the interface object"""
for action in self.interface.CALLBACKS:
try:
f = dic_functions[action]
except KeyError:
pass
else:
setattr(self.interface.... |
def populate(self, obj=None, section=None, parse_types=True):
"""Set attributes in ``obj`` with ``setattr`` from the all values in
``section``.
"""
section = self.default_section if section is None else section
obj = Settings() if obj is None else obj
is_dict = isinstanc... |
def _get_calling_module(self):
"""Get the last module in the call stack that is not this module or ``None`` if
the call originated from this module.
"""
for frame in inspect.stack():
mod = inspect.getmodule(frame[0])
logger.debug(f'calling module: {mod}')
... |
def resource_filename(self, resource_name, module_name=None):
"""Return a resource based on a file name. This uses the ``pkg_resources``
package first to find the resources. If it doesn't find it, it returns
a path on the file system.
:param: resource_name the file name of the resourc... |
def parser(self):
"Load the configuration file."
if not hasattr(self, '_conf'):
cfile = self.config_file
logger.debug('loading config %s' % cfile)
if os.path.isfile(cfile):
conf = self._create_config_parser()
conf.read(os.path.expanduse... |
def get_options(self, section='default', opt_keys=None, vars=None):
"""
Get all options for a section. If ``opt_keys`` is given return
only options with those keys.
"""
vars = vars if vars else self.default_vars
conf = self.parser
opts = {}
if opt_keys is... |
def get_option(self, name, section=None, vars=None, expect=None):
"""Return an option from ``section`` with ``name``.
:param section: section in the ini file to fetch the value; defaults to
constructor's ``default_section``
"""
vars = vars if vars else self.default_vars
... |
def get_option_list(self, name, section=None, vars=None,
expect=None, separator=','):
"""Just like ``get_option`` but parse as a list using ``split``.
"""
val = self.get_option(name, section, vars, expect)
return val.split(separator) if val else [] |
def get_option_boolean(self, name, section=None, vars=None, expect=None):
"""Just like ``get_option`` but parse as a boolean (any case `true`).
"""
val = self.get_option(name, section, vars, expect)
val = val.lower() if val else 'false'
return val == 'true' |
def get_option_int(self, name, section=None, vars=None, expect=None):
"""Just like ``get_option`` but parse as an integer."""
val = self.get_option(name, section, vars, expect)
if val:
return int(val) |
def get_option_float(self, name, section=None, vars=None, expect=None):
"""Just like ``get_option`` but parse as a float."""
val = self.get_option(name, section, vars, expect)
if val:
return float(val) |
def get_option_path(self, name, section=None, vars=None, expect=None):
"""Just like ``get_option`` but return a ``pathlib.Path`` object of
the string.
"""
val = self.get_option(name, section, vars, expect)
return Path(val) |
def property_get( prop, instance, **kwargs ):
"""Wrapper for property reads which auto-dereferences Refs if required.
prop
A Ref (which gets dereferenced and returned) or any other value (which gets returned).
instance
The context object used to dereference the Ref.
"""
if isinstan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.