Search is not available for this dataset
text stringlengths 75 104k |
|---|
def register(self, model):
"""Register a model in self."""
self.models[model._meta.table_name] = model
model._meta.database = self.database
return model |
async def manage(self):
"""Manage a database connection."""
cm = _ContextManager(self.database)
if isinstance(self.database.obj, AIODatabase):
cm.connection = await self.database.async_connect()
else:
cm.connection = self.database.connect()
return cm |
def migrate(migrator, database, **kwargs):
""" Write your migrations here.
> Model = migrator.orm['name']
> migrator.sql(sql)
> migrator.create_table(Model)
> migrator.drop_table(Model, cascade=True)
> migrator.add_columns(Model, **fields)
> migrator.change_columns(Model, **fields)
> m... |
def chain(*args):
"""Runs a series of parsers in sequence passing the result of each parser to the next.
The result of the last parser is returned.
"""
def chain_block(*args, **kwargs):
v = args[0](*args, **kwargs)
for p in args[1:]:
v = p(v)
return v
return chain... |
def one_of(these):
"""Returns the current token if is found in the collection provided.
Fails otherwise.
"""
ch = peek()
try:
if (ch is EndOfFile) or (ch not in these):
fail(list(these))
except TypeError:
if ch != these:
fail([these])
next()
r... |
def not_one_of(these):
"""Returns the current token if it is not found in the collection provided.
The negative of one_of.
"""
ch = peek()
desc = "not_one_of" + repr(these)
try:
if (ch is EndOfFile) or (ch in these):
fail([desc])
except TypeError:
if ch != t... |
def satisfies(guard):
"""Returns the current token if it satisfies the guard function provided.
Fails otherwise.
This is the a generalisation of one_of.
"""
i = peek()
if (i is EndOfFile) or (not guard(i)):
fail(["<satisfies predicate " + _fun_to_str(guard) + ">"])
next()
re... |
def not_followed_by(parser):
"""Succeeds if the given parser cannot consume input"""
@tri
def not_followed_by_block():
failed = object()
result = optional(tri(parser), failed)
if result != failed:
fail(["not " + _fun_to_str(parser)])
choice(not_followed_by_block) |
def many(parser):
"""Applies the parser to input zero or more times.
Returns a list of parser results.
"""
results = []
terminate = object()
while local_ps.value:
result = optional(parser, terminate)
if result == terminate:
break
results.append(result)
... |
def many_until(these, term):
"""Consumes as many of these as it can until it term is encountered.
Returns a tuple of the list of these results and the term result
"""
results = []
while True:
stop, result = choice(_tag(True, term),
_tag(False, these))
... |
def many_until1(these, term):
"""Like many_until but must consume at least one of these.
"""
first = [these()]
these_results, term_result = many_until(these, term)
return (first + these_results, term_result) |
def sep1(parser, separator):
"""Like sep but must consume at least one of parser.
"""
first = [parser()]
def inner():
separator()
return parser()
return first + many(tri(inner)) |
def string(string):
"""Iterates over string, matching input to the items provided.
The most obvious usage of this is to accept an entire string of characters,
However this is function is more general than that. It takes an iterable
and for each item, it tries one_of for that set. For example,
... |
def seq(*sequence):
"""Runs a series of parsers in sequence optionally storing results in a returned dictionary.
For example:
seq(whitespace, ('phone', digits), whitespace, ('name', remaining))
"""
results = {}
for p in sequence:
if callable(p):
p()
continue... |
def _fill(self, size):
"""fills the internal buffer from the source iterator"""
try:
for i in range(size):
self.buffer.append(self.source.next())
except StopIteration:
self.buffer.append((EndOfFile, EndOfFile))
self.len = len(self.buffer) |
def next(self):
"""Advances to and returns the next token or returns EndOfFile"""
self.index += 1
t = self.peek()
if not self.depth:
self._cut()
return t |
def current(self):
"""Returns the current (token, position) or (EndOfFile, EndOfFile)"""
if self.index >= self.len:
self._fill((self.index - self.len) + 1)
return self.index < self.len and self.buffer[self.index] or (EndOfFile, EndOfFile) |
def main(world_cls, referee_cls, gui_cls, gui_actor_cls, ai_actor_cls,
theater_cls=PygletTheater, default_host=DEFAULT_HOST,
default_port=DEFAULT_PORT, argv=None):
"""
Run a game being developed with the kxg game engine.
Usage:
{exe_name} sandbox [<num_ais>] [-v...]
{exe_name} client [--hos... |
def _run_supervisor(self):
"""
Poll the queues that the worker can use to communicate with the
supervisor, until all the workers are done and all the queues are
empty. Handle messages as they appear.
"""
import time
still_supervising = lambda: (
... |
def field_type(self):
"""Return database field type."""
if not self.model:
return 'JSON'
database = self.model._meta.database
if isinstance(database, Proxy):
database = database.obj
if Json and isinstance(database, PostgresqlDatabase):
return '... |
def python_value(self, value):
"""Parse value from database."""
if self.field_type == 'TEXT' and isinstance(value, str):
return self.loads(value)
return value |
def get_fsapi_endpoint(self):
"""Parse the fsapi endpoint from the device url."""
endpoint = yield from self.__session.get(self.fsapi_device_url, timeout = self.timeout)
text = yield from endpoint.text(encoding='utf-8')
doc = objectify.fromstring(text)
return doc.webfsapi.text |
def create_session(self):
"""Create a session on the frontier silicon device."""
req_url = '%s/%s' % (self.__webfsapi, 'CREATE_SESSION')
sid = yield from self.__session.get(req_url, params=dict(pin=self.pin),
timeout = self.timeout)
text = yiel... |
def call(self, path, extra=None):
"""Execute a frontier silicon API call."""
try:
if not self.__webfsapi:
self.__webfsapi = yield from self.get_fsapi_endpoint()
if not self.sid:
self.sid = yield from self.create_session()
if not isins... |
def handle_set(self, item, value):
"""Helper method for setting a value by using the fsapi API."""
doc = yield from self.call('SET/{}'.format(item), dict(value=value))
if doc is None:
return None
return doc.status == 'FS_OK' |
def handle_text(self, item):
"""Helper method for fetching a text value."""
doc = yield from self.handle_get(item)
if doc is None:
return None
return doc.value.c8_array.text or None |
def handle_int(self, item):
"""Helper method for fetching a integer value."""
doc = yield from self.handle_get(item)
if doc is None:
return None
return int(doc.value.u8.text) or None |
def handle_long(self, item):
"""Helper method for fetching a long value. Result is integer."""
doc = yield from self.handle_get(item)
if doc is None:
return None
return int(doc.value.u32.text) or None |
def handle_list(self, item):
"""Helper method for fetching a list(map) value."""
doc = yield from self.call('LIST_GET_NEXT/'+item+'/-1', dict(
maxItems=100,
))
if doc is None:
return []
if not doc.status == 'FS_OK':
return []
ret = l... |
def get_power(self):
"""Check if the device is on."""
power = (yield from self.handle_int(self.API.get('power')))
return bool(power) |
def set_power(self, value=False):
"""Power on or off the device."""
power = (yield from self.handle_set(
self.API.get('power'), int(value)))
return bool(power) |
def get_modes(self):
"""Get the modes supported by this device."""
if not self.__modes:
self.__modes = yield from self.handle_list(
self.API.get('valid_modes'))
return self.__modes |
def get_mode_list(self):
"""Get the label list of the supported modes."""
self.__modes = yield from self.get_modes()
return (yield from self.collect_labels(self.__modes)) |
def get_mode(self):
"""Get the currently active mode on the device (DAB, FM, Spotify)."""
mode = None
int_mode = (yield from self.handle_long(self.API.get('mode')))
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['band'] == int_mode:
... |
def set_mode(self, value):
"""Set the currently active mode on the device (DAB, FM, Spotify)."""
mode = -1
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['label'] == value:
mode = temp_mode['band']
return (yield from self.han... |
def get_volume_steps(self):
"""Read the maximum volume level of the device."""
if not self.__volume_steps:
self.__volume_steps = yield from self.handle_int(
self.API.get('volume_steps'))
return self.__volume_steps |
def get_mute(self):
"""Check if the device is muted."""
mute = (yield from self.handle_int(self.API.get('mute')))
return bool(mute) |
def set_mute(self, value=False):
"""Mute or unmute the device."""
mute = (yield from self.handle_set(self.API.get('mute'), int(value)))
return bool(mute) |
def get_play_status(self):
"""Get the play status of the device."""
status = yield from self.handle_int(self.API.get('status'))
return self.PLAY_STATES.get(status) |
def get_equalisers(self):
"""Get the equaliser modes supported by this device."""
if not self.__equalisers:
self.__equalisers = yield from self.handle_list(
self.API.get('equalisers'))
return self.__equalisers |
def get_equaliser_list(self):
"""Get the label list of the supported modes."""
self.__equalisers = yield from self.get_equalisers()
return (yield from self.collect_labels(self.__equalisers)) |
def set_sleep(self, value=False):
"""Set device sleep timer."""
return (yield from self.handle_set(self.API.get('sleep'), int(value))) |
def _set_range(self, start, stop, value, value_len):
"""
Assumes that start and stop are already in 'buffer' coordinates. value is a byte iterable.
value_len is fractional.
"""
assert stop >= start and value_len >= 0
range_len = stop - start
if range_len < value_l... |
def _parse_genotype(self, vcf_fields):
"""Parse genotype from VCF line data"""
format_col = vcf_fields[8].split(':')
genome_data = vcf_fields[9].split(':')
try:
gt_idx = format_col.index('GT')
except ValueError:
return []
return [int(x) for x in re... |
def setDefaultIREncoding(encoding):
'''
setDefaultIREncoding - Sets the default encoding used by IndexedRedis.
This will be the default encoding used for field data. You can override this on a
per-field basis by using an IRField (such as IRUnicodeField or IRRawField)
@param encoding - An encoding (like ut... |
def toIndex(self, value):
'''
toIndex - An optional method which will return the value prepped for index.
By default, "toStorage" will be called. If you provide "hashIndex=True" on the constructor,
the field will be md5summed for indexing purposes. This is useful for large strings, etc.
'''
if self._isI... |
def _getReprProperties(self):
'''
_getReprProperties - Get the properties of this field to display in repr().
These should be in the form of $propertyName=$propertyRepr
The default IRField implementation handles just the "hashIndex" property.
defaultValue is part of "__repr__" impl. You should just ... |
def copy(self):
'''
copy - Create a copy of this IRField.
Each subclass should implement this, as you'll need to pass in the args to constructor.
@return <IRField (or subclass)> - Another IRField that has all the same values as this one.
'''
return self.__class__(name=self.name, valueType=self.valueT... |
def getObj(self):
'''
getObj - Fetch (if not fetched) and return the obj associated with this data.
'''
if self.obj is None:
if not self.pk:
return None
self.obj = self.foreignModel.objects.get(self.pk)
return self.obj |
def getPk(self):
'''
getPk - Resolve any absent pk's off the obj's (like if an obj has been saved), and return the pk.
'''
if not self.pk and self.obj:
if self.obj._id:
self.pk = self.obj._id
return self.pk |
def objHasUnsavedChanges(self):
'''
objHasUnsavedChanges - Check if any object has unsaved changes, cascading.
'''
if not self.obj:
return False
return self.obj.hasUnsavedChanges(cascadeObjects=True) |
def getPk(self):
'''
getPk - @see ForeignLinkData.getPk
'''
if not self.pk or None in self.pk:
for i in range( len(self.pk) ):
if self.pk[i]:
continue
if self.obj[i] and self.obj[i]._id:
self.pk[i] = self.obj[i]._id
return self.pk |
def getObj(self):
'''
getObj - @see ForeignLinkData.getObj
Except this always returns a list
'''
if self.obj:
needPks = [ (i, self.pk[i]) for i in range(len(self.obj)) if self.obj[i] is None]
if not needPks:
return self.obj
fetched = list(self.foreignModel.objects.getMultiple([needPk[1] for... |
def isFetched(self):
'''
isFetched - @see ForeignLinkData.isFetched
'''
if not self.obj:
return False
if not self.pk or None in self.obj:
return False
return not bool(self.obj is None) |
def objHasUnsavedChanges(self):
'''
objHasUnsavedChanges - @see ForeignLinkData.objHasUnsavedChanges
True if ANY object has unsaved changes.
'''
if not self.obj:
return False
for thisObj in self.obj:
if not thisObj:
continue
if thisObj.hasUnsavedChanges(cascadeObjects=True):
return True... |
def assert_json_type(value: JsonValue, expected_type: JsonCheckType) -> None:
"""Check that a value has a certain JSON type.
Raise TypeError if the type does not match.
Supported types: str, int, float, bool, list, dict, and None.
float will match any number, int will only match numbers without
fr... |
def json_get(json: JsonValue, path: str, expected_type: Any = ANY) -> Any:
"""Get a JSON value by path, optionally checking its type.
>>> j = {"foo": {"num": 3.4, "s": "Text"}, "arr": [10, 20, 30]}
>>> json_get(j, "/foo/num")
3.4
>>> json_get(j, "/arr[1]")
20
Raise ValueError if the path i... |
def json_get_default(json: JsonValue, path: str,
default: Any, expected_type: Any = ANY) -> Any:
"""Get a JSON value by path, optionally checking its type.
This works exactly like json_get(), but instead of raising
ValueError or IndexError when a path part is not found, return
the ... |
def load(cls, fh):
"""
Load json or yaml data from file handle.
Args:
fh (file): File handle to load from.
Examlple:
>>> with open('data.json', 'r') as json:
>>> jsdata = composite.load(json)
>>>
>>> with open('data.yml', '... |
def from_json(cls, fh):
"""
Load json from file handle.
Args:
fh (file): File handle to load from.
Examlple:
>>> with open('data.json', 'r') as json:
>>> data = composite.load(json)
"""
if isinstance(fh, str):
return cl... |
def intersection(self, other, recursive=True):
"""
Recursively compute intersection of data. For dictionaries, items
for specific keys will be reduced to unique items. For lists, items
will be reduced to unique items. This method is meant to be analogous
to set.intersection for c... |
def union(self, other, recursive=True, overwrite=False):
"""
Recursively compute union of data. For dictionaries, items
for specific keys will be combined into a list, depending on the
status of the overwrite= parameter. For lists, items will be appended
and reduced to unique ite... |
def update(self, other):
"""
Update internal dictionary object. This is meant to be an
analog for dict.update().
"""
if self.meta_type == 'list':
raise AssertionError('Cannot update object of `list` base type!')
elif self.meta_type == 'dict':
self.... |
def items(self):
"""
Return keys for object, if they are available.
"""
if self.meta_type == 'list':
return self._list
elif self.meta_type == 'dict':
return self._dict.items() |
def values(self):
"""
Return keys for object, if they are available.
"""
if self.meta_type == 'list':
return self._list
elif self.meta_type == 'dict':
return self._dict.values() |
def append(self, item):
"""
Append to object, if object is list.
"""
if self.meta_type == 'dict':
raise AssertionError('Cannot append to object of `dict` base type!')
if self.meta_type == 'list':
self._list.append(item)
return |
def extend(self, item):
"""
Extend list from object, if object is list.
"""
if self.meta_type == 'dict':
raise AssertionError('Cannot extend to object of `dict` base type!')
if self.meta_type == 'list':
self._list.extend(item)
return |
def json(self):
"""
Return JSON representation of object.
"""
if self.meta_type == 'list':
ret = []
for dat in self._list:
if not isinstance(dat, composite):
ret.append(dat)
else:
ret.append(d... |
def write_json(self, fh, pretty=True):
"""
Write composite object to file handle in JSON format.
Args:
fh (file): File handle to write to.
pretty (bool): Sort keys and indent in output.
"""
sjson = json.JSONEncoder().encode(self.json())
if pretty:... |
def write(self, fh, pretty=True):
"""
API niceness defaulting to composite.write_json().
"""
return self.write_json(fh, pretty=pretty) |
def json(self):
"""
Return JSON representation of object.
"""
data = {}
for item in self._data:
if isinstance(self._data[item], filetree):
data[item] = self._data[item].json()
else:
data[item] = self._data[item]
retu... |
def filelist(self):
"""
Return list of files in filetree.
"""
if len(self._filelist) == 0:
for item in self._data:
if isinstance(self._data[item], filetree):
self._filelist.extend(self._data[item].filelist())
else:
... |
def prune(self, regex=r".*"):
"""
Prune leaves of filetree according to specified
regular expression.
Args:
regex (str): Regular expression to use in pruning tree.
"""
return filetree(self.root, ignore=self.ignore, regex=regex) |
def deref(self, ctx):
"""
Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return
the value this reference references.
If the call was already made, it returns a cached result.
It also makes sure there's no cyclic reference, and... |
def getModel(self):
'''
getModel - get the IndexedRedisModel associated with this list. If one was not provided in constructor,
it will be inferred from the first item in the list (if present)
@return <None/IndexedRedisModel> - None if none could be found, otherwise the IndexedRedisModel type of the ite... |
def delete(self):
'''
delete - Delete all objects in this list.
@return <int> - Number of objects deleted
'''
if len(self) == 0:
return 0
mdl = self.getModel()
return mdl.deleter.deleteMultiple(self) |
def save(self):
'''
save - Save all objects in this list
'''
if len(self) == 0:
return []
mdl = self.getModel()
return mdl.saver.save(self) |
def reload(self):
'''
reload - Reload all objects in this list.
Updates in-place. To just fetch all these objects again, use "refetch"
@return - List (same order as current objects) of either exception (KeyError) if operation failed,
or a dict of fields changed -> (old, new)
'''
if len(self) == 0... |
def refetch(self):
'''
refetch - Fetch a fresh copy of all items in this list.
Returns a new list. To update in-place, use "reload".
@return IRQueryableList<IndexedRedisModel> - List of fetched items
'''
if len(self) == 0:
return IRQueryableList()
mdl = self.getModel()
pks = [item._id for item... |
def hashDictOneLevel(myDict):
'''
A function which can generate a hash of a one-level
dict containing strings (like REDIS_CONNECTION_PARAMS)
@param myDict <dict> - Dict with string keys and values
@return <long> - Hash of myDict
'''
keys = [str(x) for x in myDict.keys()]
keys.sort()
lst = []
for key... |
def output(self, to=None, *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
for blok in self:
blok.output(to, *args, **kwargs)
return self |
def render(self, *args, **kwargs):
'''Renders as a str'''
render_to = StringIO()
self.output(render_to, *args, **kwargs)
return render_to.getvalue() |
def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
if formatted and self.blox:
self.blox[0].output(to=to, formatted=True, indent=indent, indentation=indentation, *args, **kwargs)
for blok in ... |
def start_tag(self):
'''Returns the elements HTML start tag'''
direct_attributes = (attribute.render(self) for attribute in self.render_attributes)
attributes = ()
if hasattr(self, '_attributes'):
attributes = ('{0}="{1}"'.format(key, value)
... |
def output(self, to=None, *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
to.write(self.start_tag)
if not self.tag_self_closes:
to.write(self.end_tag) |
def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
if formatted:
to.write(self.start_tag)
to.write('\n')
if not self.tag_self_closes:
for blok in self.blox:
... |
def safe_repr(obj):
"""Returns a repr of an object and falls back to a minimal representation of type and ID if the call to repr raised
an error.
:param obj: object to safe repr
:returns: repr string or '(type<id> repr error)' string
:rtype: str
"""
try:
obj_repr = repr(obj)
exc... |
def output(self, to=None, formatted=False, *args, **kwargs):
'''Outputs the set text'''
to.write('<!DOCTYPE {0}>'.format(self.type)) |
def match_to_clinvar(genome_file, clin_file):
"""
Match a genome VCF to variants in the ClinVar VCF file
Acts as a generator, yielding tuples of:
(ClinVarVCFLine, ClinVarAllele, zygosity)
'zygosity' is a string and corresponds to the genome's zygosity for that
ClinVarAllele. It can be either: ... |
def as_dict(self):
"""Return Allele data as dict object."""
self_as_dict = dict()
self_as_dict['sequence'] = self.sequence
if hasattr(self, 'frequency'):
self_as_dict['frequency'] = self.frequency
return self_as_dict |
def _parse_allele_data(self):
"""Create list of Alleles from VCF line data"""
return [Allele(sequence=x) for x in
[self.ref_allele] + self.alt_alleles] |
def _parse_info(self, info_field):
"""Parse the VCF info field"""
info = dict()
for item in info_field.split(';'):
# Info fields may be "foo=bar" or just "foo".
# For the first case, store key "foo" with value "bar"
# For the second case, store key "foo" with ... |
def as_dict(self):
"""Dict representation of parsed VCF data"""
self_as_dict = {'chrom': self.chrom,
'start': self.start,
'ref_allele': self.ref_allele,
'alt_alleles': self.alt_alleles,
'alleles': [x.as_dict(... |
def get_pos(vcf_line):
"""
Very lightweight parsing of a vcf line to get position.
Returns a dict containing:
'chrom': index of chromosome (int), indicates sort order
'pos': position on chromosome (int)
"""
if not vcf_line:
return None
vcf_dat... |
def _toStorage(self, value):
'''
_toStorage - Convert the value to a string representation for storage.
@param value - The value of the item to convert
@return A string value suitable for storing.
'''
for chainedField in self.chainedFields:
value = chainedField.toStorage(value)
return value |
def _fromStorage(self, value):
'''
_fromStorage - Convert the value from storage (string) to the value type.
@return - The converted value, or "irNull" if no value was defined (and field type is not default/string)
'''
for chainedField in reversed(self.chainedFields):
value = chainedField._fromStorage(... |
def _checkCanIndex(self):
'''
_checkCanIndex - Check if we CAN index (if all fields are indexable).
Also checks the right-most field for "hashIndex" - if it needs to hash we will hash.
'''
# NOTE: We can't just check the right-most field. For types like pickle that don't support indexing, they don't
# ... |
def byte_length(self):
"""
:returns: sum of lengthes of all ranges or None if one of the ranges is open
:rtype: int, float or None
"""
sum = 0
for r in self:
if r.is_open():
return None
sum += r.byte_length()
return sum |
def has_overlaps(self):
"""
:returns: True if one or more range in the list overlaps with another
:rtype: bool
"""
sorted_list = sorted(self)
for i in range(0, len(sorted_list) - 1):
if sorted_list[i].overlaps(sorted_list[i + 1]):
return True
... |
def max_stop(self):
"""
:returns: maximum stop in list or None if there's at least one open range
:type: int, float or None
"""
m = 0
for r in self:
if r.is_open():
return None
m = max(m, r.stop)
return m |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.