text stringlengths 18 773k |
|---|
def _fetch_objects(self, key, value):
"""Fetch Multiple linked objects"""
return self.to_cls.query.filter(**{key: value}) |
async def _write_frame_awaiting_response(self, waiter_id, frame, request,
no_wait, check_open=True, drain=True):
'''Write a frame and set a waiter for
the response (unless no_wait is set)'''
if no_wait:
await self._write_frame(frame, request, check_open=check... |
def sequencer(params, source_specs):
'''
Add a sequence of sounds to a buffer
:param params: buffer parameters, controls length of signal created
:param source_spec: list of tuples containing (source, sample). The source is added into the output buffer
at the sample position given by the second elem... |
def _load_base_class_fields(new_class, bases, attrs):
"""If this class is subclassing another Entity, add that Entity's
fields. Note that we loop over the bases in *reverse*.
This is necessary in order to maintain the correct order of fields.
"""
for base in reversed(bases):
... |
def _load_fields(new_class, attrs):
"""Load field items into Class.
This method sets up the primary attribute of an association.
If Child class has defined an attribute so `parent = field.Reference(Parent)`, then `parent`
is set up in this method, while `parent_id` is set up in `_set_up... |
def _set_up_reference_fields(new_class):
"""Walk through relation fields and setup shadow attributes"""
if new_class.meta_.declared_fields:
for _, field in new_class.meta_.declared_fields.items():
if isinstance(field, Reference):
shadow_field_name, shadow_... |
def _set_id_field(new_class):
"""Lookup the id field for this entity and assign"""
# FIXME What does it mean when there are no declared fields?
# Does it translate to an abstract entity?
if new_class.meta_.declared_fields:
try:
new_class.meta_.id_field = nex... |
def _create_id_field(new_class):
"""Create and return a default ID field that is Auto generated"""
id_field = Auto(identifier=True)
setattr(new_class, 'id', id_field)
id_field.__set_name__(new_class, 'id')
# Ensure ID field is updated properly in Meta attribute
new_clas... |
def _load_attributes(new_class):
"""Load list of attributes from declared fields"""
for field_name, field_obj in new_class.meta_.declared_fields.items():
new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj |
def unique_fields(self):
""" Return the unique fields for this entity """
return [(field_name, field_obj)
for field_name, field_obj in self.declared_fields.items()
if field_obj.unique] |
def _update_data(self, *data_dict, **kwargs):
"""
A private method to process and update entity values correctly.
:param data: A dictionary of values to be updated for the entity
:param kwargs: keyword arguments with key-value pairs to be updated
"""
# Load each of the ... |
def to_dict(self):
""" Return entity data as a dictionary """
return {field_name: getattr(self, field_name, None)
for field_name in self.meta_.declared_fields} |
def clone(self):
"""Deepclone the entity, but reset state"""
clone_copy = copy.deepcopy(self)
clone_copy.state_ = EntityState()
return clone_copy |
def get(cls, identifier: Any) -> 'Entity':
"""Get a specific Record from the Repository
:param identifier: id of the record to be fetched from the repository.
"""
logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}')
# Get the ID field for the entity
... |
def reload(self) -> None:
"""Reload Entity from the repository"""
if not self.state_.is_persisted or self.state_.is_changed:
raise InvalidStateError(f'`{self.__class__.__name__}` object is in invalid state')
# Retrieve the entity's ID by the configured Identifier field
ident... |
def find_by(cls, **kwargs) -> 'Entity':
"""Find a specific entity record that matches one or more criteria.
:param kwargs: named arguments consisting of attr_name and attr_value pairs to search on
"""
logger.debug(f'Lookup `{cls.__name__}` object with values '
f'{kw... |
def exists(cls, excludes_, **filters):
""" Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
... |
def create(cls, *args, **kwargs) -> 'Entity':
"""Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity
"""
logger.debug(
... |
def save(self):
"""Save a new Entity into repository.
Performs unique validations before creating the entity.
"""
logger.debug(
f'Saving `{self.__class__.__name__}` object')
# Fetch Model class and connected repository from Repository Factory
model_cls = rep... |
def update(self, *data, **kwargs) -> 'Entity':
"""Update a Record in the repository.
Also performs unique validations before creating the entity.
Supports both dictionary and keyword argument updates to the entity::
dog.update({'age': 10})
dog.update(age=10)
... |
def _validate_unique(self, create=True):
""" Validate the unique constraints for the entity """
# Build the filters from the unique constraints
filters, excludes = {}, {}
for field_name, field_obj in self.meta_.unique_fields:
lookup_value = getattr(self, field_name, None)
... |
def delete(self):
"""Delete a Record from the Repository
will perform callbacks and run validations before deletion.
Throws ObjectNotFoundError if the object was not found in the repository.
"""
# Fetch Model class and connected repository from Repository Factory
model_... |
def add(self, item, count=1):
'''
When we receive stream of data, we add them in the chunk
which has limit on the no. of items that it will store.
>>> s = StreamCounter(5,5)
>>> data_stream = ['a','b','c','d']
>>> for item in data_stream:
... s.add(item)
... |
def _drop_oldest_chunk(self):
'''
To handle the case when the items comming in the chunk
is more than the maximum capacity of the chunk. Our intent
behind is to remove the oldest chunk. So that the items come
flowing in.
>>> s = StreamCounter(5,5)
>>> data_stream ... |
def get(self, item, default=0, normalized=False):
'''
When we have the stream of data pushed in the chunk
we can retrive count of an item using this method.
>>> stream_counter_obj = StreamCounter(5,5)
>>> data_stream = ['a','b','c']
>>> for item in data_stream:
..... |
def message(self):
""" Convert the message to a mime compliant email string """
return '\n'.join(
[self.from_email, str(self.to), self.subject, self.body]) |
def recipients(self):
"""
Return a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).
"""
return [email for email in (self.to + self.cc + self.bcc) if email] |
def get_connection(self, fail_silently=False):
"""Retrieve connection to send email"""
from protean.services.email import get_connection
if not self.connection:
self.connection = get_connection(fail_silently=fail_silently)
return self.connection |
def send(self, fail_silently=False):
"""Send the email message."""
if not self.recipients():
# Don't bother creating the network connection if
# there's nobody to send to.
return 0
return self.get_connection(fail_silently).send_messages([self]) |
def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable,
skip_middleware=False):
"""
Adds a static route. A static route is a special route that
doesnt follow any of the normal rules, and never has any path
parameters.
Ideall... |
def prefix(self, prefix):
"""
Adds a prefix to routes contained within.
"""
original_prefix = self._prefix
self._prefix += prefix
yield self
self._prefix = original_prefix |
def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) f... |
def generate_random_string(length=6):
'''
Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_string(10) for i in range(N))) == N
True
'''
n =... |
def get_timestamp(dt=None):
'''
Return current timestamp if @dt is None
else return timestamp of @dt.
>>> t = datetime.datetime(2015, 0o5, 21)
>>> get_timestamp(t)
1432166400
'''
if dt is None: dt = datetime.datetime.utcnow()
t = dt.utctimetuple()
return calendar.timegm(t) |
def get_datetime(epoch):
'''
get datetime from an epoch timestamp
>>> get_datetime(1432188772)
datetime.datetime(2015, 5, 21, 6, 12, 52)
'''
t = time.gmtime(epoch)
dt = datetime.datetime(*t[:6])
return dt |
def convert_ts(tt):
'''
tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
>>> tt = time.strptime("23.10.2012", "%d.%m.%Y")
>>> convert_ts(tt)
1350950400
tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_ho... |
def xcode(text, encoding='utf8', mode='ignore'):
'''
Converts unicode encoding to str
>>> xcode(b'hello')
b'hello'
>>> xcode('hello')
b'hello'
'''
return text.encode(encoding, mode) if isinstance(text, str) else text |
def parse_location(loc, default_port):
'''
loc can be of the format http://<ip/domain>[:<port>]
eg:
http://localhost:8888
http://localhost/
return ip (str), port (int)
>>> parse_location('http://localhost/', 6379)
('localhost', 6379)
>>> parse_location('http://localhost:8888'... |
def serialize_dict_keys(d, prefix=""):
"""returns all the keys in nested a dictionary.
>>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }))
['a', 'a.b', 'a.b.b', 'a.b.c']
"""
keys = []
for k, v in d.items():
fqk = '{}{}'.format(prefix, k)
keys.append(fqk)
if ... |
def flatten_dict(d,
parent_key='', sep='.',
ignore_under_prefixed=True,
mark_value=True):
'''
Flattens a nested dictionary
>>> from pprint import pprint
>>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } }
>>> fd = flatten_dict(d... |
def deepgetattr(obj, attr, default=AttributeError):
"""
Recurses through an attribute chain to get the ultimate value (obj/data/member/value)
from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html
>>> class Universe(object):
... def __init__(self, galaxy):
... ... |
def set_file_limits(n):
'''
Set the limit on number of file descriptors
that this process can open.
'''
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
return True
except ValueError:
return False |
def memoize(f):
'''
Caches result of a function
From: https://goo.gl/aXt4Qy
>>> import time
>>> @memoize
... def test(msg):
... # Processing for result that takes time
... time.sleep(1)
... return msg
>>>
>>> for i in range(5):
... start = time.time(... |
def load_object(imp_path):
'''
Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
False
>>> isinstance(777, num)
True
... |
def fail(self, key, **kwargs):
"""A helper method that simply raises a `ValidationError`.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name,
... |
def _run_validators(self, value):
"""Perform validation on ``value``. Raise a :exc:`ValidationError` if
validation does not succeed.
"""
if value in self.empty_values:
return
errors = []
for validator in self.validators:
try:
valid... |
def _load(self, value: Any):
"""
Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field
"""
if value in self.empty_values:
# If a default has been set fo... |
def _extract_lookup(self, key):
"""Extract lookup method based on key name format"""
parts = key.split('__')
# 'exact' is the default lookup if there was no explicit comparison op in `key`
# Assume there is only one `__` in the key.
# FIXME Change for child attribute query su... |
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
"""Transform from json to Request
Exception:
ValueError: If path does not exist.
"""
try:
return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding)
except TypeError as e... |
def get_backend_expiry(self, expiry=DEFAULT_EXPIRY):
"""
Return the expiry value usable by this backend based upon the provided
timeout.
"""
if expiry == DEFAULT_EXPIRY:
expiry = self.default_expiry
elif expiry == 0:
# avoid time.time() related pre... |
def get_many(self, keys):
"""
Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values.
Return a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the respo... |
def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key)
if value is None:
raise ValueError("Key '%s' not found" % key)
new_value = value + delta
self.... |
def set_many(self, data, expiry=DEFAULT_EXPIRY):
"""
Set a bunch of values in the cache at once from a dict of key/value
pairs. For certain backends (memcached), this is much more efficient
than calling set() multiple times.
If timeout is given, use that timeout for the key; oth... |
def init_logger(v_num: int):
"""
Call when initialize Jumeaux !!
:return:
"""
logging.addLevelName(LogLevel.INFO_LV1.value, 'INFO_LV1') # type: ignore # Prevent for enum problem
logging.addLevelName(LogLevel.INFO_LV2.value, 'INFO_LV2') # type: ignore # Prevent for enum problem
logging.addL... |
def _initialize_providers(self):
"""Read config file and initialize providers"""
configured_providers = active_config.DATABASES
provider_objects = {}
if not isinstance(configured_providers, dict) or configured_providers == {}:
raise ConfigurationError(
"'DATA... |
def get_provider(self, provider_name='default'):
"""Fetch provider with the name specified in Configuration file"""
try:
if self._providers is None:
self._providers = self._initialize_providers()
return self._providers[provider_name]
except KeyError:
... |
def get_connection(self, provider_name='default'):
"""Fetch connection from Provider"""
try:
return self._providers[provider_name].get_connection()
except KeyError:
raise AssertionError(f'No Provider registered with name {provider_name}') |
def update_defaults(self, ext_config):
""" Update the default settings for an extension from an object"""
for setting in dir(ext_config):
if setting.isupper() and not hasattr(self, setting):
setattr(self, setting, getattr(ext_config, setting)) |
def keeprunning(wait_secs=0, exit_on_success=False,
on_success=None, on_error=None, on_done=None):
'''
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when error
happens, we should NOT terminate execution
>>> from deep... |
def fetch_entity_cls_from_registry(entity):
"""Util Method to fetch an Entity class from an entity's name"""
# Defensive check to ensure we only process if `to_cls` is a string
if isinstance(entity, str):
try:
return repo_factory.get_entity(entity)
except AssertionError:
... |
def register(self, entity_cls, provider_name=None):
""" Register the given model with the factory
:param entity_cls: Entity class to be registered
:param provider: Optional provider to associate with Entity class
"""
self._validate_entity_cls(entity_cls)
# Register the e... |
def _find_entity_in_records_by_class_name(self, entity_name):
"""Fetch by Entity Name in values"""
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
# If more than one record was found, we are dealing with... |
def _get_entity_by_class(self, entity_cls):
"""Fetch Entity record with Entity class details"""
entity_qualname = fully_qualified_name(entity_cls)
if entity_qualname in self._registry:
return self._registry[entity_qualname]
else:
return self._find_entity_in_record... |
def _get_entity_by_name(self, entity_name):
"""Fetch Entity record with an Entity name"""
if entity_name in self._registry:
return self._registry[entity_name]
else:
return self._find_entity_in_records_by_class_name(entity_name) |
def _validate_entity_cls(self, entity_cls):
"""Validate that Entity is a valid class"""
# Import here to avoid cyclic dependency
from protean.core.entity import Entity
if not issubclass(entity_cls, Entity):
raise AssertionError(
f'Entity {entity_cls.__name__}... |
def get_model(self, entity_cls):
"""Retrieve Model class connected to Entity"""
entity_record = self._get_entity_by_class(entity_cls)
model_cls = None
if entity_record.model_cls:
model_cls = entity_record.model_cls
else:
# We should ask the Provider to gi... |
def get_repository(self, entity_cls):
"""Retrieve a Repository for the Model with a live connection"""
entity_record = self._get_entity_by_class(entity_cls)
provider = self.get_provider(entity_record.provider_name)
return provider.get_repository(entity_record.entity_cls) |
async def set_heater_values(heater_data, heater):
"""Set heater values from heater data"""
heater.current_temp = heater_data.get('currentTemp')
heater.device_status = heater_data.get('deviceStatus')
heater.available = heater.device_status == 0
heater.name = heater_data.get('deviceName')
heater.f... |
async def connect(self, retry=2):
"""Connect to Mill."""
# pylint: disable=too-many-return-statements
url = API_ENDPOINT_1 + 'login'
headers = {
"Content-Type": "application/x-zc-object",
"Connection": "Keep-Alive",
"X-Zc-Major-Domain": "seanywell",
... |
def sync_connect(self):
"""Close the Mill connection."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.connect())
loop.run_until_complete(task) |
def sync_close_connection(self):
"""Close the Mill connection."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.close_connection())
loop.run_until_complete(task) |
async def request(self, command, payload, retry=3):
"""Request data."""
# pylint: disable=too-many-return-statements
if self._token is None:
_LOGGER.error("No token")
return None
_LOGGER.debug(command, payload)
nonce = ''.join(random.choice(string.ascii... |
def sync_request(self, command, payload, retry=2):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.request(command, payload, retry))
return loop.run_until_complete(task) |
async def update_rooms(self):
"""Request data."""
homes = await self.get_home_list()
for home in homes:
payload = {"homeId": home.get("homeId"), "timeZoneNum": "+01:00"}
data = await self.request("selectRoombyHome", payload)
rooms = data.get('roomInfo', [])
... |
def sync_update_rooms(self):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.update_rooms())
return loop.run_until_complete(task) |
async def set_room_temperatures_by_name(self, room_name, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps by name."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
for room_id, _room in s... |
async def set_room_temperatures(self, room_id, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
room = self.rooms.get(room_id)
if room is... |
async def update_heaters(self):
"""Request data."""
homes = await self.get_home_list()
for home in homes:
payload = {"homeId": home.get("homeId")}
data = await self.request("getIndependentDevices", payload)
if data is None:
continue
... |
def sync_update_heaters(self):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.update_heaters())
loop.run_until_complete(task) |
async def throttle_update_heaters(self):
"""Throttle update device."""
if (self._throttle_time is not None
and dt.datetime.now() - self._throttle_time < MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_time = dt.datetime.now()
await self.update_heaters() |
async def throttle_update_all_heaters(self):
"""Throttle update all devices and rooms."""
if (self._throttle_all_time is not None
and dt.datetime.now() - self._throttle_all_time
< MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_all_time = dt.datetime.... |
async def heater_control(self, device_id, fan_status=None,
power_status=None):
"""Set heater temps."""
heater = self.heaters.get(device_id)
if heater is None:
_LOGGER.error("No such device")
return
if fan_status is None:
fa... |
def sync_heater_control(self, device_id, fan_status=None,
power_status=None):
"""Set heater temps."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.heater_control(device_id,
fan_status,
... |
async def set_heater_temp(self, device_id, set_temp):
"""Set heater temp."""
payload = {"homeType": 0,
"timeZoneNum": "+02:00",
"deviceId": device_id,
"value": int(set_temp),
"key": "holidayTemp"}
await self.request("cha... |
def sync_set_heater_temp(self, device_id, set_temp):
"""Set heater temps."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.set_heater_temp(device_id, set_temp))
loop.run_until_complete(task) |
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
"""Transform csv as below.
"title1","/path1","a=1&b=2","header1=1&header2=2"
"title2","/path2","c=1"
"title3","/path3",,"header1=1&header2=2"
"title4","/path4"
Exception:
ValueEr... |
async def handle_request(self, request: Request) -> Response:
"""
coroutine: This method is called by Transport
implementation to handle the actual request.
It returns a webtype.Response object.
"""
# Get handler
try:
try:
self._set_ctx... |
def echo(params, source, delay, strength):
'''
Create an echo
:param params:
:param source:
:param delay:
:param strength:
:return:
'''
source = create_buffer(params, source)
delay = create_buffer(params, delay)
strength = create_buffer(params, strength)
output = source[:... |
def _clone(self):
"""
Return a copy of the current QuerySet.
"""
clone = self.__class__(self._entity_cls, criteria=self._criteria,
offset=self._offset, limit=self._limit,
order_by=self._order_by)
return clone |
def _add_q(self, q_object):
"""Add a Q-object to the current filter."""
self._criteria = self._criteria._combine(q_object, q_object.connector) |
def limit(self, limit):
"""Limit number of records"""
clone = self._clone()
if isinstance(limit, int):
clone._limit = limit
return clone |
def offset(self, offset):
"""Fetch results after `offset` value"""
clone = self._clone()
if isinstance(offset, int):
clone._offset = offset
return clone |
def order_by(self, order_by: Union[set, str]):
"""Update order_by setting for filter set"""
clone = self._clone()
if isinstance(order_by, str):
order_by = {order_by}
clone._order_by = clone._order_by.union(order_by)
return clone |
def all(self):
"""Primary method to fetch data based on filters
Also trigged when the QuerySet is evaluated by calling one of the following methods:
* len()
* bool()
* list()
* Iteration
* Slicing
"""
logger.debug(f'Query `{sel... |
def update(self, *data, **kwargs):
"""Updates all objects with details given if they match a set of conditions supplied.
This method updates each object individually, to fire callback methods and ensure
validations are run.
Returns the number of objects matched (which may not be equal ... |
def raw(self, query: Any, data: Any = None):
"""Runs raw query directly on the database and returns Entity objects
Note that this method will raise an exception if the returned objects
are not of the Entity type.
`query` is not checked for correctness or validity, and any errors th... |
def delete(self):
"""Deletes matching objects from the Repository
Does not throw error if no objects are matched.
Returns the number of objects matched (which may not be equal to the number of objects
deleted if objects rows already have the new value).
"""
# Fetch ... |
def update_all(self, *args, **kwargs):
"""Updates all objects with details given if they match a set of conditions supplied.
This method forwards filters and updates directly to the repository. It does not
instantiate entities and it does not trigger Entity callbacks or validations.
Up... |
def delete_all(self, *args, **kwargs):
"""Deletes objects that match a set of conditions supplied.
This method forwards filters directly to the repository. It does not instantiate entities and
it does not trigger Entity callbacks or validations.
Returns the number of objects matched an... |
def total(self):
"""Return the total number of records"""
if self._result_cache:
return self._result_cache.total
return self.all().total |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.