Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def pause(self, message=None, verbose=False):
PARAMS=set_param(["message"],[message])
response=api(url=self.__url+"/pause", PARAMS=PARAMS, verbose=verbose)
return response | [
"\n The pause command displays a dialog with the text provided in the\n message argument and waits for the user to click OK\n\n :param message: a message to display. default=None\n :param verbose: print more\n "
] |
Please provide a description of the function:def quit(self,verbose=False):
response=api(url=self.__url+"/quit", verbose=verbose)
return response | [
"\n This command causes Cytoscape to exit. It is typically used at the end\n of a script file.\n\n :param verbose: print more\n "
] |
Please provide a description of the function:def run(self,script_file,args=None,verbose=False):
PARAMS=set_param(["file","args"],[script_file,args])
response=api(url=self.__url+"/run", PARAMS=PARAMS, verbose=verbose)
return response | [
"\n The run command will execute a command script from the file pointed to\n by the file argument, which should contain Cytoscape commands, one per\n line. Arguments to the script are provided by the args argument.\n\n :param script_file: file to run\n :param args: enter the scrip... |
Please provide a description of the function:def sleep(self,duration,verbose=False):
PARAMS={"duration":str(duration)}
response=api(url=self.__url+"/sleep", PARAMS=PARAMS, verbose=verbose)
return response | [
"\n The sleep command will pause processing for a period of time as specified\n by duration seconds. It is typically used as part of a command script.\n\n :param duration: enter the time in seconds to sleep\n :param verbose: print more\n "
] |
Please provide a description of the function:def to_curl(request, compressed=False, verify=True):
parts = [
('curl', None),
('-X', request.method),
]
for k, v in sorted(request.headers.items()):
parts += [('-H', '{0}: {1}'.format(k, v))]
if request.body:
body = req... | [
"\n Returns string with curl command by provided request object\n\n Parameters\n ----------\n compressed : bool\n If `True` then `--compressed` argument will be added to result\n "
] |
Please provide a description of the function:def shared_options(rq):
"Default class options to pass to the CLI commands."
return {
'url': rq.redis_url,
'config': None,
'worker_class': rq.worker_class,
'job_class': rq.job_class,
'queue_class': rq.queue_class,
'conn... | [] |
Please provide a description of the function:def empty(rq, ctx, all, queues):
"Empty given queues."
return ctx.invoke(
rq_cli.empty,
all=all,
queues=queues or rq.queues,
**shared_options(rq)
) | [] |
Please provide a description of the function:def requeue(rq, ctx, all, job_ids):
"Requeue failed jobs."
return ctx.invoke(
rq_cli.requeue,
all=all,
job_ids=job_ids,
**shared_options(rq)
) | [] |
Please provide a description of the function:def info(rq, ctx, path, interval, raw, only_queues, only_workers, by_queue,
queues):
"RQ command-line monitor."
return ctx.invoke(
rq_cli.info,
path=path,
interval=interval,
raw=raw,
only_queues=only_queues,
on... | [] |
Please provide a description of the function:def worker(rq, ctx, burst, logging_level, name, path, results_ttl,
worker_ttl, verbose, quiet, sentry_dsn, exception_handler, pid,
queues):
"Starts an RQ worker."
ctx.invoke(
rq_cli.worker,
burst=burst,
logging_level=logg... | [] |
Please provide a description of the function:def suspend(rq, ctx, duration):
"Suspends all workers."
ctx.invoke(
rq_cli.suspend,
duration=duration,
**shared_options(rq)
) | [] |
Please provide a description of the function:def scheduler(rq, ctx, verbose, burst, queue, interval, pid):
"Periodically checks for scheduled jobs."
scheduler = rq.get_scheduler(interval=interval, queue=queue)
if pid:
with open(os.path.expanduser(pid), 'w') as fp:
fp.write(str(os.getpid(... | [] |
Please provide a description of the function:def queue(self, *args, **kwargs):
queue_name = kwargs.pop('queue', self.queue_name)
timeout = kwargs.pop('timeout', self.timeout)
result_ttl = kwargs.pop('result_ttl', self.result_ttl)
ttl = kwargs.pop('ttl', self.ttl)
depend... | [
"\n A function to queue a RQ job, e.g.::\n\n @rq.job(timeout=60)\n def add(x, y):\n return x + y\n\n add.queue(1, 2, timeout=30)\n\n :param \\\\*args: The positional arguments to pass to the queued job.\n\n :param \\\\*\\\\*kwargs: The keyword arg... |
Please provide a description of the function:def schedule(self, time_or_delta, *args, **kwargs):
queue_name = kwargs.pop('queue', self.queue_name)
timeout = kwargs.pop('timeout', self.timeout)
description = kwargs.pop('description', None)
result_ttl = kwargs.pop('result_ttl', se... | [
"\n A function to schedule running a RQ job at a given time\n or after a given timespan::\n\n @rq.job\n def add(x, y):\n return x + y\n\n add.schedule(timedelta(hours=2), 1, 2, timeout=10)\n add.schedule(datetime(2016, 12, 31, 23, 59, 59), 1, ... |
Please provide a description of the function:def cron(self, pattern, name, *args, **kwargs):
queue_name = kwargs.pop('queue', self.queue_name)
timeout = kwargs.pop('timeout', self.timeout)
description = kwargs.pop('description', None)
repeat = kwargs.pop('repeat', None)
... | [
"\n A function to setup a RQ job as a cronjob::\n\n @rq.job('low', timeout=60)\n def add(x, y):\n return x + y\n\n add.cron('* * * * *', 'add-some-numbers', 1, 2, timeout=10)\n\n :param \\\\*args: The positional arguments to pass to the queued job.\n\n ... |
Please provide a description of the function:def init_app(self, app):
# The connection related config values
self.redis_url = app.config.setdefault(
'RQ_REDIS_URL',
self.redis_url,
)
self.connection_class = app.config.setdefault(
'RQ_CONNECTIO... | [
"\n Initialize the app, e.g. can be used if factory pattern is used.\n "
] |
Please provide a description of the function:def init_cli(self, app):
# in case click isn't installed after all
if click is None:
raise RuntimeError('Cannot import click. Is it installed?')
# only add commands if we have a click context available
from .cli import add... | [
"\n Initialize the Flask CLI support in case it was enabled for the\n app.\n\n Works with both Flask>=1.0's CLI support as well as the backport\n in the Flask-CLI package for Flask<1.0.\n "
] |
Please provide a description of the function:def exception_handler(self, callback):
path = '.'.join([callback.__module__, callback.__name__])
self._exception_handlers.append(path)
return callback | [
"\n Decorator to add an exception handler to the worker, e.g.::\n\n rq = RQ()\n\n @rq.exception_handler\n def my_custom_handler(job, *exc_info):\n # do custom things here\n ...\n\n "
] |
Please provide a description of the function:def job(self, func_or_queue=None, timeout=None, result_ttl=None, ttl=None,
depends_on=None, at_front=None, meta=None, description=None):
if callable(func_or_queue):
func = func_or_queue
queue_name = None
else:
... | [
"\n Decorator to mark functions for queuing via RQ, e.g.::\n\n rq = RQ()\n\n @rq.job\n def add(x, y):\n return x + y\n\n or::\n\n @rq.job(timeout=60, result_ttl=60 * 60)\n def add(x, y):\n return x + y\n\n Adds... |
Please provide a description of the function:def get_scheduler(self, interval=None, queue=None):
if interval is None:
interval = self.scheduler_interval
if not queue:
queue = self.scheduler_queue
scheduler_cls = import_attribute(self.scheduler_class)
s... | [
"\n When installed returns a ``rq_scheduler.Scheduler`` instance to\n schedule job execution, e.g.::\n\n scheduler = rq.get_scheduler(interval=10)\n\n :param interval: Time in seconds of the periodic check for scheduled\n jobs.\n :type interval: int\n ... |
Please provide a description of the function:def get_queue(self, name=None):
if not name:
name = self.default_queue
queue = self._queue_instances.get(name)
if queue is None:
queue_cls = import_attribute(self.queue_class)
queue = queue_cls(
... | [
"\n Returns an RQ queue instance with the given name, e.g.::\n\n default_queue = rq.get_queue()\n low_queue = rq.get_queue('low')\n\n :param name: Name of the queue to return, defaults to\n :attr:`~flask_rq2.RQ.default_queue`.\n :type name: str\n ... |
Please provide a description of the function:def get_worker(self, *queues):
if not queues:
queues = self.queues
queues = [self.get_queue(name) for name in queues]
worker_cls = import_attribute(self.worker_class)
worker = worker_cls(
queues,
co... | [
"\n Returns an RQ worker instance for the given queue names, e.g.::\n\n configured_worker = rq.get_worker()\n default_worker = rq.get_worker('default')\n default_low_worker = rq.get_worker('default', 'low')\n\n :param \\\\*queues: Names of queues the worker should act ... |
Please provide a description of the function:def set_trace(host=None, port=None, patch_stdstreams=False):
if host is None:
host = os.environ.get('REMOTE_PDB_HOST', '127.0.0.1')
if port is None:
port = int(os.environ.get('REMOTE_PDB_PORT', '0'))
rdb = RemotePdb(host=host, port=port, patc... | [
"\n Opens a remote PDB on first available port.\n "
] |
Please provide a description of the function:def quasi_newton_uniform_lloyd(points, cells, *args, omega=1.0, **kwargs):
def get_new_points(mesh):
x = (
mesh.node_coords
- omega / 2 * jac_uniform(mesh) / mesh.control_volumes[:, None]
)
# update boundary and ghost... | [
"Relaxed Lloyd's algorithm. omega=1 leads to Lloyd's algorithm, overrelaxation\n omega=2 gives good results. Check out\n\n Xiao Xiao,\n Over-Relaxation Lloyd Method For Computing Centroidal Voronoi Tessellations,\n Master's thesis,\n <https://scholarcommons.sc.edu/etd/295/>.\n\n Everything above o... |
Please provide a description of the function:def fixed_point_uniform(points, cells, *args, **kwargs):
def get_new_points(mesh):
return get_new_points_volume_averaged(mesh, mesh.cell_barycenters)
mesh = MeshTri(points, cells)
runner(get_new_points, mesh, *args, **kwargs)
return mesh.node_c... | [
"Idea:\n Move interior mesh points into the weighted averages of the centroids\n (barycenters) of their adjacent cells.\n "
] |
Please provide a description of the function:def _energy_uniform_per_node(X, cells):
dim = 2
mesh = MeshTri(X, cells)
star_integrals = numpy.zeros(mesh.node_coords.shape[0])
# Python loop over the cells... slow!
for cell, cell_volume in zip(mesh.cells["nodes"], mesh.cell_volumes):
for ... | [
"The CPT mesh energy is defined as\n\n sum_i E_i,\n E_i = 1/(d+1) * sum int_{omega_i} ||x - x_i||^2 rho(x) dx,\n\n see Chen-Holst. This method gives the E_i and assumes uniform density, rho(x) = 1.\n "
] |
Please provide a description of the function:def jac_uniform(X, cells):
dim = 2
mesh = MeshTri(X, cells)
jac = numpy.zeros(X.shape)
for k in range(mesh.cells["nodes"].shape[1]):
i = mesh.cells["nodes"][:, k]
fastfunc.add.at(
jac,
i,
((mesh.node_c... | [
"The approximated Jacobian is\n\n partial_i E = 2/(d+1) (x_i int_{omega_i} rho(x) dx - int_{omega_i} x rho(x) dx)\n = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_{j, rho}) int_{tau_j} rho,\n\n see Chen-Holst. This method here assumes uniform density, rho(x) = 1, such that\n\n partial_i E =... |
Please provide a description of the function:def solve_hessian_approx_uniform(X, cells, rhs):
dim = 2
mesh = MeshTri(X, cells)
# Create matrix in IJV format
row_idx = []
col_idx = []
val = []
cells = mesh.cells["nodes"].T
n = X.shape[0]
# Main diagonal, 2/(d+1) |omega_i| x_i
... | [
"As discussed above, the approximated Jacobian is\n\n partial_i E = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.\n\n To get the Hessian, we have to form its derivative. As a simplifications,\n let us assume again that |tau_j| is independent of the node positions. Then we get\n\n partial_ii E... |
Please provide a description of the function:def quasi_newton_uniform(points, cells, *args, **kwargs):
def get_new_points(mesh):
# do one Newton step
# TODO need copy?
x = mesh.node_coords.copy()
cells = mesh.cells["nodes"]
jac_x = jac_uniform(x, cells)
x -= sol... | [
"Like linear_solve above, but assuming rho==1. Note that the energy gradient\n\n \\\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) \\\\int_{tau_j} rho\n\n becomes\n\n \\\\partial E_i = 2/(d+1) sum_{tau_j in omega_i} (x_i - b_j) |tau_j|.\n\n Because of the dependence of |tau_j| on the ... |
Please provide a description of the function:def fixed_point(points, cells, *args, **kwargs):
def get_new_points(mesh):
# move interior points into average of their neighbors
num_neighbors = numpy.zeros(len(mesh.node_coords), dtype=int)
idx = mesh.edges["nodes"]
fastfunc.add.at... | [
"Perform k steps of Laplacian smoothing to the mesh, i.e., moving each\n interior vertex to the arithmetic average of its neighboring points.\n "
] |
Please provide a description of the function:def energy(mesh, uniform_density=False):
# E = 1/(d+1) sum_i ||x_i||^2 |omega_i| - int_Omega_i ||x||^2
dim = mesh.cells["nodes"].shape[1] - 1
star_volume = numpy.zeros(mesh.node_coords.shape[0])
for i in range(3):
idx = mesh.cells["nodes"][:, i]... | [
"The mesh energy is defined as\n\n E = int_Omega |u_l(x) - u(x)| rho(x) dx\n\n where u(x) = ||x||^2 and u_l is its piecewise linearization on the mesh.\n "
] |
Please provide a description of the function:def fixed_point_uniform(points, cells, *args, **kwargs):
def get_new_points(mesh):
# Get circumcenters everywhere except at cells adjacent to the boundary;
# barycenters there.
cc = mesh.cell_circumcenters
bc = mesh.cell_barycenters
... | [
"Idea:\n Move interior mesh points into the weighted averages of the circumcenters\n of their adjacent cells. If a triangle cell switches orientation in the\n process, don't move quite so far.\n "
] |
Please provide a description of the function:def fixed_point_density_preserving(points, cells, *args, **kwargs):
def get_new_points(mesh):
# Get circumcenters everywhere except at cells adjacent to the boundary;
# barycenters there.
cc = mesh.cell_circumcenters
bc = mesh.cell_b... | [
"Idea:\n Move interior mesh points into the weighted averages of the circumcenters\n of their adjacent cells. If a triangle cell switches orientation in the\n process, don't move quite so far.\n "
] |
Please provide a description of the function:def nonlinear_optimization_uniform(
X,
cells,
tol,
max_num_steps,
verbose=False,
step_filename_format=None,
callback=None,
):
import scipy.optimize
mesh = MeshTri(X, cells)
if step_filename_format:
mesh.save(
... | [
"Optimal Delaunay Triangulation smoothing.\n\n This method minimizes the energy\n\n E = int_Omega |u_l(x) - u(x)| rho(x) dx\n\n where u(x) = ||x||^2, u_l is its piecewise linear nodal interpolation and\n rho is the density. Since u(x) is convex, u_l >= u everywhere and\n\n u_l(x) = sum_i phi_... |
Please provide a description of the function:def quasi_newton_uniform_blocks(points, cells, *args, **kwargs):
def get_new_points(mesh):
# TODO need copy?
x = mesh.node_coords.copy()
x += update(mesh)
# update ghosts
x[ghosted_mesh.is_ghost_point] = ghosted_mesh.reflect_... | [
"Lloyd's algorithm can be though of a diagonal-only Hessian; this method\n incorporates the diagonal blocks, too.\n "
] |
Please provide a description of the function:def reflect_ghost(self, p0):
# Instead of self.p1, one could take any point on the line p1--p2.
dist = self.p1 - p0
alpha = numpy.einsum("ij, ij->i", dist, self.mirror_edge)
q = dist - (alpha / self.beta)[:, None] * self.mirror_edge
... | [
"This method creates the ghost point p0', namely p0 reflected along the edge\n p1--p2, and the point q at the perpendicular intersection of the reflection.\n\n p0\n _/| \\\\__\n _/ | \\\\__\n / | \\\\\n p1----|q-------p2\n \\\\_ ... |
Please provide a description of the function:def create_append(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Dict[str, np.ndarray], col_attrs: Dict[str, np.ndarray], *, file_attrs: Dict[str, str] = None, fill_values: Dict[str, np.ndarray] = None) -> None:
deprecated... | [
"\n\t**DEPRECATED** - Use `new` instead; see https://github.com/linnarsson-lab/loompy/issues/42\n\t"
] |
Please provide a description of the function:def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection:
if filename.startswith("~/"):
filename = os.path.expanduser(filename)
if file_attrs is None:
file_attrs = {}
# Create the file (empty).
# Yes, this might cause an exception, ... | [
"\n\tCreate an empty Loom file, and return it as a context manager.\n\t"
] |
Please provide a description of the function:def create(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Union[loompy.AttributeManager, Dict[str, np.ndarray]], col_attrs: Union[loompy.AttributeManager, Dict[str, np.ndarray]], *, file_attrs: Dict[str, str] = None) -> None:... | [
"\n\tCreate a new Loom file from the given data.\n\n\tArgs:\n\t\tfilename (str): The filename (typically using a ``.loom`` file extension)\n\t\tlayers:\t\t\t\t\tOne of the following:\n\n\t\t\t\t\t\t\t\t* Two-dimensional (N-by-M) numpy ndarray of float values\n\t\t\t\t\t\t\t\t* Sparse matrix (e.g. :class:`sc... |
Please provide a description of the function:def create_from_cellranger(indir: str, outdir: str = None, genome: str = None) -> str:
if outdir is None:
outdir = indir
sampleid = os.path.split(os.path.abspath(indir))[-1]
matrix_folder = os.path.join(indir, 'outs', 'filtered_gene_bc_matrices')
if os.path.exists(ma... | [
"\n\tCreate a .loom file from 10X Genomics cellranger output\n\n\tArgs:\n\t\tindir (str):\tpath to the cellranger output folder (the one that contains 'outs')\n\t\toutdir (str):\toutput folder wher the new loom file should be saved (default to indir)\n\t\tgenome (str):\tgenome build to load (e.g. 'mm10'; if None, d... |
Please provide a description of the function:def combine(files: List[str], output_file: str, key: str = None, file_attrs: Dict[str, str] = None, batch_size: int = 1000, convert_attrs: bool = False) -> None:
if file_attrs is None:
file_attrs = {}
if len(files) == 0:
raise ValueError("The input file list was emp... | [
"\n\tCombine two or more loom files and save as a new loom file\n\tArgs:\n\t\tfiles (list of str): the list of input files (full paths)\n\t\toutput_file (str): full path of the output loom file\n\t\tkey (string): Row attribute to use to verify row ordering\n\t\tfile_attrs (dict): file attribu... |
Please provide a description of the function:def combine_faster(files: List[str], output_file: str, file_attrs: Dict[str, str] = None, selections: List[np.ndarray] = None, key: str = None, skip_attrs: List[str] = None) -> None:
if file_attrs is None:
file_attrs = {}
if len(files) == 0:
raise ValueError("The in... | [
"\n\tCombine loom files and save as a new loom file\n\n\tArgs:\n\t\tfiles (list of str): the list of input files (full paths)\n\t\toutput_file (str): full path of the output loom file\n\t\tfile_attrs (dict): file attributes (title, description, url, etc.)\n\t\tselections:\t\t\t\tlist of indicator array... |
Please provide a description of the function:def connect(filename: str, mode: str = 'r+', *, validate: bool = True, spec_version: str = "2.0.1") -> LoomConnection:
return LoomConnection(filename, mode, validate=validate, spec_version=spec_version) | [
"\n\tEstablish a connection to a .loom file.\n\n\tArgs:\n\t\tfilename:\t\tPath to the Loom file to open\n\t\tmode:\t\t\tRead/write mode, 'r+' (read/write) or 'r' (read-only), defaults to 'r+'\n\t\tvalidate:\t\tValidate the file structure against the Loom file format specification\n\t\tspec_version:\tThe loom file s... |
Please provide a description of the function:def last_modified(self) -> str:
if "last_modified" in self.attrs:
return self.attrs["last_modified"]
elif self.mode == "r+":
# Make sure the file has modification timestamps
self.attrs["last_modified"] = timestamp()
return self.attrs["last_modified"]
ret... | [
"\n\t\tReturn an ISO8601 timestamp indicating when the file was last modified\n\n\t\tReturns:\n\t\t\tAn ISO8601 timestamp indicating when the file was last modified\n\n\t\tRemarks:\n\t\t\tIf the file has no timestamp, and mode is 'r+', a new timestamp is created and returned.\n\t\t\tOtherwise, the current time in U... |
Please provide a description of the function:def get_changes_since(self, timestamp: str) -> Dict[str, List]:
rg = []
cg = []
ra = []
ca = []
layers = []
if self.last_modified() > timestamp:
if self.row_graphs.last_modified() > timestamp:
for name in self.row_graphs.keys():
if self.row_graphs... | [
"\n\t\tGet a summary of the parts of the file that changed since the given time\n\n\t\tArgs:\n\t\t\ttimestamp:\tISO8601 timestamp\n\n\t\tReturn:\n\t\t\tdict:\tDictionary like ``{\"row_graphs\": rg, \"col_graphs\": cg, \"row_attrs\": ra, \"col_attrs\": ca, \"layers\": layers}`` listing the names of objects that were... |
Please provide a description of the function:def sparse(self, rows: np.ndarray = None, cols: np.ndarray = None, layer: str = None) -> scipy.sparse.coo_matrix:
if layer is None:
return self.layers[""].sparse(rows=rows, cols=cols)
else:
return self.layers[layer].sparse(rows=rows, cols=cols) | [
"\n\t\tReturn the main matrix or specified layer as a scipy.sparse.coo_matrix, without loading dense matrix in RAM\n\n\t\tArgs:\n\t\t\trows:\t\tRows to include, or None to include all\n\t\t\tcols:\t\tColumns to include, or None to include all\n\t\t\tlayer:\t\tLayer to return, or None to return the default layer\n\n... |
Please provide a description of the function:def close(self, suppress_warning: bool = False) -> None:
if self._file is None:
if not suppress_warning:
# Warn user that they're being paranoid
# and should clean up their code
logging.warn("Connection to %s is already closed", self.filename)
else:
... | [
"\n\t\tClose the connection. After this, the connection object becomes invalid. Warns user if called after closing.\n\n\t\tArgs:\n\t\t\tsuppress_warning:\t\tSuppresses warning message if True (defaults to false)\n\t\t"
] |
Please provide a description of the function:def set_layer(self, name: str, matrix: np.ndarray, chunks: Tuple[int, int] = (64, 64), chunk_cache: int = 512, dtype: str = "float32", compression_opts: int = 2) -> None:
deprecated("'set_layer' is deprecated. Use 'ds.layer.Name = matrix' or 'ds.layer['Name'] = matrix' ... | [
"\n\t\t**DEPRECATED** - Use `ds.layer.Name = matrix` or `ds.layer[`Name`] = matrix` instead\n\t\t"
] |
Please provide a description of the function:def add_columns(self, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], col_attrs: Dict[str, np.ndarray], *, row_attrs: Dict[str, np.ndarray] = None, fill_values: Dict[str, np.ndarray] = None) -> None:
if self._file.mode != "r+":
raise IOError("C... | [
"\n\t\tAdd columns of data and attribute values to the dataset.\n\n\t\tArgs:\n\t\t\tlayers (dict or numpy.ndarray or LayerManager):\n\t\t\t\tEither:\n\t\t\t\t1) A N-by-M matrix of float32s (N rows, M columns) in this case columns are added at the default layer\n\t\t\t\t2) A dict {layer_name : matrix} specified so t... |
Please provide a description of the function:def add_loom(self, other_file: str, key: str = None, fill_values: Dict[str, np.ndarray] = None, batch_size: int = 1000, convert_attrs: bool = False, include_graphs: bool = False) -> None:
if self._file.mode != "r+":
raise IOError("Cannot add data when connected in re... | [
"\n\t\tAdd the content of another loom file\n\n\t\tArgs:\n\t\t\tother_file: filename of the loom file to append\n\t\t\tkey: Primary key to use to align rows in the other file with this file\n\t\t\tfill_values: default values to use for missing attributes (or None to drop missing attrs, ... |
Please provide a description of the function:def delete_attr(self, name: str, axis: int = 0) -> None:
deprecated("'delete_attr' is deprecated. Use 'del ds.ra.key' or 'del ds.ca.key' instead")
if axis == 0:
del self.ra[name]
else:
del self.ca[name] | [
"\n\t\t**DEPRECATED** - Use `del ds.ra.key` or `del ds.ca.key` instead, where `key` is replaced with the attribute name\n\t\t"
] |
Please provide a description of the function:def set_attr(self, name: str, values: np.ndarray, axis: int = 0, dtype: str = None) -> None:
deprecated("'set_attr' is deprecated. Use 'ds.ra.key = values' or 'ds.ca.key = values' instead")
if axis == 0:
self.ra[name] = values
else:
self.ca[name] = values | [
"\n\t\t**DEPRECATED** - Use `ds.ra.key = values` or `ds.ca.key = values` instead\n\t\t"
] |
Please provide a description of the function:def list_edges(self, *, axis: int) -> List[str]:
deprecated("'list_edges' is deprecated. Use 'ds.row_graphs.keys()' or 'ds.col_graphs.keys()' instead")
if axis == 0:
return self.row_graphs.keys()
elif axis == 1:
return self.col_graphs.keys()
else:
return ... | [
"\n\t\t**DEPRECATED** - Use `ds.row_graphs.keys()` or `ds.col_graphs.keys()` instead\n\t\t"
] |
Please provide a description of the function:def get_edges(self, name: str, *, axis: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
deprecated("'get_edges' is deprecated. Use 'ds.row_graphs[name]' or 'ds.col_graphs[name]' instead")
if axis == 0:
g = self.row_graphs[name]
return (g.row, g.col, g.data)
... | [
"\n\t\t**DEPRECATED** - Use `ds.row_graphs[name]` or `ds.col_graphs[name]` instead\n\t\t"
] |
Please provide a description of the function:def set_edges(self, name: str, a: np.ndarray, b: np.ndarray, w: np.ndarray, *, axis: int) -> None:
deprecated("'set_edges' is deprecated. Use 'ds.row_graphs[name] = g' or 'ds.col_graphs[name] = g' instead")
try:
g = scipy.sparse.coo_matrix((w, (a, b)), (self.shape[... | [
"\n\t\t**DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead\n\t\t"
] |
Please provide a description of the function:def scan(self, *, items: np.ndarray = None, axis: int = None, layers: Iterable = None, key: str = None, batch_size: int = 8 * 64) -> Iterable[Tuple[int, np.ndarray, loompy.LoomView]]:
if axis is None:
raise ValueError("Axis must be given (0 = rows, 1 = cols)")
if l... | [
"\n\t\tScan across one axis and return batches of rows (columns) as LoomView objects\n\n\t\tArgs\n\t\t----\n\t\titems: np.ndarray\n\t\t\tthe indexes [0, 2, 13, ... ,973] of the rows/cols to include along the axis\n\t\t\tOR: boolean mask array giving the rows/cols to include\n\t\taxis: int\n\t\t\t0:rows or 1:cols\n\... |
Please provide a description of the function:def batch_scan(self, cells: np.ndarray = None, genes: np.ndarray = None, axis: int = 0, batch_size: int = 1000, layer: str = None) -> Iterable[Tuple[int, np.ndarray, np.ndarray]]:
deprecated("'batch_scan' is deprecated. Use 'scan' instead")
if cells is None:
cells ... | [
"\n\t\t**DEPRECATED** - Use `scan` instead\n\t\t"
] |
Please provide a description of the function:def batch_scan_layers(self, cells: np.ndarray = None, genes: np.ndarray = None, axis: int = 0, batch_size: int = 1000, layers: Iterable = None) -> Iterable[Tuple[int, np.ndarray, Dict]]:
deprecated("'batch_scan_layers' is deprecated. Use 'scan' instead")
if cells is N... | [
"\n\t\t**DEPRECATED** - Use `scan` instead\n\t\t"
] |
Please provide a description of the function:def map(self, f_list: List[Callable[[np.ndarray], int]], *, axis: int = 0, chunksize: int = 1000, selection: np.ndarray = None) -> List[np.ndarray]:
return self.layers[""].map(f_list, axis, chunksize, selection) | [
"\n\t\tApply a function along an axis without loading the entire dataset in memory.\n\n\t\tArgs:\n\t\t\tf:\t\tFunction(s) that takes a numpy ndarray as argument\n\n\t\t\taxis:\t\tAxis along which to apply the function (0 = rows, 1 = columns)\n\n\t\t\tchunksize: Number of rows (columns) to load per chunk\n\n\t\t\tse... |
Please provide a description of the function:def permute(self, ordering: np.ndarray, axis: int) -> None:
if self._file.__contains__("tiles"):
del self._file['tiles']
ordering = list(np.array(ordering).flatten()) # Flatten the ordering, in case we got a column vector
self.layers._permute(ordering, axis=axi... | [
"\n\t\tPermute the dataset along the indicated axis.\n\n\t\tArgs:\n\t\t\tordering (list of int): \tThe desired order along the axis\n\n\t\t\taxis (int):\t\t\t\t\tThe axis along which to permute\n\n\t\tReturns:\n\t\t\tNothing.\n\t\t"
] |
Please provide a description of the function:def pandas(self, row_attr: str = None, selector: Union[List, Tuple, np.ndarray, slice] = None, columns: List[str] = None) -> pd.DataFrame:
if columns is None:
columns = [x for x in self.ca.keys()]
data: Dict[str, np.ndarray] = {}
for col in columns:
vals = se... | [
"\n\t\tCreate a Pandas DataFrame corresponding to (selected parts of) the Loom file.\n\n\t\tArgs:\n\t\t\trow_attr:\tName of the row attribute to use for selecting rows to include (or None to omit row data)\n\t\t\tselector:\tA list, a tuple, a numpy.ndarray or a slice; used to select rows (or None to include all row... |
Please provide a description of the function:def aggregate(self, out_file: str = None, select: np.ndarray = None, group_by: Union[str, np.ndarray] = "Clusters", aggr_by: str = "mean", aggr_ca_by: Dict[str, str] = None) -> np.ndarray:
ca = {} # type: Dict[str, np.ndarray]
if select is not None:
raise ValueErr... | [
"\n\t\tAggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes\n\n\t\tArgs:\n\t\t\tout_file\tThe name of the output Loom file (will be appended to if it exists)\n\t\t\tselect\t\tBool array giving the columns to include (or None, to include all)\n\t\t\tgroup_b... |
Please provide a description of the function:def export(self, out_file: str, layer: str = None, format: str = "tab") -> None:
if format != "tab":
raise NotImplementedError("Only 'tab' is supported")
with open(out_file, "w") as f:
# Emit column attributes
for ca in self.col_attrs.keys():
for ra in s... | [
"\n\t\tExport the specified layer and row/col attributes as tab-delimited file.\n\n\t\tArgs:\n\t\t\tout_file:\tPath to the output file\n\t\t\tlayer:\tName of the layer to export, or None to export the main matrix\n\t\t\tformat: Desired file format (only 'tab' is supported)\n\t\t"
] |
Please provide a description of the function:def get(self, name: str, default: Any = None) -> np.ndarray:
if name in self:
return self[name]
else:
return default | [
"\n\t\tReturn the value for a named attribute if it exists, else default.\n\t\tIf default is not given, it defaults to None, so that this method never raises a KeyError.\n\t\t"
] |
Please provide a description of the function:def last_modified(self, name: str = None) -> str:
if name is not None:
return self[name].last_modified()
ts = ""
for name in self.keys():
if ts is None:
ts = self[name].last_modified()
else:
if self[name].last_modified() > ts:
ts = self[name].l... | [
"\n\t\tReturn a compact ISO8601 timestamp (UTC timezone) indicating when the layer was last modified\n\n\t\tNote: if name is None, the modification time of the most recently modified layer is returned\n\t\t"
] |
Please provide a description of the function:def cat_colors(N: int = 1, *, hue: str = None, luminosity: str = None, bgvalue: int = None, loop: bool = False, seed: str = "cat") -> Union[List[Any], colors.LinearSegmentedColormap]:
c: List[str] = []
if N <= 25 and hue is None and luminosity is None:
c = _color_alpha... | [
"\n\tReturn a colormap suitable for N categorical values, optimized to be both aesthetically pleasing and perceptually distinct.\n\n\tArgs:\n\t\tN\t\t\tThe number of colors requested.\n\t\thue\t\t\tControls the hue of the generated color. You can pass a string representing a color name: \"red\", \"orange\", \"yello... |
Please provide a description of the function:def _renumber(a: np.ndarray, keys: np.ndarray, values: np.ndarray) -> np.ndarray:
ordering = np.argsort(keys)
keys = keys[ordering]
values = keys[ordering]
index = np.digitize(a.ravel(), keys, right=True)
return(values[index].reshape(a.shape)) | [
"\n\tRenumber 'a' by replacing any occurrence of 'keys' by the corresponding 'values'\n\t"
] |
Please provide a description of the function:def validate(self, path: str, strictness: str = "speconly") -> bool:
valid1 = True
with h5py.File(path, mode="r") as f:
valid1 = self.validate_spec(f)
if not valid1:
self.errors.append("For help, see http://linnarssonlab.org/loompy/format/")
valid2 = True... | [
"\n\t\tValidate a file for conformance to the Loom specification\n\n\t\tArgs:\n\t\t\tpath: \t\t\tFull path to the file to be validated\n\t\t\tstrictness:\t\t\"speconly\" or \"conventions\"\n\n\t\tRemarks:\n\t\t\tIn \"speconly\" mode, conformance is assessed relative to the file format specification\n\t\t\tat http:/... |
Please provide a description of the function:def validate_conventions(self, ds: loompy.LoomConnection) -> bool:
(n_genes, n_cells) = ds.shape
self._warn("Description" in ds.attrs, "Optional global attribute 'Description' is missing")
self._warn("Journal" in ds.attrs, "Optional global attribute 'Journal' is mi... | [
"\n\t\tValidate the LoomConnection object against the attribute name/dtype conventions.\n\n\t\tArgs:\n\t\t\tds:\t\t\tLoomConnection object\n\t\t\n\t\tReturns:\n\t\t\tTrue if the file conforms to the conventions, else False\n\t\t\n\t\tRemarks:\n\t\t\tUpon return, the instance attributes 'self.errors' and 'self.warni... |
Please provide a description of the function:def validate_spec(self, file: h5py.File) -> bool:
matrix_types = ["float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"]
vertex_types = ["int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"]
wei... | [
"\n\t\tValidate the LoomConnection object against the format specification.\n\n\t\tArgs:\n\t\t\tfile:\t\t\th5py File object\n\t\t\n\t\tReturns:\n\t\t\tTrue if the file conforms to the specs, else False\n\t\t\n\t\tRemarks:\n\t\t\tUpon return, the instance attributes 'self.errors' and 'self.warnings' contain\n\t\t\tl... |
Please provide a description of the function:def last_modified(self, name: str = None) -> str:
a = ["/row_attrs/", "/col_attrs/"][self.axis]
if self.ds is not None:
if name is None:
if "last_modified" in self.ds._file[a].attrs:
return self.ds._file[a].attrs["last_modified"]
elif self.ds._file.mo... | [
"\n\t\tReturn a compact ISO8601 timestamp (UTC timezone) indicating when an attribute was last modified\n\n\t\tNote: if no attribute name is given (the default), the modification time of the most recently modified attribute will be returned\n\t\tNote: if the attributes do not contain a timestamp, and the mode is 'r... |
Please provide a description of the function:def _permute(self, ordering: np.ndarray) -> None:
for key in self.keys():
self[key] = self[key][ordering] | [
"\n\t\tPermute all the attributes in the collection\n\n\t\tRemarks:\n\t\t\tThis permutes the order of the values for each attribute in the file\n\t\t"
] |
Please provide a description of the function:def get(self, name: str, default: np.ndarray) -> np.ndarray:
if name in self:
return self[name]
else:
if not isinstance(default, np.ndarray):
raise ValueError(f"Default must be an np.ndarray with exactly {self.ds.shape[self.axis]} values")
if default.sh... | [
"\n\t\tReturn the value for a named attribute if it exists, else default.\n\t\tDefault has to be a numpy array of correct size.\n\t\t"
] |
Please provide a description of the function:def normalize_attr_strings(a: np.ndarray) -> np.ndarray:
if np.issubdtype(a.dtype, np.object_):
# if np.all([type(x) is str for x in a]) or np.all([type(x) is np.str_ for x in a]) or np.all([type(x) is np.unicode_ for x in a]):
if np.all([(type(x) is str or type(x) is... | [
"\n\tTake an np.ndarray of all kinds of string-like elements, and return an array of ascii (np.string_) objects\n\t"
] |
Please provide a description of the function:def normalize_attr_array(a: Any) -> np.ndarray:
if type(a) is np.ndarray:
return a
elif type(a) is np.matrix:
if a.shape[0] == 1:
return np.array(a)[0, :]
elif a.shape[1] == 1:
return np.array(a)[:, 0]
else:
raise ValueError("Attribute values must be 1-d... | [
"\n\tTake all kinds of array-like inputs and normalize to a one-dimensional np.ndarray\n\t"
] |
Please provide a description of the function:def normalize_attr_values(a: Any) -> np.ndarray:
scalar = False
if np.isscalar(a):
a = np.array([a])
scalar = True
arr = normalize_attr_array(a)
if np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating):
pass # We allow all these types
el... | [
"\n\tTake all kinds of input values and validate/normalize them.\n\t\n\tArgs:\n\t\ta\tList, tuple, np.matrix, np.ndarray or sparse matrix\n\t\t\tElements can be strings, numbers or bools\n\t\n\tReturns\n\t\ta_normalized An np.ndarray with elements conforming to one of the valid Loom attribute types\n\t\n\tRemark... |
Please provide a description of the function:def to_html(ds: Any) -> str:
rm = min(10, ds.shape[0])
cm = min(10, ds.shape[1])
html = "<p>"
if ds.attrs.__contains__("title"):
html += "<strong>" + ds.attrs["title"] + "</strong> "
html += f"{ds.shape[0]} rows, {ds.shape[1]} columns, {len(ds.layers)} layer{'s' if ... | [
"\n\tReturn an HTML representation of the loom file or view, showing the upper-left 10x10 corner.\n\t"
] |
Please provide a description of the function:def permute(self, ordering: np.ndarray, *, axis: int) -> None:
if axis not in (0, 1):
raise ValueError("Axis must be 0 (rows) or 1 (columns)")
for layer in self.layers.values():
layer._permute(ordering, axis=axis)
if axis == 0:
if self.row_graphs is not Non... | [
"\n\t\tPermute the view, by permuting its layers, attributes and graphs\n\n\t\tArgs:\n\t\t\tordering (np.ndarray):\tThe desired ordering along the axis\n\t\t\taxis (int):\t\t\t\t0, permute rows; 1, permute columns\n\t\t"
] |
Please provide a description of the function:def sparse(self, rows: np.ndarray, cols: np.ndarray) -> scipy.sparse.coo_matrix:
return scipy.sparse.coo_matrix(self.values[rows, :][:, cols]) | [
"\n\t\tReturn the layer as :class:`scipy.sparse.coo_matrix`\n\t\t"
] |
Please provide a description of the function:def permute(self, ordering: np.ndarray, *, axis: int) -> None:
if axis == 0:
self.values = self.values[ordering, :]
elif axis == 1:
self.values = self.values[:, ordering]
else:
raise ValueError("axis must be 0 or 1") | [
"\n\t\tPermute the layer along an axis\n\n\t\tArgs:\n\t\t\taxis: The axis to permute (0, permute the rows; 1, permute the columns)\n\t\t\tordering: The permutation vector\n\t\t"
] |
Please provide a description of the function:def _resize(self, size: Tuple[int, int], axis: int = None) -> None:
if self.name == "":
self.ds._file['/matrix'].resize(size, axis)
else:
self.ds._file['/layers/' + self.name].resize(size, axis) | [
"Resize the dataset, or the specified axis.\n\n\t\tThe dataset must be stored in chunked format; it can be resized up to the \"maximum shape\" (keyword maxshape) specified at creation time.\n\t\tThe rank of the dataset cannot be changed.\n\t\t\"Size\" should be a shape tuple, or if an axis is specified, an integer.... |
Please provide a description of the function:def map(self, f_list: List[Callable[[np.ndarray], int]], axis: int = 0, chunksize: int = 1000, selection: np.ndarray = None) -> List[np.ndarray]:
if hasattr(f_list, '__call__'):
raise ValueError("f_list must be a list of functions, not a function itself")
result =... | [
"\n\t\tApply a function along an axis without loading the entire dataset in memory.\n\n\t\tArgs:\n\t\t\tf_list (list of func):\t\tFunction(s) that takes a numpy ndarray as argument\n\n\t\t\taxis (int):\t\tAxis along which to apply the function (0 = rows, 1 = columns)\n\n\t\t\tchunksize (int): Number of rows (column... |
Please provide a description of the function:def is_datafile_valid(datafile):
try:
datafile_json = json.loads(datafile)
except:
return False
try:
jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
except:
return False
return True | [
" Given a datafile determine if it is valid or not.\n\n Args:\n datafile: JSON string representing the project.\n\n Returns:\n Boolean depending upon whether datafile is valid or not.\n "
] |
Please provide a description of the function:def is_user_profile_valid(user_profile):
if not user_profile:
return False
if not type(user_profile) is dict:
return False
if UserProfile.USER_ID_KEY not in user_profile:
return False
if UserProfile.EXPERIMENT_BUCKET_MAP_KEY not in user_profile:
... | [
" Determine if provided user profile is valid or not.\n\n Args:\n user_profile: User's profile which needs to be validated.\n\n Returns:\n Boolean depending upon whether profile is valid or not.\n "
] |
Please provide a description of the function:def is_attribute_valid(attribute_key, attribute_value):
if not isinstance(attribute_key, string_types):
return False
if isinstance(attribute_value, (string_types, bool)):
return True
if isinstance(attribute_value, (numbers.Integral, float)):
return is... | [
" Determine if given attribute is valid.\n\n Args:\n attribute_key: Variable which needs to be validated\n attribute_value: Variable which needs to be validated\n\n Returns:\n False if attribute_key is not a string\n False if attribute_value is not one of the supported attribute types\n True otherw... |
Please provide a description of the function:def is_finite_number(value):
if not isinstance(value, (numbers.Integral, float)):
# numbers.Integral instead of int to accomodate long integer in python 2
return False
if isinstance(value, bool):
# bool is a subclass of int
return False
if isinst... | [
" Validates if the given value is a number, enforces\n absolute limit of 2^53 and restricts NAN, INF, -INF.\n\n Args:\n value: Value to be validated.\n\n Returns:\n Boolean: True if value is a number and not NAN, INF, -INF or\n greater than absolute limit of 2^53 else False.\n "
] |
Please provide a description of the function:def are_values_same_type(first_val, second_val):
first_val_type = type(first_val)
second_val_type = type(second_val)
# use isinstance to accomodate Python 2 unicode and str types.
if isinstance(first_val, string_types) and isinstance(second_val, string_types):
... | [
" Method to verify that both values belong to same type. Float and integer are\n considered as same type.\n\n Args:\n first_val: Value to validate.\n second_Val: Value to validate.\n\n Returns:\n Boolean: True if both values belong to same type. Otherwise False.\n "
] |
Please provide a description of the function:def reset_logger(name, level=None, handler=None):
# Make the logger and set its level.
if level is None:
level = logging.INFO
logger = logging.getLogger(name)
logger.setLevel(level)
# Make the handler and attach it.
handler = handler or logging.StreamHand... | [
"\n Make a standard python logger object with default formatter, handler, etc.\n\n Defaults are:\n - level == logging.INFO\n - handler == logging.StreamHandler()\n\n Args:\n name: a logger name.\n level: an optional initial log level for this logger.\n handler: an optional initial handler for this... |
Please provide a description of the function:def adapt_logger(logger):
if isinstance(logger, logging.Logger):
return logger
# Use the standard python logger created by these classes.
if isinstance(logger, (SimpleLogger, NoOpLogger)):
return logger.logger
# Otherwise, return whatever we were given b... | [
"\n Adapt our custom logger.BaseLogger object into a standard logging.Logger object.\n\n Adaptations are:\n - NoOpLogger turns into a logger with a single NullHandler.\n - SimpleLogger turns into a logger with a StreamHandler and level.\n\n Args:\n logger: Possibly a logger.BaseLogger, or a standard pyt... |
Please provide a description of the function:def get_variation_for_experiment(self, experiment_id):
return self.experiment_bucket_map.get(experiment_id, {self.VARIATION_ID_KEY: None}).get(self.VARIATION_ID_KEY) | [
" Helper method to retrieve variation ID for given experiment.\n\n Args:\n experiment_id: ID for experiment for which variation needs to be looked up for.\n\n Returns:\n Variation ID corresponding to the experiment. None if no decision available.\n "
] |
Please provide a description of the function:def save_variation_for_experiment(self, experiment_id, variation_id):
self.experiment_bucket_map.update({
experiment_id: {
self.VARIATION_ID_KEY: variation_id
}
}) | [
" Helper method to save new experiment/variation as part of the user's profile.\n\n Args:\n experiment_id: ID for experiment for which the decision is to be stored.\n variation_id: ID for variation that the user saw.\n "
] |
Please provide a description of the function:def get_numeric_value(event_tags, logger=None):
logger_message_debug = None
numeric_metric_value = None
if event_tags is None:
logger_message_debug = 'Event tags is undefined.'
elif not isinstance(event_tags, dict):
logger_message_debug = 'Event tags is ... | [
"\n A smart getter of the numeric value from the event tags.\n\n Args:\n event_tags: A dictionary of event tags.\n logger: Optional logger.\n\n Returns:\n A float numeric metric value is returned when the provided numeric\n metric value is in the following format:\n - A string (prope... |
Please provide a description of the function:def hash( key, seed = 0x0 ):
''' Implements 32bit murmur3 hash. '''
key = bytearray( xencode(key) )
def fmix( h ):
h ^= h >> 16
h = ( h * 0x85ebca6b ) & 0xFFFFFFFF
h ^= h >> 13
h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF
h ^= h... | [] |
Please provide a description of the function:def hash128( key, seed = 0x0, x64arch = True ):
''' Implements 128bit murmur3 hash. '''
def hash128_x64( key, seed ):
''' Implements 128bit murmur3 hash for x64. '''
def fmix( k ):
k ^= k >> 33
k = ( k * 0xff51afd7ed558ccd ) ... | [] |
Please provide a description of the function:def hash64( key, seed = 0x0, x64arch = True ):
''' Implements 64bit murmur3 hash. Returns a tuple. '''
hash_128 = hash128( key, seed, x64arch )
unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF
if unsigned_val1 & 0x8000000000000000 == 0:
signed_val1 = u... | [] |
Please provide a description of the function:def hash_bytes( key, seed = 0x0, x64arch = True ):
''' Implements 128bit murmur3 hash. Returns a byte string. '''
hash_128 = hash128( key, seed, x64arch )
bytestring = ''
for i in xrange(0, 16, 1):
lsbyte = hash_128 & 0xFF
bytestring = byte... | [] |
Please provide a description of the function:def _generate_bucket_value(self, bucketing_id):
ratio = float(self._generate_unsigned_hash_code_32_bit(bucketing_id)) / MAX_HASH_VALUE
return math.floor(ratio * MAX_TRAFFIC_VALUE) | [
" Helper function to generate bucket value in half-closed interval [0, MAX_TRAFFIC_VALUE).\n\n Args:\n bucketing_id: ID for bucketing.\n\n Returns:\n Bucket value corresponding to the provided bucketing ID.\n "
] |
Please provide a description of the function:def find_bucket(self, bucketing_id, parent_id, traffic_allocations):
bucketing_key = BUCKETING_ID_TEMPLATE.format(bucketing_id=bucketing_id, parent_id=parent_id)
bucketing_number = self._generate_bucket_value(bucketing_key)
self.config.logger.debug('Assigne... | [
" Determine entity based on bucket value and traffic allocations.\n\n Args:\n bucketing_id: ID to be used for bucketing the user.\n parent_id: ID representing group or experiment.\n traffic_allocations: Traffic allocations representing traffic allotted to experiments or variations.\n\n Returns:... |
Please provide a description of the function:def bucket(self, experiment, user_id, bucketing_id):
if not experiment:
return None
# Determine if experiment is in a mutually exclusive group
if experiment.groupPolicy in GROUP_POLICIES:
group = self.config.get_group(experiment.groupId)
... | [
" For a given experiment and bucketing ID determines variation to be shown to user.\n\n Args:\n experiment: Object representing the experiment for which user is to be bucketed.\n user_id: ID for user.\n bucketing_id: ID to be used for bucketing the user.\n\n Returns:\n Variation in which u... |
Please provide a description of the function:def _generate_key_map(entity_list, key, entity_class):
key_map = {}
for obj in entity_list:
key_map[obj[key]] = entity_class(**obj)
return key_map | [
" Helper method to generate map from key to entity object for given list of dicts.\n\n Args:\n entity_list: List consisting of dict.\n key: Key in each dict which will be key in the map.\n entity_class: Class representing the entity.\n\n Returns:\n Map mapping key to entity object.\n "
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.