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 add_new_enriched_bins_matrixes(region_files, dfs, bin_size):
"""Add enriched bins based on bed files. There is no way to find the correspondence between regi... |
dfs = _remove_epic_enriched(dfs)
names = ["Enriched_" + os.path.basename(r) for r in region_files]
regions = region_files_to_bins(region_files, names, bin_size)
new_dfs = OrderedDict()
assert len(regions.columns) == len(dfs)
for region, (n, df) in zip(regions, dfs.items()):
region... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_chromosome_dfs(df_tuple):
# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame """Merges data from the two strands into strand-agnostic counts."... |
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
return return_other(minus_df, count_column, index_cols)
if minus_df.empty:
return return_other(plus_df, count_column, index_cols)
# sum duplicate bins
# ... |
<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_log2fc_bigwigs(matrix, outdir, args):
# type: (pd.DataFrame, str, Namespace) -> None """Create bigwigs from matrix.""" |
call("mkdir -p {}".format(outdir), shell=True)
genome_size_dict = args.chromosome_sizes
outpaths = []
for bed_file in matrix[args.treatment]:
outpath = join(outdir, splitext(basename(bed_file))[0] + "_log2fc.bw")
outpaths.append(outpath)
data = create_log2fc_data(matrix, 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 add_to_island_expectations_dict(average_window_readcount, current_max_scaled_score, island_eligibility_threshold, island_expectations, gap_contribution):
# t... |
scaled_score = current_max_scaled_score + E_VALUE
for index in range(current_max_scaled_score + 1, scaled_score + 1):
island_expectation = 0.0
i = island_eligibility_threshold #i is the number of tags in the added window
current_island = int(round(index - compute_window_score(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def effective_genome_size(fasta, read_length, nb_cores, tmpdir="/tmp"):
# type: (str, int, int, str) -> None """Compute effective genome size for genome.""" |
idx = Fasta(fasta)
genome_length = sum([len(c) for c in idx])
logging.info("Temporary directory: " + tmpdir)
logging.info("File analyzed: " + fasta)
logging.info("Genome length: " + str(genome_length))
print("File analyzed: ", fasta)
print("Genome length: ", genome_length)
chromosom... |
<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_island_bins(df, window_size, genome, args):
# type: (pd.DataFrame, int, str, Namespace) -> Dict[str, Set[int]] """Finds the enriched bins in a df.""" |
# need these chromos because the df might not have islands in all chromos
chromosomes = natsorted(list(args.chromosome_sizes))
chromosome_island_bins = {} # type: Dict[str, Set[int]]
df_copy = df.reset_index(drop=False)
for chromosome in chromosomes:
cdf = df_copy.loc[df_copy.Chromosome =... |
<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_genome_size_dict(genome):
# type: (str) -> Dict[str,int] """Creates genome size dict from string containing data.""" |
size_file = get_genome_size_file(genome)
size_lines = open(size_file).readlines()
size_dict = {}
for line in size_lines:
genome, length = line.split()
size_dict[genome] = int(length)
return size_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_score_threshold(average_window_readcount, island_enriched_threshold, gap_contribution, boundary_contribution, genome_length_in_bins):
# type: (float,... |
required_p_value = poisson.pmf(island_enriched_threshold,
average_window_readcount)
prob = boundary_contribution * required_p_value
score = -log(required_p_value)
current_scaled_score = int(round(score / BIN_SIZE))
island_expectations_d = {} # type: Dict[int... |
<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_readlength(args):
# type: (Namespace) -> int """Estimate length of reads based on 10000 first.""" |
try:
bed_file = args.treatment[0]
except AttributeError:
bed_file = args.infiles[0]
filereader = "cat "
if bed_file.endswith(".gz") and search("linux", platform, IGNORECASE):
filereader = "zcat "
elif bed_file.endswith(".gz") and search("darwin", platform, IGNORECASE):
... |
<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_closest_readlength(estimated_readlength):
# type: (int) -> int """Find the predefined readlength closest to the estimated readlength. In the case of a ti... |
readlengths = [36, 50, 75, 100]
differences = [abs(r - estimated_readlength) for r in readlengths]
min_difference = min(differences)
index_of_min_difference = [i
for i, d in enumerate(differences)
if d == min_difference][0]
return read... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_version(output):
""" Parses the supplied output and returns the version string. :param output: A string containing the output of running snort. :return... |
for x in output.splitlines():
match = VERSION_PATTERN.match(x)
if match:
return match.group('version').strip()
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 parse_alert(output):
""" Parses the supplied output and yields any alerts. Example alert format: 01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPn... |
for x in output.splitlines():
match = ALERT_PATTERN.match(x)
if match:
rec = {'timestamp': datetime.strptime(match.group('timestamp'),
'%m/%d/%y-%H:%M:%S.%f'),
'sid': int(match.group('sid')),
'revisi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, pcap):
""" Runs snort against the supplied pcap. :param pcap: Filepath to pcap file to scan :returns: tuple of version, list of alerts """ |
proc = Popen(self._snort_cmd(pcap), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise Exception("\n".join(["Execution failed return code: {0}" \
.format(proc.retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, pcap):
""" Runs suricata against the supplied pcap. :param pcap: Filepath to pcap file to scan :returns: tuple of version, list of alerts """ |
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._suri_cmd(pcap, tmpdir), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyse_pcap(infile, filename):
""" Run IDS across the supplied file. :param infile: File like object containing pcap data. :param filename: Filename of the ... |
tmp = tempfile.NamedTemporaryFile(suffix=".pcap", delete=False)
m = hashlib.md5()
results = {'filename': filename,
'status': 'Failed',
'apiversion': __version__,
}
try:
size = 0
while True:
buf = infile.read(16384)
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit_and_render():
""" Blocking POST handler for file submission. Runs snort on supplied file and returns results as rendered html. """ |
data = request.files.file
template = env.get_template("results.html")
if not data:
pass
results = analyse_pcap(data.file, data.filename)
results.update(base)
return template.render(results) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_submit():
""" Blocking POST handler for file submission. Runs snort on supplied file and returns results as json text. """ |
data = request.files.file
response.content_type = 'application/json'
if not data or not hasattr(data, 'file'):
return json.dumps({"status": "Failed", "stderr": "Missing form params"})
return json.dumps(analyse_pcap(data.file, data.filename), default=jsondate, indent=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" Main entrypoint for command-line webserver. """ |
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", help="Web server Host address to bind to",
default="0.0.0.0", action="store", required=False)
parser.add_argument("-p", "--port", help="Web server Port to bind to",
default=8080, action="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 is_pcap(pcap):
""" Simple test for pcap magic bytes in supplied file. :param pcap: File path to Pcap file to check :returns: True if content is pcap (magic b... |
with open(pcap, 'rb') as tmp:
header = tmp.read(4)
# check for both big/little endian
if header == b"\xa1\xb2\xc3\xd4" or \
header == b"\xd4\xc3\xb2\xa1":
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run_ids(runner, pcap):
""" Runs the specified IDS runner. :param runner: Runner instance to use :param pcap: File path to pcap for analysis :returns: dict o... |
run = {'name': runner.conf.get('name'),
'module': runner.conf.get('module'),
'ruleset': runner.conf.get('ruleset', 'default'),
'status': STATUS_FAILED,
}
try:
run_start = datetime.now()
version, alerts = runner.run(pcap)
run['version'] = versi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(pcap):
""" Runs all configured IDS instances against the supplied pcap. :param pcap: File path to pcap file to analyse :returns: Dict with details and re... |
start = datetime.now()
errors = []
status = STATUS_FAILED
analyses = []
pool = ThreadPool(MAX_THREADS)
try:
if not is_pcap(pcap):
raise Exception("Not a valid pcap file")
runners = []
for conf in Config().modules.values():
runner = registry.get(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 _set_up_pool_config(self):
'''
Helper to configure pool options during DatabaseWrapper initialization.
'''
self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS'])
self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns)
... |
<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_connection_pool(self, conn_params):
'''
Helper to initialize the connection pool.
'''
connection_pools_lock.acquire()
try:
# One more read to prevent a read/write race condition (We do this
# here to avoid the overhead of locking each time we get a connection.)
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close(self):
'''
Override to return the connection to the pool rather than closing it.
'''
if self._wrapped_connection and self._pool:
logger.debug("Returning connection %s to pool %s" % (self._wrapped_connection, self._pool))
self._pool.putconn(self._wrapped_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def b58encode_int(i, default_one=True):
'''Encode an integer using Base58'''
if not i and default_one:
return alphabet[0]
string = ""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx] + string
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def breadcrumb_safe(context, label, viewname, *args, **kwargs):
""" Same as breadcrumb but label is not escaped. """ |
append_breadcrumb(context, _(label), viewname, args, kwargs)
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def breadcrumb_raw(context, label, viewname, *args, **kwargs):
""" Same as breadcrumb but label is not translated. """ |
append_breadcrumb(context, escape(label), viewname, args, kwargs)
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def breadcrumb_raw_safe(context, label, viewname, *args, **kwargs):
""" Same as breadcrumb but label is not escaped and translated. """ |
append_breadcrumb(context, label, viewname, args, kwargs)
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_breadcrumbs(context, *args):
""" Render breadcrumbs html using bootstrap css classes. """ |
try:
template_path = args[0]
except IndexError:
template_path = getattr(settings, 'BREADCRUMBS_TEMPLATE',
'django_bootstrap_breadcrumbs/bootstrap2.html')
links = []
for (label, viewname, view_args, view_kwargs) in context[
'request'].META.ge... |
<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_symbol(self, module, name, fallback=None):
""" Find the symbol of the specified name inside the module or raise an exception. """ |
if not hasattr(module, name) and fallback:
return self._find_symbol(module, fallback, None)
return getattr(module, name) |
<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(self, incoming):
""" Store the incoming activation, apply the activation function and store the result as outgoing activation. """ |
assert len(incoming) == self.size
self.incoming = incoming
outgoing = self.activation(self.incoming)
assert len(outgoing) == self.size
self.outgoing = outgoing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delta(self, above):
""" The derivative of the activation function at the current state. """ |
return self.activation.delta(self.incoming, self.outgoing, above) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feed(self, weights, data):
""" Evaluate the network with alternative weights on the input data and return the output activation. """ |
assert len(data) == self.layers[0].size
self.layers[0].apply(data)
# Propagate trough the remaining layers.
connections = zip(self.layers[:-1], weights, self.layers[1:])
for previous, weight, current in connections:
incoming = self.forward(weight, previous.outgoing)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_network(self):
"""Define model and initialize weights.""" |
self.network = Network(self.problem.layers)
self.weights = Matrices(self.network.shapes)
if self.load:
loaded = np.load(self.load)
assert loaded.shape == self.weights.shape, (
'weights to load must match problem definition')
self.weights.flat ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_training(self):
# pylint: disable=redefined-variable-type """Classes needed during training.""" |
if self.check:
self.backprop = CheckedBackprop(self.network, self.problem.cost)
else:
self.backprop = BatchBackprop(self.network, self.problem.cost)
self.momentum = Momentum()
self.decent = GradientDecent()
self.decay = WeightDecay()
self.tying = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _every(times, step_size, index):
""" Given a loop over batches of an iterable and an operation that should be performed every few elements. Determine whether... |
current = index * step_size
step = current // times * times
reached = current >= step
overshot = current >= step + step_size
return current and reached and not overshot |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_tax_lvl(entry, tax_lvl_depth=[]):
""" Parse a single kraken-report entry and return a dictionary of taxa for its named ranks. :type entry: dict :param ... |
# How deep in the hierarchy are we currently? Each two spaces of
# indentation is one level deeper. Also parse the scientific name at this
# level.
depth_and_name = re.match('^( *)(.*)', entry['sci_name'])
depth = len(depth_and_name.group(1))//2
name = depth_and_name.group(2)
# Remove the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_kraken_report(kdata, max_rank, min_rank):
""" Parse a single output file from the kraken-report tool. Return a list of counts at each of the acceptable... |
# map between NCBI taxonomy IDs and the string rep. of the hierarchy
taxa = OrderedDict()
# the master collection of read counts (keyed on NCBI ID)
counts = OrderedDict()
# current rank
r = 0
max_rank_idx = ranks.index(max_rank)
min_rank_idx = ranks.index(min_rank)
for entry in kda... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_samples(kraken_reports_fp, max_rank, min_rank):
""" Parse all kraken-report data files into sample counts dict and store global taxon id -> taxonomy ... |
taxa = OrderedDict()
sample_counts = OrderedDict()
for krep_fp in kraken_reports_fp:
if not osp.isfile(krep_fp):
raise RuntimeError("ERROR: File '{}' not found.".format(krep_fp))
# use the kraken report filename as the sample ID
sample_id = osp.splitext(osp.split(krep_f... |
<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_biom_table(sample_counts, taxa):
""" Create a BIOM table from sample counts and taxonomy metadata. :type sample_counts: dict :param sample_counts: A d... |
data = [[0 if taxid not in sample_counts[sid] else sample_counts[sid][taxid]
for sid in sample_counts]
for taxid in taxa]
data = np.array(data, dtype=int)
tax_meta = [{'taxonomy': taxa[taxid]} for taxid in taxa]
gen_str = "kraken-biom v{} ({})".format(__version__, _... |
<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_biom(biomT, output_fp, fmt="hdf5", gzip=False):
""" Write the BIOM table to a file. :type biomT: biom.table.Table :param biomT: A BIOM table containing... |
opener = open
mode = 'w'
if gzip and fmt != "hdf5":
if not output_fp.endswith(".gz"):
output_fp += ".gz"
opener = gzip_open
mode = 'wt'
# HDF5 BIOM files are gzipped by default
if fmt == "hdf5":
opener = h5py.File
with opener(output_fp, mode) as bio... |
<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_otu_file(otu_ids, fp):
""" Write out a file containing only the list of OTU IDs from the kraken data. One line per ID. :type otu_ids: list or iterable ... |
fpdir = osp.split(fp)[0]
if not fpdir == "" and not osp.isdir(fpdir):
raise RuntimeError("Specified path does not exist: {}".format(fpdir))
with open(fp, 'wt') as outf:
outf.write('\n'.join(otu_ids)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, X):
"""Performs predictions blending using the trained weights. Args: X (array-like):
Predictions of different models. Returns: dict with bl... |
assert np.shape(X)[0] == len(self._weights), (
'BlendingOptimizer: Number of models to blend its predictions and weights does not match: '
'n_models={}, weights_len={}'.format(np.shape(X)[0], len(self._weights)))
blended_predictions = np.average(np.power(X, self._power),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False):
"""Fit optimizer to X, then transforms X. See `fit` and `transform` for furthe... |
self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start)
return self.transform(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 escape_tags(value, valid_tags):
""" Strips text from the given html string, leaving only tags. This functionality requires BeautifulSoup, nothing will be don... |
# 1. escape everything
value = conditional_escape(value)
# 2. Reenable certain tags
if valid_tags:
# TODO: precompile somewhere once?
tag_re = re.compile(r'<(\s*/?\s*(%s))(.*?\s*)>' %
'|'.join(re.escape(tag) for tag in valid_tags))
value = tag_... |
<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_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings.""" |
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except Exception: # previously caught DatabaseError
# Return an empty list if this is called too early
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_seo_admin(admin_site, metadata_class):
"""Register the backends specified in Meta.backends with the admin.""" |
if metadata_class._meta.use_sites:
path_admin = SitePathMetadataAdmin
model_instance_admin = SiteModelInstanceMetadataAdmin
model_admin = SiteModelMetadataAdmin
view_admin = SiteViewMetadataAdmin
else:
path_admin = PathMetadataAdmin
model_instance_admin = ModelI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_form(self, i, **kwargs):
"""Override the method to change the form attribute empty_permitted.""" |
form = super(MetadataFormset, self)._construct_form(i, **kwargs)
# Monkey patch the form to always force a save.
# It's unfortunate, but necessary because we always want an instance
# Affect on performance shouldn't be too great, because ther is only
# ever one metadata attached... |
<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_metadata_model(name=None):
"""Find registered Metadata object.""" |
if name is not None:
try:
return registry[name]
except KeyError:
if len(registry) == 1:
valid_names = 'Try using the name "%s" or simply leaving it '\
'out altogether.' % list(registry)[0]
else:
valid_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_value(self, name):
""" Returns an appropriate value for the given name. """ |
name = str(name)
if name in self._metadata._meta.elements:
element = self._metadata._meta.elements[name]
# Look in instances for an explicit value
if element.editable:
value = getattr(self, name)
if value:
return v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _urls_for_js(urls=None):
""" Return templated URLs prepared for javascript. """ |
if urls is None:
# prevent circular import
from .urls import urlpatterns
urls = [url.name for url in urlpatterns if getattr(url, 'name', None)]
urls = dict(zip(urls, [get_uri_template(url) for url in urls]))
urls.update(getattr(settings, 'LEAFLET_STORAGE_EXTRA_URLS', {}))
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorated_patterns(func, *urls):
""" Utility function to decorate a group of url in urls.py Taken from http://djangosnippets.org/snippets/532/ + comments See... |
def decorate(urls, func):
for url in urls:
if isinstance(url, RegexURLPattern):
url.__class__ = DecoratedURLPattern
if not hasattr(url, "_decorate_with"):
setattr(url, "_decorate_with", [])
url._decorate_with.append(func)
... |
<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_custom_fields(self):
""" Return a list of custom fields for this model """ |
return CustomField.objects.filter(
content_type=ContentType.objects.get_for_model(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 get_custom_field(self, field_name):
""" Get a custom field object for this model field_name - Name of the custom field you want. """ |
content_type = ContentType.objects.get_for_model(self)
return CustomField.objects.get(
content_type=content_type, name=field_name) |
<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_custom_value(self, field_name):
""" Get a value for a specified custom field field_name - Name of the custom field you want. """ |
custom_field = self.get_custom_field(field_name)
return CustomFieldValue.objects.get_or_create(
field=custom_field, object_id=self.id)[0].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 set_custom_value(self, field_name, value):
""" Set a value for a specified custom field field_name - Name of the custom field you want. value - Value to set ... |
custom_field = self.get_custom_field(field_name)
custom_value = CustomFieldValue.objects.get_or_create(
field=custom_field, object_id=self.id)[0]
custom_value.value = value
custom_value.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 assign_item(self, item, origin):
""" Assigns an item from a given cluster to the closest located cluster. :param item: the item to be moved. :param origin: t... |
closest_cluster = origin
for cluster in self.__clusters:
if self.distance(item, centroid(cluster)) < self.distance(
item, centroid(closest_cluster)):
closest_cluster = cluster
if id(closest_cluster) != id(origin):
self.move_item(item,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_item(self, item, origin, destination):
""" Moves an item from one cluster to anoter cluster. :param item: the item to be moved. :param origin: the origi... |
if self.equality:
item_index = 0
for i, element in enumerate(origin):
if self.equality(element, item):
item_index = i
break
else:
item_index = origin.index(item)
destination.append(origin.pop(item_index... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialise_clusters(self, input_, clustercount):
""" Initialises the clusters by distributing the items from the data. evenly across n clusters :param input_... |
# initialise the clusters with empty lists
self.__clusters = []
for _ in range(clustercount):
self.__clusters.append([])
# distribute the items into the clusters
count = 0
for item in input_:
self.__clusters[count % clustercount].append(item)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_progress(self, total, current):
""" If a progress function was supplied, this will call that function with the total number of elements, and the rema... |
if self.progress_callback:
self.progress_callback(total, current) |
<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_linkage_method(self, method):
""" Sets the method to determine the distance between two clusters. :param method: The method to use. It can be one of ``'s... |
if method == 'single':
self.linkage = single
elif method == 'complete':
self.linkage = complete
elif method == 'average':
self.linkage = average
elif method == 'uclus':
self.linkage = uclus
elif hasattr(method, '__call__'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cluster(self, matrix=None, level=None, sequence=None):
""" Perform hierarchical clustering. :param matrix: The 2D list that is currently under processing. Th... |
logger.info("Performing cluster()")
if matrix is None:
# create level 0, first iteration (sequence)
level = 0
sequence = 0
matrix = []
# if the matrix only has two rows left, we are done
linkage = partial(self.linkage, distance_function=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(L):
""" Flattens a list. Example: [a,b,c,d,e,f] """ |
if not isinstance(L, list):
return [L]
if L == []:
return L
return flatten(L[0]) + flatten(L[1:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fullyflatten(container):
""" Completely flattens out a cluster and returns a one-dimensional set containing the cluster's items. This is useful in cases wher... |
flattened_items = []
for item in container:
if hasattr(item, 'items'):
flattened_items = flattened_items + fullyflatten(item.items)
else:
flattened_items.append(item)
return flattened_items |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minkowski_distance(x, y, p=2):
""" Calculates the minkowski distance between two points. :param x: the first point :param y: the second point :param p: the o... |
from math import pow
assert len(y) == len(x)
assert len(x) >= 1
sum = 0
for i in range(len(x)):
sum += abs(x[i] - y[i]) ** p
return pow(sum, 1.0 / float(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 magnitude(a):
"calculates the magnitude of a vecor"
from math import sqrt
sum = 0
for coord in a:
sum += coord ** 2
return sqrt(sum) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dotproduct(a, b):
"Calculates the dotproduct between two vecors"
assert(len(a) == len(b))
out = 0
for i in range(len(a)):
out += a[i] * b[i]
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def centroid(data, method=median):
"returns the central vector of a list of vectors"
out = []
for i in range(len(data[0])):
out.append(method([x[i] for x in data]))
return tuple(out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display(self, depth=0):
""" Pretty-prints this cluster. Useful for debuging. """ |
print(depth * " " + "[level %s]" % self.level)
for item in self.items:
if isinstance(item, Cluster):
item.display(depth + 1)
else:
print(depth * " " + "%s" % item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getlevel(self, threshold):
""" Retrieve all clusters up to a specific level threshold. This level-threshold represents the maximum distance between two clust... |
left = self.items[0]
right = self.items[1]
# if this object itself is below the threshold value we only need to
# return it's contents as a list
if self.level <= threshold:
return [fullyflatten(self.items)]
# if this cluster's level is higher than the thre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jsmin(js, **kwargs):
""" returns a minified version of the javascript string """ |
if not is_3:
if cStringIO and not isinstance(js, unicode):
# strings can use cStringIO for a 3x performance
# improvement, but unicode (in python2) cannot
klass = cStringIO.StringIO
else:
klass = StringIO.StringIO
else:
klass = io.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cached(fun):
""" memoizing decorator for linkage functions. Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because, the way this is coded... |
_cache = {}
@wraps(fun)
def newfun(a, b, distance_function):
frozen_a = frozenset(a)
frozen_b = frozenset(b)
if (frozen_a, frozen_b) not in _cache:
result = fun(a, b, distance_function)
_cache[(frozen_a, frozen_b)] = result
return _cache[(frozen_a, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def single(a, b, distance_function):
""" Given two collections ``a`` and ``b``, this will return the distance of the points which are closest together. ``distanc... |
left_a, right_a = min(a), max(a)
left_b, right_b = min(b), max(b)
result = min(distance_function(left_a, right_b),
distance_function(left_b, right_a))
return 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 average(a, b, distance_function):
""" Given two collections ``a`` and ``b``, this will return the mean of all distances. ``distance_function`` is used to det... |
distances = [distance_function(x, y)
for x in a for y in b]
return sum(distances) / len(distances) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def worker(self):
""" Multiprocessing task function run by worker processes """ |
tasks_completed = 0
for task in iter(self.task_queue.get, 'STOP'):
col_index, item, item2 = task
if not hasattr(item, '__iter__') or isinstance(item, tuple):
item = [item]
if not hasattr(item2, '__iter__') or isinstance(item2, tuple):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genmatrix(self, num_processes=1):
""" Actually generate the matrix :param num_processes: If you want to use multiprocessing to split up the work and run ``co... |
use_multiprocessing = num_processes > 1
if use_multiprocessing:
self.task_queue = Queue()
self.done_queue = Queue()
self.matrix = []
logger.info("Generating matrix for %s items - O(n^2)", len(self.data))
if use_multiprocessing:
logger.info("U... |
<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(fname):
""" This function uses dciodvfy to generate a list of warnings and errors discovered within the DICOM file. :param fname: Location and filen... |
validation = {
"errors": [],
"warnings": []
}
for line in _process(fname):
kind, message = _determine(line)
if kind in validation:
validation[kind].append(message)
return validation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def numpy(self):
""" Grabs image data and converts it to a numpy array """ |
# load GDCM's image reading functionality
image_reader = gdcm.ImageReader()
image_reader.SetFileName(self.fname)
if not image_reader.Read():
raise IOError("Could not read DICOM image")
pixel_array = self._gdcm_to_numpy(image_reader.GetImage())
return pixel_ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gdcm_to_numpy(self, image):
""" Converts a GDCM image to a numpy array. :param image: GDCM.ImageReader.GetImage() """ |
gdcm_typemap = {
gdcm.PixelFormat.INT8: numpy.int8,
gdcm.PixelFormat.UINT8: numpy.uint8,
gdcm.PixelFormat.UINT16: numpy.uint16,
gdcm.PixelFormat.INT16: numpy.int16,
gdcm.PixelFormat.UINT32: numpy.uint32,
gdcm.PixelFormat.INT3... |
<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_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None, cmap=None, format=None, origin=None):
""" This method saves the image from a numpy array usi... |
from matplotlib.backends.backend_agg \
import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from pylab import cm
if pixel_array is None:
pixel_array = self.numpy
if cmap is None:
cmap = cm.bone
fig = Figure(figsize... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self):
""" Returns array of dictionaries containing all the data elements in the DICOM file. """ |
def ds(data_element):
value = self._str_filter.ToStringPair(data_element.GetTag())
if value[1]:
return DataElement(data_element, value[0].strip(), value[1].strip())
results = [data for data in self.walk(ds) if data is not None]
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def walk(self, fn):
""" Loops through all data elements and allows a function to interact with each data element. Uses a generator to improve iteration. :param f... |
if not hasattr(fn, "__call__"):
raise TypeError("""walk_dataset requires a
function as its parameter""")
dataset = self._dataset
iterator = dataset.GetDES().begin()
while (not iterator.equal(dataset.GetDES().end())):
data_element = iterator.next(... |
<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(self, group=None, element=None, name=None, VR=None):
""" Searches for data elements in the DICOM file given the filters supplied to this method. :param ... |
results = self.read()
if name is not None:
def find_name(data_element):
return data_element.name.lower() == name.lower()
return filter(find_name, results)
if group is not None:
def find_group(data_element):
return (data_eleme... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def anonymize(self):
""" According to PS 3.15-2008, basic application level De-Indentification of a DICOM file requires replacing the values of a set of data ele... |
self._anon_obj = gdcm.Anonymizer()
self._anon_obj.SetFile(self._file)
self._anon_obj.RemoveGroupLength()
if self._anon_tags is None:
self._anon_tags = get_anon_tags()
for tag in self._anon_tags:
cur_tag = tag['Tag'].replace("(", "")
cur_tag ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image(self):
""" Read the loaded DICOM image data """ |
if self._image is None:
self._image = Image(self.fname)
return self._image |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repo_name(self):
""" Returns a DataFrame of the repo names present in this project directory :return: DataFrame """ |
ds = [[x.repo_name] for x in self.repos]
df = pd.DataFrame(ds, columns=['repository'])
return df |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def command(self):
"""Manually import a CSV into a nYNAB budget""" |
print('pynYNAB CSV import')
args = self.parser.parse_args()
verify_common_args(args)
verify_csvimport(args.schema, args.accountname)
client = clientfromkwargs(**args)
delta = do_csvimport(args, client)
client.push(expected_delta=delta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def command(self):
"""Manually import an OFX into a nYNAB budget""" |
print('pynYNAB OFX import')
args = self.parser.parse_args()
verify_common_args(args)
client = clientfromkwargs(**args)
delta = do_ofximport(args.file, client)
client.push(expected_delta=delta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_listener(col_attr, default):
"""Establish a default-setting listener.""" |
@event.listens_for(col_attr, "init_scalar", retval=True, propagate=True)
def init_scalar(target, value, dict_):
if default.is_callable:
# the callable of ColumnDefault always accepts a context argument
value = default.arg(None)
elif default.is_scalar:
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 has_coverage(self):
""" Returns a boolean for is a parseable .coverage file can be found in the repository :return: bool """ |
if os.path.exists(self.git_dir + os.sep + '.coverage'):
try:
with open(self.git_dir + os.sep + '.coverage', 'r') as f:
blob = f.read()
blob = blob.split('!')[2]
json.loads(blob)
return True
exce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __check_extension(files, ignore_globs=None, include_globs=None):
""" Internal method to filter a list of file changes by extension and ignore_dirs. :param fi... |
if include_globs is None or include_globs == []:
include_globs = ['*']
out = {}
for key in files.keys():
# count up the number of patterns in the ignore globs list that match
if ignore_globs is not None:
count_exclude = sum([1 if fnmatch.fnm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repo_name(self):
""" Returns the name of the repository, using the local directory name. :returns: str """ |
if self._git_repo_name is not None:
return self._git_repo_name
else:
reponame = self.repo.git_dir.split(os.sep)[-2]
if reponame.strip() == '':
return 'unknown_repo'
return reponame |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode(self, obj, context):
""" Get the python representation of the obj """ |
return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode("utf8") |
<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, instance, validated_data):
""" temporarily remove hstore virtual fields otherwise DRF considers them many2many """ |
model = self.Meta.model
meta = self.Meta.model._meta
original_virtual_fields = list(meta.virtual_fields) # copy
if hasattr(model, '_hstore_virtual_fields'):
# remove hstore virtual fields from meta
for field in model._hstore_virtual_fields.values():
... |
<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_image(self, data):
""" update image on panel, as quickly as possible """ |
if 1 in data.shape:
data = data.squeeze()
if self.conf.contrast_level is not None:
clevels = [self.conf.contrast_level, 100.0-self.conf.contrast_level]
imin, imax = np.percentile(data, clevels)
data = np.clip((data - imin)/(imax - imin + 1.e-8), 0, 1)
... |
<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_viewlimits(self, axes=None):
""" update xy limits of a plot""" |
if axes is None:
axes = self.axes
xmin, xmax, ymin, ymax = self.data_range
if len(self.conf.zoom_lims) >1:
zlims = self.conf.zoom_lims[-1]
if axes in zlims:
xmin, xmax, ymin, ymax = zlims[axes]
xmin = max(self.data_range[0], xmin)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zoom_leftup(self, event=None):
"""leftup event handler for zoom mode in images""" |
if self.zoom_ini is None:
return
ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini
try:
dx = abs(ini_x - event.x)
dy = abs(ini_y - event.y)
except:
dx, dy = 0, 0
t0 = time.time()
self.rbbox = None
self.zoom_ini = 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 collect_directories(self, directories):
""" Collects all the directories into a `set` object. If `self.recursive` is set to `True` this method will iterate t... |
directories = util.to_absolute_paths(directories)
if not self.recursive:
return self._remove_blacklisted(directories)
recursive_dirs = set()
for dir_ in directories:
walk_iter = os.walk(dir_, followlinks=True)
walk_iter = [w[0] for w in walk_iter]
... |
<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_directories(self, directories):
""" Removes any `directories` from the set of plugin directories. `directories` may be a single object or an iterable.... |
directories = util.to_absolute_paths(directories)
self.plugin_directories = util.remove_from_set(self.plugin_directories,
directories) |
<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_blacklisted_directories(self, directories):
""" Attempts to remove the `directories` from the set of blacklisted directories. If a particular director... |
directories = util.to_absolute_paths(directories)
black_dirs = self.blacklisted_directories
black_dirs = util.remove_from_set(black_dirs, directories) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.