code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''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_open, drain=drain) return None f = self._set_waiter(waiter_id) try: await self._write_frame...
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)
3.316528
2.731037
1.214384
''' 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 element in the tuple :return: '''...
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 element in the tuple :return:
5.390832
1.98794
2.711768
for base in reversed(bases): if hasattr(base, 'meta_') and \ hasattr(base.meta_, 'declared_fields'): base_class_fields = { field_name: field_obj for (field_name, field_obj) in base.meta_.declared_fields.items() ...
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.
3.057287
2.86584
1.066803
for attr_name, attr_obj in attrs.items(): if isinstance(attr_obj, (Field, Reference)): setattr(new_class, attr_name, attr_obj) new_class.meta_.declared_fields[attr_name] = attr_obj
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_reference_fields()`.
2.62409
2.586909
1.014373
if new_class.meta_.declared_fields: for _, field in new_class.meta_.declared_fields.items(): if isinstance(field, Reference): shadow_field_name, shadow_field = field.get_shadow_field() setattr(new_class, shadow_field_name, shadow_field...
def _set_up_reference_fields(new_class)
Walk through relation fields and setup shadow attributes
2.687004
2.281098
1.177943
# 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 = next( field for _, field in new_class.meta_.declared_fields.items...
def _set_id_field(new_class)
Lookup the id field for this entity and assign
4.9725
4.77886
1.04052
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_class.meta_.declared_fields['id'] = id_field new_class.meta_.id_field = id_field
def _create_id_field(new_class)
Create and return a default ID field that is Auto generated
4.909575
4.393056
1.117576
for field_name, field_obj in new_class.meta_.declared_fields.items(): new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj
def _load_attributes(new_class)
Load list of attributes from declared fields
4.028938
3.125654
1.28899
return [(field_name, field_obj) for field_name, field_obj in self.declared_fields.items() if field_obj.unique]
def unique_fields(self)
Return the unique fields for this entity
3.586236
3.132904
1.1447
# Load each of the fields given in the data dictionary self.errors = {} for data in data_dict: if not isinstance(data, dict): raise AssertionError( f'Positional argument "{data}" passed must be a dict.' f'This argumen...
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
4.538026
4.603139
0.985855
return {field_name: getattr(self, field_name, None) for field_name in self.meta_.declared_fields}
def to_dict(self)
Return entity data as a dictionary
5.067161
4.136161
1.225088
clone_copy = copy.deepcopy(self) clone_copy.state_ = EntityState() return clone_copy
def clone(self)
Deepclone the entity, but reset state
9.599423
5.756302
1.667637
logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}') # Get the ID field for the entity filters = { cls.meta_.id_field.field_name: identifier } # Find this item in the repository or raise Error results = cls.query.filter(**filt...
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.
4.852865
5.055642
0.959891
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 identifier = getattr(self, self.meta_.id_field.field_name) log...
def reload(self) -> None
Reload Entity from the repository
6.76575
6.29696
1.074447
logger.debug(f'Lookup `{cls.__name__}` object with values ' f'{kwargs}') # Find this item in the repository or raise Error results = cls.query.filter(**kwargs).limit(1).all() if not results: raise ObjectNotFoundError( f'`{cls.__...
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
5.293184
5.828649
0.908132
results = cls.query.filter(**filters).exclude(**excludes_) return bool(results)
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. :param excludes_: entities without this combination...
6.372977
8.055472
0.791136
logger.debug( f'Creating new `{cls.__name__}` object using data {kwargs}') model_cls = repo_factory.get_model(cls) repository = repo_factory.get_repository(cls) try: # Build the entity from the input arguments # Raises validation errors, if ...
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
4.334547
4.232197
1.024184
logger.debug( f'Saving `{self.__class__.__name__}` object') # Fetch Model class and connected repository from Repository Factory model_cls = repo_factory.get_model(self.__class__) repository = repo_factory.get_repository(self.__class__) try: # D...
def save(self)
Save a new Entity into repository. Performs unique validations before creating the entity.
4.428175
4.109073
1.077658
logger.debug(f'Updating existing `{self.__class__.__name__}` object with id {self.id}') # Fetch Model class and connected repository from Repository Factory model_cls = repo_factory.get_model(self.__class__) repository = repo_factory.get_repository(self.__class__) try:...
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) :param data: Dictionary of values to be updated for the en...
5.693127
5.910805
0.963173
# 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) # Ignore empty lookup values if lookup_value in Field.empty_values: ...
def _validate_unique(self, create=True)
Validate the unique constraints for the entity
4.214376
3.964496
1.06303
# Fetch Model class and connected repository from Repository Factory model_cls = repo_factory.get_model(self.__class__) repository = repo_factory.get_repository(self.__class__) try: if not self.state_.is_destroyed: # Update entity's data attributes ...
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.
8.101379
8.005634
1.01196
''' 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) >>> s.chunk_size 5 ...
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) >>> s.chunk_size 5 >>> s.n_item...
2.819869
1.585415
1.778632
''' 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 = ['a','b','c','d'] >>...
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 = ['a','b','c','d'] >>> for item in data_s...
3.442205
1.371205
2.510351
''' 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: ... stream_counter_obj.add(item) >>> str...
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: ... stream_counter_obj.add(item) >>> stream_counter_obj.get(...
2.267616
1.286741
1.762294
return '\n'.join( [self.from_email, str(self.to), self.subject, self.body])
def message(self)
Convert the message to a mime compliant email string
6.541783
4.460798
1.466505
return [email for email in (self.to + self.cc + self.bcc) if email]
def recipients(self)
Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries).
5.240727
4.046813
1.295026
from protean.services.email import get_connection if not self.connection: self.connection = get_connection(fail_silently=fail_silently) return self.connection
def get_connection(self, fail_silently=False)
Retrieve connection to send email
4.417859
3.788439
1.166142
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 send(self, fail_silently=False)
Send the email message.
6.005789
5.43772
1.104468
if isinstance(method, str): method = Methods(method.upper()) route = self._prefix + route route = route.strip('/') if route not in self._static_routes: self._static_routes[route] = {} self._static_routes[route][method] = handler
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. Ideally, this is used for non-public facing endpoints such as "/healthcheck", or "/stats" or something of that nature. All static routes SKIP mid...
2.460322
2.691989
0.913942
original_prefix = self._prefix self._prefix += prefix yield self self._prefix = original_prefix
def prefix(self, prefix)
Adds a prefix to routes contained within.
5.39168
4.650072
1.159483
if isinstance(self.messages, dict): return self.messages if not self.field_names: return {no_field_name: self.messages} return dict((name, self.messages) for name in self.field_names)
def normalized_messages(self, no_field_name='_entity')
Return all the error messages as a dictionary
3.012871
2.850517
1.056956
''' 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 = int(length / 2 + 1) x = binascii....
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
4.247778
1.899861
2.235836
''' 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_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
4.003921
1.814356
2.2068
''' 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 get_datetime(epoch)
get datetime from an epoch timestamp >>> get_datetime(1432188772) datetime.datetime(2015, 5, 21, 6, 12, 52)
3.510442
1.930657
1.818263
''' 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_hour=0, tm_min=0, ...
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_hour=0, tm_min=0, tm_sec=0, tm...
3.224228
2.06177
1.563816
''' 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 xcode(text, encoding='utf8', mode='ignore')
Converts unicode encoding to str >>> xcode(b'hello') b'hello' >>> xcode('hello') b'hello'
3.935037
2.23088
1.763895
''' 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', 6379) ('localhost', 8888) '''...
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', 6379) ('localhost', 8888)
2.599034
1.447173
1.795939
keys = [] for k, v in d.items(): fqk = '{}{}'.format(prefix, k) keys.append(fqk) if isinstance(v, dict): keys.extend(serialize_dict_keys(v, prefix="{}.".format(fqk))) return keys
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']
2.574891
2.73615
0.941064
''' Flattens a nested dictionary >>> from pprint import pprint >>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } } >>> fd = flatten_dict(d) >>> pprint(fd) {'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1} ''' items = {} for k in d: if ignore_under_prefixed...
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) >>> pprint(fd) {'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1}
2.526646
1.752833
1.441464
try: return reduce(getattr, attr.split('.'), obj) except AttributeError: if default is not AttributeError: return default raise
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): ... self.galaxy = galaxy ... >>> class Galaxy(objec...
2.226956
5.049566
0.441019
''' 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 set_file_limits(n)
Set the limit on number of file descriptors that this process can open.
4.410399
3.25257
1.355974
''' 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() ... te...
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() ... test('calling ...
3.635241
1.339032
2.714827
''' 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 ''' module_name, obj...
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
4.670107
1.752011
2.665569
try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) if isinst...
def fail(self, key, **kwargs)
A helper method that simply raises a `ValidationError`.
2.884398
2.956735
0.975535
if value in self.empty_values: return errors = [] for validator in self.validators: try: validator(value) except exceptions.ValidationError as err: if isinstance(err.messages, dict): errors.append(e...
def _run_validators(self, value)
Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed.
2.295061
2.212868
1.037143
if value in self.empty_values: # If a default has been set for the field return it if self.default is not None: default = self.default value = default() if callable(default) else default return value # If no default i...
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
3.810378
3.614449
1.054207
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 support op = 'exact' if len(parts) == 1 else parts[1] # Construct and...
def _extract_lookup(self, key)
Extract lookup method based on key name format
12.679831
12.32506
1.028784
try: return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding) except TypeError as e: raise ValueError(e)
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]
Transform from json to Request Exception: ValueError: If path does not exist.
8.55173
7.368531
1.160575
if expiry == DEFAULT_EXPIRY: expiry = self.default_expiry elif expiry == 0: # avoid time.time() related precision issues expiry = -1 return None if expiry is None else time.time() + expiry
def get_backend_expiry(self, expiry=DEFAULT_EXPIRY)
Return the expiry value usable by this backend based upon the provided timeout.
5.138274
4.91084
1.046313
d = {} for k in keys: val = self.get(k) if val is not None: d[k] = val return d
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 response dict.
2.694986
2.655385
1.014913
value = self.get(key) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta self.set(key, new_value) return new_value
def incr(self, key, delta=1)
Add delta to value in the cache. If the key does not exist, raise a ValueError exception.
2.266932
1.969591
1.150966
for key, value in data.items(): self.set(key, value, expiry=expiry) return []
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; otherwise use the default cache timeout. On backends tha...
3.929321
3.385312
1.160697
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.addLevelName(LogLevel.INFO_LV3.value, 'INFO_LV3') # type: ignore # Prevent for enum problem ...
def init_logger(v_num: int)
Call when initialize Jumeaux !! :return:
2.541404
2.570191
0.9888
configured_providers = active_config.DATABASES provider_objects = {} if not isinstance(configured_providers, dict) or configured_providers == {}: raise ConfigurationError( "'DATABASES' config must be a dict and at least one " "provider must b...
def _initialize_providers(self)
Read config file and initialize providers
2.716706
2.67583
1.015276
try: if self._providers is None: self._providers = self._initialize_providers() return self._providers[provider_name] except KeyError: raise AssertionError(f'No Provider registered with name {provider_name}')
def get_provider(self, provider_name='default')
Fetch provider with the name specified in Configuration file
3.32638
3.277958
1.014772
try: return self._providers[provider_name].get_connection() except KeyError: raise AssertionError(f'No Provider registered with name {provider_name}')
def get_connection(self, provider_name='default')
Fetch connection from Provider
4.163862
3.566284
1.167563
for setting in dir(ext_config): if setting.isupper() and not hasattr(self, setting): setattr(self, setting, getattr(ext_config, setting))
def update_defaults(self, ext_config)
Update the default settings for an extension from an object
2.623145
2.351407
1.115564
# 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: # Entity has not been registered (yet) # FIXME print a helpful debug message rai...
def fetch_entity_cls_from_registry(entity)
Util Method to fetch an Entity class from an entity's name
10.425003
9.753328
1.068866
self._validate_entity_cls(entity_cls) # Register the entity if not registered already entity_name = fully_qualified_name(entity_cls) provider_name = provider_name or entity_cls.meta_.provider or 'default' try: entity = self._get_entity_by_class(entity_cls) ...
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
3.788211
3.814405
0.993133
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 the case of # an Entity name present in multiple places (packages or plugins). Throw an...
def _find_entity_in_records_by_class_name(self, entity_name)
Fetch by Entity Name in values
4.679626
4.560884
1.026035
entity_qualname = fully_qualified_name(entity_cls) if entity_qualname in self._registry: return self._registry[entity_qualname] else: return self._find_entity_in_records_by_class_name(entity_cls.__name__)
def _get_entity_by_class(self, entity_cls)
Fetch Entity record with Entity class details
3.765598
3.614011
1.041944
if entity_name in self._registry: return self._registry[entity_name] else: return self._find_entity_in_records_by_class_name(entity_name)
def _get_entity_by_name(self, entity_name)
Fetch Entity record with an Entity name
4.238193
3.888782
1.089851
# 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__} must be subclass of `Entity`') if entity_cls.meta_.abstract is True: ...
def _validate_entity_cls(self, entity_cls)
Validate that Entity is a valid class
3.404919
3.180391
1.070598
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 give a fully baked model the first time # that has been initialized...
def get_model(self, entity_cls)
Retrieve Model class connected to Entity
3.894002
3.71322
1.048686
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)
def get_repository(self, entity_cls)
Retrieve a Repository for the Model with a live connection
4.14855
3.793899
1.093479
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.fan_status = heater_data.get('fanStatus') heater.is_holiday = heater_data.get('isHolida...
async def set_heater_values(heater_data, heater)
Set heater values from heater data
3.462774
3.447504
1.004429
# 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", "X-Zc-Msg-Name": "millService", "X...
async def connect(self, retry=2)
Connect to Mill.
2.94953
2.801799
1.052727
loop = asyncio.get_event_loop() task = loop.create_task(self.connect()) loop.run_until_complete(task)
def sync_connect(self)
Close the Mill connection.
2.550255
2.295493
1.110983
loop = asyncio.get_event_loop() task = loop.create_task(self.close_connection()) loop.run_until_complete(task)
def sync_close_connection(self)
Close the Mill connection.
2.410897
2.183629
1.104078
# 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_uppercase + string.digits) for _ in range(16)) url = API_ENDPO...
async def request(self, command, payload, retry=3)
Request data.
2.718978
2.696732
1.008249
loop = asyncio.get_event_loop() task = loop.create_task(self.request(command, payload, retry)) return loop.run_until_complete(task)
def sync_request(self, command, payload, retry=2)
Request data.
2.422893
2.339344
1.035715
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', []) for _room in rooms: _id...
async def update_rooms(self)
Request data.
2.433437
2.404096
1.012204
loop = asyncio.get_event_loop() task = loop.create_task(self.update_rooms()) return loop.run_until_complete(task)
def sync_update_rooms(self)
Request data.
2.847788
2.609641
1.091257
if sleep_temp is None and comfort_temp is None and away_temp is None: return for room_id, _room in self.rooms.items(): if _room.name == room_name: await self.set_room_temperatures(room_id, sleep_temp, comfo...
async def set_room_temperatures_by_name(self, room_name, sleep_temp=None, comfort_temp=None, away_temp=None)
Set room temps by name.
2.034973
1.953972
1.041455
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 None: _LOGGER.error("No such device") return room.sleep_temp = sleep_temp if sleep_temp else room.sleep_temp room.aw...
async def set_room_temperatures(self, room_id, sleep_temp=None, comfort_temp=None, away_temp=None)
Set room temps.
2.109535
2.068854
1.019663
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 heater_data = data.get('deviceInfo', []) ...
async def update_heaters(self)
Request data.
2.698673
2.645979
1.019915
loop = asyncio.get_event_loop() task = loop.create_task(self.update_heaters()) loop.run_until_complete(task)
def sync_update_heaters(self)
Request data.
2.394447
2.178981
1.098884
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_heaters(self)
Throttle update device.
3.040559
2.851574
1.066274
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.now() await self.find_all_heaters()
async def throttle_update_all_heaters(self)
Throttle update all devices and rooms.
3.301764
3.037074
1.087153
heater = self.heaters.get(device_id) if heater is None: _LOGGER.error("No such device") return if fan_status is None: fan_status = heater.fan_status if power_status is None: power_status = heater.power_status operation = 0 ...
async def heater_control(self, device_id, fan_status=None, power_status=None)
Set heater temps.
3.150459
3.14681
1.00116
loop = asyncio.get_event_loop() task = loop.create_task(self.heater_control(device_id, fan_status, power_status)) loop.run_until_complete(task)
def sync_heater_control(self, device_id, fan_status=None, power_status=None)
Set heater temps.
2.049922
2.07166
0.989507
payload = {"homeType": 0, "timeZoneNum": "+02:00", "deviceId": device_id, "value": int(set_temp), "key": "holidayTemp"} await self.request("changeDeviceInfo", payload)
async def set_heater_temp(self, device_id, set_temp)
Set heater temp.
9.195783
8.484187
1.083873
loop = asyncio.get_event_loop() task = loop.create_task(self.set_heater_temp(device_id, set_temp)) loop.run_until_complete(task)
def sync_set_heater_temp(self, device_id, set_temp)
Set heater temps.
1.928447
1.873771
1.02918
outputs = [] with open(payload.file, encoding=self.config.encoding) as f: rs = csv.DictReader(f, ('name', 'path', 'qs', 'headers'), restval={}, dialect=self.config.dialect) for r in rs: if len(r) > 4: raise ValueError ...
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: ValueError: If fomat is invalid.
3.857746
3.582443
1.076848
# Get handler try: try: self._set_ctx(request) handler = self.router.get_handler_for_request(request) request.app = self response = await handler(request) response.app = self except ResponseE...
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.
3.587022
3.533061
1.015273
''' 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[:] for i in range(params.length): ...
def echo(params, source, delay, strength)
Create an echo :param params: :param source: :param delay: :param strength: :return:
2.813642
2.58307
1.089263
clone = self.__class__(self._entity_cls, criteria=self._criteria, offset=self._offset, limit=self._limit, order_by=self._order_by) return clone
def _clone(self)
Return a copy of the current QuerySet.
4.125324
3.271408
1.261024
self._criteria = self._criteria._combine(q_object, q_object.connector)
def _add_q(self, q_object)
Add a Q-object to the current filter.
18.730324
13.937622
1.343868
clone = self._clone() if isinstance(limit, int): clone._limit = limit return clone
def limit(self, limit)
Limit number of records
5.96062
5.677845
1.049803
clone = self._clone() if isinstance(offset, int): clone._offset = offset return clone
def offset(self, offset)
Fetch results after `offset` value
6.097295
5.675239
1.074368
clone = self._clone() if isinstance(order_by, str): order_by = {order_by} clone._order_by = clone._order_by.union(order_by) return clone
def order_by(self, order_by: Union[set, str])
Update order_by setting for filter set
2.967677
2.544018
1.166531
logger.debug(f'Query `{self.__class__.__name__}` objects with filters {self}') # Destroy any cached results self._result_cache = None # Fetch Model class and connected repository from Repository Factory model_cls = repo_factory.get_model(self._entity_cls) repos...
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
4.608181
4.772247
0.965621
updated_item_count = 0 try: items = self.all() for item in items: item.update(*data, **kwargs) updated_item_count += 1 except Exception: # FIXME Log Exception raise return updated_item_count
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 to the number of objects updated i...
4.215932
3.980755
1.059079
logger.debug(f'Query `{self.__class__.__name__}` objects with raw query {query}') # Destroy any cached results self._result_cache = None # Fetch Model class and connected repository from Repository Factory model_cls = repo_factory.get_model(self._entity_cls) re...
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 thrown by the plugin or database are passed as...
4.987241
4.770736
1.045382
# Fetch Model class and connected repository from Repository Factory deleted_item_count = 0 try: items = self.all() for item in items: item.delete() deleted_item_count += 1 except Exception: # FIXME Log Excepti...
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).
8.766388
7.927982
1.105753
updated_item_count = 0 repository = repo_factory.get_repository(self._entity_cls) try: updated_item_count = repository.update_all(self._criteria, *args, **kwargs) except Exception: # FIXME Log Exception raise return updated_item_cou...
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. Update values can be specified either as a dict, or ...
5.0315
5.081957
0.990071
deleted_item_count = 0 repository = repo_factory.get_repository(self._entity_cls) try: deleted_item_count = repository.delete_all(self._criteria) except Exception: # FIXME Log Exception raise return deleted_item_count
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 and deleted.
5.403473
4.858203
1.112237
if self._result_cache: return self._result_cache.total return self.all().total
def total(self)
Return the total number of records
10.675164
8.505988
1.255018
if self._result_cache: return self._result_cache.items return self.all().items
def items(self)
Return result values
9.397656
8.038032
1.169149
if self._result_cache: return self._result_cache.first return self.all().first
def first(self)
Return the first result
9.508152
7.498219
1.268055