text
stringlengths
81
112k
Get axes and shape from file names. def _parse(self): """Get axes and shape from file names.""" if not self.pattern: raise TiffSequence.ParseError('invalid pattern') pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE) matches = pattern.findall(os.path.split(self.f...
Open or re-open file. def open(self): """Open or re-open file.""" if self._fh: return # file is open if isinstance(self._file, pathlib.Path): self._file = str(self._file) if isinstance(self._file, basestring): # file name self._file = os...
Read 'size' bytes from file, or until EOF is reached. def read(self, size=-1): """Read 'size' bytes from file, or until EOF is reached.""" if size < 0 and self._offset: size = self._size return self._fh.read(size)
Return numpy.memmap of data stored in file. def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): """Return numpy.memmap of data stored in file.""" if not self.is_file: raise ValueError('Cannot memory-map file without fileno') return numpy.memmap(self._fh, dtype=dtype...
Return numpy array from file in native byte order. def read_array(self, dtype, count=-1, out=None): """Return numpy array from file in native byte order.""" fh = self._fh dtype = numpy.dtype(dtype) if count < 0: size = self._size if out is None else out.nbytes c...
Return numpy record from file. def read_record(self, dtype, shape=1, byteorder=None): """Return numpy record from file.""" rec = numpy.rec try: record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder) except Exception: dtype = numpy.dtype(dtype) ...
Append size bytes to file. Position must be at end of file. def write_empty(self, size): """Append size bytes to file. Position must be at end of file.""" if size < 1: return self._fh.seek(size-1, 1) self._fh.write(b'\x00')
Write numpy array to binary file. def write_array(self, data): """Write numpy array to binary file.""" try: data.tofile(self._fh) except Exception: # BytesIO self._fh.write(data.tostring())
Set file's current position. def seek(self, offset, whence=0): """Set file's current position.""" if self._offset: if whence == 0: self._fh.seek(self._offset + offset, whence) return if whence == 2 and self._size > 0: self._fh.seek...
Close file. def close(self): """Close file.""" if self._close and self._fh: self._fh.close() self._fh = None
Re-open file if necessary. def open(self, filehandle): """Re-open file if necessary.""" with self.lock: if filehandle in self.files: self.files[filehandle] += 1 elif filehandle.closed: filehandle.open() self.files[filehandle] = 1 ...
Close openend file if no longer used. def close(self, filehandle): """Close openend file if no longer used.""" with self.lock: if filehandle in self.files: self.files[filehandle] -= 1 # trim the file cache index = 0 size = len(...
Close all opened files if not in use. def clear(self): """Close all opened files if not in use.""" with self.lock: for filehandle, refcount in list(self.files.items()): if refcount == 0: filehandle.close() del self.files[filehandle] ...
Parse a literal from the template def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += literal.count('\n') retu...
Do a preliminary check to see if a tag could be a standalone def l_sa_check(template, literal, is_standalone): """Do a preliminary check to see if a tag could be a standalone""" # If there is a newline, or the previous tag was a standalone if literal.find('\n') != -1 or is_standalone: padding = li...
Do a final checkto see if a tag could be a standalone def r_sa_check(template, tag_type, is_standalone): """Do a final checkto see if a tag could be a standalone""" # Check right side if we might be a standalone if is_standalone and tag_type not in ['variable', 'no escape']: on_newline = template....
Parse a tag from a template def parse_tag(template, l_del, r_del): """Parse a tag from a template""" global _CURRENT_LINE global _LAST_TAG_LINE tag_types = { '!': 'comment', '#': 'section', '^': 'inverted section', '/': 'end', '>': 'partial', '=': 'set d...
Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template def_ldel -- The default left delimiter ...
Render mustache templates using json files def cli_main(): """Render mustache templates using json files""" import argparse import os def is_file_or_pipe(arg): if not os.path.exists(arg) or os.path.isdir(arg): parser.error('The file {0} does not exist!'.format(arg)) else: ...
HTML escape all of these " & < > def _html_escape(string): """HTML escape all of these " & < >""" html_codes = { '"': '&quot;', '<': '&lt;', '>': '&gt;', } # & must be handled first string = string.replace('&', '&amp;') for char in html_codes: string = string.r...
Get a key from the current scope def _get_key(key, scopes): """Get a key from the current scope""" # If the key is a dot if key == '.': # Then just return the current scope return scopes[0] # Loop through the scopes for scope in scopes: try: # For every dot sep...
Load a partial def _get_partial(name, partials_dict, partials_path, partials_ext): """Load a partial""" try: # Maybe the partial is in the dictionary return partials_dict[name] except KeyError: # Nope... try: # Maybe it's in the file system path_ext =...
Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷ ├─╼ main.py ├─╼ main.ms └─┮ partials └── part.ms then main.py would make the following call: render(open('main.ms', 'r'), {...}, 'partials', 'ms') ...
Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add def bulk_add( self, item_id, ref_id=None, tags=None, time=None, title=None, url=None, wait=True ): ''' Add a new item to the user's list http://getpocket.com/developer/docs/v3/...
This method executes the bulk query, flushes stored queries and returns the response def commit(self): ''' This method executes the bulk query, flushes stored queries and returns the response ''' url = self.api_endpoints['send'] payload = { 'actions'...
Returns the request token that can be used to fetch the access token def get_request_token( cls, consumer_key, redirect_uri='http://example.com/', state=None ): ''' Returns the request token that can be used to fetch the access token ''' headers = { 'X-Accept': ...
Fetches access token from using the request token and consumer key def get_credentials(cls, consumer_key, code): ''' Fetches access token from using the request token and consumer key ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket...
This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/authentication def auth( cls, consumer_key, redirect_uri='http://example.com/', state=None, ): ''' This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/...
Remove an object from the relation def remove(self,obj): """ Remove an object from the relation """ relationship_table = self.params['relationship_table'] with self.obj.backend.transaction(implicit = True): condition = and_(relationship_table.c[self.params['related_p...
Start a new transaction. def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True...
Roll back a transaction. def rollback(self, transaction = None): """Roll back a transaction.""" if not self.in_transaction: raise NotInTransaction for collection, store in self.stores.items(): store.rollback() indexes = self.indexes[collection] in...
Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database indexes to be written to disk. def commit(self,t...
Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an index :param params: The parameters of the index :param ephemeral: Whether to create a persistent or an ephemera...
Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection def get_pk_index(self, collection): """Return the primary key index for a given collection. :param coll...
We return the result of the save method (updates are not yet implemented here). def update(self, obj, set_fields = None, unset_fields = None, update_obj = True): """ We return the result of the save method (updates are not yet implemented here). """ if set_fields: if isinsta...
Transform the query dictionary to replace e.g. documents with __ref__ fields. def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {...
Explicitly register a new document class for use in the backend. :param cls: A reference to the class to be defined :param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used to specify the collection in which to store the documen...
Autoregister a class that is encountered for the first time. :param cls: The class that should be registered. def autoregister(self, cls): """ Autoregister a class that is encountered for the first time. :param cls: The class that should be registered. """ params = se...
Serializes a given object, i.e. converts it to a representation that can be stored in the database. This usually involves replacing all `Document` instances by database references to them. :param obj: The object to serialize. :param convert_keys_to_str: If `True`, converts all dictionary keys t...
Deserializes a given object, i.e. converts references to other (known) `Document` objects by lazy instances of the corresponding class. This allows the automatic fetching of related documents from the database as required. :param obj: The object to be deserialized. :returns: The deserialized o...
Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to the class for which to create an instance. :param attributes: The attributes of the instance to be created :param lazy: Whether...
This returns a context guard which will automatically open and close a transaction def transaction(self,implicit = False): """ This returns a context guard which will automatically open and close a transaction """ class TransactionManager(object): def __init__(self,backend...
Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. def get_collection_for_cls(self, cls): """ Returns the collection name for a given document class. ...
Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. def get_collection_for_cls_name(self, cls_name): """ Returns the collection name for a given document clas...
Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name. def get_cls_for_collection(self, collection): """ Return the class for a given collection name. ...
Clear index. def clear(self): """Clear index.""" self._index = defaultdict(list) self._reverse_index = defaultdict(list) self._undefined_keys = {}
Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object def get_value(self, attributes,key = None): """Get value to be indexed from document attributes. :param attribute...
Save index to store. :raise AttributeError: If no datastore is defined def save_to_store(self): """Save index to store. :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') saved_data = sel...
Get all keys indexed. :return: All keys :rtype: list(str) def get_all_keys(self): """Get all keys indexed. :return: All keys :rtype: list(str) """ all_keys = [] for keys in self._index.values(): all_keys.extend(keys) return all_keys
Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined def load_from_store(self): """Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise ...
Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted keys :rtype: list(str) :raise ValueError: If inval...
Save index to data structure. :param in_place: Do not copy index value to a new list object :type in_place: bool :return: Index data structure :rtype: list def save_to_data(self, in_place=False): """Save index to data structure. :param in_place: Do not copy index value...
Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool def load_from_data(self, data, with_undefined=False): """Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool """ ...
Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str def get_hash_for(self, value): """Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hash...
Get keys for a given value. :param value: The value to look for :type value: object :return: The keys for the given value :rtype: list(str) def get_keys_for(self, value): """Get keys for a given value. :param value: The value to look for :type value: object ...
Add hashed value to the index. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object def add_hashed_value(self, hash_value, store_key): """Add hashed value to the index....
Add key to the index. :param attributes: Attributes to be added to the index :type attributes: dict(str) :param store_key: The key for the document in the store :type store_key: str def add_key(self, attributes, store_key): """Add key to the index. :param attributes: A...
Remove key from the index. :param store_key: The key for the document in the store :type store_key: str def remove_key(self, store_key): """Remove key from the index. :param store_key: The key for the document in the store :type store_key: str """ if store_key...
Initialize cache. def _init_cache(self): """Initialize cache.""" self._add_cache = defaultdict(list) self._reverse_add_cache = defaultdict(list) self._undefined_cache = {} self._remove_cache = {}
Commit current transaction. def commit(self): """Commit current transaction.""" if (not self._add_cache and not self._remove_cache and not self._undefined_cache): return for store_key, hash_values in self._add_cache.items(): for hash_valu...
Drop changes from current transaction. def rollback(self): """Drop changes from current transaction.""" if not self._in_transaction: raise NotInTransaction self._init_cache() self._in_transaction = False
Add hashed value in the context of the current transaction. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object def add_hashed_value(self, hash_value, store_key): """A...
Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str def remove_key(self, store_key): """Remove key in the context of the current transaction. :param store_key: The key for the document in the store ...
Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the given value :rtype: list(str) def get_keys_for(self, value, in...
Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports all query operators that are available in SQLAlchemy and returns a query set ...
Transform the query dictionary to replace e.g. documents with __ref__ fields. def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): for encoder in self.query_encoders: ...
Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports most query operators that are available in MongoDB and returns a query...
Generate boolean operator checking function. def boolean_operator_query(boolean_operator): """Generate boolean operator checking function.""" def _boolean_operator_query(expressions): """Apply boolean operator to expressions.""" def _apply_boolean_operator(query_function, expressions=expression...
Filter documents with a key that satisfies an expression. def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expres...
Apply logical not operator to expression. def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = ind...
Generate comparison operator checking function. def comparison_operator_query(comparison_operator): """Generate comparison operator checking function.""" def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expre...
Check that documents have a key that satisfies expression. def exists_query(expression): """Check that documents have a key that satisfies expression.""" def _exists(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expres...
Apply regular expression to result of expression. def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ ...
Match arrays that contain all elements in the query. def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else express...
Match any of the values that exist in an array specified in query. def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callabl...
Compile each expression in query recursively. def compile_query(query): """Compile each expression in query recursively.""" if isinstance(query, dict): expressions = [] for key, value in query.items(): if key.startswith('$'): if key not in query_funcs: ...
Temporarily changes the ansible verbosity. Relies on a single display instance being referenced by the __main__ module. This is setup when suitable is imported, though Ansible could already be imported beforehand, in which case the output might not be as verbose as expected. To be sure, import sui...
Temporarily overrides an environment variable. def environment_variable(key, value): """ Temporarily overrides an environment variable. """ if key not in os.environ: previous = None else: previous = os.environ[key] os.environ[key] = value yield if previous is None: d...
Temporarily disables host_key_checking, which is set globally. def host_key_checking(enable): """ Temporarily disables host_key_checking, which is set globally. """ def as_string(b): return b and 'True' or 'False' with environment_variable('ANSIBLE_HOST_KEY_CHECKING', as_string(enable)): ...
Hooks this module up to the given api. def hookup(self, api): """ Hooks this module up to the given api. """ assert not hasattr(api, self.module_name), """ '{}' conflicts with existing attribute """.format(self.module_name) self.api = api setattr(api, self.module_...
Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result. def execute(self, *args, **kwargs): """ Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result. """ assert self.is_hooked_up, "the module should...
Takes a server out of the list. def ignore_further_calls_to_server(self, server): """ Takes a server out of the list. """ log.error(u'ignoring further calls to {}'.format(server)) self.api.servers.remove(server)
prepare the result of runner call for use with RunnerResults. def evaluate_results(self, callback): """ prepare the result of runner call for use with RunnerResults. """ for server, result in callback.unreachable.items(): log.error(u'{} could not be reached'.format(server)) log...
Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's...
Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log') def valid_return_codes(self, *codes): """ Sets codes which ...
Construct the URL with a given IP address. def construct_url(ip_address: str) -> str: """Construct the URL with a given IP address.""" if 'http://' not in ip_address and 'https://' not in ip_address: ip_address = '{}{}'.format('http://', ip_address) if ip_address[-1] == '/': ip_address...
Retrieve the data from the printer. Throws ValueError if host does not support SyncThru async def update(self) -> None: """ Retrieve the data from the printer. Throws ValueError if host does not support SyncThru """ url = '{}{}'.format(self.url, ENDPOINT) ...
Return the model name of the printer. def model(self): """Return the model name of the printer.""" try: return self.data.get('identity').get('model_name') except (KeyError, AttributeError): return self.device_status_simple('')
Return the location of the printer. def location(self): """Return the location of the printer.""" try: return self.data.get('identity').get('location') except (KeyError, AttributeError): return self.device_status_simple('')
Return the serial number of the printer. def serial_number(self): """Return the serial number of the printer.""" try: return self.data.get('identity').get('serial_num') except (KeyError, AttributeError): return self.device_status_simple('')
Return the hostname of the printer. def hostname(self): """Return the hostname of the printer.""" try: return self.data.get('identity').get('host_name') except (KeyError, AttributeError): return self.device_status_simple('')
Return the status of the device as string. def device_status(self): """Return the status of the device as string.""" try: return self.device_status_simple( self.data.get('status').get('status1')) except (KeyError, AttributeError): return self.device...
Return the capabilities of the printer. def capability(self) -> Dict[str, Any]: """Return the capabilities of the printer.""" try: return self.data.get('capability', {}) except (KeyError, AttributeError): return {}
Return the state of all toners cartridges. def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NAMES: try: toner_stat = self.data.get( ...
Return the state of all input trays. def input_tray_status(self, filter_supported: bool = True) -> Dict[int, Any]: """Return the state of all input trays.""" tray_status = {} for i in range(1, 5): try: tray_stat = self.data.get('{}{}'....
Return the state of all output trays. def output_tray_status(self) -> Dict[int, Dict[str, str]]: """Return the state of all output trays.""" tray_status = {} try: tray_stat = self.data.get('outputTray', []) for i, stat in enumerate(tray_stat): tray_...
Return the state of all drums. def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all drums.""" drum_status = {} for color in self.COLOR_NAMES: try: drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color), ...
Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger. def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None: """ Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger. """ # noinspection PyBroadException t...
A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It returns ``None`` otherwise. def get_class_name_from_frame(fr: FrameType) -> ...
Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) Example: .. code-block:: python from ca...