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 sites_at_edges( self ):
""" Finds the six sites with the maximum and minimum coordinates along x, y, and z. Args: None Returns: (List(List)):
In the order [... |
min_x = min( [ s.r[0] for s in self.sites ] )
max_x = max( [ s.r[0] for s in self.sites ] )
min_y = min( [ s.r[1] for s in self.sites ] )
max_y = max( [ s.r[1] for s in self.sites ] )
min_z = min( [ s.r[2] for s in self.sites ] )
max_z = max( [ s.r[2] for s in self.sites... |
<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_periodically_contiguous( self ):
""" logical check whether a cluster connects with itself across the simulation periodic boundary conditions. Args: none R... |
edges = self.sites_at_edges()
is_contiguous = [ False, False, False ]
along_x = any( [ s2 in s1.p_neighbours for s1 in edges[0] for s2 in edges[1] ] )
along_y = any( [ s2 in s1.p_neighbours for s1 in edges[2] for s2 in edges[3] ] )
along_z = any( [ s2 in s1.p_neighbours for s1 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_sites_from_neighbours( self, remove_labels ):
""" Removes sites from the set of neighbouring sites if these have labels in remove_labels. Args: Remove... |
if type( remove_labels ) is str:
remove_labels = [ remove_labels ]
self.neighbours = set( n for n in self.neighbours if n.label not in remove_labels ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cumulative_probabilities( self ):
""" Cumulative sum of the relative probabilities for all possible jumps. Args: None Returns: (np.array):
Cumulative sum of... |
partition_function = np.sum( self.p )
return np.cumsum( self.p ) / partition_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 random( self ):
""" Select a jump at random with appropriate relative probabilities. Args: None Returns: (Jump):
The randomly selected Jump. """ |
j = np.searchsorted( self.cumulative_probabilities(), random.random() )
return self.jumps[ j ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time_to_jump( self ):
""" The timestep until the next jump. Args: None Returns: (Float):
The timestep until the next jump. """ |
k_tot = rate_prefactor * np.sum( self.p )
return -( 1.0 / k_tot ) * math.log( random.random() ) |
<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_real_ip(self):
""" Get IP from request. :param request: A usual request object :type request: HttpRequest :return: ipv4 string or None """ |
try:
# Trying to work with most common proxy headers
real_ip = self.request.META['HTTP_X_FORWARDED_FOR']
return real_ip.split(',')[0]
except KeyError:
return self.request.META['REMOTE_ADDR']
except Exception:
# Unknown IP
r... |
<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_ip_range(self):
""" Fetches IpRange instance if request IP is found in database. :param request: A ususal request object :type request: HttpRequest :ret... |
ip = self._get_real_ip()
try:
geobase_entry = IpRange.objects.by_ip(ip)
except IpRange.DoesNotExist:
geobase_entry = None
return geobase_entry |
<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_stored_location(self):
""" Get location from cookie. :param request: A ususal request object :type request: HttpRequest :return: Custom location model "... |
location_storage = storage_class(request=self.request, response=None)
return location_storage.get() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazy_translations(cls):
"""Lazy translations.""" |
return {
cloudfiles.errors.NoSuchContainer: errors.NoContainerException,
cloudfiles.errors.NoSuchObject: errors.NoObjectException,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_info(cls, container, info_obj):
"""Create from subdirectory or file info object.""" |
create_fn = cls.from_subdir if 'subdir' in info_obj \
else cls.from_file_info
return create_fn(container, info_obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_subdir(cls, container, info_obj):
"""Create from subdirectory info object.""" |
return cls(container,
info_obj['subdir'],
obj_type=cls.type_cls.SUBDIR) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose_type(cls, content_type):
"""Choose object type from content type.""" |
return cls.type_cls.SUBDIR if content_type in cls.subdir_types \
else cls.type_cls.FILE |
<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_connection(self):
"""Return native connection object.""" |
kwargs = {
'username': self.account,
'api_key': self.secret_key,
}
# Only add kwarg for servicenet if True because user could set
# environment variable 'RACKSPACE_SERVICENET' separately.
if self.servicenet:
kwargs['servicenet'] = 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 delta_E( self ):
""" The change in system energy if this jump were accepted. Args: None Returns: (Float):
delta E """ |
site_delta_E = self.final_site.energy - self.initial_site.energy
if self.nearest_neighbour_energy:
site_delta_E += self.nearest_neighbour_delta_E()
if self.coordination_number_energy:
site_delta_E += self.coordination_number_delta_E()
return site_delta_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 nearest_neighbour_delta_E( self ):
""" Nearest-neighbour interaction contribution to the change in system energy if this jump were accepted. Args: None Retur... |
delta_nn = self.final_site.nn_occupation() - self.initial_site.nn_occupation() - 1 # -1 because the hopping ion is not counted in the final site occupation number
return ( delta_nn * self.nearest_neighbour_energy ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coordination_number_delta_E( self ):
""" Coordination-number dependent energy conrtibution to the change in system energy if this jump were accepted. Args: N... |
initial_site_neighbours = [ s for s in self.initial_site.p_neighbours if s.is_occupied ] # excludes final site, since this is always unoccupied
final_site_neighbours = [ s for s in self.final_site.p_neighbours if s.is_occupied and s is not self.initial_site ] # excludes initial site
initial_cn_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dr( self, cell_lengths ):
""" Particle displacement vector for this jump Args: cell_lengths (np.array(x,y,z)):
Cell lengths for the orthogonal simulation ce... |
half_cell_lengths = cell_lengths / 2.0
this_dr = self.final_site.r - self.initial_site.r
for i in range( 3 ):
if this_dr[ i ] > half_cell_lengths[ i ]:
this_dr[ i ] -= cell_lengths[ i ]
if this_dr[ i ] < -half_cell_lengths[ i ]:
this_dr[ 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 relative_probability_from_lookup_table( self, jump_lookup_table ):
""" Relative probability of accepting this jump from a lookup-table. Args: jump_lookup_tab... |
l1 = self.initial_site.label
l2 = self.final_site.label
c1 = self.initial_site.nn_occupation()
c2 = self.final_site.nn_occupation()
return jump_lookup_table.jump_probability[ l1 ][ l2 ][ c1 ][ c2 ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def module_cache_get(cache, module):
""" Import a module with an optional yaml config file, but only if we haven't imported it already. :param cache: object whic... |
if getattr(cache, "config", False):
config_file = module[:-2] + "yaml"
if config_file not in cache.config_files and os.path.exists(config_file):
try:
config = yaml_safe_load(config_file, type=dict)
except TypeError as e:
tangelo.log_warning("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 close(self):
"""Flush data, write 28 bytes BGZF EOF marker, and close BGZF file. samtools will look for a magic EOF marker, just a 28 byte empty BGZF block, ... |
if self._buffer:
self.flush()
self._handle.write(_bgzf_eof)
self._handle.flush()
self._handle.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_secret():
"""Check if secret key to encryot sessions exists, generate it otherwise.""" |
home_dir = os.environ['HOME']
file_name = home_dir + "/.ipcamweb"
if os.path.exists(file_name):
with open(file_name, "r") as s_file:
secret = s_file.readline()
else:
secret = os.urandom(24)
with open(file_name, "w") as s_file:
secret = s_file.write(secret... |
<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_snapshots_for_a_minute(path, cam_id, day, hourm):
"""Returns a list of screenshots""" |
screenshoots_path = path+"/"+str(cam_id)+"/"+day+"/"+hourm
if os.path.exists(screenshoots_path):
screenshots = [scr for scr in sorted(os.listdir(screenshoots_path))]
return screenshots
else:
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 is_snv(self):
"""Return ``True`` if it is a SNV""" |
return len(self.REF) == 1 and all(a.type == "SNV" for a in self.ALT) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def affected_start(self):
"""Return affected start position in 0-based coordinates For SNVs, MNVs, and deletions, the behaviour is the start position. In the cas... |
types = {alt.type for alt in self.ALT} # set!
BAD_MIX = {INS, SV, BND, SYMBOLIC} # don't mix well with others
if (BAD_MIX & types) and len(types) == 1 and list(types)[0] == INS:
# Only insertions, return 0-based position right of first base
return self.POS # right of ... |
<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_filter(self, label):
"""Add label to FILTER if not set yet, removing ``PASS`` entry if present """ |
if label not in self.FILTER:
if "PASS" in self.FILTER:
self.FILTER = [f for f in self.FILTER if f != "PASS"]
self.FILTER.append(label) |
<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_format(self, key, value=None):
"""Add an entry to format The record's calls ``data[key]`` will be set to ``value`` if not yet set and value is not ``None... |
if key in self.FORMAT:
return
self.FORMAT.append(key)
if value is not None:
for call in self:
call.data.setdefault(key, 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 gt_type(self):
"""The type of genotype, returns one of ``HOM_REF``, ``HOM_ALT``, and ``HET``. """ |
if not self.called:
return None # not called
elif all(a == 0 for a in self.gt_alleles):
return HOM_REF
elif len(set(self.gt_alleles)) == 1:
return HOM_ALT
else:
return HET |
<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_filtered(self, require=None, ignore=None):
"""Return ``True`` for filtered calls :param iterable ignore: if set, the filters to ignore, make sure to inclu... |
ignore = ignore or ["PASS"]
if "FT" not in self.data or not self.data["FT"]:
return False
for ft in self.data["FT"]:
if ft in ignore:
continue # skip
if not require:
return True
elif ft in require:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self):
"""Return string representation for VCF""" |
if self.mate_chrom is None:
remote_tag = "."
else:
if self.within_main_assembly:
mate_chrom = self.mate_chrom
else:
mate_chrom = "<{}>".format(self.mate_chrom)
tpl = {FORWARD: "[{}:{}[", REVERSE: "]{}:{}]"}[self.mate_orient... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def trend_coefficients(self, order=LINEAR):
'''Calculate trend coefficients for the specified order.'''
if not len(self.points):
raise ArithmeticError('Cannot calculate the trend of an empty series')
return LazyImport.numpy().polyfit(self.timestamps, self.values, order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def moving_average(self, window, method=SIMPLE):
'''Calculate a moving average using the specified method and window'''
if len(self.points) < window:
raise ArithmeticError('Not enough points for moving average')
numpy = LazyImport.numpy()
if method == TimeSeries.SIMPLE:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def forecast(self, horizon, method=ARIMA, frequency=None):
'''Forecast points beyond the time series range using the specified
forecasting method. `horizon` is the number of points to forecast.'''
if len(self.points) <= 1:
raise ArithmeticError('Cannot run forecast when len(series) <... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def decompose(self, frequency, window=None, periodic=False):
'''Use STL to decompose the time series into seasonal, trend, and
residual components.'''
R = LazyImport.rpy2()
if periodic:
window = 'periodic'
elif window is None:
window = frequency
ti... |
<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, label=None, colour='g', style='-'): # pragma: no cover
'''Plot the time series.'''
pylab = LazyImport.pylab()
pylab.plot(self.dates, self.values, '%s%s' % (colour, style), label=label)
if label is not None:
pylab.legend()
pylab.show() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def table_output(data):
'''Get a table representation of a dictionary.'''
if type(data) == DictType:
data = data.items()
headings = [ item[0] for item in data ]
rows = [ item[1] for item in data ]
columns = zip(*rows)
if len(columns):
widths = [ max([ len(str(y)) for y in row ]) ... |
<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_datetime(time):
'''Convert `time` to a datetime.'''
if type(time) == IntType or type(time) == LongType:
time = datetime.fromtimestamp(time // 1000)
return time |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def spellCheckTextgrid(tg, targetTierName, newTierName, isleDict,
printEntries=False):
'''
Spell check words by using the praatio spellcheck function
Incorrect items are noted in a new tier and optionally
printed to the screen
'''
def checkFunc(word):
... |
<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_mapping(pair_str):
"""Split the ``str`` in ``pair_str`` at ``'='`` Warn if key needs to be stripped """ |
orig_key, value = pair_str.split("=", 1)
key = orig_key.strip()
if key != orig_key:
warnings.warn(
"Mapping key {} has leading or trailing space".format(repr(orig_key)),
LeadingTrailingSpaceInKey,
)
return key, 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 parse_mapping(value):
"""Parse the given VCF header line mapping Such a mapping consists of "key=value" pairs, separated by commas and for certain known keys... |
if not value.startswith("<") or not value.endswith(">"):
raise exceptions.InvalidHeaderException(
"Header mapping value was not wrapped in angular brackets"
)
# split the comma-separated list into pairs, ignoring commas in quotes
pairs = split_quoted_string(value[1:-1], delim=",... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_header_parsers():
"""Return mapping for parsers to use for each VCF header type Inject the WarningHelper into the parsers. """ |
result = {
"ALT": MappingHeaderLineParser(header.AltAlleleHeaderLine),
"contig": MappingHeaderLineParser(header.ContigHeaderLine),
"FILTER": MappingHeaderLineParser(header.FilterHeaderLine),
"FORMAT": MappingHeaderLineParser(header.FormatHeaderLine),
"INFO": MappingHeaderLin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_field_value(type_, value):
"""Convert atomic field value according to the type""" |
if value == ".":
return None
elif type_ in ("Character", "String"):
if "%" in value:
for k, v in record.UNESCAPE_MAPPING:
value = value.replace(k, v)
return value
else:
try:
return _CONVERTERS[type_](value)
except ValueError:
... |
<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_field_value(field_info, value):
"""Parse ``value`` according to ``field_info`` """ |
if field_info.id == "FT":
return [x for x in value.split(";") if x != "."]
elif field_info.type == "Flag":
return True
elif field_info.number == 1:
return convert_field_value(field_info.type, value)
else:
if value == ".":
return []
else:
r... |
<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_breakend(alt_str):
"""Parse breakend and return tuple with results, parameters for BreakEnd constructor """ |
arr = BREAKEND_PATTERN.split(alt_str)
mate_chrom, mate_pos = arr[1].split(":", 1)
mate_pos = int(mate_pos)
if mate_chrom[0] == "<":
mate_chrom = mate_chrom[1:-1]
within_main_assembly = False
else:
within_main_assembly = True
FWD_REV = {True: record.FORWARD, False: record... |
<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_sub_grow(ref, alt_str):
"""Process substution where the string grows""" |
if len(alt_str) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty ALT")
elif len(alt_str) == 1:
if ref[0] == alt_str[0]:
return record.Substitution(record.DEL, alt_str)
else:
return record.Substitution(record.INDEL, alt_str)
else:
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 process_sub_shrink(ref, alt_str):
"""Process substution where the string shrink""" |
if len(ref) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty REF")
elif len(ref) == 1:
if ref[0] == alt_str[0]:
return record.Substitution(record.INS, alt_str)
else:
return record.Substitution(record.INDEL, alt_str)
else:
return recor... |
<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_alt(header, ref, alt_str):
# pylint: disable=W0613 """Process alternative value using Header in ``header``""" |
# By its nature, this function contains a large number of case distinctions
if "]" in alt_str or "[" in alt_str:
return record.BreakEnd(*parse_breakend(alt_str))
elif alt_str[0] == "." and len(alt_str) > 0:
return record.SingleBreakEnd(record.FORWARD, alt_str[1:])
elif alt_str[-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 run(self, s):
"""Split string ``s`` at delimiter, correctly interpreting quotes Further, interprets arrays wrapped in one level of ``[]``. No recursive brack... |
begins, ends = [0], []
# transition table
DISPATCH = {
self.NORMAL: self._handle_normal,
self.QUOTED: self._handle_quoted,
self.ARRAY: self._handle_array,
self.DELIM: self._handle_delim,
self.ESCAPED: self._handle_escaped,
}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_calls(self, alts, format_, format_str, arr):
"""Handle FORMAT and calls columns, factored out of parse_line""" |
if format_str not in self._format_cache:
self._format_cache[format_str] = list(map(self.header.get_format_field_info, format_))
# per-sample calls
calls = []
for sample, raw_data in zip(self.samples.names, arr[9:]):
if self.samples.is_parsed(sample):
... |
<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_line(self, line_str):
"""Split line and check number of columns""" |
arr = line_str.rstrip().split("\t")
if len(arr) != self.expected_fields:
raise exceptions.InvalidRecordException(
(
"The line contains an invalid number of fields. Was "
"{} but expected {}\n{}".format(len(arr), 9 + len(self.samples.na... |
<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_info(self, info_str, num_alts):
"""Parse INFO column from string""" |
result = OrderedDict()
if info_str == ".":
return result
# The standard is very nice to parsers, we can simply split at
# semicolon characters, although I (Manuel) don't know how strict
# programs follow this
for entry in info_str.split(";"):
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 _parse_calls_data(klass, format_, infos, gt_str):
"""Parse genotype call information from arrays using format array :param list format: List of strings with ... |
data = OrderedDict()
# The standard is very nice to parsers, we can simply split at
# colon characters, although I (Manuel) don't know how strict
# programs follow this
for key, info, value in zip(format_, infos, gt_str.split(":")):
data[key] = parse_field_value(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 run(self, call, num_alts):
"""Check ``FORMAT`` of a record.Call Currently, only checks for consistent counts are implemented """ |
for key, value in call.data.items():
self._check_count(call, key, value, num_alts) |
<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_next_line(self):
"""Read next line store in self._line and return old one""" |
prev_line = self._line
self._line = self.stream.readline()
return prev_line |
<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_samples_line(klass, arr):
"""Peform additional check on samples line""" |
if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER):
if tuple(arr) != REQUIRE_NO_SAMPLE_HEADER:
raise exceptions.IncorrectVCFFormat(
"Sample header line indicates no sample but does not "
"equal required prefix {}".format("\t".join(REQUIRE_NO_SAMPLE_... |
<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():
'''Lazily import the numpy module'''
if LazyImport.numpy_module is None:
try:
LazyImport.numpy_module = __import__('numpypy')
except ImportError:
try:
LazyImport.numpy_module = __import__('numpy')
ex... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rpy2():
'''Lazily import the rpy2 module'''
if LazyImport.rpy2_module is None:
try:
rpy2 = __import__('rpy2.robjects')
except ImportError:
raise ImportError('The rpy2 module is required')
LazyImport.rpy2_module = rpy2
tr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_position(pos):
"""Map natural position to machine code postion""" |
posiction_dict = dict(zip(range(1, 17), [i for i in range(30, 62) if i % 2]))
return posiction_dict[pos] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snap(self, path=None):
"""Get a snapshot and save it to disk.""" |
if path is None:
path = "/tmp"
else:
path = path.rstrip("/")
day_dir = datetime.datetime.now().strftime("%d%m%Y")
hour_dir = datetime.datetime.now().strftime("%H%M")
ensure_snapshot_dir(path+"/"+self.cam_id+"/"+day_dir+"/"+hour_dir)
f_path = "{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 getNumPhones(isleDict, word, maxFlag):
'''
Get the number of syllables and phones in this word
If maxFlag=True, use the longest pronunciation. Otherwise, take the
average length.
'''
phoneCount = 0
syllableCount = 0
syllableCountList = []
phoneCountList = []
w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def findOODWords(isleDict, wordList):
'''
Returns all of the out-of-dictionary words found in a list of utterances
'''
oodList = []
for word in wordList:
try:
isleDict.lookup(word)
except WordNotInISLE:
oodList.append(word)
oodList = list(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _buildDict(self):
'''
Builds the isle textfile into a dictionary for fast searching
'''
lexDict = {}
with io.open(self.islePath, "r", encoding='utf-8') as fd:
wordList = [line.rstrip('\n') for line in fd]
for row in wordList:
word, pro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def timestamps(self):
'''Get all timestamps from all series in the group.'''
timestamps = set()
for series in self.groups.itervalues():
timestamps |= set(series.timestamps)
return sorted(list(timestamps)) |
<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, overlay=True, **labels): # pragma: no cover
'''Plot all time series in the group.'''
pylab = LazyImport.pylab()
colours = list('rgbymc')
colours_len = len(colours)
colours_pos = 0
plots = len(self.groups)
for name, series in self.groups.iteritems():... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rename(self, **kwargs):
'''Rename series in the group.'''
for old, new in kwargs.iteritems():
if old in self.groups:
self.groups[new] = self.groups[old]
del self.groups[old] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, chrom_or_region, begin=None, end=None):
"""Jump to the start position of the given chromosomal position and limit iteration to the end position :... |
if begin is not None and end is None:
raise ValueError("begin and end must both be None or neither")
# close tabix file if any and is open
if self.tabix_file and not self.tabix_file.closed:
self.tabix_file.close()
# open tabix file if not yet open
if not ... |
<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):
"""Close underlying stream""" |
if self.tabix_file and not self.tabix_file.closed:
self.tabix_file.close()
if self.stream:
self.stream.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize_for_header(key, value):
"""Serialize value for the given mapping key for a VCF header line""" |
if key in QUOTE_FIELDS:
return json.dumps(value)
elif isinstance(value, str):
if " " in value or "\t" in value:
return json.dumps(value)
else:
return value
elif isinstance(value, list):
return "[{}]".format(", ".join(value))
else:
return 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 mapping_to_str(mapping):
"""Convert mapping to string""" |
result = ["<"]
for i, (key, value) in enumerate(mapping.items()):
if i > 0:
result.append(",")
result += [key, "=", serialize_for_header(key, value)]
result += [">"]
return "".join(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 _build_indices(self):
"""Build indices for the different field types""" |
result = {key: OrderedDict() for key in LINES_WITH_ID}
for line in self.lines:
if line.key in LINES_WITH_ID:
result.setdefault(line.key, OrderedDict())
if line.mapping["ID"] in result[line.key]:
warnings.warn(
("See... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Return a copy of this header""" |
return Header([line.copy() for line in self.lines], self.samples.copy()) |
<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_lines(self, key):
"""Return header lines having the given ``key`` as their type""" |
if key in self._indices:
return self._indices[key].values()
else:
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 has_header_line(self, key, id_):
"""Return whether there is a header line with the given ID of the type given by ``key`` :param key: The VCF header key/line ... |
if key not in self._indices:
return False
else:
return id_ in self._indices[key] |
<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_line(self, header_line):
"""Add header line, updating any necessary support indices :return: ``False`` on conflicting line and ``True`` otherwise """ |
self.lines.append(header_line)
self._indices.setdefault(header_line.key, OrderedDict())
if not hasattr(header_line, "mapping"):
return False # no registration required
if self.has_header_line(header_line.key, header_line.mapping["ID"]):
warnings.warn(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Return a copy""" |
mapping = OrderedDict(self.mapping.items())
return self.__class__(self.key, self.value, mapping) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _adjustSyllabification(adjustedPhoneList, syllableList):
'''
Inserts spaces into a syllable if needed
Originally the phone list and syllable list contained the same number
of phones. But the adjustedPhoneList may have some insertions which are
not accounted for in the syllableList.
'''... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _findBestPronunciation(isleWordList, aPron):
'''
Words may have multiple candidates in ISLE; returns the 'optimal' one.
'''
aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory
numDiffList = []
withStress = []
i = 0
alignedSyllabificationList = []
ali... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _syllabifyPhones(phoneList, syllableList):
'''
Given a phone list and a syllable list, syllabify the phones
Typically used by findBestSyllabification which first aligns the phoneList
with a dictionary phoneList and then uses the dictionary syllabification
to syllabify the input phoneList.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def alignPronunciations(pronI, pronA):
'''
Align the phones in two pronunciations
'''
# First prep the two pronunctions
pronI = [char for char in pronI]
pronA = [char for char in pronA]
# Remove any elements not in the other list (but maintain order)
pronITmp = pronI
pronAT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _findBestSyllabification(inputIsleWordList, actualPronunciationList):
'''
Find the best syllabification for a word
First find the closest pronunciation to a given pronunciation. Then take
the syllabification for that pronunciation and map it onto the
input pronunciation.
'''
retList... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _getSyllableNucleus(phoneList):
'''
Given the phones in a syllable, retrieves the vowel index
'''
cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList]
vowelCount = cvList.count('V')
if vowelCount > 1:
raise TooManyVowelsInSyllable(phoneList, cvList)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def findClosestPronunciation(inputIsleWordList, aPron):
'''
Find the closest dictionary pronunciation to a provided pronunciation
'''
retList = _findBestPronunciation(inputIsleWordList, aPron)
isleWordList = retList[0]
bestIndex = retList[3]
return isleWordList[bestIndex] |
<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_switch(type, settings, pin):
"""Create a switch. Args: type: (str):
type of the switch [A,B,C,D] settings (str):
a comma separted list pin (int):
... |
switch = None
if type == "A":
group, device = settings.split(",")
switch = pi_switch.RCSwitchA(group, device)
elif type == "B":
addr, channel = settings.split(",")
addr = int(addr)
channel = int(channel)
switch = pi_switch.RCSwitchB(addr, channel)
elif type == "C":
family, group, device = settings... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_atomic(value):
"""Format atomic value This function also takes care of escaping the value in case one of the reserved characters occurs in the value. ... |
# Perform escaping
if isinstance(value, str):
if any(r in value for r in record.RESERVED_CHARS):
for k, v in record.ESCAPE_MAPPING:
value = value.replace(k, v)
# String-format the given value
if value is None:
return "."
else:
return str(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 format_value(field_info, value, section):
"""Format possibly compound value given the FieldInfo""" |
if section == "FORMAT" and field_info.id == "FT":
if not value:
return "."
elif isinstance(value, list):
return ";".join(map(format_atomic, value))
elif field_info.number == 1:
if value is None:
return "."
else:
return format_atomi... |
<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_header(self):
"""Write out the header""" |
for line in self.header.lines:
print(line.serialize(), file=self.stream)
if self.header.samples.names:
print(
"\t".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names),
file=self.stream,
)
else:
prin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_record(self, record):
"""Serialize whole Record""" |
f = self._empty_to_dot
row = [record.CHROM, record.POS]
row.append(f(";".join(record.ID)))
row.append(f(record.REF))
if not record.ALT:
row.append(".")
else:
row.append(",".join([f(a.serialize()) for a in record.ALT]))
row.append(f(record.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_info(self, record):
"""Return serialized version of record.INFO""" |
result = []
for key, value in record.INFO.items():
info = self.header.get_info_field_info(key)
if info.type == "Flag":
result.append(key)
else:
result.append("{}={}".format(key, format_value(info, value, "INFO")))
return ";".jo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_call(self, format_, call):
"""Return serialized version of the Call using the record's FORMAT'""" |
if isinstance(call, record.UnparsedCall):
return call.unparsed_data
else:
result = [
format_value(self.header.get_format_field_info(key), call.data.get(key), "FORMAT")
for key in format_
]
return ":".join(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 _create_extended_jinja_tags(self, nodes):
"""Loops through the nodes and looks for special jinja tags that contains more than one tag but only one ending tag... |
jinja_a = None
jinja_b = None
ext_node = None
ext_nodes = []
for node in nodes:
if isinstance(node, EmptyLine):
continue
if node.has_children():
node.children = self._create_extended_jinja_tags(node.children)
... |
<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_children(self):
"returns False if children is empty or contains only empty lines else True."
return bool([x for x in self.children if not isinstance(x, EmptyLine)]) |
<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_requirements(path):
"""Parse ``requirements.txt`` at ``path``.""" |
requirements = []
with open(path, "rt") as reqs_f:
for line in reqs_f:
line = line.strip()
if line.startswith("-r"):
fname = line.split()[1]
inner_path = os.path.join(os.path.dirname(path), fname)
requirements += parse_requirements... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watch(cams, path=None, delay=10):
"""Get screenshots from all cams at defined intervall.""" |
while True:
for c in cams:
c.snap(path)
time.sleep(delay) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score(self, phone_number, account_lifecycle_event, **params):
""" Score is an API that delivers reputation scoring based on phone number intelligence, traffi... |
return self.post(SCORE_RESOURCE.format(phone_number=phone_number),
account_lifecycle_event=account_lifecycle_event,
**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 generate_telesign_headers(customer_id, api_key, method_name, resource, url_encoded_fields, date_rfc2616=None, nonce=None, user_agent=None, content_type=None):... |
if date_rfc2616 is None:
date_rfc2616 = formatdate(usegmt=True)
if nonce is None:
nonce = str(uuid.uuid4())
if not content_type:
content_type = "application/x-www-form-urlencoded" if method_name in ("POST", "PUT") else ""
auth_method = "HMA... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, resource, **params):
""" Generic TeleSign REST API POST handler. :param resource: The partial resource URI to perform the request against, as a st... |
return self._execute(self.session.post, 'POST', resource, **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 get(self, resource, **params):
""" Generic TeleSign REST API GET handler. :param resource: The partial resource URI to perform the request against, as a stri... |
return self._execute(self.session.get, 'GET', resource, **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 put(self, resource, **params):
""" Generic TeleSign REST API PUT handler. :param resource: The partial resource URI to perform the request against, as a stri... |
return self._execute(self.session.put, 'PUT', resource, **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 delete(self, resource, **params):
""" Generic TeleSign REST API DELETE handler. :param resource: The partial resource URI to perform the request against, as ... |
return self._execute(self.session.delete, 'DELETE', resource, **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 _execute(self, method_function, method_name, resource, **params):
""" Generic TeleSign REST API request handler. :param method_function: The Requests HTTP re... |
resource_uri = "{api_host}{resource}".format(api_host=self.api_host, resource=resource)
url_encoded_fields = self._encode_params(params)
headers = RestClient.generate_telesign_headers(self.customer_id,
self.api_key,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.