text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def properties_for_args(cls, arg_names='_arg_names'):
"""For a class with an attribute `arg_names` containing a list of names, add a property for every name in t... |
from qnet.algebra.core.scalar_algebra import Scalar
scalar_args = False
if hasattr(cls, '_scalar_args'):
scalar_args = cls._scalar_args
for arg_name in getattr(cls, arg_names):
def get_arg(self, name):
val = getattr(self, "_%s" % name)
if scalar_args:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_category(self, slug):
""" Get the category object """ |
try:
return get_category_for_slug(slug)
except ObjectDoesNotExist as e:
raise Http404(str(e)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_unique_slug(self, cleaned_data):
""" Test whether the slug is unique within a given time period. """ |
date_kwargs = {}
error_msg = _("The slug is not unique")
# The /year/month/slug/ URL determines when a slug can be unique.
pubdate = cleaned_data['publication_date'] or now()
if '{year}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE:
date_kwargs['year'] = pubdate.yea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _apply_rules_no_recurse(expr, rules):
"""Non-recursively match expr again all rules""" |
try:
# `rules` is an OrderedDict key => (pattern, replacement)
items = rules.items()
except AttributeError:
# `rules` is a list of (pattern, replacement) tuples
items = enumerate(rules)
for key, (pat, replacement) in items:
matched = pat.match(expr)
if matche... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, *args, **kwargs):
"""Instantiate while applying automatic simplifications Instead of directly instantiating `cls`, it is recommended to use :meth... |
global LEVEL
if LOG:
logger = logging.getLogger('QNET.create')
logger.debug(
"%s%s.create(*args, **kwargs); args = %s, kwargs = %s",
(" " * LEVEL), cls.__name__, args, kwargs)
LEVEL += 1
key = cls._get_instance_key(args, kwarg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kwargs(self):
"""The dictionary of keyword-only arguments for the instantiation of the Expression""" |
# Subclasses must override this property if and only if they define
# keyword-only arguments in their __init__ method
if hasattr(self, '_has_kwargs') and self._has_kwargs:
raise NotImplementedError(
"Class %s does not provide a kwargs property"
% str(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def substitute(self, var_map):
"""Substitute sub-expressions Args: var_map (dict):
Dictionary with entries of the form ``{expr: substitution}`` """ |
if self in var_map:
return var_map[self]
return self._substitute(var_map) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_rules(self, rules, recursive=True):
"""Rebuild the expression while applying a list of rules The rules are applied against the instantiated expression,... |
if recursive:
new_args = [_apply_rules(arg, rules) for arg in self.args]
new_kwargs = {
key: _apply_rules(val, rules)
for (key, val) in self.kwargs.items()}
else:
new_args = self.args
new_kwargs = self.kwargs
simpli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_rule(self, pattern, replacement, recursive=True):
"""Apply a single rules to the expression This is equivalent to :meth:`apply_rules` with ``rules=[(pa... |
return self.apply_rules([(pattern, replacement)], recursive=recursive) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bound_symbols(self):
"""Set of bound SymPy symbols in the expression""" |
if self._bound_symbols is None:
res = set.union(
set([]), # dummy arg (union fails without arguments)
*[_bound_symbols(val) for val in self.kwargs.values()])
res.update(
set([]), # dummy arg (update fails without arguments)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(url, dest):
""" Platform-agnostic downloader. """ |
u = urllib.FancyURLopener()
logger.info("Downloading %s..." % url)
u.retrieve(url, dest)
logger.info('Done, see %s' % dest)
return dest |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def logged_command(cmds):
"helper function to log a command and then run it"
logger.info(' '.join(cmds))
os.system(' '.join(cmds)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_cufflinks():
"Download cufflinks GTF files"
for size, md5, url in cufflinks:
cuff_gtf = os.path.join(args.data_dir, os.path.basename(url))
if not _up_to_date(md5, cuff_gtf):
download(url, cuff_gtf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bams():
""" Download BAM files if needed, extract only chr17 reads, and regenerate .bai """ |
for size, md5, url in bams:
bam = os.path.join(
args.data_dir,
os.path.basename(url).replace('.bam', '_%s.bam' % CHROM))
if not _up_to_date(md5, bam):
logger.info(
'Downloading reads on chromosome %s from %s to %s'
% (CHROM, url, b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_gtf():
""" Download GTF file from Ensembl, only keeping the chr17 entries. """ |
size, md5, url = GTF
full_gtf = os.path.join(args.data_dir, os.path.basename(url))
subset_gtf = os.path.join(
args.data_dir,
os.path.basename(url).replace('.gtf.gz', '_%s.gtf' % CHROM))
if not _up_to_date(md5, subset_gtf):
download(url, full_gtf)
cmds = [
'z... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_db():
""" Create gffutils database """ |
size, md5, fn = DB
if not _up_to_date(md5, fn):
gffutils.create_db(fn.replace('.db', ''), fn, verbose=True, force=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cufflinks_conversion():
""" convert Cufflinks output GTF files into tables of score and FPKM. """ |
for size, md5, fn in cufflinks_tables:
fn = os.path.join(args.data_dir, fn)
table = fn.replace('.gtf.gz', '.table')
if not _up_to_date(md5, table):
logger.info("Converting Cufflinks GTF %s to table" % fn)
fout = open(table, 'w')
fout.write('id\tscore\tfpk... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, feature):
""" Spawns a new figure showing data for `feature`. :param feature: A `pybedtools.Interval` object Using the pybedtools.Interval `featur... |
if isinstance(feature, gffutils.Feature):
feature = asinterval(feature)
self.make_fig()
axes = []
for ax, method in self.panels():
feature = method(ax, feature)
axes.append(ax)
return axes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def example_panel(self, ax, feature):
""" A example panel that just prints the text of the feature. """ |
txt = '%s:%s-%s' % (feature.chrom, feature.start, feature.stop)
ax.text(0.5, 0.5, txt, transform=ax.transAxes)
return feature |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signal_panel(self, ax, feature):
""" Plots each genomic signal as a line using the corresponding plotting_kwargs """ |
for gs, kwargs in zip(self.genomic_signal_objs, self.plotting_kwargs):
x, y = gs.local_coverage(feature, **self.local_coverage_kwargs)
ax.plot(x, y, **kwargs)
ax.axis('tight')
return feature |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def panels(self):
""" Add 2 panels to the figure, top for signal and bottom for gene models """ |
ax1 = self.fig.add_subplot(211)
ax2 = self.fig.add_subplot(212, sharex=ax1)
return (ax2, self.gene_panel), (ax1, self.signal_panel) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple():
"""Simple example using just the Bar class This example is intended to show usage of the Bar class at the lowest level. """ |
MAX_VALUE = 100
# Create our test progress bar
bar = Bar(max_value=MAX_VALUE, fallback=True)
bar.cursor.clear_lines(2)
# Before beginning to draw our bars, we save the position
# of our cursor so we can restore back to this position before writing
# the next time.
bar.cursor.save... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tree():
"""Example showing tree progress view""" |
#############
# Test data #
#############
# For this example, we're obviously going to be feeding fictitious data
# to ProgressTree, so here it is
leaf_values = [Value(0) for i in range(6)]
bd_defaults = dict(type=Bar, kwargs=dict(max_value=10))
test_d = {
"Warp Jump": {
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ci_plot(x, arr, conf=0.95, ax=None, line_kwargs=None, fill_kwargs=None):
""" Plots the mean and 95% ci for the given array on the given axes Parameters x : 1... |
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
line_kwargs = line_kwargs or {}
fill_kwargs = fill_kwargs or {}
m, lo, hi = ci(arr, conf)
ax.plot(x, m, **line_kwargs)
ax.fill_between(x, lo, hi, **fill_kwargs)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_labels_to_subsets(ax, subset_by, subset_order, text_kwargs=None, add_hlines=True, hline_kwargs=None):
""" Helper function for adding labels to subsets wi... |
_text_kwargs = dict(transform=ax.get_yaxis_transform())
if text_kwargs:
_text_kwargs.update(text_kwargs)
_hline_kwargs = dict(color='k')
if hline_kwargs:
_hline_kwargs.update(hline_kwargs)
pos = 0
for label in subset_order:
ind = subset_by == label
last_pos = p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_limits(array_dict, method='global', percentiles=None, limit=()):
""" Calculate limits for a group of arrays in a flexible manner. Returns a diction... |
if percentiles is not None:
for percentile in percentiles:
if not 0 <= percentile <= 100:
raise ValueError("percentile (%s) not between [0, 100]")
if method == 'global':
all_arrays = np.concatenate(
[i.ravel() for i in array_dict.itervalues()]
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ci(arr, conf=0.95):
""" Column-wise confidence interval. Parameters arr : array-like conf : float Confidence interval Returns ------- m : array column-wise m... |
m = arr.mean(axis=0)
n = len(arr)
se = arr.std(axis=0) / np.sqrt(n)
h = se * stats.t._ppf((1 + conf) / 2., n - 1)
return m, m - h, m + h |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nice_log(x):
""" Uses a log scale but with negative numbers. :param x: NumPy array """ |
neg = x < 0
xi = np.log2(np.abs(x) + 1)
xi[neg] = -xi[neg]
return xi |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tip_fdr(a, alpha=0.05):
""" Returns adjusted TIP p-values for a particular `alpha`. (see :func:`tip_zscores` for more info) :param a: NumPy array, where each... |
zscores = tip_zscores(a)
pvals = stats.norm.pdf(zscores)
rejected, fdrs = fdrcorrection(pvals)
return fdrs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_logged(x, y):
""" Transform `x` and `y` to a log scale while dealing with zeros. This function scales `x` and `y` such that the points that are zero ... |
xi = np.log2(x)
yi = np.log2(y)
xv = np.isfinite(xi)
yv = np.isfinite(yi)
global_min = min(xi[xv].min(), yi[yv].min())
global_max = max(xi[xv].max(), yi[yv].max())
xi[~xv] = global_min
yi[~yv] = global_min
return xi, yi |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _updatecopy(orig, update_with, keys=None, override=False):
""" Update a copy of dest with source. If `keys` is a list, then only update with those keys. """ |
d = orig.copy()
if keys is None:
keys = update_with.keys()
for k in keys:
if k in update_with:
if k in d and not override:
continue
d[k] = update_with[k]
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, x, y, scatter_kwargs, hist_kwargs=None, xhist_kwargs=None, yhist_kwargs=None, num_ticks=3, labels=None, hist_share=False, marginal_histograms=Tru... |
scatter_kwargs = scatter_kwargs or {}
hist_kwargs = hist_kwargs or {}
xhist_kwargs = xhist_kwargs or {}
yhist_kwargs = yhist_kwargs or {}
yhist_kwargs.update(dict(orientation='horizontal'))
# Plot the scatter
coll = self.scatter_ax.scatter(x, y, **scatter_kwargs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_legends(self, xhists=True, yhists=False, scatter=True, **kwargs):
""" Add legends to axes. """ |
axs = []
if xhists:
axs.extend(self.hxs)
if yhists:
axs.extend(self.hys)
if scatter:
axs.extend(self.ax)
for ax in axs:
ax.legend(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genomic_signal(fn, kind):
""" Factory function that makes the right class for the file format. Typically you'll only need this function to create a new genom... |
try:
klass = _registry[kind.lower()]
except KeyError:
raise ValueError(
'No support for %s format, choices are %s'
% (kind, _registry.keys()))
m = klass(fn)
m.kind = kind
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genome(self):
""" "genome" dictionary ready for pybedtools, based on the BAM header. """ |
# This gets the underlying pysam Samfile object
f = self.adapter.fileobj
d = {}
for ref, length in zip(f.references, f.lengths):
d[ref] = (0, length)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mapped_read_count(self, force=False):
""" Counts total reads in a BAM file. If a file self.bam + '.scale' exists, then just read the first line of that file ... |
# Already run?
if self._readcount and not force:
return self._readcount
if os.path.exists(self.fn + '.mmr') and not force:
for line in open(self.fn + '.mmr'):
if line.startswith('#'):
continue
self._readcount = float(l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_2x2_table(table, row_labels, col_labels, fmt="%d"):
""" Prints a table used for Fisher's exact test. Adds row, column, and grand totals. :param table: ... |
grand = sum(table)
# Separate table into components and get row/col sums
t11, t12, t21, t22 = table
# Row sums, col sums, and grand total
r1 = t11 + t12
r2 = t21 + t22
c1 = t11 + t21
c2 = t12 + t22
# Re-cast everything as the appropriate format
t11, t12, t21, t22, c1, c2, r1,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_row_perc_table(table, row_labels, col_labels):
""" given a table, print the percentages rather than the totals """ |
r1c1, r1c2, r2c1, r2c2 = map(float, table)
row1 = r1c1 + r1c2
row2 = r2c1 + r2c2
blocks = [
(r1c1, row1),
(r1c2, row1),
(r2c1, row2),
(r2c2, row2)]
new_table = []
for cell, row in blocks:
try:
x = cell / row
except ZeroDivisionError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_col_perc_table(table, row_labels, col_labels):
""" given a table, print the cols as percentages """ |
r1c1, r1c2, r2c1, r2c2 = map(float, table)
col1 = r1c1 + r2c1
col2 = r1c2 + r2c2
blocks = [
(r1c1, col1),
(r1c2, col2),
(r2c1, col1),
(r2c2, col2)]
new_table = []
for cell, row in blocks:
try:
x = cell / row
except ZeroDivisionErro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
"""Draw ``tree`` to the terminal :type tree: dict :param tree: ``tree`` should be a tree repre... |
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to display
lines_required = self.lines_required(tree)
ens... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_room(self, tree):
"""Clear lines in terminal below current cursor position as required This is important to do before drawing to ensure sufficient room ... |
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lines_required(self, tree, count=0):
"""Calculate number of lines required to draw ``tree``""" |
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tree.get("kwargs", {}).get("title_pos") in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_values(self, tree, bar_d):
"""Calculate values for drawing bars of non-leafs in ``tree`` Recurses through ``tree``, replaces ``dict``s with ``(Bar... |
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
bar_desc = self._calculate_values(t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _draw(self, tree, indent=0):
"""Recurse through ``tree`` and draw all nodes""" |
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwargs = dict(title_pos="above", in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_features_and_arrays(prefix, mmap_mode='r'):
""" Returns the features and NumPy arrays that were saved with save_features_and_arrays. Parameters prefix :... |
features = pybedtools.BedTool(prefix + '.features')
arrays = np.load(prefix + '.npz', mmap_mode=mmap_mode)
return features, arrays |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_features_and_arrays(features, arrays, prefix, compressed=False, link_features=False, overwrite=False):
""" Saves NumPy arrays of processed data, along w... |
if link_features:
if isinstance(features, pybedtools.BedTool):
assert isinstance(features.fn, basestring)
features_filename = features.fn
else:
assert isinstance(features, basestring)
features_filename = features
if overwrite:
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_all(fritz, args):
"""Command that prints all device information.""" |
devices = fritz.get_devices()
for device in devices:
print('#' * 30)
print('name=%s' % device.name)
print(' ain=%s' % device.ain)
print(' id=%s' % device.identifier)
print(' productname=%s' % device.productname)
print(' manufacturer=%s' % device.manufacturer... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def device_statistics(fritz, args):
"""Command that prints the device statistics.""" |
stats = fritz.get_device_statistics(args.ain)
print(stats) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunker(f, n):
""" Utility function to split iterable `f` into `n` chunks """ |
f = iter(f)
x = []
while 1:
if len(x) < n:
try:
x.append(f.next())
except StopIteration:
if len(x) > 0:
yield tuple(x)
break
else:
yield tuple(x)
x = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_feature(f, n):
""" Split an interval into `n` roughly equal portions """ |
if not isinstance(n, int):
raise ValueError('n must be an integer')
orig_feature = copy(f)
step = (f.stop - f.start) / n
for i in range(f.start, f.stop, step):
f = copy(orig_feature)
start = i
stop = min(i + step, orig_feature.stop)
f.start = start
f.stop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tointerval(s):
""" If string, then convert to an interval; otherwise just return the input """ |
if isinstance(s, basestring):
m = coord_re.search(s)
if m.group('strand'):
return pybedtools.create_interval_from_list([
m.group('chrom'),
m.group('start'),
m.group('stop'),
'.',
'0',
m.group... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_width(self):
"""Get maximum width of progress bar :rtype: int :returns: Maximum column width of progress bar """ |
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot draw "
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def full_line_width(self):
"""Find actual length of bar_str e.g., Progress [ | ] 10/10 """ |
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space between end_ch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _supports_colors(term, raise_err, colors):
"""Check if ``term`` supports ``colors`` :raises ColorUnsupportedError: This is raised if ``raise_err`` is ``False... |
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupported by you... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_format_callable(term, color, back_color):
"""Get string-coloring callable Get callable for string output using ``color`` on ``back_color`` on ``term`` :... |
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self, value, newline=True, flush=True):
"""Draw the progress bar :type value: int :param value: Progress value relative to ``self.max_value`` :type newl... |
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_text(nodelist):
"""Get the value from a text node.""" |
value = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
value.append(node.data)
return ''.join(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request(self, url, params=None, timeout=10):
"""Send a request with parameters.""" |
rsp = self._session.get(url, params=params, timeout=timeout)
rsp.raise_for_status()
return rsp.text.strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _login_request(self, username=None, secret=None):
"""Send a login request with paramerters.""" |
url = 'http://' + self._host + '/login_sid.lua'
params = {}
if username:
params['username'] = username
if secret:
params['response'] = secret
plain = self._request(url, params)
dom = xml.dom.minidom.parseString(plain)
sid = get_text(dom.g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _logout_request(self):
"""Send a logout request.""" |
_LOGGER.debug('logout')
url = 'http://' + self._host + '/login_sid.lua'
params = {
'security:command/logout': '1',
'sid': self._sid
}
self._request(url, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_login_secret(challenge, password):
"""Create a login secret.""" |
to_hash = (challenge + '-' + password).encode('UTF-16LE')
hashed = hashlib.md5(to_hash).hexdigest()
return '{0}-{1}'.format(challenge, hashed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _aha_request(self, cmd, ain=None, param=None, rf=str):
"""Send an AHA request.""" |
url = 'http://' + self._host + '/webservices/homeautoswitch.lua'
params = {
'switchcmd': cmd,
'sid': self._sid
}
if param:
params['param'] = param
if ain:
params['ain'] = ain
plain = self._request(url, params)
if p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self):
"""Login and get a valid session ID.""" |
try:
(sid, challenge) = self._login_request()
if sid == '0000000000000000':
secret = self._create_login_secret(challenge, self._password)
(sid2, challenge) = self._login_request(username=self._user,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_elements(self):
"""Get the DOM elements for the device list.""" |
plain = self._aha_request('getdevicelistinfos')
dom = xml.dom.minidom.parseString(plain)
_LOGGER.debug(dom)
return dom.getElementsByTagName("device") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_element(self, ain):
"""Get the DOM element for the specified device.""" |
elements = self.get_device_elements()
for element in elements:
if element.getAttribute('identifier') == ain:
return element
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_devices(self):
"""Get the list of all known devices.""" |
devices = []
for element in self.get_device_elements():
device = FritzhomeDevice(self, node=element)
devices.append(device)
return devices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_by_ain(self, ain):
"""Returns a device specified by the AIN.""" |
devices = self.get_devices()
for device in devices:
if device.ain == ain:
return device |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_target_temperature(self, ain, temperature):
"""Set the thermostate target temperature.""" |
param = 16 + ((float(temperature) - 8) * 2)
if param < min(range(16, 56)):
param = 253
elif param > max(range(16, 56)):
param = 254
self._aha_request('sethkrtsoll', ain=ain, param=int(param)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update the device values.""" |
node = self._fritz.get_device_element(self.ain)
self._update_from_node(node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hkr_state(self):
"""Get the thermostate state.""" |
self.update()
try:
return {
126.5: 'off',
127.0: 'on',
self.eco_temperature: 'eco',
self.comfort_temperature: 'comfort'
}[self.target_temperature]
except KeyError:
return 'manual' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_hkr_state(self, state):
"""Set the state of the thermostat. Possible values for state are: 'on', 'off', 'comfort', 'eco'. """ |
try:
value = {
'off': 0,
'on': 100,
'eco': self.eco_temperature,
'comfort': self.comfort_temperature
}[state]
except KeyError:
return
self.set_target_temperature(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, s):
"""Writes ``s`` to the terminal output stream Writes can be disabled by setting the environment variable `PROGRESSIVE_NOWRITE` to `'True'` ""... |
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
self._stream.write(s) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
"""Saves current cursor position, so that it can be restored later""" |
self.write(self.term.save)
self._saved = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def newline(self):
"""Effects a newline by moving the cursor down and clearing""" |
self.write(self.term.move_down)
self.write(self.term.clear_bol) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach_db(self, db):
""" Attach a gffutils.FeatureDB for access to features. Useful if you want to attach a db after this instance has already been created. ... |
if db is not None:
if isinstance(db, basestring):
db = gffutils.FeatureDB(db)
if not isinstance(db, gffutils.FeatureDB):
raise ValueError(
"`db` must be a filename or a gffutils.FeatureDB")
self._kwargs['db'] = db
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def features(self, ignore_unknown=False):
""" Generator of features. If a gffutils.FeatureDB is attached, returns a pybedtools.Interval for every feature in the ... |
if not self.db:
raise ValueError("Please attach a gffutils.FeatureDB")
for i in self.data.index:
try:
yield gffutils.helpers.asinterval(self.db[i])
except gffutils.FeatureNotFoundError:
if ignore_unknown:
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reindex_to(self, x, attribute="Name"):
""" Returns a copy that only has rows corresponding to feature names in x. Parameters x : str or pybedtools.BedTool BE... |
names = [i[attribute] for i in x]
new = self.copy()
new.data = new.data.reindex(names)
return new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def align_with(self, other):
""" Align the dataframe's index with another. """ |
return self.__class__(self.data.reindex_like(other), **self._kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def radviz(self, column_names, transforms=dict(), **kwargs):
""" Radviz plot. Useful for exploratory visualization, a radviz plot can show multivariate data in 2... |
# make a copy of data
x = self.data[column_names].copy()
for k, v in transforms.items():
x[k] = v(x[k])
def normalize(series):
mn = min(series)
mx = max(series)
return (series - mn) / (mx - mn)
df = x.apply(normalize)
t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_unknown_features(self):
""" Remove features not found in the `gffutils.FeatureDB`. This will typically include 'ambiguous', 'no_feature', etc, but can ... |
if not self.db:
return self
ind = []
for i, gene_id in enumerate(self.data.index):
try:
self.db[gene_id]
ind.append(i)
except gffutils.FeatureNotFoundError:
pass
ind = np.array(ind)
return self._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genes_with_peak(self, peaks, transform_func=None, split=False, intersect_kwargs=None, id_attribute='ID', *args, **kwargs):
""" Returns a boolean index of gen... |
def _transform_func(x):
"""
In order to support transform funcs that return a single feature or
an iterable of features, we need to wrap it
"""
result = transform_func(x)
if isinstance(result, pybedtools.Interval):
result =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enriched(self, thresh=0.05, idx=True):
""" Enriched features. {threshdoc} """ |
return self.upregulated(thresh=thresh, idx=idx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upregulated(self, thresh=0.05, idx=True):
""" Upregulated features. {threshdoc} """ |
ind = (
(self.data[self.pval_column] <= thresh)
& (self.data[self.lfc_column] > 0)
)
if idx:
return ind
return self[ind] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disenriched(self, thresh=0.05, idx=True):
""" Disenriched features. {threshdoc} """ |
return self.downregulated(thresh=thresh, idx=idx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def colormapped_bedfile(self, genome, cmap=None):
""" Create a BED file with padj encoded as color Features will be colored according to adjusted pval (phred tra... |
if self.db is None:
raise ValueError("FeatureDB required")
db = gffutils.FeatureDB(self.db)
def scored_feature_generator(d):
for i in range(len(d)):
try:
feature = db[d.ix[i]]
except gffutils.FeatureNotFoundError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _array_parallel(fn, cls, genelist, chunksize=250, processes=1, **kwargs):
""" Returns an array of genes in `genelist`, using `bins` bins. `genelist` is a lis... |
pool = multiprocessing.Pool(processes)
chunks = list(chunker(genelist, chunksize))
# pool.map can only pass a single argument to the mapped function, so you
# need this trick for passing multiple arguments; idea from
# http://stackoverflow.com/questions/5442910/
# python-multiproc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _array_star(args):
""" Unpacks the tuple `args` and calls _array. Needed to pass multiple args to a pool.map-ed function """ |
fn, cls, genelist, kwargs = args
return _array(fn, cls, genelist, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_npz(self, bigwig, metric='mean0', outdir=None):
""" Bin data for bigwig and save to disk. The .npz file will have the pattern {outdir}/{bigwig}.{chrom}.{w... |
if isinstance(bigwig, _genomic_signal.BigWigSignal):
bigwig = bigwig.fn
if outdir is None:
outdir = os.path.dirname(bigwig)
basename = os.path.basename(bigwig)
windowsize = self.windowsize
outfiles = []
for chrom in self.chroms:
tmp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(signal1, signal2, features, outfn, comparefunc=np.subtract, batchsize=5000, array_kwargs=None, verbose=False):
""" Compares two genomic signal object... |
fout = open(outfn, 'w')
fout.write('track type=bedGraph\n')
i = 0
this_batch = []
for feature in features:
if i <= batchsize:
this_batch.append(feature)
i += 1
continue
if verbose:
print 'working on batch of %s' % batchsize
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_next_prime(N):
"""Find next prime >= N""" |
def is_prime(n):
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i:
i += 2
else:
return False
return True
if N < 3:
return 2
if N % 2 == 0:
N += 1
for n in range(N, 2*N, 2):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def File(name, mode='a', chunk_cache_mem_size=1024**2, w0=0.75, n_cache_chunks=None, **kwds):
"""Create h5py File object with cache specification This function i... |
import sys
import numpy as np
import h5py
name = name.encode(sys.getfilesystemencoding())
open(name, mode).close() # Just make sure the file exists
if mode in [m+b for m in ['w', 'w+', 'r+', 'a', 'a+'] for b in ['', 'b']]:
mode = h5py.h5f.ACC_RDWR
else:
mode = h5py.h5f.ACC_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(c, prefix, relative_paths=True):
""" Save data from a Chipseq object. Parameters c : Chipseq object Chipseq object, most likely after calling the `diffe... |
dirname = os.path.dirname(prefix)
pybedtools.BedTool(c.features).saveas(prefix + '.intervals')
def usepath(f):
if relative_paths:
return os.path.relpath(f, start=dirname)
else:
return os.path.abspath(f)
with open(prefix + '.info', 'w') as fout:
info = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xcorr(x, y, maxlags):
""" Streamlined version of matplotlib's `xcorr`, without the plots. :param x, y: NumPy arrays to cross-correlate :param maxlags: Max nu... |
xlen = len(x)
ylen = len(y)
assert xlen == ylen
c = np.correlate(x, y, mode=2)
# normalize
c /= np.sqrt(np.dot(x, x) * np.dot(y, y))
lags = np.arange(-maxlags, maxlags + 1)
c = c[xlen - 1 - maxlags:xlen + maxlags]
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, x, row_order=None, imshow_kwargs=None, strip=True):
""" Plot the scaled ChIP-seq data. :param x: X-axis to use (e.g, for TSS +/- 1kb with 100 bins... |
nrows = self.diffed_array.shape[0]
if row_order is None:
row_order = np.arange(nrows)
extent = (min(x), max(x), 0, nrows)
axes_info = metaseq.plotutils.matrix_and_line_shell(strip=strip)
fig, matrix_ax, line_ax, strip_ax, cbar_ax = axes_info
_imshow_kwargs = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def callback(self, event):
""" Callback function to spawn a mini-browser when a feature is clicked. """ |
artist = event.artist
ind = artist.ind
limit = 5
browser = True
if len(event.ind) > limit:
print "more than %s genes selected; not spawning browsers" % limit
browser = False
for i in event.ind:
feature = artist.features[ind[i]]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, event=None):
""" Remove all the registered observers for the given event name. Arguments: event (str):
event name to remove. """ |
observers = self._pool.get(event)
if observers:
self._pool[event] = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger(self, event, *args, **kw):
""" Triggers event observers for the given event name, passing custom variadic arguments. """ |
observers = self._pool.get(event)
# If no observers registered for the event, do no-op
if not observers or len(observers) == 0:
return None
# Trigger observers coroutines in FIFO sequentially
for fn in observers:
# Review: perhaps this should not wait
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def until(coro, coro_test, assert_coro=None, *args, **kw):
""" Repeatedly call `coro` coroutine function until `coro_test` returns `True`. This function is the i... |
@asyncio.coroutine
def assert_coro(value):
return not value
return (yield from whilst(coro, coro_test,
assert_coro=assert_coro, *args, **kw)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def curry(arity_or_fn=None, ignore_kwargs=False, evaluator=None, *args, **kw):
""" Creates a function that accepts one or more arguments of a function and either... |
def isvalidarg(x):
return all([
x.kind != x.VAR_KEYWORD,
x.kind != x.VAR_POSITIONAL,
any([
not ignore_kwargs,
ignore_kwargs and x.default == x.empty
])
])
def params(fn):
return inspect.signature(fn).parame... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose(*coros):
""" Creates a coroutine function based on the composition of the passed coroutine functions. Each function consumes the yielded result of th... |
# Make list to inherit built-in type methods
coros = list(coros)
@asyncio.coroutine
def reducer(acc, coro):
return (yield from coro(acc))
@asyncio.coroutine
def wrapper(acc):
return (yield from reduce(reducer, coros,
initializer=acc, right=Tru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.