text
stringlengths
81
112k
Return the dictionary database object def get_connection(self): """Return the dictionary database object """ database = { 'data': _databases.setdefault(self.identifier, defaultdict(dict)), 'lock': _locks.setdefault(self.identifier, Lock()), 'counters': _counters ...
Return a repository object configured with a live connection def get_repository(self, entity_cls): """Return a repository object configured with a live connection""" model_cls = self.get_model(entity_cls) return DictRepository(self, entity_cls, model_cls)
Extract values from DB that match the given criteria def _evaluate_lookup(self, key, value, negated, db): """Extract values from DB that match the given criteria""" results = {} for record_key, record_value in db.items(): match = True stripped_key, lookup_class = self._...
Run raw queries on the database As an example of running ``raw`` queries on a Dict repository, we will run the query on all possible schemas, and return all results. def raw(self, query: Any, data: Any = None): """Run raw queries on the database As an example of running ``raw`` querie...
Set the values of the auto field using counter def _set_auto_fields(self, model_obj): """Set the values of the auto field using counter""" for field_name, field_obj in \ self.entity_cls.meta_.auto_fields: counter_key = f'{self.schema_name}_{field_name}' if not (f...
Write a record to the dict repository def create(self, model_obj): """Write a record to the dict repository""" # Update the value of the counters model_obj = self._set_auto_fields(model_obj) # Add the entity to the repository identifier = model_obj[self.entity_cls.meta_.id_fiel...
Recursive function to filter items from dictionary def _filter(self, criteria: Q, db): """Recursive function to filter items from dictionary""" # Filter the dictionary objects based on the filters negated = criteria.negated input_db = None if criteria.connector == criteria.AND:...
Read the repository and return results as per the filer def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()): """Read the repository and return results as per the filer""" if criteria.children: items = list(self._filter(criteria, self.conn['data'][self.schem...
Update the entity record in the dictionary def update(self, model_obj): """Update the entity record in the dictionary """ identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['lock']: # Check if object is present if identifier not in self.conn...
Update all objects satisfying the criteria def update_all(self, criteria: Q, *args, **kwargs): """Update all objects satisfying the criteria """ items = self._filter(criteria, self.conn['data'][self.schema_name]) update_count = 0 for key in items: item = items[key] ...
Delete the dictionary object by its criteria def delete_all(self, criteria: Q = None): """Delete the dictionary object by its criteria""" if criteria: # Delete the object from the dictionary and return the deletion count items = self._filter(criteria, self.conn['data'][self.sche...
Run raw query on Repository. For this stand-in repository, the query string is a json string that contains kwargs criteria with straigh-forward equality checks. Individual criteria are always ANDed and the result is always a subset of the full repository. We will ignore the `data` para...
Return source with transformations, if any def process_source(self): """Return source with transformations, if any""" if isinstance(self.source, str): # Replace single and double quotes with escaped single-quote self.source = self.source.replace("'", "\'").replace('"', "\'") ...
Return target with transformations, if any def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") ...
Response is dict like `Trial` because Status(OwlEnum) can't be pickled. def challenge(arg: ChallengeArg) -> dict: """ Response is dict like `Trial` because Status(OwlEnum) can't be pickled. """ name: str = arg.req.name.get_or(str(arg.seq)) log_prefix = f"[{arg.seq} / {arg.number_of_request}]" log...
Transforms a URL to a topic. `GET /bar/{id}` -> `get.bar.*` `POST /bar/{id}` -> `post.bar.*` `GET /foo/bar/{id}/baz` -? `get.foo.bar.*.baz` Possible gotchas `GET /foo/{id}` -> `get.foo.*` `GET /foo/{id}:action` -> `get.foo.*` However, once it hits the service the router will be able to d...
the 'futurize' param is simply because aioamqp doesnt send another job until this method returns (completes), so we ensure the future of ourselves and return immediately so we can handle many requests at a time. async def handle_request(self, channel: Channel, body, envelope, ...
Use for example of Transformer.function def wrap(anything: bytes, encoding: str) -> str: """Use for example of Transformer.function """ return json.dumps({ "wrap": load_json(anything.decode(encoding)) }, ensure_ascii=False)
Filter objects from the repository. Method must return a `ResultSet` object def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()) -> ResultSet: """ Filter objects from the repository. Method must return a `ResultSet` object """
Utility method packaged along with the factory to be able to construct Request Object classes on the fly. Example: .. code-block:: python UserShowRequestObject = Factory.create_request_object( 'CreateRequestObject', [('identifier', int, {'required':...
Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory. def _format_fields(cls, declared_fields: typing.List[tuple]): """Process declared fields and construct a list of tuples that can be fed into dataclass constructor factory. """ ...
Write a sequence of samples as a WAV file Currently a 16 bit mono file def save(params, filename, source): ''' Write a sequence of samples as a WAV file Currently a 16 bit mono file ''' writer = wave.open(filename, 'wb'); # Set the WAV file parameters, currently default values writer.se...
Return the item with the lowest priority. Raises IndexError if the object is empty. def smallest(self): """Return the item with the lowest priority. Raises IndexError if the object is empty. """ heap = self._heap v, k = heap[0] while k not in self or self[k] !...
Return the item with the lowest priority and remove it. Raises IndexError if the object is empty. def pop_smallest(self): """Return the item with the lowest priority and remove it. Raises IndexError if the object is empty. """ heap = self._heap v, k = heappop(heap) ...
This method bundles all essential artifacts and initiates usecase execution. :param entity_cls: The entity class to be used for running the usecase :param usecase_cls: The usecase class that will be executed by the tasklet. :param request_object_cls: The request object to be used...
Decoded Body def body(self) -> dict: """ Decoded Body """ if self.ignore_content_type: return self.original_body if self._body is None and self.original_body is not None: if isinstance(self.original_body, bytes): self._body = self.parser.decode(self.origi...
Encoded Body def raw_body(self) -> bytes: """ Encoded Body """ if self._raw_body is None and self.original_body is not None: if isinstance(self.original_body, dict): self._raw_body = self.parser.encode(self.original_body) if isinstance(self._raw_body, str): ...
Redirect messages to the dummy outbox def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() email.outbox.append(message) msg_count += 1 ...
Generate a square wave :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :param ratio: ratio of high to low time (array ...
Generate a noise signal :param params: buffer parameters, controls length of signal created :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :return: array of resulting signal def noise(params, amplitude=1, offset=0): ''' Generate a...
Generate a wave from a wavetable :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :param table: table of values represe...
Generate a sine wave Convenience function, table_wave generates a sine wave by default :param params: buffer parameters, controls length of signal created :param frequency: wave frequency (array or value) :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero ...
Convert a midi value to a frequency. Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to one semitone :param params: buffer parameters, controls length of signal created :param midi: midi value :return: array of resulting frequency def midi2f(params, midi=69): '...
Fetch all Lookups def get_lookups(cls): """Fetch all Lookups""" class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)] return cls.merge_dicts(class_lookups)
Fetch Lookup by name def get_lookup(self, lookup_name): """Fetch Lookup by name""" from protean.core.repository import BaseLookup lookup = self._get_lookup(lookup_name) # If unable to find Lookup, or if Lookup is the wrong class, raise Error if lookup is None or (lookup is not ...
Merge dicts in reverse to preference the order of the original list. e.g., merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'. def merge_dicts(dicts): """ Merge dicts in reverse to preference the order of the original list. e.g., merge_dicts([a, b]) will preference th...
Register a Lookup to a class def register_lookup(cls, lookup, lookup_name=None): """Register a Lookup to a class""" if lookup_name is None: lookup_name = lookup.lookup_name if 'class_lookups' not in cls.__dict__: cls.class_lookups = {} cls.class_lookups[lookup_n...
Remove given lookup from cls lookups. For use in tests only as it's not thread-safe. def _unregister_lookup(cls, lookup, lookup_name=None): """ Remove given lookup from cls lookups. For use in tests only as it's not thread-safe. """ if lookup_name is None: lo...
Deconstruct a Q Object def deconstruct(self): """Deconstruct a Q Object""" path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) args, kwargs = (), {} if len(self.children) == 1 and not isinstance(self.children[0], Q): child = self.children[0] kw...
If the given setting is a string import notation, then perform the necessary import or imports. def perform_import(val): """ If the given setting is a string import notation, then perform the necessary import or imports. """ if val is None: return None elif isinstance(val, str): ...
Attempt to import a class from a string representation. def import_from_string(val): """ Attempt to import a class from a string representation. """ try: module_path, class_name = val.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) excep...
Load Context with data def set_context(self, data): """Load Context with data""" for key in data: setattr(self.local_context, key, data[key])
Reset all associated values and clean up dictionary items def _reset_values(self, instance): """Reset all associated values and clean up dictionary items""" self.value = None self.reference.value = None instance.__dict__.pop(self.field_name, None) instance.__dict__.pop(self.refe...
Property to retrieve to_cls as an entity when possible def to_cls(self): """Property to retrieve to_cls as an entity when possible""" # Checks if ``to_cls`` is a string # If it is, checks if the entity is imported and available # If it is, register the class try: ...
Choose the Linkage attribute between `via` and designated `id_field` of the target class This method is initially called from `__set_name__()` -> `get_attribute_name()` at which point, the `to_cls` has not been initialized properly. We simply default the linked attribute to 'id' in that case. ...
Choose the Linkage attribute between `via` and own entity's `id_field` FIXME Explore converting this method into an attribute, and treating it uniformly at `association` level. def _linked_attribute(self, owner): """Choose the Linkage attribute between `via` and own entity's `id_field` ...
Fetch Multiple linked objects def _fetch_objects(self, key, value): """Fetch Multiple linked objects""" return self.to_cls.query.filter(**{key: value})
Write a frame and set a waiter for the response (unless no_wait is set) 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)''' ...
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(para...
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. def _load_base_class_fields(new_class, bases, attrs): """If this class is subclassing another Entity, add th...
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()`. def _load_fields(new_cla...
Walk through relation fields and setup shadow attributes 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, ...
Lookup the id field for this entity and assign 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...
Create and return a default ID field that is Auto generated 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...
Load list of attributes from declared fields 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
Return the unique fields for this entity 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]
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 def _update_data(self, *data_dict, **kwargs): """ A private method to process and update ...
Return entity data as a dictionary 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}
Deepclone the entity, but reset state def clone(self): """Deepclone the entity, but reset state""" clone_copy = copy.deepcopy(self) clone_copy.state_ = EntityState() return clone_copy
Get a specific Record from the Repository :param identifier: id of the record to be fetched from the repository. 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. """ l...
Reload Entity from the repository 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 config...
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 def find_by(cls, **kwargs) -> 'Entity': """Find a specific entity record that matches one or more criteria. :param kwargs: named arguments ...
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...
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 def create(cls, *args, **kwargs) -> 'Entity': """Create a new record in the repository. ...
Save a new Entity into repository. Performs unique validations before creating the entity. def save(self): """Save a new Entity into repository. Performs unique validations before creating the entity. """ logger.debug( f'Saving `{self.__class__.__name__}` object') ...
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...
Validate the unique constraints for the entity 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: l...
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. def delete(self): """Delete a Record from the Repository will perform callbacks and run validations before deletio...
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...
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...
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(...
Convert the message to a mime compliant email string 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])
Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). 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 (sel...
Retrieve connection to send 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.conn...
Send the email message. 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_message...
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...
Adds a prefix to routes contained within. def prefix(self, prefix): """ Adds a prefix to routes contained within. """ original_prefix = self._prefix self._prefix += prefix yield self self._prefix = original_prefix
Return all the error messages as a dictionary 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.message...
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 def generate_random_string(length=6): ''' Returns a rand...
Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400 def get_timestamp(dt=None): ''' Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21)...
get datetime from an epoch timestamp >>> get_datetime(1432188772) datetime.datetime(2015, 5, 21, 6, 12, 52) 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 = dat...
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...
Converts unicode encoding to str >>> xcode(b'hello') b'hello' >>> xcode('hello') b'hello' 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, mod...
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...
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'] 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'...
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} def flatten_dict(d, parent_key='', sep='.', igno...
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...
Set the limit on number of file descriptors that this process can open. 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: re...
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 ...
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 load_object(imp_path): ''' ...
A helper method that simply raises a `ValidationError`. 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 = MISSI...
Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed. def _run_validators(self, value): """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed. """ if value in self.empty_values: ret...
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 def _load(self, value: Any): """ Load the value for the field, run validators and return the value. Subclasses can over...
Extract lookup method based on key name format 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. ...
Transform from json to Request Exception: ValueError: If path does not exist. def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]: """Transform from json to Request Exception: ValueError: If path does not exist. """ try: return R...
Return the expiry value usable by this backend based upon the provided timeout. 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 = ...
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. def get_many(self, keys): "...
Add delta to value in the cache. If the key does not exist, raise a ValueError exception. 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: ...
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...
Call when initialize Jumeaux !! :return: 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: igno...