_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q17800 | NeighbourMovementTracking.calculate_costs | train | def calculate_costs(self, detections_1, detections_2, calculate_match_cost, params):
"""
Calculates assignment costs between detections and 'empty' spaces. The smaller cost the better.
@param detections_1: cell list of size n in previous frame
@param detections_2: cell list of size m in... | python | {
"resource": ""
} |
q17801 | NeighbourMovementTracking.solve_assignement | train | def solve_assignement(self, costs):
"""
Solves assignment problem using Hungarian implementation by Brian M. Clapper.
@param costs: square cost matrix
@return: assignment function
@rtype: int->int
"""
if costs is None or len(costs) == 0:
return dict... | python | {
"resource": ""
} |
q17802 | circular_gaussian_kernel | train | def circular_gaussian_kernel(sd,radius):
"""Create a 2-d Gaussian convolution kernel
sd - standard deviation of the gaussian in pixels
radius - build a circular kernel that convolves all points in the circle
bounded by this radius
"""
i,j = np.mgrid[-radius:radius+1,-radius:ra... | python | {
"resource": ""
} |
q17803 | get_threshold | train | def get_threshold(threshold_method, threshold_modifier, image,
mask=None, labels = None,
threshold_range_min = None, threshold_range_max = None,
threshold_correction_factor = 1.0,
adaptive_window_size = 10, **kwargs):
"""Compute a threshold fo... | python | {
"resource": ""
} |
q17804 | get_global_threshold | train | def get_global_threshold(threshold_method, image, mask = None, **kwargs):
"""Compute a single threshold over the whole image"""
if mask is not None and not np.any(mask):
return 1
if threshold_method == TM_OTSU:
fn = get_otsu_threshold
elif threshold_method == TM_MOG:
fn = ge... | python | {
"resource": ""
} |
q17805 | get_per_object_threshold | train | def get_per_object_threshold(method, image, threshold, mask=None, labels=None,
threshold_range_min = None,
threshold_range_max = None,
**kwargs):
"""Return a matrix giving threshold per pixel calculated per-object
image ... | python | {
"resource": ""
} |
q17806 | mad | train | def mad(a):
'''Calculate the median absolute deviation of a sample
a - a numpy array-like collection of values
returns the median of the deviation of a from its median.
'''
a = np.asfarray(a).flatten()
return np.median(np.abs(a - np.median(a))) | python | {
"resource": ""
} |
q17807 | get_kapur_threshold | train | def get_kapur_threshold(image, mask=None):
"""The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space."""
cropped_image = np.array(image.flat) if mask is None else image[mask]
if np.product(cropped_image.shape)<3:
return 0
if np.min(cropped_image) == np.max(cropped_image):
... | python | {
"resource": ""
} |
q17808 | weighted_variance | train | def weighted_variance(image, mask, binary_image):
"""Compute the log-transformed variance of foreground and background
image - intensity image used for thresholding
mask - mask of ignored pixels
binary_image - binary image marking foreground and background
"""
if not np.any(mask):... | python | {
"resource": ""
} |
q17809 | sum_of_entropies | train | def sum_of_entropies(image, mask, binary_image):
"""Bin the foreground and background pixels and compute the entropy
of the distribution of points among the bins
"""
mask=mask.copy()
mask[np.isnan(image)] = False
if not np.any(mask):
return 0
#
# Clamp the dynamic range of the f... | python | {
"resource": ""
} |
q17810 | log_transform | train | def log_transform(image):
'''Renormalize image intensities to log space
Returns a tuple of transformed image and a dictionary to be passed into
inverse_log_transform. The minimum and maximum from the dictionary
can be applied to an image by the inverse_log_transform to
convert it back to its f... | python | {
"resource": ""
} |
q17811 | numpy_histogram | train | def numpy_histogram(a, bins=10, range=None, normed=False, weights=None):
'''A version of numpy.histogram that accounts for numpy's version'''
args = inspect.getargs(np.histogram.__code__)[0]
if args[-1] == "new":
return np.histogram(a, bins, range, normed, weights, new=True)
return np.histogram(... | python | {
"resource": ""
} |
q17812 | rank_order | train | def rank_order(image, nbins=None):
"""Return an image of the same shape where each pixel has the
rank-order value of the corresponding pixel in the image.
The returned image's elements are of type np.uint32 which
simplifies processing in C code.
"""
flat_image = image.ravel()
sort_order = fl... | python | {
"resource": ""
} |
q17813 | quantize | train | def quantize(image, nlevels):
"""Quantize an image into integers 0, 1, ..., nlevels - 1.
image -- a numpy array of type float, range [0, 1]
nlevels -- an integer
"""
tmp = np.array(image // (1.0 / nlevels), dtype='i1')
return tmp.clip(0, nlevels - 1) | python | {
"resource": ""
} |
q17814 | cooccurrence | train | def cooccurrence(quantized_image, labels, scale_i=3, scale_j=0):
"""Calculates co-occurrence matrices for all the objects in the image.
Return an array P of shape (nobjects, nlevels, nlevels) such that
P[o, :, :] is the cooccurence matrix for object o.
quantized_image -- a numpy array of integer type
... | python | {
"resource": ""
} |
q17815 | Haralick.H5 | train | def H5(self):
"Inverse difference moment."
t = 1 + toeplitz(self.levels) ** 2
repeated = np.tile(t[np.newaxis], (self.nobjects, 1, 1))
return (1.0 / repeated * self.P).sum(2).sum(1) | python | {
"resource": ""
} |
q17816 | Haralick.H6 | train | def H6(self):
"Sum average."
if not hasattr(self, '_H6'):
self._H6 = ((self.rlevels2 + 2) * self.p_xplusy).sum(1)
return self._H6 | python | {
"resource": ""
} |
q17817 | Haralick.H8 | train | def H8(self):
"Sum entropy."
return -(self.p_xplusy * np.log(self.p_xplusy + self.eps)).sum(1) | python | {
"resource": ""
} |
q17818 | Haralick.H10 | train | def H10(self):
"Difference variance."
c = (self.rlevels * self.p_xminusy).sum(1)
c1 = np.tile(c, (self.nlevels,1)).transpose()
e = self.rlevels - c1
return (self.p_xminusy * e ** 2).sum(1) | python | {
"resource": ""
} |
q17819 | Haralick.H11 | train | def H11(self):
"Difference entropy."
return -(self.p_xminusy * np.log(self.p_xminusy + self.eps)).sum(1) | python | {
"resource": ""
} |
q17820 | Haralick.H12 | train | def H12(self):
"Information measure of correlation 1."
maxima = np.vstack((self.hx, self.hy)).max(0)
return (self.H9() - self.hxy1) / maxima | python | {
"resource": ""
} |
q17821 | Haralick.H13 | train | def H13(self):
"Information measure of correlation 2."
# An imaginary result has been encountered once in the Matlab
# version. The reason is unclear.
return np.sqrt(1 - np.exp(-2 * (self.hxy2 - self.H9()))) | python | {
"resource": ""
} |
q17822 | construct_zernike_lookuptable | train | def construct_zernike_lookuptable(zernike_indexes):
"""Return a lookup table of the sum-of-factorial part of the radial
polynomial of the zernike indexes passed
zernike_indexes - an Nx2 array of the Zernike polynomials to be
computed.
"""
n_max = np.max(zernike_indexes[:,0... | python | {
"resource": ""
} |
q17823 | score_zernike | train | def score_zernike(zf, radii, labels, indexes=None):
"""Score the output of construct_zernike_polynomials
zf - the output of construct_zernike_polynomials which is I x J x K
where K is the number of zernike polynomials computed
radii - a vector of the radius of each of N labeled objects
lab... | python | {
"resource": ""
} |
q17824 | slow_augmenting_row_reduction | train | def slow_augmenting_row_reduction(n, ii, jj, idx, count, x, y, u, v, c):
'''Perform the augmenting row reduction step from the Jonker-Volgenaut algorithm
n - the number of i and j in the linear assignment problem
ii - the unassigned i
jj - the j-index of every entry in c
idx - the index of the ... | python | {
"resource": ""
} |
q17825 | collapse_degenerate_markers | train | def collapse_degenerate_markers(linkage_records):
"""Group all markers with no genetic distance as distinct features
to generate a BED file with.
Simple example with sixteen degenerate markers:
>>> marker_features = [
... ['36915_sctg_207_31842', 1, 0, 207, 31842],
... ['36941_sct... | python | {
"resource": ""
} |
q17826 | linkage_group_ordering | train | def linkage_group_ordering(linkage_records):
"""Convert degenerate linkage records into ordered info_frags-like records
for comparison purposes.
Simple example:
>>> linkage_records = [
... ['linkage_group_1', 31842, 94039, 'sctg_207'],
... ['linkage_group_1', 95303, 95303, 'sctg_20... | python | {
"resource": ""
} |
q17827 | compare_orderings | train | def compare_orderings(info_frags_records, linkage_orderings):
"""Given linkage groups and info_frags records, link pseudo-chromosomes to
scaffolds based on the initial contig composition of each group. Because
info_frags records are usually richer and may contain contigs not found
in linkage groups, th... | python | {
"resource": ""
} |
q17828 | get_missing_blocks | train | def get_missing_blocks(info_frags_records, matching_pairs, linkage_orderings):
"""Get missing blocks in a scaffold based on the genetic map order.
Given matching scaffold blocks/genetic map blocks (based on restriction
sites and SNP markers, respectively), move around the scaffold blocks
such that the... | python | {
"resource": ""
} |
q17829 | parse_info_frags | train | def parse_info_frags(info_frags):
"""Import an info_frags.txt file and return a dictionary where each key
is a newly formed scaffold and each value is the list of bins and their
origin on the initial scaffolding.
"""
new_scaffolds = {}
with open(info_frags, "r") as info_frags_handle:
cu... | python | {
"resource": ""
} |
q17830 | format_info_frags | train | def format_info_frags(info_frags):
"""A function to seamlessly run on either scaffold dictionaries or
info_frags.txt files without having to check the input first.
"""
if isinstance(info_frags, dict):
return info_frags
else:
try:
scaffolds = parse_info_frags(info_frags)
... | python | {
"resource": ""
} |
q17831 | plot_info_frags | train | def plot_info_frags(scaffolds):
"""A crude way to visualize new scaffolds according to their origin on the
initial scaffolding. Each scaffold spawns a new plot. Orientations are
represented by different colors.
"""
scaffolds = format_info_frags(scaffolds)
for name, scaffold in scaffolds.items(... | python | {
"resource": ""
} |
q17832 | remove_spurious_insertions | train | def remove_spurious_insertions(scaffolds):
"""Remove all bins whose left and right neighbors belong to the same,
different scaffold.
Example with three such insertions in two different scaffolds:
>>> scaffolds = {
... "scaffold1": [
... ["contig1", 0, 0, 100, 1],
... | python | {
"resource": ""
} |
q17833 | rearrange_intra_scaffolds | train | def rearrange_intra_scaffolds(scaffolds):
"""Rearranges all bins within each scaffold such that all bins belonging
to the same initial contig are grouped together in the same order. When
two such groups are found, the smaller one is moved to the larger one.
"""
scaffolds = format_info_frags(scaffo... | python | {
"resource": ""
} |
q17834 | write_fasta | train | def write_fasta(
init_fasta, info_frags, output=DEFAULT_NEW_GENOME_NAME, junction=False
):
"""Convert an info_frags.txt file into a fasta file given a reference.
Optionally adds junction sequences to reflect the possibly missing base
pairs between two newly joined scaffolds.
"""
init_genome = ... | python | {
"resource": ""
} |
q17835 | is_block | train | def is_block(bin_list):
"""Check if a bin list has exclusively consecutive bin ids.
"""
id_set = set((my_bin[1] for my_bin in bin_list))
start_id, end_id = min(id_set), max(id_set)
return id_set == set(range(start_id, end_id + 1)) | python | {
"resource": ""
} |
q17836 | internal2external_grad | train | def internal2external_grad(xi, bounds):
"""
Calculate the internal to external gradiant
Calculates the partial of external over internal
"""
ge = np.empty_like(xi)
for i, (v, bound) in enumerate(zip(xi, bounds)):
a = bound[0] # minimum
b = bound[1] # maximum
... | python | {
"resource": ""
} |
q17837 | internal2external | train | def internal2external(xi, bounds):
""" Convert a series of internal variables to external variables"""
xe = np.empty_like(xi)
for i, (v, bound) in enumerate(zip(xi, bounds)):
a = bound[0] # minimum
b = bound[1] # maximum
if a == None and b == None: # No constraints
... | python | {
"resource": ""
} |
q17838 | external2internal | train | def external2internal(xe, bounds):
""" Convert a series of external variables to internal variables"""
xi = np.empty_like(xe)
for i, (v, bound) in enumerate(zip(xe, bounds)):
a = bound[0] # minimum
b = bound[1] # maximum
if a == None and b == None: # No constraints
... | python | {
"resource": ""
} |
q17839 | calc_cov_x | train | def calc_cov_x(infodic, p):
"""
Calculate cov_x from fjac, ipvt and p as is done in leastsq
"""
fjac = infodic["fjac"]
ipvt = infodic["ipvt"]
n = len(p)
# adapted from leastsq function in scipy/optimize/minpack.py
perm = np.take(np.eye(n), ipvt - 1, 0)
r = np.triu(np.transpose(fjac... | python | {
"resource": ""
} |
q17840 | leastsqbound | train | def leastsqbound(func, x0, bounds, args=(), **kw):
"""
Constrained multivariant Levenberg-Marquard optimization
Minimize the sum of squares of a given function using the
Levenberg-Marquard algorithm. Contraints on parameters are inforced using
variable transformations as described in the MINUIT U... | python | {
"resource": ""
} |
q17841 | GitHubInterface.start_review | train | def start_review(self):
"""Mark our review as started."""
if self.set_status:
self.github_repo.create_status(
state="pending",
description="Static analysis in progress.",
context="inline-plz",
sha=self.last_sha,
) | python | {
"resource": ""
} |
q17842 | GitHubInterface.finish_review | train | def finish_review(self, success=True, error=False):
"""Mark our review as finished."""
if self.set_status:
if error:
self.github_repo.create_status(
state="error",
description="Static analysis error! inline-plz failed to run.",
... | python | {
"resource": ""
} |
q17843 | GitHubInterface.out_of_date | train | def out_of_date(self):
"""Check if our local latest sha matches the remote latest sha"""
try:
latest_remote_sha = self.pr_commits(self.pull_request.refresh(True))[-1].sha
print("Latest remote sha: {}".format(latest_remote_sha))
try:
print("Ratelimit re... | python | {
"resource": ""
} |
q17844 | GitHubInterface.position | train | def position(self, message):
"""Calculate position within the PR, which is not the line number"""
if not message.line_number:
message.line_number = 1
for patched_file in self.patch:
target = patched_file.target_file.lstrip("b/")
if target == message.path:
... | python | {
"resource": ""
} |
q17845 | abs_contact_2_coo_file | train | def abs_contact_2_coo_file(abs_contact_file, coo_file):
"""Convert contact maps between old-style and new-style formats.
A legacy function that converts contact maps from the older GRAAL format to
the simpler instaGRAAL format. This is useful with datasets generated by
Hi-C box.
Parameters
---... | python | {
"resource": ""
} |
q17846 | fill_sparse_pyramid_level | train | def fill_sparse_pyramid_level(pyramid_handle, level, contact_file, nfrags):
"""Fill a level with sparse contact map data
Fill values from the simple text matrix file to the hdf5-based pyramid
level with contact data.
Parameters
----------
pyramid_handle : h5py.File
The hdf5 file ha... | python | {
"resource": ""
} |
q17847 | init_frag_list | train | def init_frag_list(fragment_list, new_frag_list):
"""Adapt the original fragment list to fit the build function requirements
Parameters
----------
fragment_list : str, file or pathlib.Path
The input fragment list.
new_frag_list : str, file or pathlib.Path
The output fragment list to... | python | {
"resource": ""
} |
q17848 | pyramid.zoom_in_pixel | train | def zoom_in_pixel(self, curr_pixel):
""" return the curr_frag at a higher resolution"""
low_frag = curr_pixel[0]
high_frag = curr_pixel[1]
level = curr_pixel[2]
if level > 0:
str_level = str(level)
low_sub_low = self.spec_level[str_level]["fragments_dict"]... | python | {
"resource": ""
} |
q17849 | pyramid.zoom_out_pixel | train | def zoom_out_pixel(self, curr_pixel):
""" return the curr_frag at a lower resolution"""
low_frag = curr_pixel[0]
high_frag = curr_pixel[1]
level = curr_pixel[2]
str_level = str(level)
if level < self.n_level - 1:
low_super = self.spec_level[str_level]["fragmen... | python | {
"resource": ""
} |
q17850 | pyramid.zoom_in_area | train | def zoom_in_area(self, area):
""" zoom in area"""
x = area[0]
y = area[1]
level = x[2]
logger.debug("x = {}".format(x))
logger.debug("y = {}".format(y))
logger.debug("level = {}".format(level))
if level == y[2] and level > 0:
new_level = level ... | python | {
"resource": ""
} |
q17851 | load_config | train | def load_config(args, config_path=".inlineplz.yml"):
"""Load inline-plz config from yaml config file with reasonable defaults."""
config = {}
try:
with open(config_path) as configfile:
config = yaml.safe_load(configfile) or {}
if config:
print("Loaded config f... | python | {
"resource": ""
} |
q17852 | LinterRunner.cleanup | train | def cleanup():
"""Delete standard installation directories."""
for install_dir in linters.INSTALL_DIRS:
try:
shutil.rmtree(install_dir, ignore_errors=True)
except Exception:
print(
"{0}\nFailed to delete {1}".format(
... | python | {
"resource": ""
} |
q17853 | CloudDatabaseManager.get | train | def get(self, item):
"""
This additional code is necessary to properly return the 'volume'
attribute of the instance as a CloudDatabaseVolume object instead of
a raw dict.
"""
resource = super(CloudDatabaseManager, self).get(item)
resource.volume = CloudDatabaseVo... | python | {
"resource": ""
} |
q17854 | CloudDatabaseManager._create_body | train | def _create_body(self, name, flavor=None, volume=None, databases=None,
users=None, version=None, type=None):
"""
Used to create the dict required to create a Cloud Database instance.
"""
if flavor is None:
flavor = 1
flavor_ref = self.api._get_flavor_ref(f... | python | {
"resource": ""
} |
q17855 | CloudDatabaseManager.list_backups | train | def list_backups(self, instance=None, marker=0, limit=20):
"""
Returns a paginated list of backups, or just for a particular
instance.
"""
return self.api._backup_manager.list(instance=instance, limit=limit,
marker=marker) | python | {
"resource": ""
} |
q17856 | CloudDatabaseManager._list_backups_for_instance | train | def _list_backups_for_instance(self, instance, marker=0, limit=20):
"""
Instance-specific backups are handled through the instance manager,
not the backup manager.
"""
uri = "/%s/%s/backups?limit=%d&marker=%d" % (self.uri_base,
... | python | {
"resource": ""
} |
q17857 | CloudDatabaseUserManager.list_user_access | train | def list_user_access(self, user):
"""
Returns a list of all database names for which the specified user
has access rights.
"""
user = utils.get_name(user)
uri = "/%s/%s/databases" % (self.uri_base, user)
try:
resp, resp_body = self.api.method_get(uri)
... | python | {
"resource": ""
} |
q17858 | CloudDatabaseUserManager.grant_user_access | train | def grant_user_access(self, user, db_names, strict=True):
"""
Gives access to the databases listed in `db_names` to the user. You may
pass in either a single db or a list of dbs.
If any of the databases do not exist, a NoSuchDatabase exception will
be raised, unless you specify ... | python | {
"resource": ""
} |
q17859 | CloudDatabaseBackupManager.list | train | def list(self, instance=None, limit=20, marker=0):
"""
Return a paginated list of backups, or just for a particular
instance.
"""
if instance is None:
return super(CloudDatabaseBackupManager, self).list()
return self.api._manager._list_backups_for_instance(ins... | python | {
"resource": ""
} |
q17860 | CloudDatabaseInstance.list_databases | train | def list_databases(self, limit=None, marker=None):
"""Returns a list of the names of all databases for this instance."""
return self._database_manager.list(limit=limit, marker=marker) | python | {
"resource": ""
} |
q17861 | CloudDatabaseInstance.list_users | train | def list_users(self, limit=None, marker=None):
"""Returns a list of the names of all users for this instance."""
return self._user_manager.list(limit=limit, marker=marker) | python | {
"resource": ""
} |
q17862 | CloudDatabaseInstance.get_user | train | def get_user(self, name):
"""
Finds the user in this instance with the specified name, and
returns a CloudDatabaseUser object. If no match is found, a
NoSuchDatabaseUser exception is raised.
"""
try:
return self._user_manager.get(name)
except exc.NotFo... | python | {
"resource": ""
} |
q17863 | CloudDatabaseInstance.get_database | train | def get_database(self, name):
"""
Finds the database in this instance with the specified name, and
returns a CloudDatabaseDatabase object. If no match is found, a
NoSuchDatabase exception is raised.
"""
try:
return [db for db in self.list_databases()
... | python | {
"resource": ""
} |
q17864 | CloudDatabaseInstance.delete_database | train | def delete_database(self, name_or_obj):
"""
Deletes the specified database. If no database by that name
exists, no exception will be raised; instead, nothing at all
is done.
"""
name = utils.get_name(name_or_obj)
self._database_manager.delete(name) | python | {
"resource": ""
} |
q17865 | CloudDatabaseInstance.delete_user | train | def delete_user(self, user):
"""
Deletes the specified user. If no user by that name
exists, no exception will be raised; instead, nothing at all
is done.
"""
name = utils.get_name(user)
self._user_manager.delete(name) | python | {
"resource": ""
} |
q17866 | CloudDatabaseInstance.enable_root_user | train | def enable_root_user(self):
"""
Enables login from any host for the root user and provides
the user with a generated root password.
"""
uri = "/instances/%s/root" % self.id
resp, body = self.manager.api.method_post(uri)
return body["user"]["password"] | python | {
"resource": ""
} |
q17867 | CloudDatabaseInstance.root_user_status | train | def root_user_status(self):
"""
Returns True or False, depending on whether the root user
for this instance has been enabled.
"""
uri = "/instances/%s/root" % self.id
resp, body = self.manager.api.method_get(uri)
return body["rootEnabled"] | python | {
"resource": ""
} |
q17868 | CloudDatabaseInstance.resize | train | def resize(self, flavor):
"""Set the size of this instance to a different flavor."""
# We need the flavorRef, not the flavor or size.
flavorRef = self.manager.api._get_flavor_ref(flavor)
body = {"flavorRef": flavorRef}
self.manager.action(self, "resize", body=body) | python | {
"resource": ""
} |
q17869 | CloudDatabaseInstance.resize_volume | train | def resize_volume(self, size):
"""Changes the size of the volume for this instance."""
curr_size = self.volume.size
if size <= curr_size:
raise exc.InvalidVolumeResize("The new volume size must be larger "
"than the current volume size of '%s'." % curr_size)
... | python | {
"resource": ""
} |
q17870 | CloudDatabaseInstance.list_backups | train | def list_backups(self, limit=20, marker=0):
"""
Returns a paginated list of backups for this instance.
"""
return self.manager._list_backups_for_instance(self, limit=limit,
marker=marker) | python | {
"resource": ""
} |
q17871 | CloudDatabaseInstance.create_backup | train | def create_backup(self, name, description=None):
"""
Creates a backup of this instance, giving it the specified name along
with an optional description.
"""
return self.manager.create_backup(self, name, description=description) | python | {
"resource": ""
} |
q17872 | CloudDatabaseClient.list_databases | train | def list_databases(self, instance, limit=None, marker=None):
"""Returns all databases for the specified instance."""
return instance.list_databases(limit=limit, marker=marker) | python | {
"resource": ""
} |
q17873 | CloudDatabaseClient.create_database | train | def create_database(self, instance, name, character_set=None,
collate=None):
"""Creates a database with the specified name on the given instance."""
return instance.create_database(name, character_set=character_set,
collate=collate) | python | {
"resource": ""
} |
q17874 | CloudDatabaseClient.list_users | train | def list_users(self, instance, limit=None, marker=None):
"""Returns all users for the specified instance."""
return instance.list_users(limit=limit, marker=marker) | python | {
"resource": ""
} |
q17875 | CloudDatabaseClient.grant_user_access | train | def grant_user_access(self, instance, user, db_names, strict=True):
"""
Gives access to the databases listed in `db_names` to the user
on the specified instance.
"""
return instance.grant_user_access(user, db_names, strict=strict) | python | {
"resource": ""
} |
q17876 | CloudDatabaseClient.revoke_user_access | train | def revoke_user_access(self, instance, user, db_names, strict=True):
"""
Revokes access to the databases listed in `db_names` for the user
on the specified instance.
"""
return instance.revoke_user_access(user, db_names, strict=strict) | python | {
"resource": ""
} |
q17877 | CloudDatabaseClient.list_flavors | train | def list_flavors(self, limit=None, marker=None):
"""Returns a list of all available Flavors."""
return self._flavor_manager.list(limit=limit, marker=marker) | python | {
"resource": ""
} |
q17878 | CloudDatabaseClient._get_flavor_ref | train | def _get_flavor_ref(self, flavor):
"""
Flavors are odd in that the API expects an href link, not an ID, as with
nearly every other resource. This method takes either a
CloudDatabaseFlavor object, a flavor ID, a RAM size, or a flavor name,
and uses that to determine the appropriat... | python | {
"resource": ""
} |
q17879 | runproc | train | def runproc(cmd):
"""
Convenience method for executing operating system commands.
Accepts a single string that would be the command as executed on the
command line.
Returns a 2-tuple consisting of the output of (STDOUT, STDERR). In your
code you should check for an empty STDERR output to deter... | python | {
"resource": ""
} |
q17880 | _join_chars | train | def _join_chars(chars, length):
"""
Used by the random character functions.
"""
mult = int(length / len(chars)) + 1
mult_chars = chars * mult
return "".join(random.sample(mult_chars, length)) | python | {
"resource": ""
} |
q17881 | random_unicode | train | def random_unicode(length=20):
"""
Generates a random name; useful for testing.
Returns an encoded string of the specified length containing unicode values
up to code point 1000.
"""
def get_char():
return six.unichr(random.randint(32, 1000))
chars = u"".join([get_char() for ii in s... | python | {
"resource": ""
} |
q17882 | coerce_to_list | train | def coerce_to_list(val):
"""
For parameters that can take either a single string or a list of strings,
this function will ensure that the result is a list containing the passed
values.
"""
if val:
if not isinstance(val, (list, tuple)):
val = [val]
else:
val = []
... | python | {
"resource": ""
} |
q17883 | folder_size | train | def folder_size(pth, ignore=None):
"""
Returns the total bytes for the specified path, optionally ignoring
any files which match the 'ignore' parameter. 'ignore' can either be
a single string pattern, or a list of such patterns.
"""
if not os.path.isdir(pth):
raise exc.FolderNotFound
... | python | {
"resource": ""
} |
q17884 | add_method | train | def add_method(obj, func, name=None):
"""Adds an instance method to an object."""
if name is None:
name = func.__name__
if sys.version_info < (3,):
method = types.MethodType(func, obj, obj.__class__)
else:
method = types.MethodType(func, obj)
setattr(obj, name, method) | python | {
"resource": ""
} |
q17885 | wait_until | train | def wait_until(obj, att, desired, callback=None, interval=5, attempts=0,
verbose=False, verbose_atts=None):
"""
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att... | python | {
"resource": ""
} |
q17886 | _wait_until | train | def _wait_until(obj, att, desired, callback, interval, attempts, verbose,
verbose_atts):
"""
Loops until either the desired value of the attribute is reached, or the
number of attempts is exceeded.
"""
if not isinstance(desired, (list, tuple)):
desired = [desired]
if verbose_atts... | python | {
"resource": ""
} |
q17887 | _parse_datetime_string | train | def _parse_datetime_string(val):
"""
Attempts to parse a string representation of a date or datetime value, and
returns a datetime if successful. If not, a InvalidDateTimeString exception
will be raised.
"""
dt = None
lenval = len(val)
fmt = {19: "%Y-%m-%d %H:%M:%S", 10: "%Y-%m-%d"}.get(... | python | {
"resource": ""
} |
q17888 | rfc2822_format | train | def rfc2822_format(val):
"""
Takes either a date, a datetime, or a string, and returns a string that
represents the value in RFC 2822 format. If a string is passed it is
returned unchanged.
"""
if isinstance(val, six.string_types):
return val
elif isinstance(val, (datetime.datetime, ... | python | {
"resource": ""
} |
q17889 | get_id | train | def get_id(id_or_obj):
"""
Returns the 'id' attribute of 'id_or_obj' if present; if not,
returns 'id_or_obj'.
"""
if isinstance(id_or_obj, six.string_types + (int,)):
# It's an ID
return id_or_obj
try:
return id_or_obj.id
except AttributeError:
return id_or_ob... | python | {
"resource": ""
} |
q17890 | get_name | train | def get_name(name_or_obj):
"""
Returns the 'name' attribute of 'name_or_obj' if present; if not,
returns 'name_or_obj'.
"""
if isinstance(name_or_obj, six.string_types):
# It's a name
return name_or_obj
try:
return name_or_obj.name
except AttributeError:
raise... | python | {
"resource": ""
} |
q17891 | params_to_dict | train | def params_to_dict(params, dct):
"""
Updates the 'dct' dictionary with the 'params' dictionary, filtering out
all those whose param value is None.
"""
for param, val in params.items():
if val is None:
continue
dct[param] = val
return dct | python | {
"resource": ""
} |
q17892 | dict_to_qs | train | def dict_to_qs(dct):
"""
Takes a dictionary and uses it to create a query string.
"""
itms = ["%s=%s" % (key, val) for key, val in list(dct.items())
if val is not None]
return "&".join(itms) | python | {
"resource": ""
} |
q17893 | match_pattern | train | def match_pattern(nm, patterns):
"""
Compares `nm` with the supplied patterns, and returns True if it matches
at least one.
Patterns are standard file-name wildcard strings, as defined in the
`fnmatch` module. For example, the pattern "*.py" will match the names
of all Python scripts.
"""
... | python | {
"resource": ""
} |
q17894 | update_exc | train | def update_exc(exc, msg, before=True, separator="\n"):
"""
Adds additional text to an exception's error message.
The new text will be added before the existing text by default; to append
it after the original text, pass False to the `before` parameter.
By default the old and new text will be separ... | python | {
"resource": ""
} |
q17895 | case_insensitive_update | train | def case_insensitive_update(dct1, dct2):
"""
Given two dicts, updates the first one with the second, but considers keys
that are identical except for case to be the same.
No return value; this function modified dct1 similar to the update() method.
"""
lowkeys = dict([(key.lower(), key) for key ... | python | {
"resource": ""
} |
q17896 | env | train | def env(*args, **kwargs):
"""
Returns the first environment variable set
if none are non-empty, defaults to "" or keyword arg default
"""
for arg in args:
value = os.environ.get(arg, None)
if value:
return value
return kwargs.get("default", "") | python | {
"resource": ""
} |
q17897 | to_slug | train | def to_slug(value, incoming=None, errors="strict"):
"""Normalize string.
Convert to lowercase, remove non-word characters, and convert spaces
to hyphens.
This function was copied from novaclient.openstack.strutils
Inspired by Django's `slugify` filter.
:param value: Text to slugify
:para... | python | {
"resource": ""
} |
q17898 | _WaitThread.run | train | def run(self):
"""Starts the thread."""
resp = _wait_until(obj=self.obj, att=self.att,
desired=self.desired, callback=None,
interval=self.interval, attempts=self.attempts,
verbose=False, verbose_atts=None)
self.callback(resp) | python | {
"resource": ""
} |
q17899 | assure_volume | train | def assure_volume(fnc):
"""
Converts a volumeID passed as the volume to a CloudBlockStorageVolume object.
"""
@wraps(fnc)
def _wrapped(self, volume, *args, **kwargs):
if not isinstance(volume, CloudBlockStorageVolume):
# Must be the ID
volume = self._manager.get(volum... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.