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 qrlist(self, name_start, name_end, limit): """ Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` in descending order .. note:: ...
limit = get_positive_integer("limit", limit) return self.execute_command('qrlist', 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 qrange(self, name, offset, limit): """ Return a ``limit`` slice of the list ``name`` at position ``offset`` ``offset`` can be negative numbers just like Pyth...
offset = get_integer('offset', offset) limit = get_positive_integer('limit', limit) return self.execute_command('qrange', name, offset, 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 setx(self, name, value, ttl): """ Set the value of key ``name`` to ``value`` that expires in ``ttl`` seconds. ``ttl`` can be represented by an integer or a P...
if isinstance(ttl, datetime.timedelta): ttl = ttl.seconds + ttl.days * 24 * 3600 ttl = get_positive_integer('ttl', ttl) return self.execute_command('setx', name, value, ttl)
<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_ip6_address(interface_name, expand=False): """ Extracts the IPv6 address for a particular interface from `ifconfig`. :param interface_name: Name of the n...
address = _get_address(interface_name, IP6_PATTERN) if address and expand: return ':'.join(_expand_groups(address)) return address
<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_current_roles(): """ Determines the list of roles, that the current host is assigned to. If ``env.roledefs`` is not set, an empty list is returned. :retu...
current_host = env.host_string roledefs = env.get('roledefs') if roledefs: return [role for role, hosts in six.iteritems(roledefs) if current_host in hosts] 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 add_all_database_reactions(model, compartments): """Add all reactions from database that occur in given compartments. Args: model: :class:`psamm.metabolicmod...
added = set() for rxnid in model.database.reactions: reaction = model.database.get_reaction(rxnid) if all(compound.compartment in compartments for compound, _ in reaction.compounds): if not model.has_reaction(rxnid): added.add(rxnid) 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 add_all_exchange_reactions(model, compartment, allow_duplicates=False): """Add all exchange reactions to database and to model. Args: model: :class:`psamm.me...
all_reactions = {} if not allow_duplicates: # TODO: Avoid adding reactions that already exist in the database. # This should be integrated in the database. for rxnid in model.database.reactions: rx = model.database.get_reaction(rxnid) all_reactions[rx] = rxnid ...
<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_all_transport_reactions(model, boundaries, allow_duplicates=False): """Add all transport reactions to database and to model. Add transport reactions for ...
all_reactions = {} if not allow_duplicates: # TODO: Avoid adding reactions that already exist in the database. # This should be integrated in the database. for rxnid in model.database.reactions: rx = model.database.get_reaction(rxnid) all_reactions[rx] = rxnid ...
<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_model(model, db_penalty=None, ex_penalty=None, tp_penalty=None, penalties=None): """Create an extended model for gap-filling. Create a :class...
# Create metabolic model model_extended = model.create_metabolic_model() extra_compartment = model.extracellular_compartment compartment_ids = set(c.id for c in model.compartments) # Add database reactions to extended model if len(compartment_ids) > 0: logger.info( 'Using...
<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 formula balance command"""
# Create a set of excluded reactions exclude = set(self._args.exclude) count = 0 unbalanced = 0 unchecked = 0 for reaction, result in formula_balance(self._model): count += 1 if reaction.id in exclude or reaction.equation is 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 _is_shadowed(self, reaction_id, database): """Whether reaction in database is shadowed by another database"""
for other_database in self._databases: if other_database == database: break if other_database.has_reaction(reaction_id): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push_log(self, info, level=None, *args, **kwargs): """ Prints the log as usual for fabric output, enhanced with the prefix "docker". :param info: Log output....
if args: msg = info % args else: msg = info try: puts('docker: {0}'.format(msg)) except UnicodeDecodeError: puts('docker: -- non-printable 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 push_progress(self, status, object_id, progress): """ Prints progress information. :param status: Status text. :type status: unicode :param object_id: Object...
fastprint(progress_fmt(status, object_id, progress), end='\n')
<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): """ Closes the connection and any tunnels created for it. """
try: super(DockerFabricClient, self).close() finally: if self._tunnel is not None: self._tunnel.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 ranged_property(min=None, max=None): """Decorator for creating ranged property with fixed bounds."""
min_value = -_INF if min is None else min max_value = _INF if max is None else max return lambda fget: RangedProperty( fget, fmin=lambda obj: min_value, fmax=lambda obj: max_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 value(self): """Value of property."""
if self._prop.fget is None: raise AttributeError('Unable to read attribute') return self._prop.fget(self._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 min(self): """Minimum value."""
if self._prop.fmin is None: return -_INF return self._prop.fmin(self._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 max(self): """Maximum value."""
if self._prop.fmax is None: return _INF return self._prop.fmax(self._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 define(self, names, **kwargs): """Define variables within the namespace. This is similar to :meth:`.Problem.define` except that names must be given as an ite...
define_kwargs = dict(self._define_kwargs) define_kwargs.update(kwargs) self._problem.define( *((self, name) for name in names), **define_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, names): """Return a variable set of the given names in the namespace. """
return self._problem.set((self, name) for name in names)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expr(self, items): """Return the sum of each name multiplied by a coefficient. """
return Expression({(self, name): value for name, value in items})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_value(self, expression): """Get value of variable or expression in result Expression can be an object defined as a name in the problem, in which case the...
if isinstance(expression, Expression): return self._evaluate_expression(expression) elif not self._has_variable(expression): raise ValueError('Unknown expression: {}'.format(expression)) return self._get_value(expression)
<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 linear objective of problem."""
if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression() self._p.setObjective( self._grb_expr_from_value_set(expression.values()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_python(self, message, namespace): """Open interactive python console"""
# Importing readline will in some cases print weird escape # characters to stdout. To avoid this we only import readline # and related packages at this point when we are certain # they are needed. from code import InteractiveConsole import readline import rlcomp...
<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 check for duplicates"""
# Create dictonary of signatures database_signatures = {} for entry in self._model.reactions: signature = reaction_signature( entry.equation, direction=self._args.compare_direction, stoichiometry=self._args.compare_stoichiometry) database...
<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_charge(reaction, compound_charge): """Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. com...
charge_sum = 0.0 for compound, value in reaction.compounds: charge = compound_charge.get(compound.name, float('nan')) charge_sum += charge * float(value) return charge_sum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def charge_balance(model): """Calculate the overall charge for all reactions in the model. Yield (reaction, charge) pairs. Args: model: :class:`psamm.datasource....
compound_charge = {} for compound in model.compounds: if compound.charge is not None: compound_charge[compound.id] = compound.charge for reaction in model.reactions: charge = reaction_charge(reaction.equation, compound_charge) yield reaction, charge
<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_formula(reaction, compound_formula): """Calculate formula compositions for both sides of the specified reaction. If the compounds in the reaction al...
def multiply_formula(compound_list): for compound, count in compound_list: yield count * compound_formula[compound.name] for compound, _ in reaction.compounds: if compound.name not in compound_formula: return None else: left_form = reduce( opera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formula_balance(model): """Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs,...
# Mapping from compound id to formula compound_formula = {} for compound in model.compounds: if compound.formula is not None: try: f = Formula.parse(compound.formula).flattened() compound_formula[compound.id] = f except ParseError as 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 run(self): """Run flux consistency check 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) epsilon = self._args.epsilon if self._args.unrestricted: # Allow all exchan...
<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 charge balance 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) # Create a set of excluded reactions exclude = set(self._args.exclude) count = 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 create_property_type_from_traits(trait_set): """Takes an iterable of trait names, and tries to compose a property type from that. Raises an exception if this...
wanted_traits = set(trait_set) stock_types = dict( (k, v) for k, v in PROPERTY_TYPES.items() if set(k).issubset(wanted_traits) ) traits_available = set() for key in stock_types.keys(): traits_available.update(key) missing_traits = wanted_traits - traits_available 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 _resolve_source(self, source): """Resolve source to filepath if it is a directory."""
if os.path.isdir(source): sources = glob.glob(os.path.join(source, '*.sbml')) if len(sources) == 0: raise ModelLoadError('No .sbml file found in source directory') elif len(sources) > 1: raise ModelLoadError( 'More than one...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flipped(self): """Return the flipped version of this direction."""
forward, reverse = self.value return self.__class__((reverse, forward))
<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 variability 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 = self._get_objective() if not self._mm.has_reaction(reaction): 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 placeholder(type_): """Returns the EmptyVal instance for the given type"""
typetuple = type_ if isinstance(type_, tuple) else (type_,) if any in typetuple: typetuple = any if typetuple not in EMPTY_VALS: EMPTY_VALS[typetuple] = EmptyVal(typetuple) return EMPTY_VALS[typetuple]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def itertypes(iterable): """Iterates over an iterable containing either type objects or tuples of type objects and yields once for every type object found."""
seen = set() for entry in iterable: if isinstance(entry, tuple): for type_ in entry: if type_ not in seen: seen.add(type_) yield type_ else: if entry not in seen: seen.add(entry) yiel...
<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_ignore(path, use_sudo=False, force=False): """ Recursively removes a file or directory, ignoring any errors that may occur. Should only be used for te...
which = sudo if use_sudo else run which(rm(path, recursive=True, force=force), warn_only=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 is_directory(path, use_sudo=False): """ Check if the remote path exists and is a directory. :param path: Remote path to check. :type path: unicode :param use...
result = single_line_stdout('if [[ -f {0} ]]; then echo 0; elif [[ -d {0} ]]; then echo 1; else echo -1; fi'.format(path), sudo=use_sudo, quiet=True) if result == '0': return False elif result == '1': return True else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False): """ Creates a temporary directory on the remote machine. The direct...
path = get_remote_temp() try: if apply_chmod: run(chmod(apply_chmod, path)) if apply_chown: if remove_using_sudo is None: remove_using_sudo = True sudo(chown(apply_chown, path)) yield path finally: remove_ignore(path, use_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 local_temp_dir(): """ Creates a local temporary directory. The directory is removed when no longer needed. Failure to do so will be ignored. :return: Path to...
path = tempfile.mkdtemp() yield path shutil.rmtree(path, ignore_errors=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 get_response(self, environ=None): """Get a list of headers."""
response = super(SameContentException, self).get_response( environ=environ ) if self.etag is not None: response.set_etag(self.etag) if self.last_modified is not None: response.headers['Last-Modified'] = http_date(self.last_modified) return res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classify_coupling(coupling): """Return a constant indicating the type of coupling. Depending on the type of coupling, one of the constants from :class:`.Coup...
lower, upper = coupling if lower is None and upper is None: return CouplingClass.Uncoupled elif lower is None or upper is None: return CouplingClass.DirectionalReverse elif lower == 0.0 and upper == 0.0: return CouplingClass.Inconsistent elif lower <= 0.0 and upper >= 0.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 solve(self, reaction_1, reaction_2): """Return the flux coupling between two reactions The flux coupling is returned as a tuple indicating the minimum and ma...
# Update objective for reaction_1 self._prob.set_objective(self._vbow(reaction_1)) # Update constraint for reaction_2 if self._reaction_constr is not None: self._reaction_constr.delete() self._reaction_constr, = self._prob.add_linear_constraints( 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 perform(action_name, container, **kwargs): """ Performs an action on the given container map and configuration. :param action_name: Name of the action (e.g. ...
cf = container_fabric() cf.call(action_name, container, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_sbml_model(model): """Convert raw SBML model to extended model. Args: model: :class:`NativeModel` obtained from :class:`SBMLReader`. """
biomass_reactions = set() for reaction in model.reactions: # Extract limits if reaction.id not in model.limits: lower, upper = parse_flux_bounds(reaction) if lower is not None or upper is not None: model.limits[reaction.id] = reaction.id, 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 entry_id_from_cobra_encoding(cobra_id): """Convert COBRA-encoded ID string to decoded ID string."""
for escape, symbol in iteritems(_COBRA_DECODE_ESCAPES): cobra_id = cobra_id.replace(escape, symbol) return cobra_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 create_convert_sbml_id_function( compartment_prefix='C_', reaction_prefix='R_', compound_prefix='M_', decode_id=entry_id_from_cobra_encoding): """Create func...
def convert_sbml_id(entry): if isinstance(entry, BaseCompartmentEntry): prefix = compartment_prefix elif isinstance(entry, BaseReactionEntry): prefix = reaction_prefix elif isinstance(entry, BaseCompoundEntry): prefix = compound_prefix new_id = 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 translate_sbml_reaction(entry, new_id, compartment_map, compound_map): """Translate SBML reaction entry."""
new_entry = DictReactionEntry(entry, id=new_id) # Convert compound IDs in reaction equation if new_entry.equation is not None: compounds = [] for compound, value in new_entry.equation.compounds: # Translate compartment to new ID, if available. compartment = compartm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_sbml_compound(entry, new_id, compartment_map): """Translate SBML compound entry."""
new_entry = DictCompoundEntry(entry, id=new_id) if 'compartment' in new_entry.properties: old_compartment = new_entry.properties['compartment'] new_entry.properties['compartment'] = compartment_map.get( old_compartment, old_compartment) # Get XHTML notes properties for 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 parse_xhtml_notes(entry): """Yield key, value pairs parsed from the XHTML notes section. Each key, value pair must be defined in its own text block, e.g. ``<...
for note in entry.xml_notes.itertext(): m = re.match(r'^([^:]+):(.+)$', note) if m: key, value = m.groups() key = key.strip().lower().replace(' ', '_') value = value.strip() m = re.match(r'^"(.*)"$', value) if m: value = m....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_xhtml_species_notes(entry): """Return species properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML ...
properties = {} if entry.xml_notes is not None: cobra_notes = dict(parse_xhtml_notes(entry)) for key in ('pubchem_id', 'chebi_id'): if key in cobra_notes: properties[key] = cobra_notes[key] if 'formula' in cobra_notes: properties['formula'] = co...
<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_xhtml_reaction_notes(entry): """Return reaction properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTM...
properties = {} if entry.xml_notes is not None: cobra_notes = dict(parse_xhtml_notes(entry)) if 'subsystem' in cobra_notes: properties['subsystem'] = cobra_notes['subsystem'] if 'gene_association' in cobra_notes: properties['genes'] = cobra_notes['gene_associat...
<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_objective_coefficient(entry): """Return objective value for reaction entry. Detect objectives that are specified using the non-standardized kinetic law...
for parameter in entry.kinetic_law_reaction_parameters: pid, name, value, units = parameter if (pid == 'OBJECTIVE_COEFFICIENT' or name == 'OBJECTIVE_COEFFICIENT'): return value return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_flux_bounds(entry): """Return flux bounds for reaction entry. Detect flux bounds that are specified using the non-standardized kinetic law parameters w...
lower_bound = None upper_bound = None for parameter in entry.kinetic_law_reaction_parameters: pid, name, value, units = parameter if pid == 'UPPER_BOUND' or name == 'UPPER_BOUND': upper_bound = value elif pid == 'LOWER_BOUND' or name == 'LOWER_BOUND': lower_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_extracellular_compartment(model): """Detect the identifier for equations with extracellular compartments. Args: model: :class:`NativeModel`. """
extracellular_key = Counter() for reaction in model.reactions: equation = reaction.equation if equation is None: continue if len(equation.compounds) == 1: compound, _ = equation.compounds[0] compartment = compound.compartment extracellul...
<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_exchange_to_compounds(model): """Convert exchange reactions in model to exchange compounds. Only exchange reactions in the extracellular compartment ...
# Build set of exchange reactions exchanges = set() for reaction in model.reactions: equation = reaction.properties.get('equation') if equation is None: continue if len(equation.compounds) != 1: # Provide warning for exchange reactions with more than ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _element_get_id(self, element): """Get id of reaction or species element. In old levels the name is used as the id. This method returns the correct attribute...
if self._reader._level > 1: entry_id = element.get('id') else: entry_id = element.get('name') return entry_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 properties(self): """All species properties as a dict"""
properties = {'id': self._id, 'boundary': self._boundary} if 'name' in self._root.attrib: properties['name'] = self._root.get('name') if 'compartment' in self._root.attrib: properties['compartment'] = self._root.get('compartment') charge = ...
<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_species_references(self, name): """Yield species id and parsed value for a speciesReference list"""
for species in self._root.iterfind('./{}/{}'.format( self._reader._sbml_tag(name), self._reader._sbml_tag('speciesReference'))): species_id = species.get('species') if self._reader._level == 1: # In SBML level 1 only positive integers ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kinetic_law_reaction_parameters(self): """Iterator over the values of kinetic law reaction parameters"""
for parameter in self._root.iterfind( './{}/{}/{}'.format(self._reader._sbml_tag('kineticLaw'), self._reader._sbml_tag('listOfParameters'), self._reader._sbml_tag('parameter'))): param_id = parameter.get('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 properties(self): """All reaction properties as a dict"""
properties = {'id': self._id, 'reversible': self._rev, 'equation': self._equation} if 'name' in self._root.attrib: properties['name'] = self._root.get('name') if self._lower_flux is not None: properties['lower_flux'] = self._lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def properties(self): """All compartment properties as a dict."""
properties = {'id': self._id} if self._name is not None: properties['name'] = self._name return 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_model(self): """Create model from reader. Returns: :class:`psamm.datasource.native.NativeModel`. """
properties = { 'name': self.name, 'default_flux_limit': 1000 } # Load objective as biomass reaction objective = self.get_active_objective() if objective is not None: reactions = dict(objective.reactions) if len(reactions) == 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 _make_safe_id(self, id): """Returns a modified id that has been made safe for SBML. Replaces or deletes the ones that aren't allowed. """
substitutions = { '-': '_DASH_', '/': '_FSLASH_', '\\': '_BSLASH_', '(': '_LPAREN_', ')': '_RPAREN_', '[': '_LSQBKT_', ']': '_RSQBKT_', ',': '_COMMA_', '.': '_PERIOD_', "'": '_APOS_' ...
<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_flux_bounds(self, r_id, model, flux_limits, equation): """Read reaction's limits to set up strings for limits in the output file. """
if r_id not in flux_limits or flux_limits[r_id][0] is None: if equation.direction == Direction.Forward: lower = 0 else: lower = -model.default_flux_limit else: lower = flux_limits[r_id][0] if r_id not in flux_limits or 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 _add_gene_associations(self, r_id, r_genes, gene_ids, r_tag): """Adds all the different kinds of genes into a list."""
genes = ET.SubElement( r_tag, _tag('geneProductAssociation', FBC_V2)) if isinstance(r_genes, list): e = Expression(And(*(Variable(i) for i in r_genes))) else: e = Expression(r_genes) gene_stack = [(e.root, genes)] while len(gene_stack) > 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_gene_list(self, parent_tag, gene_id_dict): """Create list of all gene products as sbml readable elements."""
list_all_genes = ET.SubElement(parent_tag, _tag( 'listOfGeneProducts', FBC_V2)) for id, label in sorted(iteritems(gene_id_dict)): gene_tag = ET.SubElement( list_all_genes, _tag('geneProduct', FBC_V2)) gene_tag.set(_tag('id', FBC_V2), id) g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_to_initkwargs(self, json_data, kwargs): """Subclassing hook to specialize how JSON data is converted to keyword arguments"""
if isinstance(json_data, basestring): json_data = json.loads(json_data) return json_to_initkwargs(self, json_data, kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_group_id(groupname): """ Returns the group id to a given group name. Returns ``None`` if the group does not exist. :param groupname: Group name. :type gr...
gid = single_line_stdout('id -g {0}'.format(groupname), expected_errors=(1,), shell=False) return check_int(gid)
<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_user_id(username): """ Returns the user id to a given user name. Returns ``None`` if the user does not exist. :param username: User name. :type username:...
uid = single_line_stdout('id -u {0}'.format(username), expected_errors=(1,), shell=False) return check_int(uid)
<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_group(groupname, gid, system=True): """ Creates a new user group with a specific id. :param groupname: Group name. :type groupname: unicode :param gid...
sudo(addgroup(groupname, gid, system))
<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_user(username, uid, system=False, no_login=True, no_password=False, group=False, gecos=None): """ Creates a new user with a specific id. :param userna...
sudo(adduser(username, uid, system, no_login, no_password, group, gecos))
<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_or_create_group(groupname, gid_preset, system=False, id_dependent=True): """ Returns the id for the given group, and creates it first in case it does not...
gid = get_group_id(groupname) if gid is None: create_group(groupname, gid_preset, system) return gid_preset elif id_dependent and gid != gid_preset: error("Present group id '{0}' does not match the required id of the environment '{1}'.".format(gid, gid_preset)) return gid
<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_or_create_user(username, uid_preset, groupnames=[], system=False, no_password=False, no_login=True, gecos=None, id_dependent=True): """ Returns the id of...
uid = get_user_id(username) gid = get_group_id(username) if id_dependent and gid is not None and gid != uid_preset: error("Present group id '{0}' does not match the required id of the environment '{1}'.".format(gid, uid_preset)) if gid is None: create_group(username, uid_preset, system)...
<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_kegg_entries(f, context=None): """Iterate over entries in KEGG file."""
section_id = None entry_line = None properties = {} for lineno, line in enumerate(f): if line.strip() == '///': # End of entry mark = FileMark(context, entry_line, 0) yield KEGGEntry(properties, filemark=mark) properties = {} section_...
<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_reaction(s): """Parse a KEGG reaction string"""
def parse_count(s): m = re.match(r'^\((.+)\)$', s) if m is not None: s = m.group(1) m = re.match(r'^\d+$', s) if m is not None: return int(m.group(0)) return Expression(s) def parse_compound(s): m = re.match(r'(.+)\((.+)\)', 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 stdout_result(cmd, expected_errors=(), shell=True, sudo=False, quiet=False): """ Runs a command and returns the result, that would be written to `stdout`, as...
which = operations.sudo if sudo else operations.run with hide('warnings'): result = which(cmd, shell=shell, quiet=quiet, warn_only=True) if result.return_code == 0: return result if result.return_code not in expected_errors: error("Received unexpected error code {0} while execu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def single_line_stdout(cmd, expected_errors=(), shell=True, sudo=False, quiet=False): """ Runs a command and returns the first line of the result, that would be ...
return single_line(stdout_result(cmd, expected_errors, shell, sudo, quiet))
<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 FastGapFill command"""
# Create solver solver = self._get_solver() # 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) # TODO: The exchange and transport ...
<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(self, *args): """Add constraints to the model."""
self._constrs.extend(self._moma._prob.add_linear_constraints(*args))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _adjustment_reactions(self): """Yield all the non exchange reactions in the model."""
for reaction_id in self._model.reactions: if not self._model.is_exchange(reaction_id): 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 _solve(self, sense=None): """Remove old constraints and then solve the current problem. Args: sense: Minimize or maximize the objective. (:class:`.lp.Objecti...
# Remove the constraints from the last run while len(self._remove_constr) > 0: self._remove_constr.pop().delete() try: return self._prob.solve(sense=sense) except lp.SolverError as e: raise_from(MOMAError(text_type(e)), e) finally: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve_fba(self, objective): """Solve the wild type problem using FBA. Args: objective: The objective reaction to be maximized. Returns: The LP Result object ...
self._prob.set_objective(self._v_wt[objective]) return self._solve(lp.ObjectiveSense.Maximize)
<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_fba_flux(self, objective): """Return a dictionary of all the fluxes solved by FBA. Dictionary of fluxes is used in :meth:`.lin_moma` and :meth:`.moma` to...
flux_result = self.solve_fba(objective) fba_fluxes = {} # Place all the flux values in a dictionary for key in self._model.reactions: fba_fluxes[key] = flux_result.get_value(self._v_wt[key]) return fba_fluxes
<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_minimal_fba_flux(self, objective): """Find the FBA solution that minimizes all the flux values. Maximize the objective flux then minimize all other fluxe...
# Define constraints vs_wt = self._v_wt.set(self._model.reactions) zs = self._z.set(self._model.reactions) wt_obj_flux = self.get_fba_obj_flux(objective) with self.constraints() as constr: constr.add( zs >= vs_wt, vs_wt >= -zs, self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fba_obj_flux(self, objective): """Return the maximum objective flux solved by FBA."""
flux_result = self.solve_fba(objective) return flux_result.get_value(self._v_wt[objective])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lin_moma(self, wt_fluxes): """Minimize the redistribution of fluxes using a linear objective. The change in flux distribution is mimimized by minimizing the ...
reactions = set(self._adjustment_reactions()) z_diff = self._z_diff v = self._v with self.constraints() as constr: for f_reaction, f_value in iteritems(wt_fluxes): if f_reaction in reactions: # Add the constraint that finds the optimal 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 lin_moma2(self, objective, wt_obj): """Find the smallest redistribution vector using a linear objective. The change in flux distribution is mimimized by mini...
reactions = set(self._adjustment_reactions()) z_diff = self._z_diff v = self._v v_wt = self._v_wt with self.constraints() as constr: for f_reaction in reactions: # Add the constraint that finds the optimal solution, such # that the d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def moma(self, wt_fluxes): """Minimize the redistribution of fluxes using Euclidean distance. Minimizing the redistribution of fluxes using a quadratic objective...
reactions = set(self._adjustment_reactions()) v = self._v obj_expr = 0 for f_reaction, f_value in iteritems(wt_fluxes): if f_reaction in reactions: # Minimize the Euclidean distance between the two vectors obj_expr += (f_value - v[f_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 moma2(self, objective, wt_obj): """Find the smallest redistribution vector using Euclidean distance. Minimizing the redistribution of fluxes using a quadrati...
obj_expr = 0 for reaction in self._adjustment_reactions(): v_wt = self._v_wt[reaction] v = self._v[reaction] obj_expr += (v_wt - v)**2 self._prob.set_objective(obj_expr) with self.constraints(self._v_wt[objective] >= wt_obj): self._solve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Connects to the SSDB server if not already connected """
if self._sock: return try: sock = self._connect() except socket.error: e = sys.exc_info()[1] raise ConnectionError(self._error_message(e)) self._sock = sock try: self.on_connect() except SSDBError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _connect(self): """ Create a TCP socket connection """
# we want to mimic what socket.create_connection does to support # ipv4/ipv6, but we want to set options prior to calling # socket.connect() err = None for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """ Disconnects from the SSDB server """
self._parser.on_disconnect() if self._sock is None: return try: self._sock.shutdown(socket.SHUT_RDWR) self._sock.close() except socket.error: pass self._sock = 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 pack_command(self, *args): """ Pack a series of arguments into a value SSDB command """
# the client might have included 1 or more literal arguments in # the command name, e.g., 'CONFIG GET'. The SSDB server expects # these arguments to be sent separately, so split the first # argument manually. All of these arguements get wrapped # in the Token class to prevent th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_env_lazy(loader, node): """ Substitutes a variable read from a YAML node with the value stored in Fabric's ``env`` dictionary. Creates an object for l...
val = loader.construct_scalar(node) return lazy_once(env_get, val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_record_iter(a, b, fs_a=None, fs_b=None, options=None): """This generator function compares a record, slot by slot, and yields differences found as ``...
if not options: options = DiffOptions() if not options.duck_type and type(a) != type(b) and not ( a is _nothing or b is _nothing ): raise TypeError( "cannot compare %s with %s" % (type(a).__name__, type(b).__name__) ) if fs_a is None: fs_a = FieldSe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_whitespace(self, value): """Normalizes whitespace; called if ``ignore_ws`` is true."""
if isinstance(value, unicode): return u" ".join( x for x in re.split(r'\s+', value, flags=re.UNICODE) if len(x) ) else: return " ".join(value.split())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_val(self, value=_nothing): """Hook which is called on every value before comparison, and should return the scrubbed value or ``self._nothing`` to i...
if isinstance(value, basestring): value = self.normalize_text(value) if self.ignore_empty_slots and self.value_is_empty(value): value = _nothing return 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 normalize_object_slot(self, value=_nothing, prop=None, obj=None): """This hook wraps ``normalize_slot``, and performs clean-ups which require access to the o...
if value is not _nothing and hasattr(prop, "compare_as"): method, nargs = getattr(prop, "compare_as_info", (False, 1)) args = [] if method: args.append(obj) if nargs: args.append(value) value = prop.compare_as(*args) ...