text
stringlengths
18
773k
def dates_in_range(start_date, end_date): """Returns all dates between two dates. Inclusive of the start date but not the end date. Args: start_date (datetime.date) end_date (datetime.date) Returns: (list) of datetime.date objects """ return [ start_date + time...
def load_hooks(): """ Load the exposed hooks. Returns a dict of hooks where the keys are the name of the hook and the values are the actual hook functions. """ hooks = {} for entrypoint in pkg_resources.iter_entry_points(ENTRYPOINT): name = str(entrypoint).split('=')[0].strip() ...
def gettext(ui_file_path): """ Let you use gettext instead of the Qt tools for l18n """ with open(ui_file_path, 'r') as fin: content = fin.read() # replace ``_translate("context", `` by ``_(`` content = re.sub(r'_translate\(".*",\s', '_(', content) content = content.replace( ...
def stream_json_file(local_file): """Stream a JSON file (in JSON-per-line format) Args: local_file (file-like object) an open file-handle that contains a JSON string on each line Yields: (dict) JSON objects """ for i, line in enumerate(local_file): try: ...
def download(self, force=False): """ Download file containing this package. :param force: Force download even if it seems file already exists :return: Full path with filename of downloaded package file. """ exists, dest_path = self._downloader.cache.exists_packed(package=...
def find_dependencies(self, depslock_file_path, property_validate=True, deps_content=None): """ Find all dependencies by package :param depslock_file_path: :param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file, :param deps_...
def find_usedby(self, depslock_file_path, property_validate=True): """ Find all dependencies by package :param depslock_file_path: :param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file, we can skip validate part :re...
def get_params(self, param_list=None, get_path=False, merged=False, raw=False): """ Get Package params :param param_list: name or list of parameters :param get_path: :param merged: if version splited, True return version in string :param raw: :return: """ ...
def get_none_packages(self): """ Get packages with None (not founded), recursively """ not_found = set() for package_name, package in self.packages.items(): if package is None: not_found.add(package_name) else: if package.pa...
def get_usedby_aql(self, params): """ Возвращает запрос AQL (без репозитория), из файла конфигурации :param params: :return: """ if self._usedby is None: return None _result = {} params = self.merge_valued(params) for k, v in self._use...
def get_params_with_extra(self, rule_name, params): """ Get params with extra, like 'any' :param rule_name: 'path' :param params: default params :return: list of combination params """ # HACK for prefer-local result = [] extra_params = self._rules_...
def split_fixed_pattern(path): """ Split path into fixed and masked parts :param path: e.g https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz :return: _path_fixed: https://repo.example.com/artifactory/li...
def split_fixed_pattern_with_file_name(path): """ Split path into fixed, masked parts and filename :param path: e.g https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz :return: _path_fixed: https://repo.example.c...
def basic_client(): """Returns an Elasticsearch basic client that is responsive to the environment variable ELASTICSEARCH_ENDPOINT""" es_connected = False while not es_connected: try: ES = Elasticsearch( hosts=[HOSTNAME] ) es_connected = True ...
def create_index(index_name, index_config, client): """Creates an index with a given configuration Args: index_name (str): Name of the index you want to create index_config (dict) configuration for the index client (Elasticsearch.IndicesClient) the Elasticsearch client """ clien...
def get_index_from_alias(alias_name, index_client=None): """Retrieve the base index name from an alias Args: alias_name (str) Name of the alias index_client (Elasticsearch.IndicesClient) an Elasticsearch index client. Optional, will create one if not given Returns: (str) Name o...
def atomic_swap(alias_name, new_index_name, index_client): """Points an alias to a new index, then delete the old index if needed Uses client.update_aliases to perform this with zero downtime Args: alias_name (str) Name of the alias new_index_name (str) The new index that the alias should ...
def zero_downtime_index(index_name, index_config): """Context manager to create a new index based on a given alias, allow the caller to index it, and then point the alias to the new index Args: index_name (str) Name of an alias that should point to the new index index_config (dict) Configur...
def replace(self): """Replace index with a new one zero_downtime_index for safety and rollback """ with zero_downtime_index(self.alias_name, self.index_config()) as target_index: self.index_all(target_index)
def append(self): """Index documents onto an existing index""" target_index = get_index_from_alias(self.alias_name) if not target_index: self.replace() else: self.index_all(target_index)
def index_all(self, index_name): """Index all available documents, using streaming_bulk for speed Args: index_name (string): The index """ oks = 0 notoks = 0 for ok, item in streaming_bulk( self.es_client, self._iter_documents(index_name) ...
def build_args(cmd, src, dst): """ Build arguments list for passing to subprocess.call_check :param cmd str: Command string to interpolate src and dst filepaths into. Typically the output of `config.Config.uic_command` or `config.Config.rcc_command`. :param src str: Source filep...
def register_output_format(name): """ Load output format function to dictionary (decorator with this function name) """ def check_decorator(fn): _output_format_map[name] = fn def wrapper(*args, **kwargs): return fn(*args, **kwargs) return wrapper return check_...
def write_output(self, params, packages): """ Функция вызывает определенную функцию для фиксированного out-format :param params: :param packages: :return: """ if params['out_format'] not in _output_format_map: raise CrosspmException( CR...
def output_format_lock(self, packages, **kwargs): """ Text to lock file """ self._output_config['type'] = PLAIN text = '' tmp_packages = OrderedDict() columns = self._config.get_columns() widths = {} for _pkg in packages.values(): _pkg_name = _pkg.pack...
def output_format_module(self, packages, esc_path=False): """ Create out with child first position """ def create_ordered_list(packages_): """ Recursive for package.packages """ list_ = [] for _pkg_name in packages_: ...
def smart(**kwargs): """ Simple decorator to get custom fields on admin class, using this you will use less line codes :param short_description: description of custom field :type str: :param admin_order_field: field to order on click :type str: :param allow_tags: allow html tags :type...
def create_buffer(params, value): ''' If the value is a float, create a numpy array of the required length, filled with value If the value is a numpy array, check its length Otherwise throw a type error ''' try: fv = float(value) return np.full(params.length, fv, np.float) ex...
def set_time(self, time): ''' Update the length of the buffer in seconds :param time: number of seconds :return: self ''' self.length = int(time*self.sample_rate) return self
def make_request(self, method, service, path, body=None, query_params: QueryParams=None, headers: dict=None, correlation_id: str=None, content_type: str='application/json', context: Req...
def get(self, service, path, **kwargs): """ Make a get request (this returns a coroutine)""" return self.make_request(Methods.GET, service, path, **kwargs)
def put(self, service, path, body, **kwargs): """ Make a put request (this returns a coroutine)""" return self.make_request(Methods.POST, service, path, body=body, **kwargs)
def patch(self, service, path, body, **kwargs): """ Make a patche requests (this returns a coroutine)""" return self.make_request(Methods.PATCH, service, path, body=body, **kwargs)
def delete(self, service, path, **kwargs): """ Make a delete requests (this returns a coroutine)""" return self.make_request(Methods.DELETE, service, path, **kwargs)
def process_request(self, request_object): """Fetch Resource and return Entity""" identifier = request_object.identifier # Look for the object by its ID and return it resource = request_object.entity_cls.get(identifier) return ResponseSuccess(Status.SUCCESS, resource)
def from_dict(cls, entity_cls, adict): """Initialize a ListRequestObject object from a dictionary.""" invalid_req = InvalidRequestObject() # Extract the pagination parameters from the input page = int(adict.pop('page', 1)) per_page = int(adict.pop( 'per_page', getatt...
def process_request(self, request_object): """Return a list of resources""" resources = (request_object.entity_cls.query .filter(**request_object.filters) .offset((request_object.page - 1) * request_object.per_page) .limit(request_object.per...
def process_request(self, request_object): """Process Create Resource Request""" resource = request_object.entity_cls.create(**request_object.data) return ResponseSuccessCreated(resource)
def process_request(self, request_object): """Process Update Resource Request""" # Retrieve the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) # Update the object and return the updated data resource = entity.update(request_object.dat...
def process_request(self, request_object): """Process the Delete Resource Request""" # Delete the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) entity.delete() # FIXME Check for return value of `delete()` # We have successfu...
def _cast_to_type(self, value): """ Convert the value to its string representation""" if isinstance(value, str) or value is None: return value return str(value)
def _cast_to_type(self, value): """ Convert the value to an int and raise error on failures""" try: return int(value) except (ValueError, TypeError): self.fail('invalid', value=value)
def _cast_to_type(self, value): """ Convert the value to a float and raise error on failures""" try: return float(value) except (ValueError, TypeError): self.fail('invalid', value=value)
def _cast_to_type(self, value): """ Convert the value to a boolean and raise error on failures""" if value in (True, False): return bool(value) if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False self.fail(...
def _cast_to_type(self, value): """ Raise error if the value is not a list """ if not isinstance(value, list): self.fail('invalid', value=value) return value
def _cast_to_type(self, value): """ Raise error if the value is not a dict """ if not isinstance(value, dict): self.fail('invalid', value=value) return value
def _cast_to_type(self, value): """ Convert the value to a date and raise error on failures""" if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value try: value = date_parser(value) re...
def _cast_to_type(self, value): """ Convert the value to a datetime and raise error on failures""" if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) return v...
async def make_request(self, service: str, method: str, path: str, body: bytes=None, query: str=None, headers: dict=None, correlation_id: str=None, content_type: str=None, timeout:int = 30, ...
def execute(self, request_object): """Generic executor method of all UseCases""" # If the request object is not valid then return a failure response if not request_object.is_valid: return ResponseFailure.build_from_invalid_request( request_object) # Try to p...
def FunctionTimer(on_done=None): ''' To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some function that uses the time output ... print(details) .....
async def exchange_declare(self): """ Override this method to change how a exchange is declared """ await self.channel.exchange_declare( self.exchange, self.exchange_type, durable=self.durable, auto_delete=self.auto_delete, no_wait=self.no_wait...
async def queue_declare(self): """ Override this method to change how a queue is declared """ await self.channel.queue_declare( self.queue, durable=self.durable, exclusive=self.exclusive, no_wait=self.no_wait )
def from_entity(cls, entity: Entity) -> 'DictModel': """Convert the entity to a dictionary record """ dict_obj = {} for field_name in entity.meta_.attributes: dict_obj[field_name] = getattr(entity, field_name) return dict_obj
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 database
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)
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._extract_lookup(key) lookup = lookup_class(...
def raw(self, query: Any, data: Any = None): """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. """ assert isinstance(query, str) conn = self.get_connec...
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 (field_name in model_obj and model_obj[field_name]...
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_field.field_name] with self.conn['l...
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: # Trim database records over successive...
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.schema_name]).values()) else: items = list...
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['data'][self.schema_name]: ...
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] item.update(*args) item.upda...
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.schema_name]) # Delete all the matchi...
def raw(self, query: Any, data: Any = None): """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 ...
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 "\"{source}\"".format(source...
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('"', "\'") return "\"{target}\"".format(target...
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}]" logger.info_lv3(f"{log_prefix} {'-'*80}") logger.info_lv3(f"{log_prefix}...
def parse_url_to_topic(method, route): """ 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, on...
async def handle_request(self, channel: Channel, body, envelope, properties, futurize=True): """ 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 im...
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)
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 """
def construct(cls, name: str, declared_fields: typing.List[tuple]): """ 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( ...
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. """ formatted_fields = [] for declared_field in declared_fields: field_name = field_type = field...
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.setnchannels(1) writer.setsampwidth(2) writer.setframerate(params.samp...
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] != v: heappop(heap) v, k = heap[0] return k
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) while k not in self or self[k] != v: v, k = heappop(heap) del self[k] retu...
def perform(cls, entity_cls, usecase_cls, request_object_cls, payload: dict, raise_error=False): """ 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_...
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.original_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): ...
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 return msg_count
def square_wave(params, frequency=400, amplitude=1, offset=0, ratio=0.5): ''' 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 offs...
def noise(params, amplitude=1, offset=0): ''' 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 table_wave(params, frequency=400, amplitude=1, offset=0, table=None): ''' 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) :...
def sine_wave(params, frequency=400, amplitude=1, offset=0): ''' 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 amp...
def midi2f(params, midi=69): ''' 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 freq...
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)
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 None and not issubclas...
def merge_dicts(dicts): """ 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'. """ merged = {} for d in reversed(dicts): merged.update(d) return merged
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_name] = lookup cls._cle...
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: lookup_name = lookup.lookup_name del cls.class_lookups[lookup_name]
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] kwargs = {child[0]: child[...
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): return import_from_string(val) elif isinstance(val, (list, tuple)): return [import_f...
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) except (ImportError, AttributeError) as e: msg = f"Cou...
def set_context(self, data): """Load Context with data""" for key in data: setattr(self.local_context, key, data[key])
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.reference.field_name, None) self.reference.delete_cache...
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: if isinstance(self._to_cls, str): self....
def linked_attribute(self): """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 l...
def _linked_attribute(self, owner): """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. """ return self.via or (utils.inflection.underscore(owner...