code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# check inputs
# N.B., ensure int8 so we can use cython optimisation
h = HaplotypeArray(np.asarray(h), copy=False)
if h.min() < 0:
raise NotImplementedError('missing calls are not supported')
# initialise
n_variants = h.n_variants # number of rows, i.e., variants
n_haplotypes... | def ehh_decay(h, truncate=False) | Compute the decay of extended haplotype homozygosity (EHH)
moving away from the first variant.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
truncate : bool, optional
If True, the return array will exclude trailing zeros.
Returns
... | 5.557188 | 4.834898 | 1.149391 |
# check inputs
# N.B., ensure int8 so we can use cython optimisation
h = HaplotypeArray(np.asarray(h), copy=False)
if h.max() > 1:
raise NotImplementedError('only biallelic variants are supported')
if h.min() < 0:
raise NotImplementedError('missing calls are not supported')
... | def voight_painting(h) | Paint haplotypes, assigning a unique integer to each shared haplotype
prefix.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
painting : ndarray, int, shape (n_variants, n_haplotypes)
Painting array.
indices :... | 8.174321 | 5.725085 | 1.427808 |
import seaborn as sns
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
if flank == 'left':
painting = painting[::-1]
n_colors = painting.max()
palette = sns.color_palette(palette, n_colors)
# use white for singleton haplotypes
cmap = ListedColo... | def plot_voight_painting(painting, palette='colorblind', flank='right',
ax=None, height_factor=0.01) | Plot a painting of shared haplotype prefixes.
Parameters
----------
painting : array_like, int, shape (n_variants, n_haplotypes)
Painting array.
ax : axes, optional
The axes on which to draw. If not provided, a new figure will be
created.
palette : string, optional
A... | 2.273869 | 2.110427 | 1.077445 |
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import seaborn as sns
# check inputs
h = asarray_ndim(h, 2)
if index is None:
# use midpoint
index = h.shape[0] // 2
# divide data into two flanks
hl = h[:index+1][::-1]
hr = h[index:]
... | def fig_voight_painting(h, index=None, palette='colorblind',
height_factor=0.01, fig=None) | Make a figure of shared haplotype prefixes for both left and right
flanks, centred on some variant of choice.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
index : int, optional
Index of the variant within the haplotype array to centre ... | 2.22909 | 2.195085 | 1.015491 |
# check inputs
if map_pos is None:
# integrate over physical distance
map_pos = pos
else:
map_pos = asarray_ndim(map_pos, 1)
check_dim0_aligned(pos, map_pos)
# compute physical gaps
physical_gaps = np.diff(pos)
# compute genetic gaps
gaps = np.diff(map... | def compute_ihh_gaps(pos, map_pos, gap_scale, max_gap, is_accessible) | Compute spacing between variants for integrating haplotype
homozygosity.
Parameters
----------
pos : array_like, int, shape (n_variants,)
Variant positions (physical distance).
map_pos : array_like, float, shape (n_variants,)
Variant positions (genetic map distance).
gap_scale :... | 3.100428 | 2.803179 | 1.10604 |
# check inputs
h = asarray_ndim(h, 2)
check_integer_dtype(h)
h = memoryview_safe(h)
# # check there are no invariant sites
# ac = h.count_alleles()
# assert np.all(ac.is_segregating()), 'please remove non-segregating sites'
if use_threads and multiprocessing.cpu_count() > 1:
... | def nsl(h, use_threads=True) | Compute the unstandardized number of segregating sites by length (nSl)
for each variant, comparing the reference and alternate alleles,
after Ferrer-Admetlla et al. (2014).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
use_threads : bool, o... | 2.813623 | 2.658876 | 1.0582 |
# check inputs
h1 = asarray_ndim(h1, 2)
check_integer_dtype(h1)
h2 = asarray_ndim(h2, 2)
check_integer_dtype(h2)
check_dim0_aligned(h1, h2)
h1 = memoryview_safe(h1)
h2 = memoryview_safe(h2)
if use_threads and multiprocessing.cpu_count() > 1:
# use multiple threads
... | def xpnsl(h1, h2, use_threads=True) | Cross-population version of the NSL statistic.
Parameters
----------
h1 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the first population.
h2 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the second population.
use_threads : bool,... | 1.956562 | 1.808496 | 1.081872 |
# check inputs
h = HaplotypeArray(h, copy=False)
# number of haplotypes
n = h.n_haplotypes
# compute haplotype frequencies
f = h.distinct_frequencies()
# estimate haplotype diversity
hd = (1 - np.sum(f**2)) * n / (n - 1)
return hd | def haplotype_diversity(h) | Estimate haplotype diversity.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
hd : float
Haplotype diversity. | 3.881711 | 3.745231 | 1.036441 |
hd = moving_statistic(values=h, statistic=haplotype_diversity, size=size,
start=start, stop=stop, step=step)
return hd | def moving_haplotype_diversity(h, size, start=0, stop=None, step=None) | Estimate haplotype diversity in moving windows.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
size : int
The window size (number of variants).
start : int, optional
The index at which to start.
stop : int, optional
T... | 4.451364 | 5.769802 | 0.771493 |
# check inputs
h = HaplotypeArray(h, copy=False)
# compute haplotype frequencies
f = h.distinct_frequencies()
# compute H1
h1 = np.sum(f**2)
# compute H12
h12 = np.sum(f[:2])**2 + np.sum(f[2:]**2)
# compute H123
h123 = np.sum(f[:3])**2 + np.sum(f[3:]**2)
# compute ... | def garud_h(h) | Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures
of soft sweeps, as defined in Garud et al. (2015).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
h1 : float
H1 statistic (sum of squares of... | 2.802237 | 2.050823 | 1.366397 |
gh = moving_statistic(values=h, statistic=garud_h, size=size, start=start,
stop=stop, step=step)
h1 = gh[:, 0]
h12 = gh[:, 1]
h123 = gh[:, 2]
h2_h1 = gh[:, 3]
return h1, h12, h123, h2_h1 | def moving_garud_h(h, size, start=0, stop=None, step=None) | Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures
of soft sweeps, as defined in Garud et al. (2015), in moving windows,
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
size : int
The window size (number of variants).... | 3.078356 | 2.410369 | 1.277131 |
import matplotlib.pyplot as plt
import seaborn as sns
# check inputs
h = HaplotypeArray(h, copy=False)
# setup figure
if ax is None:
width = plt.rcParams['figure.figsize'][0]
height = width / 10
fig, ax = plt.subplots(figsize=(width, height))
sns.despine(a... | def plot_haplotype_frequencies(h, palette='Paired', singleton_color='w',
ax=None) | Plot haplotype frequencies.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
palette : string, optional
A Seaborn palette name.
singleton_color : string, optional
Color to paint singleton haplotypes.
ax : axes, optional
... | 2.430124 | 2.522438 | 0.963403 |
# determine windows
windows = np.asarray(list(index_windows(h, size=size, start=start,
stop=stop, step=None)))
# setup output
hr = np.zeros((windows.shape[0], h.shape[1]), dtype='i4')
# iterate over windows
for i, (window_start, window_stop) in... | def moving_hfs_rank(h, size, start=0, stop=None) | Helper function for plotting haplotype frequencies in moving windows.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
size : int
The window size (number of variants).
start : int, optional
The index at which to start.
stop : i... | 3.577598 | 3.199792 | 1.118072 |
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
# setup figure
if ax is None:
fig, ax = plt.subplots()
# compute haplotype frequencies
# N.B., here we use a haplotype rank data structure to enable the use of
# pcolormesh() which is a lot fas... | def plot_moving_haplotype_frequencies(pos, h, size, start=0, stop=None, n=None,
palette='Paired', singleton_color='w',
ax=None) | Plot haplotype frequencies in moving windows over the genome.
Parameters
----------
pos : array_like, int, shape (n_items,)
Variant positions, using 1-based coordinates, in ascending order.
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
size : int
The... | 3.221464 | 3.163503 | 1.018322 |
d1 = moving_tajima_d(ac1, size=size, start=start, stop=stop, step=step)
d2 = moving_tajima_d(ac2, size=size, start=start, stop=stop, step=step)
delta = d1 - d2
delta_z = (delta - np.mean(delta)) / np.std(delta)
return delta_z | def moving_delta_tajima_d(ac1, ac2, size, start=0, stop=None, step=None) | Compute the difference in Tajima's D between two populations in
moving windows.
Parameters
----------
ac1 : array_like, int, shape (n_variants, n_alleles)
Allele counts array for the first population.
ac2 : array_like, int, shape (n_variants, n_alleles)
Allele counts array for the s... | 1.924526 | 2.139789 | 0.8994 |
# copy and sort the array
y = np.array(x).flatten()
y.sort()
# setup bins
bins = [y[0]]
# determine step size
step = len(y) // n
# add bin edges
for i in range(step, len(y), step):
# get value at this index
v = y[i]
# only add bin edge if larger than... | def make_similar_sized_bins(x, n) | Utility function to create a set of bins over the range of values in `x`
such that each bin contains roughly the same number of values.
Parameters
----------
x : array_like
The values to be binned.
n : int
The number of bins to create.
Returns
-------
bins : ndarray
... | 3.36796 | 3.610729 | 0.932764 |
score = asarray_ndim(score, 1)
return (score - np.nanmean(score)) / np.nanstd(score) | def standardize(score) | Centre and scale to unit variance. | 4.078053 | 3.738752 | 1.090752 |
from scipy.stats import binned_statistic
# check inputs
score = asarray_ndim(score, 1)
aac = asarray_ndim(aac, 1)
check_dim0_aligned(score, aac)
# remove nans
nonan = ~np.isnan(score)
score_nonan = score[nonan]
aac_nonan = aac[nonan]
if bins is None:
# make our o... | def standardize_by_allele_count(score, aac, bins=None, n_bins=None,
diagnostics=True) | Standardize `score` within allele frequency bins.
Parameters
----------
score : array_like, float
The score to be standardized, e.g., IHS or NSL.
aac : array_like, int
An array of alternate allele counts.
bins : array_like, int, optional
Allele count bins, overrides `n_bins`... | 2.100507 | 2.07336 | 1.013093 |
# normalise and check inputs
ac1 = AlleleCountsArray(ac1)
ac2 = AlleleCountsArray(ac2)
ac3 = AlleleCountsArray(ac3)
check_dim0_aligned(ac1, ac2, ac3)
# compute fst
fst12 = moving_hudson_fst(ac1, ac2, size=window_size, start=window_start,
stop=window_stop,... | def pbs(ac1, ac2, ac3, window_size, window_start=0, window_stop=None,
window_step=None, normed=True) | Compute the population branching statistic (PBS) which performs a comparison
of allele frequencies between three populations to detect genome regions that are
unusually differentiated in one population relative to the other two populations.
Parameters
----------
ac1 : array_like, int
Allele... | 2.157999 | 2.173892 | 0.992689 |
windows = index_windows(values, size, start, stop, step)
# setup output
out = np.array([statistic(values[i:j], **kwargs) for i, j in windows])
return out | def moving_statistic(values, statistic, size, start=0, stop=None, step=None, **kwargs) | Calculate a statistic in a moving window over `values`.
Parameters
----------
values : array_like
The data to summarise.
statistic : function
The statistic to compute within each window.
size : int
The window size (number of values).
start : int, optional
The in... | 4.132967 | 7.458116 | 0.554157 |
# determine step
if stop is None:
stop = len(values)
if step is None:
# non-overlapping
step = size
# iterate over windows
for window_start in range(start, stop, step):
window_stop = window_start + size
if window_stop > stop:
# ensure all w... | def index_windows(values, size, start, stop, step) | Convenience function to construct windows for the
:func:`moving_statistic` function. | 3.675659 | 3.991235 | 0.920933 |
last = False
# determine start and stop positions
if start is None:
start = pos[0]
if stop is None:
stop = pos[-1]
if step is None:
# non-overlapping
step = size
windows = []
for window_start in range(start, stop, step):
# determine window stop... | def position_windows(pos, size, start, stop, step) | Convenience function to construct windows for the
:func:`windowed_statistic` and :func:`windowed_count` functions. | 2.665921 | 2.800678 | 0.951884 |
start_locs = np.searchsorted(pos, windows[:, 0])
stop_locs = np.searchsorted(pos, windows[:, 1], side='right')
locs = np.column_stack((start_locs, stop_locs))
return locs | def window_locations(pos, windows) | Locate indices in `pos` corresponding to the start and stop positions
of `windows`. | 2.384029 | 1.971983 | 1.20895 |
# assume sorted positions
if not isinstance(pos, SortedIndex):
pos = SortedIndex(pos, copy=False)
# setup windows
if windows is None:
windows = position_windows(pos, size, start, stop, step)
else:
windows = asarray_ndim(windows, 2)
# find window locations
locs... | def windowed_count(pos, size=None, start=None, stop=None, step=None,
windows=None) | Count the number of items in windows over a single chromosome/contig.
Parameters
----------
pos : array_like, int, shape (n_items,)
The item positions in ascending order, using 1-based coordinates..
size : int, optional
The window size (number of bases).
start : int, optional
... | 3.497408 | 3.942016 | 0.887213 |
# calculate window sizes
if is_accessible is None:
# N.B., window stops are included
n_bases = np.diff(windows, axis=1).reshape(-1) + 1
else:
n_bases = np.array([np.count_nonzero(is_accessible[i-1:j])
for i, j in windows])
# deal with multidimen... | def per_base(x, windows, is_accessible=None, fill=np.nan) | Calculate the per-base value of a windowed statistic.
Parameters
----------
x : array_like, shape (n_windows,)
The statistic to average per-base.
windows : array_like, int, shape (n_windows, 2)
The windows used, as an array of (window_start, window_stop)
positions using 1-based... | 3.297151 | 3.097034 | 1.064615 |
pos_accessible, = np.nonzero(is_accessible)
pos_accessible += 1 # convert to 1-based coordinates
# N.B., need some care in handling start and stop positions, these are
# genomic positions at which to start and stop the windows
if start:
pos_accessible = pos_accessible[pos_accessible >... | def equally_accessible_windows(is_accessible, size, start=0, stop=None, step=None) | Create windows each containing the same number of accessible bases.
Parameters
----------
is_accessible : array_like, bool, shape (n_bases,)
Array defining accessible status of all bases on a contig/chromosome.
size : int
Window size (number of accessible bases).
start : int, option... | 5.548234 | 5.772595 | 0.961133 |
if context['user'].has_perm('attachments.add_attachment'):
return {
'form': AttachmentForm(),
'form_url': add_url_for_obj(obj),
'next': context.request.build_absolute_uri(),
}
else:
return {'form': None} | def attachment_form(context, obj) | Renders a "upload attachment" form.
The user must own ``attachments.add_attachment permission`` to add
attachments. | 3.879322 | 3.88872 | 0.997583 |
if context['user'].has_perm('attachments.delete_foreign_attachments') or (
context['user'] == attachment.creator
and context['user'].has_perm('attachments.delete_attachment')
):
return {
'next': context.request.build_absolute_uri(),
'delete_url': reverse(
... | def attachment_delete_link(context, attachment) | Renders a html link to the delete view of the given attachment. Returns
no content if the request-user has no permission to delete attachments.
The user must own either the ``attachments.delete_attachment`` permission
and is the creator of the attachment, that he can delete it or he has
``attachments.d... | 3.11341 | 2.582671 | 1.2055 |
return 'attachments/{app}_{model}/{pk}/{filename}'.format(
app=instance.content_object._meta.app_label,
model=instance.content_object._meta.object_name.lower(),
pk=instance.content_object.pk,
filename=filename,
) | def attachment_upload(instance, filename) | Stores the attachment in a "per module/appname/primary key" folder | 2.383163 | 2.079283 | 1.146147 |
if output_file is None:
if enable_scroll:
# Add a new axes which will be used as scroll bar.
axpos = plt.axes([0.12, 0.1, 0.625, 0.03])
spos = Slider(axpos, "Scroll", 10, len(self.pyfile.lines))
def update(val):
... | def show_heatmap(self, blocking=True, output_file=None, enable_scroll=False) | Method to actually display the heatmap created.
@param blocking: When set to False makes an unblocking plot show.
@param output_file: If not None the heatmap image is output to this
file. Supported formats: (eps, pdf, pgf, png, ps, raw, rgba, svg,
svgz)
@para... | 3.837347 | 3.743881 | 1.024965 |
self.line_profiler = pprofile.Profile()
self.line_profiler.runfile(
open(self.pyfile.path, "r"), {}, self.pyfile.path
) | def __profile_file(self) | Method used to profile the given file line by line. | 9.242121 | 7.038261 | 1.313126 |
if self.line_profiler is None:
return {}
# the [0] is because pprofile.Profile.file_dict stores the line_dict
# in a list so that it can be modified in a thread-safe way
# see https://github.com/vpelletier/pprofile/blob/da3d60a1b59a061a0e2113bf768b7cb4bf002ccb/pprof... | def __get_line_profile_data(self) | Method to procure line profiles.
@return: Line profiles if the file has been profiles else empty
dictionary. | 10.116194 | 10.391701 | 0.973488 |
# Read lines from file.
with open(self.pyfile.path, "r") as file_to_read:
for line in file_to_read:
# Remove return char from the end of the line and add a
# space in the beginning for better visibility.
self.pyfile.lines.append(" " +... | def __fetch_heatmap_data_from_profile(self) | Method to create heatmap data from profile information. | 4.378494 | 4.304142 | 1.017275 |
# Define the heatmap plot.
height = len(self.pyfile.lines) / 3
width = max(map(lambda x: len(x), self.pyfile.lines)) / 8
self.fig, self.ax = plt.subplots(figsize=(width, height))
# Set second sub plot to occupy bottom 20%
plt.subplots_adjust(bottom=0.20)
... | def __create_heatmap_plot(self) | Method to actually create the heatmap from profile stats. | 3.702285 | 3.651086 | 1.014023 |
# Create command line parser.
parser = argparse.ArgumentParser()
# Adding command line arguments.
parser.add_argument("-o", "--out", help="Output file", default=None)
parser.add_argument(
"pyfile", help="Python file to be profiled", default=None
)
# Parse command line arguments.... | def main() | Starting point for the program execution. | 3.658683 | 3.588584 | 1.019534 |
if ndigits is None:
ndigits = 0
return self.__class__(
amount=self.amount.quantize(Decimal('1e' + str(-ndigits))),
currency=self.currency) | def round(self, ndigits=0) | Rounds the amount using the current ``Decimal`` rounding algorithm. | 4.072252 | 3.661433 | 1.112202 |
sys.path.insert(0, os.getcwd())
logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler()])
parser = argparse.ArgumentParser(description="Manage Application", add_help=False)
parser.add_argument('app', metavar='app',
type=str, help='Application module path')... | def run() | CLI endpoint. | 3.362551 | 3.328443 | 1.010248 |
def wrapper(func):
header = '\n'.join([s for s in (func.__doc__ or '').split('\n')
if not s.strip().startswith(':')])
parser = self.parsers.add_parser(func.__name__, description=header)
args, vargs, kw, defs, kwargs, kwdefs, anns = in... | def command(self, init=False) | Define CLI command. | 2.980294 | 2.929942 | 1.017185 |
if router is None:
router = app.router
handler = to_coroutine(handler)
resources = []
for path in paths:
# Register any exception to app
if isinstance(path, type) and issubclass(path, BaseException):
app._error_handlers[path] = handler
continue
... | def routes_register(app, handler, *paths, methods=None, router=None, name=None) | Register routes. | 3.818318 | 3.775804 | 1.01126 |
parsed = re.sre_parse.parse(path)
for case, _ in parsed:
if case not in (re.sre_parse.LITERAL, re.sre_parse.ANY):
break
else:
return path
path = path.strip('^$')
def parse_(match):
[part] = match.groups()
match = DYNR_RE.match(part)
params =... | def parse(path) | Parse URL path and convert it to regexp if needed. | 4.705942 | 4.509855 | 1.04348 |
parsed = re.sre_parse.parse(self._pattern.pattern)
subgroups = {n:str(v) for n, v in enumerate(subgroups, 1)}
groups_ = dict(parsed.pattern.groupdict)
subgroups.update({
groups_[k0]: str(v0)
for k0, v0 in groups.items()
if k0 in groups_
... | def url_for(self, *subgroups, **groups) | Build URL. | 5.965344 | 5.825681 | 1.023974 |
value = negate = chr(value)
while value == negate:
value = choice(self.literals)
yield value | def state_not_literal(self, value) | Parse not literal. | 14.903009 | 13.898149 | 1.072302 |
min_, max_, value = value
value = [val for val in Traverser(value, self.groups)]
if not min_ and max_:
for val in value:
if isinstance(val, required):
min_ = 1
break
for val in value * min_:
yield v... | def state_max_repeat(self, value) | Parse repeatable parts. | 9.689876 | 8.447779 | 1.147032 |
value = [val for val in Traverser(value, self.groups)]
if not value or not value[0]:
for val in self.literals - set(value):
return (yield val)
yield value[0] | def state_in(self, value) | Parse ranges. | 11.025874 | 10.232718 | 1.077512 |
if value == re.sre_parse.CATEGORY_DIGIT:
return (yield '0')
if value == re.sre_parse.CATEGORY_WORD:
return (yield 'x') | def state_category(value) | Parse categories. | 6.933387 | 6.227973 | 1.113265 |
num, *_, parsed = value
if num in self.groups:
return (yield required(self.groups[num]))
yield from Traverser(parsed, groups=self.groups) | def state_subpattern(self, value) | Parse subpatterns. | 16.915947 | 14.667678 | 1.153281 |
if isinstance(secret, str):
secret = secret.encode(encoding)
if isinstance(value, str):
value = value.encode(encoding)
if isinstance(digestmod, str):
digestmod = getattr(hashlib, digestmod, hashlib.sha1)
hm = hmac.new(secret, digestmod=digestmod)
hm.update(value)
... | def create_signature(secret, value, digestmod='sha256', encoding='utf-8') | Create HMAC Signature from secret for value. | 1.815694 | 1.699767 | 1.068202 |
return hmac.compare_digest(signature, create_signature(*args, **kwargs)) | def check_signature(signature, *args, **kwargs) | Check for the signature is correct. | 4.542671 | 3.986631 | 1.139476 |
salt = ''.join(random.sample(SALT_CHARS, salt_length))
signature = create_signature(salt, password, digestmod=digestmod)
return '$'.join((digestmod, salt, signature)) | def generate_password_hash(password, digestmod='sha256', salt_length=8) | Hash a password with given method and salt length. | 3.855955 | 4.028919 | 0.95707 |
package = sys.modules[package_name]
return {
name: importlib.import_module(package_name + '.' + name)
for _, name, _ in pkgutil.walk_packages(package.__path__)
if not submodules or name in submodules
} | def import_submodules(package_name, *submodules) | Import all submodules by package name. | 2.554299 | 2.556634 | 0.999086 |
def wrapper(method):
method = to_coroutine(method)
setattr(method, ROUTE_PARAMS_ATTR, (paths, methods, name))
if handler and not hasattr(handler, method.__name__):
setattr(handler, method.__name__, method)
return method
return wrapper | def register(*paths, methods=None, name=None, handler=None) | Mark Handler.method to aiohttp handler.
It uses when registration of the handler with application is postponed.
::
class AwesomeHandler(Handler):
def get(self, request):
return "I'm awesome!"
@register('/awesome/best')
def best(self, request):
... | 4.445278 | 5.449153 | 0.815774 |
docs = getattr(view, '__doc__', None)
view = to_coroutine(view)
methods = methods or ['GET']
if METH_ANY in methods:
methods = METH_ALL
def proxy(self, *args, **kwargs):
return view(*args, **kwargs)
params = {m.lower(): proxy for m in m... | def from_view(cls, view, *methods, name=None) | Create a handler class from function or coroutine. | 3.690965 | 3.314548 | 1.113565 |
cls.app = app
if cls.app is not None:
for _, m in inspect.getmembers(cls, predicate=inspect.isfunction):
if not hasattr(m, ROUTE_PARAMS_ATTR):
continue
paths_, methods_, name_ = getattr(m, ROUTE_PARAMS_ATTR)
name_ =... | def bind(cls, app, *paths, methods=None, name=None, router=None, view=None) | Bind to the given application. | 3.553853 | 3.47043 | 1.024038 |
if cls.app is None:
return register(*args, handler=cls, **kwargs)
return cls.app.register(*args, handler=cls, **kwargs) | def register(cls, *args, **kwargs) | Register view to handler. | 4.495387 | 3.666326 | 1.226128 |
if view is None and request.method not in self.methods:
raise HTTPMethodNotAllowed(request.method, self.methods)
method = getattr(self, view or request.method.lower())
response = await method(request, **kwargs)
return await self.make_response(request, response) | async def dispatch(self, request, view=None, **kwargs) | Dispatch request. | 3.248433 | 2.963771 | 1.096047 |
while iscoroutine(response):
response = await response
if isinstance(response, StreamResponse):
return response
if isinstance(response, str):
return Response(text=response, content_type='text/html')
if isinstance(response, bytes):
... | async def make_response(self, request, response) | Convert a handler result to web response. | 2.168294 | 2.008909 | 1.079339 |
if request.content_type in {'application/x-www-form-urlencoded', 'multipart/form-data'}:
return await request.post()
if request.content_type == 'application/json':
return await request.json()
return await request.text() | async def parse(self, request) | Return a coroutine which parses data from request depends on content-type.
Usage: ::
def post(self, request):
data = await self.parse(request)
# ... | 2.368665 | 2.227536 | 1.063357 |
self.app = app
for name, ptype in self.dependencies.items():
if name not in app.ps or not isinstance(app.ps[name], ptype):
raise PluginException(
'Plugin `%s` requires for plugin `%s` to be installed to the application.' % (
... | def setup(self, app) | Initialize the plugin.
Fill the plugin's options from application. | 3.959815 | 3.689188 | 1.073357 |
@web.middleware
async def middleware(request, handler):
try:
return await handler(request)
except Exception as exc:
for cls in type(exc).mro():
if cls in app._error_handlers:
request.exception = exc
response = ... | def _exc_middleware_factory(app) | Handle exceptions.
Route exceptions to handlers if they are registered in application. | 2.803114 | 2.878675 | 0.973751 |
if isinstance(methods, str):
methods = [methods]
def wrapper(view):
if handler is None:
handler_ = view
methods_ = methods or [METH_ANY]
if isfunction(handler_) or ismethod(handler_):
handler_ = Handl... | def register(self, *paths, methods=None, name=None, handler=None) | Register function/coroutine/muffin.Handler with the application.
Usage example:
.. code-block:: python
@app.register('/hello')
def hello(request):
return 'Hello World!' | 3.353996 | 3.837464 | 0.874014 |
config = LStruct(self.defaults)
module = config['CONFIG'] = os.environ.get(
CONFIGURATION_ENVIRON_VARIABLE, config['CONFIG'])
if module:
try:
module = import_module(module)
config.update({
name: getattr(module,... | def cfg(self) | Load the application configuration.
This method loads configuration from python module. | 3.833775 | 3.742921 | 1.024274 |
source = plugin
if isinstance(plugin, str):
module, _, attr = plugin.partition(':')
module = import_module(module)
plugin = getattr(module, attr or 'Plugin', None)
if isinstance(plugin, types.ModuleType):
plugin = getattr(module, 'Plugin... | def install(self, plugin, name=None, **opts) | Install plugin to the application. | 2.652138 | 2.586711 | 1.025293 |
if self.frozen:
return False
if self._error_handlers:
self.middlewares.append(_exc_middleware_factory(self))
# Register static paths
for path in self.cfg.STATIC_FOLDERS:
self.router.register_resource(SafeStaticResource(self.cfg.STATIC_PREFIX... | async def startup(self) | Start the application.
Support for start-callbacks and lock the application's configuration and plugins. | 8.879982 | 8.25675 | 1.075482 |
self.middlewares.append(web.middleware(to_coroutine(func))) | def middleware(self, func) | Register given middleware (v1). | 12.756689 | 10.964072 | 1.163499 |
expected = getattr(settings, 'HONEYPOT_VALUE', '')
if callable(expected):
expected = expected()
return val == expected | def honeypot_equals(val) | Default verifier used if HONEYPOT_VERIFIER is not specified.
Ensures val == HONEYPOT_VALUE or HONEYPOT_VALUE() if it's a callable. | 5.572617 | 4.370236 | 1.275129 |
verifier = getattr(settings, 'HONEYPOT_VERIFIER', honeypot_equals)
if request.method == 'POST':
field = field_name or settings.HONEYPOT_FIELD_NAME
if field not in request.POST or not verifier(request.POST[field]):
resp = render_to_string('honeypot/honeypot_error.html',
... | def verify_honeypot_value(request, field_name) | Verify that request.POST[field_name] is a valid honeypot.
Ensures that the field exists and passes verification according to
HONEYPOT_VERIFIER. | 3.170713 | 3.124417 | 1.014818 |
# hack to reverse arguments if called with str param
if isinstance(func, six.string_types):
func, field_name = field_name, func
def decorated(func):
def inner(request, *args, **kwargs):
response = verify_honeypot_value(request, field_name)
if response:
... | def check_honeypot(func=None, field_name=None) | Check request.POST for valid honeypot field.
Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if
not specified. | 2.890679 | 2.985103 | 0.968368 |
# borrowing liberally from django's csrf_exempt
def wrapped(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped.honeypot_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped) | def honeypot_exempt(view_func) | Mark view as exempt from honeypot validation | 3.173992 | 3.005466 | 1.056073 |
if not field_name:
field_name = settings.HONEYPOT_FIELD_NAME
value = getattr(settings, 'HONEYPOT_VALUE', '')
if callable(value):
value = value()
return {'fieldname': field_name, 'value': value} | def render_honeypot_field(field_name=None) | Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME). | 2.58112 | 2.365477 | 1.091163 |
import argparse
import textwrap
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
Command line utility to generate .svg badges.
This utility can be used to generate .svg badge images, using confi... | def parse_args() | Parse the command line arguments. | 3.905239 | 3.881821 | 1.006033 |
# Parse command line arguments
args = parse_args()
label = args.label
threshold_text = args.args
suffix = args.suffix
# Check whether thresholds were sent as one word, and is in the
# list of templates. If so, swap in the template.
if len(args.args) == 1 and args.args[0] in BADGE... | def main() | Generate a badge based on command line arguments. | 3.605532 | 3.404263 | 1.059123 |
try:
a = float(self.value)
b = int(a)
except ValueError:
return False
else:
return a == b | def value_is_int(self) | Identify whether the value text is an int. | 3.338303 | 2.942923 | 1.134349 |
return self.get_font_width(font_name=self.font_name, font_size=self.font_size) | def font_width(self) | Return the badge font width. | 3.400949 | 3.143653 | 1.081846 |
return self.get_text_width(' ') + self.label_width + \
int(float(self.font_width) * float(self.num_padding_chars)) | def color_split_position(self) | The SVG x position where the color split should occur. | 11.142128 | 9.8192 | 1.134729 |
return self.get_text_width(' ' + ' ' * int(float(self.num_padding_chars) * 2.0)) \
+ self.label_width + self.value_width | def badge_width(self) | The total width of badge.
>>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif',
... font_size=11)
>>> badge.badge_width
91 | 8.074352 | 9.741892 | 0.828828 |
# Identify whether template is a file or the actual template text
if len(self.template.split('\n')) == 1:
with open(self.template, mode='r') as file_handle:
badge_text = file_handle.read()
else:
badge_text = self.template
return badge_te... | def badge_svg_text(self) | The badge SVG text. | 2.301442 | 2.250804 | 1.022498 |
return len(text) * self.get_font_width(self.font_name, self.font_size) | def get_text_width(self, text) | Return the width of text.
This implementation assumes a fixed font of:
font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"
>>> badge = Badge('x', 1, font_name='DejaVu Sans,Verdana,Geneva,sans-serif', font_size=11)
>>> badge.get_text_width('pylint')
42 | 3.691097 | 4.451964 | 0.829094 |
# If no thresholds were passed then return the default color
if not self.thresholds:
return self.default_color
if self.value_type == str:
if self.value in self.thresholds:
return self.thresholds[self.value]
else:
retur... | def badge_color(self) | Find the badge color based on the thresholds. | 3.291011 | 3.078486 | 1.069036 |
# Validate path (part 1)
if file_path.endswith('/'):
raise Exception('File location may not be a directory.')
# Get absolute filepath
path = os.path.abspath(file_path)
if not path.lower().endswith('.svg'):
path += '.svg'
# Validate path... | def write_badge(self, file_path, overwrite=False) | Write badge to file. | 3.098847 | 3.081875 | 1.005507 |
global DEFAULT_SERVER_PORT, DEFAULT_SERVER_LISTEN_ADDRESS, DEFAULT_LOGGING_LEVEL
# Check for environment variables
if 'ANYBADGE_PORT' in environ:
DEFAULT_SERVER_PORT = environ['ANYBADGE_PORT']
if 'ANYBADGE_LISTEN_ADDRESS' in environ:
DEFAULT_SERVER_LISTEN_ADDRESS = environ['ANYBA... | def main() | Run server. | 2.231319 | 2.177221 | 1.024847 |
name_dispatch = {
ast.Name: "id",
ast.Attribute: "attr",
ast.Call: "func",
ast.FunctionDef: "name",
ast.ClassDef: "name",
ast.Subscript: "value",
}
# This is a new ast type in Python 3
if hasattr(ast, "arg"):
name_dispatch[ast.arg] = "arg"
... | def get_object_name(obj) | Return the name of a given object | 3.340395 | 3.081795 | 1.083912 |
return attr.value.id if isinstance(attr.value, ast.Name) else None | def get_attribute_name_id(attr) | Return the attribute name identifier | 6.482441 | 6.97545 | 0.929322 |
if not method.args.args:
return False
first_arg = method.args.args[0]
first_arg_name = get_object_name(first_arg)
return first_arg_name == arg_name | def is_class_method_bound(method, arg_name=BOUND_METHOD_ARGUMENT_NAME) | Return whether a class method is bound to the class | 3.409397 | 3.193754 | 1.06752 |
return [
node
for node in cls.body
if isinstance(node, ast.FunctionDef)
] | def get_class_methods(cls) | Return methods associated with a given class | 4.072762 | 3.935611 | 1.034849 |
return [
target
for node in cls.body
if isinstance(node, ast.Assign)
for target in node.targets
] | def get_class_variables(cls) | Return class variables associated with a given class | 5.155317 | 5.234011 | 0.984965 |
node_attributes = [
child
for child in ast.walk(node)
if isinstance(child, ast.Attribute) and
get_attribute_name_id(child) == bound_name_classifier
]
node_function_call_names = [
get_object_name(child)
for child in ast.walk(node)
if isinstance(chi... | def get_instance_variables(node, bound_name_classifier=BOUND_METHOD_ARGUMENT_NAME) | Return instance variables used in an AST node | 2.319423 | 2.260033 | 1.026278 |
return [
child
for child in ast.walk(node)
if isinstance(child, ast.ClassDef)
] | def get_module_classes(node) | Return classes associated with a given module | 3.491954 | 3.185154 | 1.096322 |
return [
os.path.join(root, filename)
for root, directories, filenames in os.walk(directory)
for filename in filenames
] | def recursively_get_files_from_directory(directory) | Return all filenames under recursively found in a directory | 2.341351 | 2.198281 | 1.065083 |
if isinstance(key, int):
return SeedID(key)
if key not in SeedID._member_map_:
extend_enum(SeedID, key, default)
return SeedID[key] | def get(key, default=-1) | Backport support for original codes. | 5.852302 | 5.142142 | 1.138106 |
if isinstance(key, int):
return PriorityLevel(key)
if key not in PriorityLevel._member_map_:
extend_enum(PriorityLevel, key, default)
return PriorityLevel[key] | def get(key, default=-1) | Backport support for original codes. | 4.86712 | 4.224414 | 1.152141 |
if isinstance(key, int):
return TOS_THR(key)
if key not in TOS_THR._member_map_:
extend_enum(TOS_THR, key, default)
return TOS_THR[key] | def get(key, default=-1) | Backport support for original codes. | 4.819141 | 4.525868 | 1.064799 |
if not (isinstance(value, int) and 0 <= value <= 1):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
super()._missing_(value) | def _missing_(cls, value) | Lookup function used when value is not found. | 4.971387 | 5.194452 | 0.957057 |
if isinstance(key, int):
return Registration(key)
if key not in Registration._member_map_:
extend_enum(Registration, key, default)
return Registration[key] | def get(key, default=-1) | Backport support for original codes. | 6.904724 | 5.936065 | 1.163182 |
if isinstance(key, int):
return ErrorCode(key)
if key not in ErrorCode._member_map_:
extend_enum(ErrorCode, key, default)
return ErrorCode[key] | def get(key, default=-1) | Backport support for original codes. | 4.544353 | 3.972285 | 1.144015 |
from pcapkit.protocols.protocol import Protocol
try:
flag = issubclass(value, Protocol)
except TypeError:
flag = issubclass(type(value), Protocol)
if flag or isinstance(value, Protocol):
value = value.__index__()
if isinstance(valu... | def count(self, value) | S.count(value) -> integer -- return number of occurrences of value | 4.008952 | 3.943568 | 1.01658 |
if start is not None and start < 0:
start = max(len(self) + start, 0)
if stop is not None and stop < 0:
stop += len(self)
try:
if not isinstance(start, numbers.Integral):
start = self.index(start)
if not isinstance(stop, n... | def index(self, value, start=0, stop=None) | S.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but
recommended. | 2.868403 | 2.886238 | 0.993821 |
return self.__alias__.index(value, start, stop) | def index(self, value, start=None, stop=None) | Return first index of value. | 13.25986 | 9.419764 | 1.407664 |
if isinstance(key, int):
return NAT_Traversal(key)
if key not in NAT_Traversal._member_map_:
extend_enum(NAT_Traversal, key, default)
return NAT_Traversal[key] | def get(key, default=-1) | Backport support for original codes. | 6.982631 | 6.226829 | 1.121378 |
if length is None:
length = len(self)
_vers = self._read_unpack(1)
_type = self._read_unpack(1)
_tlen = self._read_unpack(2)
_rtid = self._read_id_numbers()
_area = self._read_id_numbers()
_csum = self._read_fileng(2)
_autp = self._re... | def read_ospf(self, length) | Read Open Shortest Path First.
Structure of OSPF header [RFC 2328]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| V... | 3.60043 | 3.120723 | 1.153716 |
_byte = self._read_fileng(4)
_addr = '.'.join([str(_) for _ in _byte])
return _addr | def _read_id_numbers(self) | Read router and area IDs. | 12.279835 | 9.116343 | 1.347013 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.