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 parse_exchange_table_file(f):
"""Parse a space-separated file containing exchange compound flux limits. The first two columns contain compound IDs and compar... |
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
# A line can specify lower limit only (useful for
# medium compounds), or both lower and upper limit.
fields = line.split(None)
if len(fields) < 2 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_exchange_file(path, default_compartment):
"""Parse a file as a list of exchange compounds with flux limits. The file format is detected and the file is... |
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing exchange file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for entry in parse_exchange_table_file(f):
yie... |
<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_limit(limit_def):
"""Parse a structured flux limit definition as obtained from a YAML file Returns a tuple of reaction, lower and upper bound. """ |
lower, upper = get_limits(limit_def)
reaction = limit_def.get('reaction')
return reaction, lower, upper |
<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_limits_list(path, limits):
"""Parse a structured list of flux limits as obtained from a YAML file Yields tuples of reaction ID, lower and upper flux bo... |
context = FilePathContext(path)
for limit_def in limits:
if 'include' in limit_def:
include_context = context.resolve(limit_def['include'])
for limit in parse_limits_file(include_context):
yield limit
else:
yield parse_limit(limit_def) |
<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_limits_table_file(f):
"""Parse a space-separated file containing reaction flux limits The first column contains reaction IDs while the second column co... |
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
# A line can specify lower limit only (useful for
# exchange reactions), or both lower and upper limit.
fields = line.split(None)
if len(fields) < ... |
<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_limits_file(path):
"""Parse a file as a list of reaction flux limits The file format is detected and the file is parsed accordingly. Path can be given ... |
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing limits file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for limit in parse_limits_table_file(f):
yield l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_model_group(path, group):
"""Parse a structured model group as obtained from a YAML file Path can be given as a string or a context. """ |
context = FilePathContext(path)
for reaction_id in group.get('reactions', []):
yield reaction_id
# Parse subgroups
for reaction_id in parse_model_group_list(
context, group.get('groups', [])):
yield reaction_id |
<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_model_group_list(path, groups):
"""Parse a structured list of model groups as obtained from a YAML file Yields reaction IDs. Path can be given as a str... |
context = FilePathContext(path)
for model_group in groups:
if 'include' in model_group:
include_context = context.resolve(model_group['include'])
for reaction_id in parse_model_file(include_context):
yield reaction_id
else:
for reaction_id in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reaction_representer(dumper, data):
"""Generate a parsable reaction representation to the YAML parser. Check the number of compounds in the reaction, if it ... |
if len(data.compounds) > _MAX_REACTION_LENGTH:
def dict_make(compounds):
for compound, value in compounds:
yield OrderedDict([
('id', text_type(compound.name)),
('compartment', compound.compartment),
('value', 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 reader_from_path(cls, path):
"""Create a model from specified path. Path can be a directory containing a ``model.yaml`` or ``model.yml`` file or it can be a ... |
context = FilePathContext(path)
try:
with open(context.filepath, 'r') as f:
return ModelReader(f, context)
except IOError:
# Try to open the default file
for filename in cls.DEFAULT_MODEL:
try:
context = Fil... |
<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_compartments(self):
"""Parse compartment information from model. Return tuple of: 1) iterator of :class:`psamm.datasource.entry.CompartmentEntry`; 2) S... |
compartments = OrderedDict()
boundaries = set()
if 'compartments' in self._model:
boundary_map = {}
for compartment_def in self._model['compartments']:
compartment_id = compartment_def.get('id')
_check_id(compartment_id, 'Compartment')
... |
<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_reactions(self):
"""Yield tuples of reaction ID and reactions defined in the model""" |
# Parse reactions defined in the main model file
if 'reactions' in self._model:
for reaction in parse_reaction_list(
self._context, self._model['reactions'],
self.default_compartment):
yield reaction |
<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_model(self):
"""Yield reaction IDs of model reactions""" |
if self.has_model_definition():
for reaction_id in parse_model_group_list(
self._context, self._model['model']):
yield reaction_id |
<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_limits(self):
"""Yield tuples of reaction ID, lower, and upper bound flux limits""" |
if 'limits' in self._model:
if not isinstance(self._model['limits'], list):
raise ParseError('Expected limits to be a list')
for limit in parse_limits_list(
self._context, self._model['limits']):
yield limit |
<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_exchange(self):
"""Yield tuples of exchange compounds. Each exchange compound is a tuple of compound, reaction ID, lower and upper flux limits. """ |
if 'media' in self._model:
if 'exchange' in self._model:
raise ParseError('Both "media" and "exchange" are specified')
logger.warning(
'The "media" key is deprecated! Please use "exchange" instead:'
' https://psamm.readthedocs.io/en/stabl... |
<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_compounds(self):
"""Yield CompoundEntries for defined compounds""" |
if 'compounds' in self._model:
for compound in parse_compound_list(
self._context, self._model['compounds']):
yield compound |
<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_compartment_entry(self, compartment, adjacencies):
"""Convert compartment entry to YAML dict. Args: compartment: :class:`psamm.datasource.entry.Compa... |
d = OrderedDict()
d['id'] = compartment.id
if adjacencies is not None:
d['adjacent_to'] = adjacencies
order = {key: i for i, key in enumerate(['name'])}
prop_keys = set(compartment.properties)
for prop in sorted(prop_keys,
key=lamb... |
<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_compound_entry(self, compound):
"""Convert compound entry to YAML dict.""" |
d = OrderedDict()
d['id'] = compound.id
order = {
key: i for i, key in enumerate(
['name', 'formula', 'formula_neutral', 'charge', 'kegg',
'cas'])}
prop_keys = (
set(compound.properties) - {'boundary', 'compartment'})
for... |
<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_reaction_entry(self, reaction):
"""Convert reaction entry to YAML dict.""" |
d = OrderedDict()
d['id'] = reaction.id
def is_equation_valid(equation):
# If the equation is a Reaction object, it must have non-zero
# number of compounds.
return (equation is not None and (
not isinstance(equation, Reaction) or
... |
<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_entries(self, stream, entries, converter, properties=None):
"""Write iterable of entries as YAML object to stream. Args: stream: File-like object. ent... |
def iter_entries():
for c in entries:
entry = converter(c)
if entry is None:
continue
if properties is not None:
entry = OrderedDict(
(key, value) for key, value in iteritems(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 write_compartments(self, stream, compartments, adjacencies, properties=None):
"""Write iterable of compartments as YAML object to stream. Args: stream: File-... |
def convert(entry):
return self.convert_compartment_entry(
entry, adjacencies.get(entry.id))
self._write_entries(stream, compartments, convert, properties) |
<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_compounds(self, stream, compounds, properties=None):
"""Write iterable of compounds as YAML object to stream. Args: stream: File-like object. compounds... |
self._write_entries(
stream, compounds, self.convert_compound_entry, properties) |
<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_reactions(self, stream, reactions, properties=None):
"""Write iterable of reactions as YAML object to stream. Args: stream: File-like object. compounds... |
self._write_entries(
stream, reactions, self.convert_reaction_entry, properties) |
<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_api_errorhandler(**kwargs):
r"""Create an API error handler. E.g. register a 404 error: .. code-block:: python app.errorhandler(404)(create_api_errorh... |
def api_errorhandler(e):
if isinstance(e, RESTException):
return e.get_response()
elif isinstance(e, HTTPException) and e.description:
kwargs['message'] = e.description
if kwargs.get('status', 400) >= 500 and hasattr(g, 'sentry_event_id'):
kwargs['error_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 get_method_serializers(self, http_method):
"""Get request method serializers + default media type. Grab serializers from ``method_serializers`` if defined, o... |
if http_method == 'HEAD' and 'HEAD' not in self.method_serializers:
http_method = 'GET'
return (
self.method_serializers.get(http_method, self.serializers),
self.default_method_media_type.get(
http_method, self.default_media_type)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_serializers_by_query_arg(self, serializers):
"""Match serializer by query arg.""" |
# if the format query argument is present, match the serializer
arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME')
if arg_name:
arg_value = request.args.get(arg_name, None)
if arg_value is None:
return None
# Search for the ser... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_serializers_by_accept_headers(self, serializers, default_media_type):
"""Match serializer by `Accept` headers.""" |
# Bail out fast if no accept headers were given.
if len(request.accept_mimetypes) == 0:
return serializers[default_media_type]
# Determine best match based on quality.
best_quality = -1
best = None
has_wildcard = False
for client_accept, quality in 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 match_serializers(self, serializers, default_media_type):
"""Choose serializer for a given request based on query arg or headers. Checks if query arg `format... |
return self._match_serializers_by_query_arg(serializers) or self.\
_match_serializers_by_accept_headers(serializers,
default_media_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_response(self, *args, **kwargs):
"""Create a Flask Response. Dispatch the given arguments to the serializer best matching the current request's Accept h... |
serializer = self.match_serializers(
*self.get_method_serializers(request.method))
if serializer:
return serializer(*args, **kwargs)
abort(406) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch_request(self, *args, **kwargs):
"""Dispatch current request. Dispatch the current request using :class:`flask.views.MethodView` `dispatch_request()`... |
result = super(ContentNegotiatedMethodView, self).dispatch_request(
*args, **kwargs
)
if isinstance(result, Response):
return result
elif isinstance(result, (list, tuple)):
return self.make_response(*result)
else:
return self.make... |
<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_etag(self, etag, weak=False):
"""Validate the given ETag with current request conditions. Compare the given ETag to the ones in the request header If-M... |
# bool(:py:class:`werkzeug.datastructures.ETags`) is not consistent
# in Python 3. bool(Etags()) == True even though it is empty.
if len(request.if_match.as_set(include_weak=weak)) > 0 or \
request.if_match.star_tag:
contains_etag = (request.if_match.contains_weak(et... |
<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_if_modified_since(self, dt, etag=None):
"""Validate If-Modified-Since with current request conditions.""" |
dt = dt.replace(microsecond=0)
if request.if_modified_since and dt <= request.if_modified_since:
raise SameContentException(etag, last_modified=dt) |
<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_default_compartment(model):
"""Return what the default compartment should be set to. If some compounds have no compartment, unique compartment name is re... |
default_compartment = 'c'
default_key = set()
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
for compound, _ in equation.compounds:
default_key.add(compound.compartment)
if None in default_key and default_com... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_best_flux_limit(model):
"""Detect the best default flux limit to use for model output. The default flux limit does not change the model but selecting ... |
flux_limit_count = Counter()
for reaction in model.reactions:
if reaction.id not in model.limits:
continue
equation = reaction.properties['equation']
if equation is None:
continue
_, lower, upper = model.limits[reaction.id]
if upper is not 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 reactions_to_files(model, dest, writer, split_subsystem):
"""Turn the reaction subsystems into their own files. If a subsystem has a number of reactions over... |
def safe_file_name(origin_name):
safe_name = re.sub(
r'\W+', '_', origin_name, flags=re.UNICODE)
safe_name = re.sub(
r'_+', '_', safe_name.lower(), flags=re.UNICODE)
safe_name = safe_name.strip('_')
return safe_name
common_reactions = []
reaction_fil... |
<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_limit_items(lower, upper):
"""Yield key, value pairs for limits dictionary. Yield pairs of key, value where key is ``lower``, ``upper`` or ``fixed`... |
# Use value + 0 to convert any -0.0 to 0.0 which looks better.
if lower is not None and upper is not None and lower == upper:
yield 'fixed', upper + 0
else:
if lower is not None:
yield 'lower', lower + 0
if upper is not None:
yield 'upper', upper + 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 model_exchange(model):
"""Return exchange definition as YAML dict.""" |
# Determine the default flux limits. If the value is already at the
# default it does not need to be included in the output.
lower_default, upper_default = None, None
if model.default_flux_limit is not None:
lower_default = -model.default_flux_limit
upper_default = model.default_flux_li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_reaction_limits(model):
"""Yield model reaction limits as YAML dicts.""" |
for reaction in sorted(model.reactions, key=lambda r: r.id):
equation = reaction.properties.get('equation')
if equation is None:
continue
# Determine the default flux limits. If the value is already at the
# default it does not need to be included in the output.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_compartment_entries(model):
"""Infer compartment entries for model based on reaction compounds.""" |
compartment_ids = set()
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
for compound, _ in equation.compounds:
compartment = compound.compartment
if compartment is None:
compartment = model.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_compartment_adjacency(model):
"""Infer compartment adjacency for model based on reactions.""" |
def reaction_compartments(seq):
for compound, _ in seq:
compartment = compound.compartment
if compartment is None:
compartment = model.default_compartment
if compartment is not None:
yield compartment
for reaction in model.reactions:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_genes(model):
"""Count the number of distinct genes in model reactions.""" |
genes = set()
for reaction in model.reactions:
if reaction.genes is None:
continue
if isinstance(reaction.genes, boolean.Expression):
genes.update(v.symbol for v in reaction.genes.variables)
else:
genes.update(reaction.genes)
return len(genes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _try_parse_formula(self, compound_id, s):
"""Try to parse the given compound formula string. Logs a warning if the formula could not be parsed. """ |
s = s.strip()
if s == '':
return None
try:
# Do not return the parsed formula. For now it is better to keep
# the original formula string unchanged in all cases.
formula.Formula.parse(s)
except formula.ParseError:
logger.warni... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _try_parse_reaction(self, reaction_id, s, parser=parse_reaction, **kwargs):
"""Try to parse the given reaction equation string. Returns the parsed Reaction o... |
try:
return parser(s, **kwargs)
except ReactionParseError as e:
if e.indicator is not None:
logger.error('{}\n{}\n{}'.format(
str(e), s, e.indicator))
raise ParseError('Unable to parse reaction {}: {}'.format(
react... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _try_parse_gene_association(self, reaction_id, s):
"""Try to parse the given gene association rule. Logs a warning if the association rule could not be parse... |
s = s.strip()
if s == '':
return None
try:
return boolean.Expression(s)
except boolean.ParseError as e:
msg = 'Failed to parse gene association for {}: {}'.format(
reaction_id, text_type(e))
if e.indicator is not 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 require_content_types(*allowed_content_types):
r"""Decorator to test if proper Content-Type is provided. :param \*allowed_content_types: List of allowed cont... |
def decorator(f):
@wraps(f)
def inner(*args, **kwargs):
if request.mimetype not in allowed_content_types:
raise InvalidContentType(allowed_content_types)
return f(*args, **kwargs)
return inner
return decorator |
<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, *args, **kwargs):
""" Create a new connection, or return an existing one from the cache. Uses Fabric's current ``env.host_string`` and t... |
key = env.get('host_string'), kwargs.get('base_url', env.get('docker_base_url'))
default_config = _get_default_config(None)
if default_config:
if key not in self:
self[key] = default_config
return default_config.get_client()
config = self.get_or_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 filter_solvers(solvers, requirements):
"""Yield solvers that fullfil the requirements.""" |
for solver in solvers:
for req, value in iteritems(requirements):
if (req in ('integer', 'quadratic', 'rational', 'name') and
(req not in solver or solver[req] != value)):
break
else:
yield solver |
<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_solver_setting(s):
"""Parse a string containing a solver setting""" |
try:
key, value = s.split('=', 1)
except ValueError:
key, value = s, 'yes'
if key in ('rational', 'integer', 'quadratic'):
value = value.lower() in ('1', 'yes', 'true', 'on')
elif key in ('threads',):
value = int(value)
elif key in ('feasibility_tolerance', 'optima... |
<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_reaction_values(self, reaction_id):
"""Return stoichiometric values of reaction as a dictionary""" |
if reaction_id not in self._reaction_set:
raise ValueError('Unknown reaction: {}'.format(repr(reaction_id)))
return self._database.get_reaction_values(reaction_id) |
<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_compound_reactions(self, compound_id):
"""Iterate over all reaction ids the includes the given compound""" |
if compound_id not in self._compound_set:
raise ValueError('Compound not in model: {}'.format(compound_id))
for reaction_id in self._database.get_compound_reactions(compound_id):
if reaction_id in self._reaction_set:
yield reaction_id |
<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_reversible(self, reaction_id):
"""Whether the given reaction is reversible""" |
if reaction_id not in self._reaction_set:
raise ValueError('Reaction not in model: {}'.format(reaction_id))
return self._database.is_reversible(reaction_id) |
<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_exchange(self, reaction_id):
"""Whether the given reaction is an exchange reaction.""" |
reaction = self.get_reaction(reaction_id)
return (len(reaction.left) == 0) != (len(reaction.right) == 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 add_reaction(self, reaction_id):
"""Add reaction to model""" |
if reaction_id in self._reaction_set:
return
reaction = self._database.get_reaction(reaction_id)
self._reaction_set.add(reaction_id)
for compound, _ in reaction.compounds:
self._compound_set.add(compound) |
<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_reaction(self, reaction):
"""Remove reaction from model""" |
if reaction not in self._reaction_set:
return
self._reaction_set.remove(reaction)
self._limits_lower.pop(reaction, None)
self._limits_upper.pop(reaction, None)
# Remove compound from compound_set if it is not referenced
# by any other reactions in the mode... |
<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 copy of model""" |
model = self.__class__(self._database)
model._limits_lower = dict(self._limits_lower)
model._limits_upper = dict(self._limits_upper)
model._reaction_set = set(self._reaction_set)
model._compound_set = set(self._compound_set)
return model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_model(cls, database, reaction_iter=None, exchange=None, limits=None, v_max=None):
"""Get model from reaction name iterator. The model will contain all r... |
model_args = {}
if v_max is not None:
model_args['v_max'] = v_max
model = cls(database, **model_args)
if reaction_iter is None:
reaction_iter = iter(database.reactions)
for reaction_id in reaction_iter:
model.add_reaction(reaction_id)
... |
<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):
"""Run flux analysis command.""" |
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
# Reaction genes information
def reaction_genes_string(id):
if id not in sel... |
<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_fba_minimized(self, reaction):
"""Run normal FBA and flux minimization on model.""" |
epsilon = self._args.epsilon
solver = self._get_solver()
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
start_time = time.time()
# Maximize reaction flux
try:
p.maximize(reaction)
except fluxanalysis.FluxBalanceError as e:
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 run_tfba(self, reaction):
"""Run FBA and tFBA on model.""" |
solver = self._get_solver(integer=True)
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
start_time = time.time()
p.add_thermodynamic()
try:
p.maximize(reaction)
except fluxanalysis.FluxBalanceError as e:
self.report_flux_balance_error(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 is_consistent(database, solver, exchange=set(), zeromass=set()):
"""Try to assign a positive mass to each compound Return True if successful. The masses are ... |
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=1)
prob.set_objective(m.sum(mass_compounds))
# Define constraints
massbalance_lhs = {re... |
<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_reaction_consistency(database, solver, exchange=set(), checked=set(), zeromass=set(), weights={}):
"""Check inconsistent reactions by minimizing mass r... |
# Create Flux balance problem
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=1)
# Define residual mass variables and objective constriants... |
<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_compound_consistency(database, solver, exchange=set(), zeromass=set()):
"""Yield each compound in the database with assigned mass Each compound will be... |
# Create mass balance problem
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=0)
# Define z variables
z = prob.namespace(mass_compounds... |
<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_unique_id(prefix, existing_ids):
"""Return a unique string ID from the prefix. First check if the prefix is itself a unique ID in the set-like paramet... |
if prefix in existing_ids:
suffix = 1
while True:
new_id = '{}_{}'.format(prefix, suffix)
if new_id not in existing_ids:
return new_id
suffix += 1
return prefix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def git_try_describe(repo_path):
"""Try to describe the current commit of a Git repository. Return a string containing a string with the commit ID and/or a base ... |
try:
p = subprocess.Popen(['git', 'describe', '--always', '--dirty'],
cwd=repo_path, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, _ = p.communicate()
except:
return None
else:
if p.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 convex_cardinality_relaxed(f, epsilon=1e-5):
"""Transform L1-norm optimization function into cardinality optimization. The given function must optimize a con... |
def convex_cardinality_wrapper(*args, **kwargs):
def dict_result(r):
if isinstance(r, tuple):
return dict(r[0])
return dict(r)
# Initial run with default weights
full_result = f(*args, **kwargs)
result = dict_result(full_result)
def... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, s):
"""Write message to logger.""" |
for line in re.split(r'\n+', s):
if line != '':
self._logger.log(self._level, 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 fullname(self):
"""Returns the name of the ``Record`` class this ``Property`` is attached to, and attribute name it is attached as.""" |
if not self.bound:
if self.name is not None:
return "(unbound).%s" % self.name
else:
return "(unbound)"
elif not self.class_():
classname = "(GC'd class)"
else:
classname = self.class_().__name__
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 run(self):
"""Run robustness command.""" |
reaction = self._get_objective()
if not self._mm.has_reaction(reaction):
self.fail('Specified biomass reaction is not in model: {}'.format(
reaction))
varying_reaction = self._args.varying
if not self._mm.has_reaction(varying_reaction):
self.fai... |
<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_objective(self, expression):
"""Set objective of problem.""" |
if isinstance(expression, numbers.Number):
# Allow expressions with no variables as objective,
# represented as a number
expression = Expression(offset=expression)
# Clear previous objective
for i in range(swiglpk.glp_get_num_cols(self._p)):
swi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self):
"""Return string indicating the error encountered on failure.""" |
self._check_valid()
if self._ret_val == swiglpk.GLP_ENOPFS:
return 'No primal feasible solution'
elif self._ret_val == swiglpk.GLP_ENODFS:
return 'No dual feasible solution'
return str(swiglpk.glp_get_status(self._problem._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 default_weight(element):
"""Return weight of formula element. This implements the default weight proposed for MapMaker. """ |
if element in (Atom.N, Atom.O, Atom.P):
return 0.4
elif isinstance(element, Radical):
return 40.0
return 1.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 _weighted_formula(form, weight_func):
"""Yield weight of each formula element.""" |
for e, mf in form.items():
if e == Atom.H:
continue
yield e, mf, weight_func(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 _transfers(reaction, delta, elements, result, epsilon):
"""Yield transfers obtained from result.""" |
left = set(c for c, _ in reaction.left)
right = set(c for c, _ in reaction.right)
for c1, c2 in product(left, right):
items = {}
for e in elements:
v = result.get_value(delta[c1, c2, e])
nearest_int = round(v)
if abs(v - nearest_int) < epsilon:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_generic(of, coll):
"""Used to make a new Collection type, without that type having to be defined explicitly. Generates a new type name using the item t... |
assert(issubclass(coll, Collection))
key = (coll.__name__, "%s.%s" % (of.__module__, of.__name__))
if key in GENERIC_TYPES:
if GENERIC_TYPES[key].itemtype != of:
raise exc.PropertyNotUnique(key=key)
else:
# oh, we get to name it? Goodie!
generic_name = "%s%s" % (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 coerce_value(cls, v):
"""Coerce a value to the right type for the collection, or return it if it is already of the right type.""" |
if isinstance(v, cls.itemtype):
return v
else:
try:
return cls.coerceitem(v)
except Exception as e:
raise exc.CollectionItemCoerceError(
itemtype=cls.itemtype,
colltype=cls,
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 extend(self, iterable):
"""Adds new values to the end of the collection, coercing items. """ |
# perhaps: self[len(self):len(self)] = iterable
self._values.extend(self.coerce_value(item) for item in iterable) |
<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_response(self, connection, command_name, **options):
""" Parses a response from the ssdb server """ |
response = connection.read_response()
if command_name in self.response_callbacks and len(response):
status = nativestr(response[0])
if status == RES_STATUS.OK:
return self.response_callbacks[command_name](response[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 incr(self, name, amount=1):
""" Increase the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` . Like **Redi... |
amount = get_integer('amount', amount)
return self.execute_command('incr', name, amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decr(self, name, amount=1):
""" Decrease the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` . Like **... |
amount = get_positive_integer('amount', amount)
return self.execute_command('decr', name, amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getbit(self, name, offset):
""" Returns a boolean indicating the value of ``offset`` in ``name`` Like **Redis.GETBIT** :param string name: the key name :para... |
offset = get_positive_integer('offset', offset)
return self.execute_command('getbit', name, offset) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def countbit(self, name, start=None, size=None):
""" Returns the count of set bits in the value of ``key``. Optional ``start`` and ``size`` paramaters indicate w... |
if start is not None and size is not None:
start = get_integer('start', start)
size = get_integer('size', size)
return self.execute_command('countbit', name, start, size)
elif start is not None:
start = get_integer('start', start)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def substr(self, name, start=None, size=None):
""" Return a substring of the string at key ``name``. ``start`` and ``size`` are 0-based integers specifying the p... |
if start is not None and size is not None:
start = get_integer('start', start)
size = get_integer('size', size)
return self.execute_command('substr', name, start, size)
elif start is not None:
start = get_integer('start', start)
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keys(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` Similiar with **Redis.KEYS** ... |
limit = get_positive_integer('limit', limit)
return self.execute_command('keys', name_start, name_end, limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hincr(self, name, key, amount=1):
""" Increase the value of ``key`` in hash ``name`` by ``amount``. If no key exists, the value will be initialized as ``amou... |
amount = get_integer('amount', amount)
return self.execute_command('hincr', name, key, amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hdecr(self, name, key, amount=1):
""" Decrease the value of ``key`` in hash ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``... |
amount = get_positive_integer('amount', amount)
return self.execute_command('hdecr', name, key, amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hkeys(self, name, key_start, key_end, limit=10):
""" Return a list of the top ``limit`` keys between ``key_start`` and ``key_end`` in hash ``name`` Similiar ... |
limit = get_positive_integer('limit', limit)
return self.execute_command('hkeys', name, key_start, key_end, limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` hash's name between ``name_start`` and ``name_end`` in ascending order ..... |
limit = get_positive_integer('limit', limit)
return self.execute_command('hlist', name_start, name_end, limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hrlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` hash's name between ``name_start`` and ``name_end`` in descending order ... |
limit = get_positive_integer('limit', limit)
return self.execute_command('hrlist', name_start, name_end, limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zset(self, name, key, score=1):
""" Set the score of ``key`` from the zset ``name`` to ``score`` Like **Redis.ZADD** :param string name: the zset name :param... |
score = get_integer('score', score)
return self.execute_command('zset', name, key, 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 zincr(self, name, key, amount=1):
""" Increase the score of ``key`` in zset ``name`` by ``amount``. If no key exists, the value will be initialized as ``amou... |
amount = get_integer('amount', amount)
return self.execute_command('zincr', name, key, amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zdecr(self, name, key, amount=1):
""" Decrease the value of ``key`` in zset ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``... |
amount = get_positive_integer('amount', amount)
return self.execute_command('zdecr', name, key, amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in ascending order ..... |
limit = get_positive_integer('limit', limit)
return self.execute_command('zlist', name_start, name_end, limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zrlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in descending order ... |
limit = get_positive_integer('limit', limit)
return self.execute_command('zrlist', name_start, name_end, limit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zkeys(self, name, key_start, score_start, score_end, limit=10):
""" Return a list of the top ``limit`` keys after ``key_start`` from zset ``name`` with score... |
score_start = get_integer_or_emptystring('score_start', score_start)
score_end = get_integer_or_emptystring('score_end', score_end)
limit = get_positive_integer('limit', limit)
return self.execute_command('zkeys', name, key_start, score_start,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zcount(self, name, score_start, score_end):
""" Returns the number of elements in the sorted set at key ``name`` with a score between ``score_start`` and ``s... |
score_start = get_integer_or_emptystring('score_start', score_start)
score_end = get_integer_or_emptystring('score_end', score_end)
return self.execute_command('zcount', name, score_start, score_end) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qget(self, name, index):
""" Get the element of ``index`` within the queue ``name`` :param string name: the queue name :param int index: the specified index,... |
index = get_integer('index', index)
return self.execute_command('qget', name, 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 qset(self, name, index, value):
""" Set the list element at ``index`` to ``value``. :param string name: the queue name :param int index: the specified index,... |
index = get_integer('index', index)
return self.execute_command('qset', name, index, 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 qpop_front(self, name, size=1):
""" Remove and return the first ``size`` item of the list ``name`` Like **Redis.LPOP** :param string name: the queue name :pa... |
size = get_positive_integer("size", size)
return self.execute_command('qpop_front', name, size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qpop_back(self, name, size=1):
""" Remove and return the last ``size`` item of the list ``name`` Like **Redis.RPOP** :param string name: the queue name :para... |
size = get_positive_integer("size", size)
return self.execute_command('qpop_back', name, size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qlist(self, name_start, name_end, limit):
""" Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` in ascending order .. note:: Th... |
limit = get_positive_integer("limit", limit)
return self.execute_command('qlist', name_start, name_end, limit) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.