INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Loads/ dumps message: param msg:: param msg_type:: param obj:: return:
async def message(self, msg, msg_type=None, obj=None): """ Loads/dumps message :param msg: :param msg_type: :param obj: :return: """ elem_type = msg_type if msg_type is not None else msg.__class__ obj = collections.OrderedDict() if not x.has_elem(o...
Archive field: param elem:: param elem_type:: param params:: param obj:: return:
async def field(self, elem=None, elem_type=None, params=None, obj=None): """ Archive field :param elem: :param elem_type: :param params: :param obj: :return: """ elem_type = elem_type if elem_type else elem.__class__ fvalue = None ...
Convenience method that round input to valid ScaleIO Volume size ( 8GB increments ): param volsize: Size in MB: rtype int: Valid ScaleIO Volume size rounded to nearest 8GB increment above or equal to volsize
def is_valid_volsize(self,volsize): """ Convenience method that round input to valid ScaleIO Volume size (8GB increments) :param volsize: Size in MB :rtype int: Valid ScaleIO Volume size rounded to nearest 8GB increment above or equal to volsize """ if type(volsi...
removeMode = ONLY_ME | INCLUDING_DESCENDANTS | DESCENDANTS_ONLY | WHOLE_VTREE Using kwargs it will be possible to tell delete_volume () to unmap all SDCs before delting. Not working yet
def delete_volume(self, volObj, removeMode='ONLY_ME', **kwargs): """ removeMode = 'ONLY_ME' | 'INCLUDING_DESCENDANTS' | 'DESCENDANTS_ONLY' | 'WHOLE_VTREE' Using kwargs it will be possible to tell delete_volume() to unmap all SDCs before delting. Not working yet """ if kwargs: ...
Map a Volume to SDC: param volumeObj: ScaleIO Volume object: param sdcObj: ScaleIO SDC object: param allowMultipleMappings: True to allow more than one SDC to be mapped to volume: return: POST request response: rtype: Requests POST response object
def map_volume_to_sdc(self, volumeObj, sdcObj=None, allowMultipleMappings=False, **kwargs): """ Map a Volume to SDC :param volumeObj: ScaleIO Volume object :param sdcObj: ScaleIO SDC object :param allowMultipleMappings: True to allow more than one SDC to be mapped to volume ...
Unmap a Volume from SDC or all SDCs: param volObj: ScaleIO Volume object: param sdcObj: ScaleIO SDC object: param \ ** kwargs:: Keyword Arguments: * disableMapAllSdcs * ( bool ) -- True to disable all SDCs mapping: return: POST request response: rtype: Requests POST response object: raise RuntimeError: If failure happe...
def unmap_volume_from_sdc(self, volObj, sdcObj=None, **kwargs): """ Unmap a Volume from SDC or all SDCs :param volObj: ScaleIO Volume object :param sdcObj: ScaleIO SDC object :param \**kwargs: :Keyword Arguments: *disableMapAllSdcs* (``bool``) -- True to disable a...
: param sdcObj: SDC object: return: list of Volumes attached to SDC: rtyoe: ScaleIO Volume object
def get_volumes_for_sdc(self, sdcObj): """ :param sdcObj: SDC object :return: list of Volumes attached to SDC :rtyoe: ScaleIO Volume object """ self.conn.connection._check_login() all_volumes = [] response = self.conn.connection._do_get("{}/{}{}/{}".format...
Get ScaleIO Volume object by its ID: param name: ID of volume: return: ScaleIO Volume object: raise KeyError: No Volume with specified ID found: rtype: ScaleIO Volume object
def get_volume_by_id(self, id): """ Get ScaleIO Volume object by its ID :param name: ID of volume :return: ScaleIO Volume object :raise KeyError: No Volume with specified ID found :rtype: ScaleIO Volume object """ for vol in self.conn.volumes: ...
: param vtreeObj: VTree object Protection Domain Object: return: list of Volumes attached to VTree: rtype: ScaleIO Volume object
def get_volumes_for_vtree(self, vtreeObj): """ :param vtreeObj: VTree object Protection Domain Object :return: list of Volumes attached to VTree :rtype: ScaleIO Volume object """ self.conn.connection._check_login() all_volumes = [] response = s...
Get ScaleIO Volume object by its Name: param name: Name of volume: return: ScaleIO Volume object: raise KeyError: No Volume with specified name found: rtype: ScaleIO Volume object
def get_volume_by_name(self, name): """ Get ScaleIO Volume object by its Name :param name: Name of volume :return: ScaleIO Volume object :raise KeyError: No Volume with specified name found :rtype: ScaleIO Volume object """ for vol in self.conn.volumes: ...
Resize a volume to new GB size must be larger than original.: param volumeObj: ScaleIO Volume Object: param sizeInGb: New size in GB ( have to be larger than original ): param bsize: 1000: return: POST request response: rtype: Requests POST response object
def resize_volume(self, volumeObj, sizeInGb, bsize=1000): """ Resize a volume to new GB size, must be larger than original. :param volumeObj: ScaleIO Volume Object :param sizeInGb: New size in GB (have to be larger than original) :param bsize: 1000 :return: POST request r...
Create snapshot for list of volumes: param systemID: Cluster ID: param snapshotSpecificationObject: Of class SnapshotSpecification: rtype: SnapshotGroupId
def create_snapshot(self, systemId, snapshotSpecificationObject): """ Create snapshot for list of volumes :param systemID: Cluster ID :param snapshotSpecificationObject: Of class SnapshotSpecification :rtype: SnapshotGroupId """ self.conn.connection._check_login(...
: param systemId: ID of Cluster: param snapshotGroupId: ID of snapshot group ID to be removed/ api/ instances/ System:: { id }/ action/ removeConsistencyGroupSnapshots type: POST Required: snapGroupId Return: numberOfVolumes - number of volumes that were removed because of this operation
def delete_snapshot(self, systemId, snapshotGroupId): """ :param systemId: ID of Cluster :param snapshotGroupId: ID of snapshot group ID to be removed /api/instances/System::{id}/action/removeConsistencyGroupSnapshots type: POST Required: sna...
Get list of SDC mapped to a specific volume: param volObj: ScaleIO volume object: return: List of ScaleIO SDC objects ( empty list if no mapping exist ): rtype: SDC object
def get_sdc_for_volume(self, volObj): """ Get list of SDC mapped to a specific volume :param volObj: ScaleIO volume object :return: List of ScaleIO SDC objects (empty list if no mapping exist) :rtype: SDC object """ sdcList = [] if volObj.mapped_sdcs is no...
Create an index. html for one package.
def make_index_for(package, index_dir, verbose=True): """ Create an 'index.html' for one package. :param package: Package object to use. :param index_dir: Where 'index.html' should be created. """ index_template = """\ <html> <head><title>{title}</title></head> <body> <h1>{title}</h1> <ul> {p...
Create a pypi server like file structure below download directory.
def make_package_index(download_dir): """ Create a pypi server like file structure below download directory. :param download_dir: Download directory with packages. EXAMPLE BEFORE: +-- downloads/ +-- alice-1.0.zip +-- alice-1.0.tar.gz +-- bob-1.3.0.tar.gz ...
Return a list value translating from other types if necessary.
def _convert_to_list(self, value, delimiters): """ Return a list value translating from other types if necessary. :param str value: The value to convert. """ if not value: return [] if delimiters: return [l.strip() for l in value.split(delimiters...
A convenience method which coerces the option in the specified section to a list of strings.
def getlist(self, section, option, raw=False, vars=None, fallback=[], delimiters=','): """ A convenience method which coerces the option in the specified section to a list of strings. """ v = self.get(section, option, raw=raw, vars=vars, fallback=fallback) return self._convert_to...
A convenience method which coerces the option in the specified section to a file.
def getfile(self, section, option, raw=False, vars=None, fallback="", validate=False): """ A convenience method which coerces the option in the specified section to a file. """ v = self.get(section, option, raw=raw, vars=vars, fallback=fallback) v = self._convert_to_path(v) ...
A convenience method which coerces the option in the specified section to a directory.
def getdir(self, section, option, raw=False, vars=None, fallback="", validate=False): """ A convenience method which coerces the option in the specified section to a directory. """ v = self.get(section, option, raw=raw, vars=vars, fallback=fallback) v = self._convert_to_path(v) ...
A convenience method which coerces the option in the specified section to a list of directories.
def getdirs(self, section, option, raw=False, vars=None, fallback=[]): """ A convenience method which coerces the option in the specified section to a list of directories. """ globs = self.getlist(section, option, fallback=[]) return [f for g in globs for f in glob.glob(g) if os....
Extends: meth: ~configparser. ConfigParser. set by auto formatting byte strings into unicode strings.
def set(self, section, option, value=None): """ Extends :meth:`~configparser.ConfigParser.set` by auto formatting byte strings into unicode strings. """ if isinstance(section, bytes): section = section.decode('utf8') if isinstance(option, bytes): option =...
Extends: meth: ~configparser. ConfigParser. set by auto formatting byte strings into unicode strings.
def update(self, **kwargs): """ Extends :meth:`~configparser.ConfigParser.set` by auto formatting byte strings into unicode strings. """ # Override the template values with the override values. for s in config.sections(): for o in config.options(s): ov...
Register a new document.
def register(self, name, content, description=None): """ Register a new document. :param content: Content of this document. Jinja and rst are supported. :type content: str :param name: Unique name of the document for documentation purposes. :param description: Short desc...
Registers a new document.
def register(self, name, content, plugin, description=None): """ Registers a new document. .. warning: You can not use any relative links inside a given document. For instance, sphinx's toctree, image, figure or include statements do not work. :param content: Conten...
Unregisters an existing document so that this document is no longer available.
def unregister(self, document): """ Unregisters an existing document, so that this document is no longer available. This function is mainly used during plugin deactivation. :param document: Name of the document """ if document not in self.documents.keys(): s...
Get one or more documents.
def get(self, document=None, plugin=None): """ Get one or more documents. :param document: Name of the document :type document: str :param plugin: Plugin object, under which the document was registered :type plugin: GwBasePattern """ if plugin is not None...
Initialises given plugins but does not activate them.
def initialise_by_names(self, plugins=None): """ Initialises given plugins, but does not activate them. This is needed to import and configure libraries, which are imported by used patterns, like GwFlask. After this action, all needed python modules are imported and configured. ...
Activates given plugins.
def activate(self, plugins=[]): """ Activates given plugins. This calls mainly plugin.activate() and plugins register needed resources like commands, signals or documents. If given plugins have not been initialised, this is also done via :func:`_load`. :param plugins: ...
Deactivates given plugins.
def deactivate(self, plugins=[]): """ Deactivates given plugins. A given plugin must be activated, otherwise it is ignored and no action takes place (no signals are fired, no deactivate functions are called.) A deactivated plugin is still loaded and initialised and can be react...
Returns the plugin object with the given name. Or if a name is not given the complete plugin dictionary is returned.
def get(self, name=None): """ Returns the plugin object with the given name. Or if a name is not given, the complete plugin dictionary is returned. :param name: Name of a plugin :return: None, single plugin or dictionary of plugins """ if name is None: ...
Returns True if plugin exists and is active. If plugin does not exist it returns None
def is_active(self, name): """ Returns True if plugin exists and is active. If plugin does not exist, it returns None :param name: plugin name :return: boolean or None """ if name in self._plugins.keys(): return self._plugins["name"].active re...
Registers plugin classes which are in sys. path and have an entry_point called groundwork. plugin.: return: dict of plugin classes
def _get_plugins_by_entry_points(self): """ Registers plugin classes, which are in sys.path and have an entry_point called 'groundwork.plugin'. :return: dict of plugin classes """ # Let's find and register every plugin, which is in sys.path and has defined a entry_point 'groundwo...
Registers new plugins.
def register(self, classes=[]): """ Registers new plugins. The registration only creates a new entry for a plugin inside the _classes dictionary. It does not activate or even initialise the plugin. A plugin must be a class, which inherits directly or indirectly from GwBasePatte...
Returns the plugin class object with the given name. Or if a name is not given the complete plugin dictionary is returned.
def get(self, name=None): """ Returns the plugin class object with the given name. Or if a name is not given, the complete plugin dictionary is returned. :param name: Name of a plugin :return: None, single plugin or dictionary of plugins """ if name is None: ...
Normalize path to unicode: param path: path: return: normalize path
def _(path): """ Normalize path to unicode :param path: path :return: normalize path >>> _(None) u'' >>> _(u("test1")) u'test1' >>> _("test2") u'test2' """ if path is None: return u("") if not PY3: if type(path) == unicode: return path ...
Normalize remote href: param href: remote path: return: normalize href
def remote(href): """ Normalize remote href :param href: remote path :return: normalize href >>> remote("/test/hello.txt") u'/test/hello.txt' >>> remote("test/hello.txt") u'/test/hello.txt' >>> remote("test\hello.txt") u'/test/hello.txt' >>> remote(None) u'/' """ ...
Get common headers: return:
def getHeaders(self): """ Get common headers :return: """ basicauth = base64.encodestring(b(self.user + ':' + self.password)).strip() return { "Depth": "1", "Authorization": 'Basic ' + _decode_utf8(basicauth), "Accept": "*/*" }
list of files and directories at remote server: param href: remote folder: return: list ( folders files ) and list ( None None ) if folder doesn t exist
def list(self, href): """ list of files and directories at remote server :param href: remote folder :return: list(folders, files) and list(None,None) if folder doesn't exist """ for iTry in range(TRYINGS): logger.info(u("list(%s): %s") % (iTry, href)) ...
Sync local and remote folders: param localpath: local folder: param href: remote folder: param exclude: filter folder which need to exlude: return: respose
def sync(self, localpath, href, exclude=None, block=True): """ Sync local and remote folders :param localpath: local folder :param href: remote folder :param exclude: filter folder which need to exlude :return: respose """ logger.info(u("sync: %s %s") % (l...
create remote folder: param href: remote path: return: response
def mkdir(self, href): """ create remote folder :param href: remote path :return: response """ for iTry in range(TRYINGS): logger.info(u("mkdir(%s): %s") % (iTry, href)) try: href = remote(href) con = self.getConnect...
Download file to localstorage: param href: remote path: param localpath: local path: return: response
def downloadTo(self, href, localpath): """ Download file to localstorage :param href: remote path :param localpath: local path :return: response """ for iTry in range(TRYINGS): logger.info(u("downloadTo(%s): %s %s") % (iTry, href, localpath)) ...
Upload file from localpath to remote server: param localpath: local path: param href: remote path: return: response
def upload(self, localpath, href): """ Upload file from localpath to remote server :param localpath: local path :param href: remote path :return: response """ localpath = _(localpath) href = remote(href) if not os.path.exists(localpath): ...
Internal method to import instance variables data from a dictionary
def _import(self, datadict): """ Internal method to import instance variables data from a dictionary :param dict datadict: The dictionary containing variables values. """ self.GUID = datadict.get("GUID", uuid.uuid1()) self.FileName = datadict.get("FileName", "") ...
Writes the. sln file to disk.
def write(self): """ Writes the ``.sln`` file to disk. """ filters = { 'MSGUID': lambda x: ('{%s}' % x).upper(), 'relslnfile': lambda x: os.path.relpath(x, os.path.dirname(self.FileName)) } context = { 'sln': self } retu...
Log - normalizes and filters the expression data.
def preprocess_data(self, div=1, downsample=0, sum_norm=None, include_genes=None, exclude_genes=None, include_cells=None, exclude_cells=None, norm='log', min_expression=1, thresh=0.01, filter_genes=True): """Log-norm...
Loads the specified data file. The file can be a table of read counts ( i. e.. csv or. txt ) with genes as rows and cells as columns by default. The file can also be a pickle file ( output from save_sparse_data ) or an h5ad file ( output from save_anndata ).
def load_data(self, filename, transpose=True, save_sparse_file='h5ad', sep=',', **kwargs): """Loads the specified data file. The file can be a table of read counts (i.e. '.csv' or '.txt'), with genes as rows and cells as columns by default. The file can also be a pickle file (o...
Saves the tuple ( raw_data all_cell_names all_gene_names ) in a Pickle file.
def save_sparse_data(self, fname): """Saves the tuple (raw_data,all_cell_names,all_gene_names) in a Pickle file. Parameters ---------- fname - string The filename of the output file. """ data = self.adata_raw.X.T if data.getformat()=='csr': ...
Saves adata_raw to a. h5ad file ( AnnData s native file format ).
def save_anndata(self, fname, data = 'adata_raw', **kwargs): """Saves `adata_raw` to a .h5ad file (AnnData's native file format). Parameters ---------- fname - string The filename of the output file. """ x = self.__dict__[data] x.write_h5ad(fname, **...
Loads cell annotations.
def load_annotations(self, aname, sep=','): """Loads cell annotations. Loads the cell annoations specified by the 'aname' path. Parameters ---------- aname - string The path to the annotations file. First column should be cell IDs and second column shoul...
Computes the spatial dispersion factors for each gene.
def dispersion_ranking_NN(self, nnm, num_norm_avg=50): """Computes the spatial dispersion factors for each gene. Parameters ---------- nnm - scipy.sparse, float Square cell-to-cell nearest-neighbor matrix. num_norm_avg - int, optional, default 50 The top...
Computes the contribution of the gene IDs in genes to each principal component ( PC ) of the filtered expression data as the mean of the absolute value of the corresponding gene loadings. High values correspond to PCs that are highly correlated with the features in genes. These PCs can then be regressed out of the data...
def calculate_regression_PCs(self, genes=None, npcs=None, plot=False): """Computes the contribution of the gene IDs in 'genes' to each principal component (PC) of the filtered expression data as the mean of the absolute value of the corresponding gene loadings. High values correspond to ...
Regress out the principal components in PCs from the filtered expression data ( SAM. D ). Assumes calculate_regression_PCs has been previously called.
def regress_genes(self, PCs): """Regress out the principal components in 'PCs' from the filtered expression data ('SAM.D'). Assumes 'calculate_regression_PCs' has been previously called. Parameters ---------- PCs - int, numpy.array, list The principal compone...
Runs the Self - Assembling Manifold algorithm.
def run(self, max_iter=10, verbose=True, projection='umap', stopping_condition=5e-3, num_norm_avg=50, k=20, distance='correlation', preprocessing='Normalizer', proj_kwargs={}): """Runs the Self-Assembling...
Plots orthogonal expression patterns.
def plot_correlated_groups(self, group=None, n_genes=5, **kwargs): """Plots orthogonal expression patterns. In the default mode, plots orthogonal gene expression patterns. A specific correlated group of genes can be specified to plot gene expression patterns within that group. ...
Plots gene expression patterns correlated with the input gene.
def plot_correlated_genes( self, name, n_genes=5, number_of_features=1000, **kwargs): """Plots gene expression patterns correlated with the input gene. Parameters ---------- name - string The name of the gene with r...
A ( hacky ) method for binning groups of genes correlated along the SAM manifold.
def corr_bin_genes(self, number_of_features=None, input_gene=None): """A (hacky) method for binning groups of genes correlated along the SAM manifold. Parameters ---------- number_of_features - int, optional, default None The number of genes to bin. Capped at 5000 du...
Wrapper for sklearn s t - SNE implementation.
def run_tsne(self, X=None, metric='correlation', **kwargs): """Wrapper for sklearn's t-SNE implementation. See sklearn for the t-SNE documentation. All arguments are the same with the exception that 'metric' is set to 'precomputed' by default, implying that this function expects a dista...
Wrapper for umap - learn.
def run_umap(self, X=None, metric=None, **kwargs): """Wrapper for umap-learn. See https://github.com/lmcinnes/umap sklearn for the documentation and source code. """ import umap as umap if metric is None: metric = self.distance if(X is not None): ...
Experimental -- running UMAP on the diffusion components
def run_diff_umap(self,use_rep='X_pca', metric='euclidean', n_comps=15, method='gauss', **kwargs): """ Experimental -- running UMAP on the diffusion components """ import scanpy.api as sc sc.pp.neighbors(self.adata,use_rep=use_rep,n_neig...
Display a scatter plot.
def scatter(self, projection=None, c=None, cmap='rainbow', linewidth=0.0, edgecolor='k', axes=None, colorbar=True, s=10, **kwargs): """Display a scatter plot. Displays a scatter plot using the SAM projection or another input projection with or without annotations. Param...
Display a gene s expressions.
def show_gene_expression(self, gene, avg=True, axes=None, **kwargs): """Display a gene's expressions. Displays a scatter plot using the SAM projection or another input projection with a particular gene's expressions overlaid. Parameters ---------- gene - string ...
Runs Louvain clustering using the vtraag implementation. Assumes that louvain optional dependency is installed.
def louvain_clustering(self, X=None, res=1, method='modularity'): """Runs Louvain clustering using the vtraag implementation. Assumes that 'louvain' optional dependency is installed. Parameters ---------- res - float, optional, default 1 The resolution parameter whic...
Performs k - means clustering.
def kmeans_clustering(self, numc, X=None, npcs=15): """Performs k-means clustering. Parameters ---------- numc - int Number of clusters npcs - int, optional, default 15 Number of principal components to use as inpute for k-means clustering. ...
Ranks marker genes for each cluster using a random forest classification approach.
def identify_marker_genes_rf(self, labels=None, clusters=None, n_genes=4000): """ Ranks marker genes for each cluster using a random forest classification approach. Parameters ---------- labels - numpy.array or str, optional, default Non...
Ranks marker genes for each cluster using a SAM - weighted expression - ratio approach ( works quite well ).
def identify_marker_genes_ratio(self, labels=None): """ Ranks marker genes for each cluster using a SAM-weighted expression-ratio approach (works quite well). Parameters ---------- labels - numpy.array or str, optional, default None Cluster labels to use fo...
Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster - specific reference expression profiles.
def identify_marker_genes_corr(self, labels=None, n_genes=4000): """ Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster-specific reference expression profiles. Parameters ---------- labels - numpy.array or str...
Add ability are allowed using two arguments.
def add(self, action=None, subject=None, **conditions): """ Add ability are allowed using two arguments. The first one is the action you're setting the permission for, the second one is the class of object you're setting it on. the third one is the subject's conditions must be m...
Defines an ability which cannot be done.
def addnot(self, action=None, subject=None, **conditions): """ Defines an ability which cannot be done. """ self.add_rule(Rule(False, action, subject, **conditions))
Check if the user has permission to perform a given action on an object
def can(self, action, subject, **conditions): """ Check if the user has permission to perform a given action on an object """ for rule in self.relevant_rules_for_match(action, subject): if rule.matches_conditions(action, subject, **conditions): return rule.bas...
retrive match action and subject
def relevant_rules_for_match(self, action, subject): """retrive match action and subject""" matches = [] for rule in self.rules: rule.expanded_actions = self.expand_actions(rule.actions) if rule.is_relevant(action, subject): matches.append(rule) r...
Accepts an array of actions and returns an array of actions which match
def expand_actions(self, actions): """ Accepts an array of actions and returns an array of actions which match """ r = [] for action in actions: r.append(action) if action in self.aliased_actions: r.extend(self.aliased_actions[action]) ...
Alias one or more actions into another one.
def alias_action(self, *args, **kwargs): """ Alias one or more actions into another one. self.alias_action('create', 'read', 'update', 'delete', to='crud') """ to = kwargs.pop('to', None) if not to: return error_message = ("You can't specify target (...
Convenience wrapper for database SELECT and fetch all.
def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): """Convenience wrapper for database SELECT and fetch all.""" return select(table, cols, where, group, order, limit, **kwargs).fetchall()
Convenience wrapper for database SELECT and fetch one.
def fetchone(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): """Convenience wrapper for database SELECT and fetch one.""" return select(table, cols, where, group, order, limit, **kwargs).fetchone()
Convenience wrapper for database INSERT.
def insert(table, values=(), **kwargs): """Convenience wrapper for database INSERT.""" values = dict(values, **kwargs).items() sql, args = makeSQL("INSERT", table, values=values) return execute(sql, args).lastrowid
Convenience wrapper for database SELECT.
def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): """Convenience wrapper for database SELECT.""" where = dict(where, **kwargs).items() sql, args = makeSQL("SELECT", table, cols, where, group, order, limit) return execute(sql, args)
Convenience wrapper for database UPDATE.
def update(table, values, where=(), **kwargs): """Convenience wrapper for database UPDATE.""" where = dict(where, **kwargs).items() sql, args = makeSQL("UPDATE", table, values=values, where=where) return execute(sql, args).rowcount
Convenience wrapper for database DELETE.
def delete(table, where=(), **kwargs): """Convenience wrapper for database DELETE.""" where = dict(where, **kwargs).items() sql, args = makeSQL("DELETE", table, where=where) return execute(sql, args).rowcount
Returns a cursor to the database making new connection if not cached.
def make_cursor(path, init_statements=(), _connectioncache={}): """Returns a cursor to the database, making new connection if not cached.""" connection = _connectioncache.get(path) if not connection: is_new = not os.path.exists(path) or not os.path.getsize(path) try: is_new and os.maked...
Returns ( SQL statement string parameter dict ).
def makeSQL(action, table, cols="*", where=(), group="", order=(), limit=(), values=()): """Returns (SQL statement string, parameter dict).""" cols = cols if isinstance(cols, basestring) else ", ".join(cols) group = group if isinstance(group, basestring) else ", ".join(group) order = [order] ...
Prompt the user to continue or not
def continue_prompt(message=""): """Prompt the user to continue or not Returns True when the user type Yes. :param message: message to display :type message: str :rtype: bool """ answer = False message = message + "\n'Yes' or 'No' to continue: " while answer not in ('Yes', 'No'): ...
Write msg on stdout. If no encoding is specified the detected encoding of stdout is used. If the encoding can t encode some chars they are replaced by ?
def printo(msg, encoding=None, errors='replace', std_type='stdout'): """Write msg on stdout. If no encoding is specified the detected encoding of stdout is used. If the encoding can't encode some chars they are replaced by '?' :param msg: message :type msg: unicode on python2 | str on python3 "...
Format table
def format_table(rows, sep=' '): """Format table :param sep: separator between columns :type sep: unicode on python2 | str on python3 Given the table:: table = [ ['foo', 'bar', 'foo'], [1, 2, 3], ['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'], ['foo'...
Format a python tree structure
def format_tree(tree): """Format a python tree structure Given the python tree:: tree = { 'node': ['ROOT', 'This is the root of the tree'], 'childs': [{ 'node': 'A1', 'childs': [{ 'node': 'B1', 'childs': [{...
Map func on a list using gevent greenlets.
def parallel_map(func, iterable, args=None, kwargs=None, workers=None): """Map func on a list using gevent greenlets. :param func: function applied on iterable elements :type func: function :param iterable: elements to map the function over :type iterable: iterable :param args: arguments of fun...
A general method for parsing word - representations of numbers. Supports floats and integers.
def parse(self, words): """A general method for parsing word-representations of numbers. Supports floats and integers. Args: words (str): Description of an arbitrary number. Returns: A double representation of the words. """ def exact(words): ...
Convert a floating - point number described in words to a double.
def parseFloat(self, words): """Convert a floating-point number described in words to a double. Supports two kinds of descriptions: those with a 'point' (e.g., "one point two five") and those with a fraction (e.g., "one and a quarter"). Args: words (str): Descriptio...
Parses words to the integer they describe.
def parseInt(self, words): """Parses words to the integer they describe. Args: words (str): Description of the integer. Returns: An integer representation of the words. """ # Remove 'and', case-sensitivity words = words.replace(" and ", " ").lowe...
Parses a number m into a human - ready string representation. For example crops off floats if they re too accurate.
def parseMagnitude(m): """Parses a number m into a human-ready string representation. For example, crops off floats if they're too accurate. Arguments: m (float): Floating-point number to be cleaned. Returns: Human-ready string description of the number. ...
Extracts the longest valid numerical description from a string. Not guaranteed to return a result even if some valid numerical description exists ( i. e. method is not particularly advanced ).
def longestNumber(self, inp): """Extracts the longest valid numerical description from a string. Not guaranteed to return a result even if some valid numerical description exists (i.e., method is not particularly advanced). Args: inp (str): An arbitrary string, hopefully con...
Encode the private part of the key in a base64 format by default but when raw is True it will return hex encoded bytes.
def serialize(self, raw=False): '''Encode the private part of the key in a base64 format by default, but when raw is True it will return hex encoded bytes. @return: bytes ''' if raw: return self._key.encode() return self._key.encode(nacl.encoding.Base64Encoder...
Create a PublicKey from a base64 encoded bytes.: return: a PublicKey
def deserialize(cls, serialized): ''' Create a PublicKey from a base64 encoded bytes. :return: a PublicKey ''' return PublicKey( nacl.public.PublicKey(serialized, encoder=nacl.encoding.Base64Encoder))
Convenient method for GET requests Returns http request status value from a POST request
def _do_get(self, url, **kwargs): """ Convenient method for GET requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_post_hea...
Convenient method for POST requests Returns http request status value from a POST request
def _do_post(self, url, **kwargs): """ Convenient method for POST requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_post_h...
Get response content and headers from a discharge macaroons error.
def discharge_required_response(macaroon, path, cookie_suffix_name, message=None): ''' Get response content and headers from a discharge macaroons error. @param macaroon may hold a macaroon that, when discharged, may allow access to a service. @param path holds the URL p...
Determines the bakery protocol version from a client request. If the protocol cannot be determined or is invalid the original version of the protocol is used. If a later version is found the latest known version is used which is OK because versions are backwardly compatible.
def request_version(req_headers): ''' Determines the bakery protocol version from a client request. If the protocol cannot be determined, or is invalid, the original version of the protocol is used. If a later version is found, the latest known version is used, which is OK because versions are backwardl...
Create an error from a JSON - deserialized object
def from_dict(cls, serialized): '''Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict} ''' # Some servers return lower case field names for message and code. # The Go client is tolerant of this, so be similarly tolerant...
Checks whether the error is an InteractionRequired error that implements the method with the given name and JSON - unmarshals the method - specific data into x by calling its from_dict method with the deserialized JSON object.
def interaction_method(self, kind, x): ''' Checks whether the error is an InteractionRequired error that implements the method with the given name, and JSON-unmarshals the method-specific data into x by calling its from_dict method with the deserialized JSON object. @param kind T...
Create a new ErrorInfo object from a JSON deserialized dictionary
def from_dict(cls, serialized): '''Create a new ErrorInfo object from a JSON deserialized dictionary @param serialized The JSON object {dict} @return ErrorInfo object ''' if serialized is None: return None macaroon = serialized.get('Macaroon') ...