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:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of keys to be returned, empty string ``''`` means +inf :param string name_end: The upper bound(included) of keys to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list ['queue_1'] ['queue_2', 'queue_1'] ['queue_2', 'queue_1'] """
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 Python slicing notation Similiar with **Redis.LRANGE** :param string name: the queue name :param int offset: the returned list will start at this offset :param int limit: number of elements will be returned :return: a list of elements :rtype: list """
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 Python timedelta object. Like **Redis.SETEX** :param string name: the key name :param string value: a string or an object can be converted to string :param int ttl: positive int seconds or timedelta object :return: ``True`` on success, ``False`` if not :rtype: bool True 'ttl' """
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 network interface (e.g. ``eth0``). :type interface_name: unicode :param expand: If set to ``True``, an abbreviated address is expanded to the full address. :type expand: bool :return: IPv6 address; ``None`` if the interface is present but no address could be extracted. :rtype: unicode """
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. :return: List of roles of the current host. :rtype: list """
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.metabolicmodel.MetabolicModel`. """
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.add_reaction(rxnid) return added
<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.metabolicmodel.MetabolicModel`. """
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 added = set() added_compounds = set() initial_compounds = set(model.compounds) reactions = set(model.database.reactions) for model_compound in initial_compounds: compound = model_compound.in_compartment(compartment) if compound in added_compounds: continue rxnid_ex = create_exchange_id(reactions, compound) reaction_ex = Reaction(Direction.Both, {compound: -1}) if reaction_ex not in all_reactions: model.database.set_reaction(rxnid_ex, reaction_ex) reactions.add(rxnid_ex) else: rxnid_ex = all_reactions[reaction_ex] if not model.has_reaction(rxnid_ex): added.add(rxnid_ex) model.add_reaction(rxnid_ex) added_compounds.add(compound) return added
<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 boundaries. Boundaries are defined by pairs (2-tuples) of compartment IDs. Transport reactions are added for all compounds in the model, not just for compounds in the two boundary compartments. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`. boundaries: Set of compartment boundary pairs. Returns: Set of IDs of reactions that were added. """
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 boundary_pairs = set() for source, dest in boundaries: if source != dest: boundary_pairs.add(tuple(sorted((source, dest)))) added = set() added_pairs = set() initial_compounds = set(model.compounds) reactions = set(model.database.reactions) for compound in initial_compounds: for c1, c2 in boundary_pairs: compound1 = compound.in_compartment(c1) compound2 = compound.in_compartment(c2) pair = compound1, compound2 if pair in added_pairs: continue rxnid_tp = create_transport_id(reactions, compound1, compound2) reaction_tp = Reaction(Direction.Both, { compound1: -1, compound2: 1 }) if reaction_tp not in all_reactions: model.database.set_reaction(rxnid_tp, reaction_tp) reactions.add(rxnid_tp) else: rxnid_tp = all_reactions[reaction_tp] if not model.has_reaction(rxnid_tp): added.add(rxnid_tp) model.add_reaction(rxnid_tp) added_pairs.add(pair) return added
<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:`psamm.metabolicmodel.MetabolicModel` with all reactions added (the reaction database in the model is taken to be the universal database) and also with artificial exchange and transport reactions added. Return the extended :class:`psamm.metabolicmodel.MetabolicModel` and a weight dictionary for added reactions in that model. Args: model: :class:`psamm.datasource.native.NativeModel`. db_penalty: penalty score for database reactions, default is `None`. ex_penalty: penalty score for exchange reactions, default is `None`. tb_penalty: penalty score for transport reactions, default is `None`. penalties: a dictionary of penalty scores for database reactions. """
# 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 all database reactions in compartments: {}...'.format( ', '.join('{}'.format(c) for c in compartment_ids))) db_added = add_all_database_reactions(model_extended, compartment_ids) else: logger.warning( 'No compartments specified in the model; database reactions will' ' not be used! Add compartment specification to model to include' ' database reactions for those compartments.') db_added = set() # Add exchange reactions to extended model logger.info( 'Using artificial exchange reactions for compartment: {}...'.format( extra_compartment)) ex_added = add_all_exchange_reactions( model_extended, extra_compartment, allow_duplicates=True) # Add transport reactions to extended model boundaries = model.compartment_boundaries if len(boundaries) > 0: logger.info( 'Using artificial transport reactions for the compartment' ' boundaries: {}...'.format( '; '.join('{}<->{}'.format(c1, c2) for c1, c2 in boundaries))) tp_added = add_all_transport_reactions( model_extended, boundaries, allow_duplicates=True) else: logger.warning( 'No compartment boundaries specified in the model;' ' artificial transport reactions will not be used!') tp_added = set() # Add penalty weights on reactions weights = {} if db_penalty is not None: weights.update((rxnid, db_penalty) for rxnid in db_added) if tp_penalty is not None: weights.update((rxnid, tp_penalty) for rxnid in tp_added) if ex_penalty is not None: weights.update((rxnid, ex_penalty) for rxnid in ex_added) if penalties is not None: for rxnid, penalty in iteritems(penalties): weights[rxnid] = penalty return model_extended, weights
<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: continue if result is None: unchecked += 1 continue left_form, right_form = result if right_form != left_form: unbalanced += 1 right_missing, left_missing = Formula.balance( right_form, left_form) print('{}\t{}\t{}\t{}\t{}'.format( reaction.id, left_form, right_form, left_missing, right_missing)) logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count)) logger.info('Unchecked reactions due to missing formula: {}/{}'.format( unchecked, count)) logger.info('Reactions excluded from check: {}/{}'.format( len(exclude), count))
<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. :type info: unicode :param level: Logging level. Has no effect here. :type level: int """
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 that the progress is reported on. :type object_id: unicode :param progress: Progress bar. :type progress: unicode """
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 iterable. This method accepts the same keyword arguments as :meth:`.Problem.define`. """
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 corresponding value is simply returned. If expression is an actual :class:`.Expression` object, it will be evaluated using the values from the result. """
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 rlcompleter readline.set_completer(rlcompleter.Completer(namespace).complete) readline.parse_and_bind('tab: complete') console = InteractiveConsole(namespace) console.interact(message)
<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_signatures.setdefault(signature, set()).add( (entry.id, entry.equation, entry.filemark)) for reaction_set in itervalues(database_signatures): if len(reaction_set) > 1: print('Found {} duplicate reactions:'.format( len(reaction_set))) for reaction, equation, filemark in reaction_set: result = ' - {}: {}'.format(reaction, equation) if filemark is not None: result += ' (found in {})'.format(filemark) print(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reaction_charge(reaction, compound_charge): """Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. compound_charge: a map from each compound to charge values. """
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.native.NativeModel`. """
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 all have formula, then calculate and return the chemical compositions for both sides, otherwise return `None`. Args: reaction: :class:`psamm.reaction.Reaction`. compound_formula: a map from compound id to formula. """
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( operator.or_, multiply_formula(reaction.left), Formula()) right_form = reduce( operator.or_, multiply_formula(reaction.right), Formula()) return left_form, right_form
<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, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.native.NativeModel`. """
# 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: msg = 'Error parsing formula for compound {}:\n{}\n{}'.format( compound.id, e, compound.formula) if e.indicator is not None: msg += '\n{}'.format(e.indicator) logger.warning(msg) for reaction in model.reactions: yield reaction, reaction_formula(reaction.equation, compound_formula)
<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 exchange reactions with no flux limits for reaction in self._mm.reactions: if self._mm.is_exchange(reaction): del self._mm.limits[reaction].bounds loop_removal = self._get_loop_removal_option() enable_tfba = loop_removal == 'tfba' enable_fastcore = self._args.fastcore if enable_tfba and enable_fastcore: self.argument_error( 'Using Fastcore with thermodynamic constraints' ' is not supported!') start_time = time.time() if enable_fastcore: solver = self._get_solver() try: inconsistent = set(fastcore.fastcc( self._mm, epsilon, solver=solver)) except fluxanalysis.FluxBalanceError as e: self.report_flux_balance_error(e) else: if enable_tfba: solver = self._get_solver(integer=True) else: solver = self._get_solver() if self._args.reduce_lp: logger.info('Running with reduced number of LP problems.') try: inconsistent = set( fluxanalysis.consistency_check( self._mm, self._mm.reactions, epsilon, tfba=enable_tfba, solver=solver)) except fluxanalysis.FluxBalanceError as e: self.report_flux_balance_error(e) else: logger.info('Using flux bounds to determine consistency.') try: inconsistent = set(self._run_fva_fluxcheck( self._mm, solver, enable_tfba, epsilon)) except FluxCheckFVATaskError: self.report_flux_balance_error() logger.info('Solving took {:.2f} seconds'.format( time.time() - start_time)) # Count the number of reactions that are fixed at zero. While these # reactions are still inconsistent, they are inconsistent because they # have been explicitly disabled. disabled_exchange = 0 disabled_internal = 0 count_exchange = 0 total_exchange = 0 count_internal = 0 total_internal = 0 # Print result for reaction in sorted(self._mm.reactions): disabled = self._mm.limits[reaction].bounds == (0, 0) if self._mm.is_exchange(reaction): total_exchange += 1 count_exchange += int(reaction in inconsistent) disabled_exchange += int(disabled) else: total_internal += 1 count_internal += int(reaction in inconsistent) disabled_internal += int(disabled) if reaction in inconsistent: rx = self._mm.get_reaction(reaction) rxt = rx.translated_compounds(compound_name) print('{}\t{}'.format(reaction, rxt)) logger.info('Model has {}/{} inconsistent internal reactions' ' ({} disabled by user)'.format( count_internal, total_internal, disabled_internal)) logger.info('Model has {}/{} inconsistent exchange reactions' ' ({} disabled by user)'.format( count_exchange, total_exchange, disabled_exchange))
<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 unbalanced = 0 unchecked = 0 for reaction, charge in charge_balance(self._model): count += 1 if reaction.id in exclude or reaction.equation is None: continue if math.isnan(charge): logger.debug('Not checking reaction {};' ' missing charge'.format(reaction.id)) unchecked += 1 elif abs(charge) > self._args.epsilon: unbalanced += 1 rxt = reaction.equation.translated_compounds(compound_name) print('{}\t{}\t{}'.format(reaction.id, charge, rxt)) logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count)) logger.info('Unchecked reactions due to missing charge: {}/{}'.format( unchecked, count)) logger.info('Reactions excluded from check: {}/{}'.format( len(exclude), count))
<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 is not possible. Extra traits not requested are not acceptable. If this automatic generation doesn't work for you for some reason, then compose your property types manually. The details of this composition should not be relied upon; it may change in future releases. However, a given normalize version should behave consistently for multiple runs, given the same starting sets of properties, the composition order will be the same every time. """
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 if missing_traits: raise exc.PropertyTypeMixinNotPossible( traitlist=repr(trait_set), missing=repr(tuple(sorted(missing_traits))), ) made_types = [] # mix together property types, until we have made the right type. while trait_set not in PROPERTY_TYPES: # be somewhat deterministic: always start with types which provide the # 'first' trait on the list start_with = set( k for k in stock_types.keys() if k and k[0] == trait_set[0] ) # prefer extending already composed trait sets, by only adding to the # longest ones longest = max(len(x) for x in start_with) made_type = False for base in sorted(start_with): if len(base) != longest: continue # pick a type to join on which reduces the short-fall as much as # possible. shortfall = len(wanted_traits) - len(base) mix_in = None for other in sorted(stock_types.keys()): # skip mixes that will fail; this means that the type on the # list is a trait subset of 'base' mixed_traits = tuple(sorted(set(base) | set(other))) if mixed_traits in PROPERTY_TYPES: continue this_shortfall = len(wanted_traits - (set(base) | set(other))) if this_shortfall < shortfall: mix_in = other mixed_in_product = mixed_traits shortfall = this_shortfall if shortfall == 0: break if mix_in: base_type = PROPERTY_TYPES[base] other_type = PROPERTY_TYPES[other] new_name = _merge_camel_case_names( base_type.__name__, other_type.__name__, ) new_type = type(new_name, (base_type, other_type), {}) stock_types[mixed_in_product] = new_type made_types.append(new_type) made_type = True if not made_type: raise exc.PropertyTypeMixinFailure( traitlist=repr(trait_set), newtypelist=", ".join( "%r (%s)" % (x.traits, x.__name__) for x in made_types ) )
<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 .sbml file found in source directory') return sources[0] return source
<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): self.fail( 'Specified reaction is not in model: {}'.format(reaction)) loop_removal = self._get_loop_removal_option() enable_tfba = loop_removal == 'tfba' if enable_tfba: solver = self._get_solver(integer=True) else: solver = self._get_solver() start_time = time.time() try: fba_fluxes = dict(fluxanalysis.flux_balance( self._mm, reaction, tfba=False, solver=solver)) except fluxanalysis.FluxBalanceError as e: self.report_flux_balance_error(e) threshold = self._args.threshold if threshold.relative: threshold.reference = fba_fluxes[reaction] logger.info('Setting objective threshold to {}'.format( threshold)) handler_args = ( self._mm, solver, enable_tfba, float(threshold), reaction) executor = self._create_executor( FVATaskHandler, handler_args, cpus_per_worker=2) def iter_results(): results = {} with executor: for (reaction_id, direction), value in executor.imap_unordered( product(self._mm.reactions, (1, -1)), 16): if reaction_id not in results: results[reaction_id] = value continue other_value = results[reaction_id] if direction == -1: bounds = value, other_value else: bounds = other_value, value yield reaction_id, bounds executor.join() for reaction_id, (lower, upper) in iter_results(): rx = self._mm.get_reaction(reaction_id) rxt = rx.translated_compounds(compound_name) print('{}\t{}\t{}\t{}'.format(reaction_id, lower, upper, rxt)) logger.info('Solving took {:.2f} seconds'.format( time.time() - start_time))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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) yield 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 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 temporary files that can be assumed to be cleaned up at a later point. :param path: Path to file or directory to remove. :type path: unicode :param use_sudo: Use the `sudo` command. :type use_sudo: bool :param force: Force the removal. :type force: bool """
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_sudo: Use the `sudo` command. :type use_sudo: bool :return: `True` if the path exists and is a directory; `False` if it exists, but is a file; `None` if it does not exist. :rtype: bool or ``None`` """
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 directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :type apply_chmod: unicode :param remove_using_sudo: Use sudo for removing the directory. ``None`` (default) means it is used depending on whether ``apply_chown`` has been set. :type remove_using_sudo: bool | NoneType :param remove_force: Force the removal. :type remove_force: bool :return: Path to the temporary directory. :rtype: unicode """
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_sudo=remove_using_sudo, force=remove_force)
<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 the temporary directory. :rtype: unicode """
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 response
<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:`.CouplingClass` is returned. Args: coupling: Tuple of minimum and maximum flux ratio """
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: return CouplingClass.DirectionalForward elif abs(lower - upper) < 1e-6: return CouplingClass.Full else: return CouplingClass.Partial
<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 maximum value of the v1/v2 reaction flux ratio. A value of None as either the minimum or maximum indicates that the interval is unbounded in that direction. """
# 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._vbow(reaction_2) == 1) results = [] for sense in (lp.ObjectiveSense.Minimize, lp.ObjectiveSense.Maximize): try: result = self._prob.solve(sense) except lp.SolverError: results.append(None) else: results.append(result.get_value(self._vbow(reaction_1))) return tuple(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform(action_name, container, **kwargs): """ Performs an action on the given container map and configuration. :param action_name: Name of the action (e.g. ``update``). :param container: Container configuration name. :param kwargs: Keyword arguments for the action implementation. """
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 # Detect objective objective = parse_objective_coefficient(reaction) if objective is not None and objective != 0: biomass_reactions.add(reaction.id) if len(biomass_reactions) == 1: model.biomass_reaction = next(iter(biomass_reactions)) # Convert model to mutable entries convert_model_entries(model) # Detect extracelluar compartment if model.extracellular_compartment is None: extracellular = detect_extracellular_compartment(model) model.extracellular_compartment = extracellular # Convert exchange reactions to exchange compounds convert_exchange_to_compounds(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 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 function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes are common on IDs in SBML models because the IDs live in a global namespace. """
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 = entry.id if decode_id is not None: new_id = decode_id(new_id) if prefix is not None and new_id.startswith(prefix): new_id = new_id[len(prefix):] return new_id return convert_sbml_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 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 = compartment_map.get( compound.compartment, compound.compartment) new_compound = compound.translate( lambda name: compound_map.get(name, name)).in_compartment( compartment) compounds.append((new_compound, value)) new_entry.equation = Reaction( new_entry.equation.direction, compounds) # Get XHTML notes properties for key, value in iteritems(parse_xhtml_reaction_notes(entry)): if key not in new_entry.properties: new_entry.properties[key] = value return new_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 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, value in iteritems(parse_xhtml_species_notes(entry)): if key not in new_entry.properties: new_entry.properties[key] = value return new_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 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. ``<p>key: value</p><p>key2: value2</p>``. The key and value must be separated by a colon. Whitespace is stripped from both key and value, and quotes are removed from values if present. The key is normalized by conversion to lower case and spaces replaced with underscores. Args: entry: :class:`_SBMLEntry`. """
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.group(1) if value != '': yield key, value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_xhtml_species_notes(entry): """Return species properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML notes section because structured methods for defining properties had not been developed. This will try to parse the following properties: ``PUBCHEM ID``, ``CHEBI ID``, ``FORMULA``, ``KEGG ID``, ``CHARGE``. Args: entry: :class:`SBMLSpeciesEntry`. """
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'] = cobra_notes['formula'] if 'kegg_id' in cobra_notes: properties['kegg'] = cobra_notes['kegg_id'] if 'charge' in cobra_notes: try: value = int(cobra_notes['charge']) except ValueError: logger.warning( 'Unable to parse charge for {} as an' ' integer: {}'.format( entry.id, cobra_notes['charge'])) value = cobra_notes['charge'] properties['charge'] = value 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 parse_xhtml_reaction_notes(entry): """Return reaction properties defined in the XHTML notes. Older SBML models often define additional properties in the XHTML notes section because structured methods for defining properties had not been developed. This will try to parse the following properties: ``SUBSYSTEM``, ``GENE ASSOCIATION``, ``EC NUMBER``, ``AUTHORS``, ``CONFIDENCE``. Args: entry: :class:`SBMLReactionEntry`. """
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_association'] if 'ec_number' in cobra_notes: properties['ec'] = cobra_notes['ec_number'] if 'authors' in cobra_notes: properties['authors'] = [ a.strip() for a in cobra_notes['authors'].split(';')] if 'confidence' in cobra_notes: try: value = int(cobra_notes['confidence']) except ValueError: logger.warning( 'Unable to parse confidence level for {} as an' ' integer: {}'.format( entry.id, cobra_notes['confidence'])) value = cobra_notes['confidence'] properties['confidence'] = value 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 parse_objective_coefficient(entry): """Return objective value for reaction entry. Detect objectives that are specified using the non-standardized kinetic law parameters which are used by many pre-FBC SBML models. The objective coefficient is returned for the given reaction, or None if undefined. Args: entry: :class:`SBMLReactionEntry`. """
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 which are used by many pre-FBC SBML models. The flux bounds are returned as a pair of lower, upper bounds. The returned bound is None if undefined. Args: entry: :class:`SBMLReactionEntry`. """
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_bound = value return lower_bound, upper_bound
<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 extracellular_key[compartment] += 1 if len(extracellular_key) == 0: return None else: best_key, _ = extracellular_key.most_common(1)[0] logger.info('{} is extracellular compartment'.format(best_key)) return best_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 convert_exchange_to_compounds(model): """Convert exchange reactions in model to exchange compounds. Only exchange reactions in the extracellular compartment are converted. The extracelluar compartment must be defined for the model. Args: model: :class:`NativeModel`. """
# 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 # one compound, they won't be put into the exchange definition if (len(equation.left) == 0) != (len(equation.right) == 0): logger.warning('Exchange reaction {} has more than one' ' compound, it was not converted to' ' exchange compound'.format(reaction.id)) continue exchanges.add(reaction.id) # Convert exchange reactions into exchange compounds for reaction_id in exchanges: equation = model.reactions[reaction_id].equation compound, value = equation.compounds[0] if compound.compartment != model.extracellular_compartment: continue if compound in model.exchange: logger.warning( 'Compound {} is already defined in the exchange' ' definition'.format(compound)) continue # We multiply the flux bounds by value in order to create equivalent # exchange reactions with stoichiometric value of one. If the flux # bounds are not set but the reaction is unidirectional, the implicit # flux bounds must be used. lower_flux, upper_flux = None, None if reaction_id in model.limits: _, lower, upper = model.limits[reaction_id] if lower is not None: lower_flux = lower * abs(value) if upper is not None: upper_flux = upper * abs(value) if lower_flux is None and equation.direction == Direction.Forward: lower_flux = 0 if upper_flux is None and equation.direction == Direction.Reverse: upper_flux = 0 # If the stoichiometric value of the reaction is reversed, the flux # limits must be flipped. if value > 0: lower_flux, upper_flux = ( -upper_flux if upper_flux is not None else None, -lower_flux if lower_flux is not None else None) model.exchange[compound] = ( compound, reaction_id, lower_flux, upper_flux) model.reactions.discard(reaction_id) model.limits.pop(reaction_id, 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 _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 depending on the level. """
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 = self.charge if charge is not None: properties['charge'] = charge formula = self.formula if formula is not None: properties['formula'] = formula 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 _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 are allowed for # stoichiometry but a positive integer denominator can be # specified. try: value = int(species.get('stoichiometry', 1)) denom = int(species.get('denominator', 1)) species_value = Fraction(value, denom) except ValueError: message = ('Non-integer stoichiometry is not allowed in' ' SBML level 1 (reaction {})'.format(self.id)) if self._reader._strict: raise ParseError(message) else: logger.warning(message) species_value = Decimal(species.get('stoichiometry', 1)) elif self._reader._level == 2: # Stoichiometric value is a double but can alternatively be # specified using math (not implemented). value_str = species.get('stoichiometry', None) if value_str is None: if 'stoichiometryMath' in species: raise ParseError('stoichiometryMath in ' 'speciesReference is not implemented') species_value = 1 else: species_value = Decimal(value_str) elif self._reader._level == 3: # Stoichiometric value is a double but can alternatively be # specified using initial assignment (not implemented). value_str = species.get('stoichiometry', None) if value_str is None: raise ParseError('Missing stoichiometry in' ' speciesReference is not implemented') species_value = Decimal(value_str) if species_value % 1 == 0: species_value = int(species_value) yield species_id, species_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 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') param_name = parameter.get('name') param_value = Decimal(parameter.get('value')) param_units = parameter.get('units') yield param_id, param_name, param_value, param_units
<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._lower_flux if self._upper_flux is not None: properties['upper_flux'] = self._upper_flux 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 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: reaction, value = next(iteritems(reactions)) if ((value < 0 and objective.type == 'minimize') or (value > 0 and objective.type == 'maximize')): properties['biomass'] = reaction model = NativeModel(properties) # Load compartments into model for compartment in self.compartments: model.compartments.add_entry(compartment) # Load compounds into model for compound in self.species: model.compounds.add_entry(compound) # Load reactions into model for reaction in self.reactions: model.reactions.add_entry(reaction) # Create model reaction set for reaction in model.reactions: model.model[reaction.id] = None # Convert reaction limits properties to proper limits for reaction in model.reactions: props = reaction.properties if 'lower_flux' in props or 'upper_flux' in props: lower = props.get('lower_flux') upper = props.get('upper_flux') model.limits[reaction.id] = reaction.id, lower, upper # Load model limits from FBC V1 bounds if present, i.e. if FBC V1 is # used instead of V2. limits_lower = {} limits_upper = {} for bounds in self.flux_bounds: reaction = bounds.reaction if reaction in model.limits: continue if bounds.operation == SBMLFluxBoundEntry.LESS_EQUAL: if reaction not in limits_upper: limits_upper[reaction] = bounds.value else: raise ParseError( 'Conflicting bounds for {}'.format(reaction)) elif bounds.operation == SBMLFluxBoundEntry.GREATER_EQUAL: if reaction not in limits_lower: limits_lower[reaction] = bounds.value else: raise ParseError( 'Conflicting bounds for {}'.format(reaction)) elif bounds.operation == SBMLFluxBoundEntry.EQUAL: if (reaction not in limits_lower and reaction not in limits_upper): limits_lower[reaction] = bounds.value limits_upper[reaction] = bounds.value else: raise ParseError( 'Conflicting bounds for {}'.format(reaction)) for reaction in model.reactions: if reaction.id in limits_lower or reaction.id in limits_upper: lower = limits_lower.get(reaction.id, None) upper = limits_upper.get(reaction.id, None) model.limits[reaction.id] = reaction.id, lower, upper 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 _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_' } id = re.sub(r'\(([a-z])\)$', '_\\1', id) for symbol, escape in iteritems(substitutions): id = id.replace(symbol, escape) id = re.sub(r'[^a-zA-Z0-9_]', '', id) return 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_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_limits[r_id][1] is None: if equation.direction == Direction.Reverse: upper = 0 else: upper = model.default_flux_limit else: upper = flux_limits[r_id][1] if lower % 1 == 0: lower = int(lower) if upper % 1 == 0: upper = int(upper) return text_type(lower), text_type(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 _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: current, parent = gene_stack.pop() if isinstance(current, Or): gene_tag = ET.SubElement(parent, _tag('or', FBC_V2)) elif isinstance(current, And): gene_tag = ET.SubElement(parent, _tag('and', FBC_V2)) elif isinstance(current, Variable): gene_tag = ET.SubElement(parent, _tag( 'geneProductRef', FBC_V2)) if current.symbol not in gene_ids: id = 'g_' + util.create_unique_id( self._make_safe_id(current.symbol), gene_ids) gene_ids[id] = current.symbol gene_tag.set(_tag('geneProduct', FBC_V2), id) if isinstance(current, (Or, And)): for item in current: gene_stack.append((item, gene_tag))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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) gene_tag.set(_tag('label', FBC_V2), label)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 groupname: unicode :return: Group id. :rtype: int """
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: unicode :return: User id. :rtype: int """
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: Group id. :type gid: int or unicode :param system: Creates a system group. """
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 username: User name. :type username: unicode :param uid: User id. :type uid: int or unicode :param system: Creates a system user. :type system: bool :param no_login: Disallow login of this user and group, and skip creating the home directory. Default is ``True``. :type no_login: bool :param no_password: Do not set a password for the new user. :type: no_password: bool :param group: Create a group with the same id. :type group: bool :param gecos: Provide GECOS info and suppress prompt. :type gecos: unicode """
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 exist. :param groupname: Group name. :type groupname: unicode :param gid_preset: Group id to set if a new group is created. :type gid_preset: int or unicode :param system: Create a system group. :type system: bool :param id_dependent: If the group exists, but its id does not match `gid_preset`, an error is thrown. :type id_dependent: bool :return: Group id of the existing or new group. :rtype: int """
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 the given user name, and creates it first in case it does not exist. A default group is created as well. :param username: User name. :type username: unicode :param uid_preset: User id to set in case a new user is created. :type uid_preset: int or unicode :param groupnames: Additional names of groups to assign the user to. If the user exists, these will be appended to existing group assignments. :type groupnames: iterable :param system: Create a system user. :type system: bool :param no_login: Disallow login of this user and group, and skip creating the home directory. Default is ``True``. :type no_login: bool :param no_password: Do not set a password for the new user. :type: no_password: bool :param gecos: Provide GECOS info and suppress prompt. :type gecos: unicode :param id_dependent: If the user exists, but its id does not match `uid_preset`, an error is thrown. :type id_dependent: bool :return: """
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) gid = uid_preset if uid is None: create_user(username, gid, system, no_login, no_password, False, gecos) if groupnames: assign_user_groups(username, groupnames) return uid elif id_dependent and uid != uid_preset: error("Present user id '{0}' does not match the required id of the environment '{1}'.".format(uid, uid_preset)) current_groups = get_user_groups(username) new_groups = set(groupnames).discard(tuple(current_groups)) if new_groups: assign_user_groups(username, new_groups) return 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 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_id = None entry_line = None else: if entry_line is None: entry_line = lineno # Look for beginning of section m = re.match(r'([A-Z_]+)\s+(.*)', line.rstrip()) if m is not None: section_id = m.group(1).lower() properties[section_id] = [m.group(2)] elif section_id is not None: properties[section_id].append(line.strip()) else: raise ParseError( 'Missing section identifier at line {}'.format(lineno))
<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) if m is not None: return Compound(m.group(1), arguments=[Expression(m.group(2))]) return Compound(s) def parse_compound_list(s): for cpd in s.split(' + '): if cpd == '': continue fields = cpd.strip().split(' ') if len(fields) > 2: raise ParseError( 'Malformed compound specification: {}'.format(cpd)) if len(fields) == 1: count = 1 compound = parse_compound(fields[0]) else: count = parse_count(fields[0]) compound = parse_compound(fields[1]) yield compound, count cpd_left, cpd_right = s.split('<=>') left = parse_compound_list(cpd_left.strip()) right = parse_compound_list(cpd_right.strip()) return Reaction(Direction.Both, left, right)
<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 a string. The output itself can be suppressed. :param cmd: Command to run. :type cmd: unicode :param expected_errors: If the return code is non-zero, but found in this tuple, it will be ignored. ``None`` is returned in this case. :type expected_errors: tuple :param shell: Use a shell. :type shell: bool :param sudo: Use `sudo`. :type sudo: bool :param quiet: If set to ``True``, does not show any output. :type quiet: bool :return: The result of the command as would be written to `stdout`. :rtype: unicode """
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 executing!".format(result.return_code)) 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 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 written to `stdout`, as a string. The output itself can be suppressed. :param cmd: Command to run. :type cmd: unicode :param expected_errors: If the return code is non-zero, but found in this tuple, it will be ignored. ``None`` is returned in this case. :type expected_errors: tuple :param shell: Use a shell. :type shell: bool :param sudo: Use `sudo`. :type sudo: bool :param quiet: If set to ``True``, does not show any output. :type quiet: bool :return: The result of the command as would be written to `stdout`. :rtype: unicode """
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 reactions have tuple names. This # means that in Python 3 the reactions can no longer be directly # compared (e.g. while sorting) so define this helper function as a # workaround. def reaction_key(r): return r if isinstance(r, tuple) else (r,) # Calculate penalty if penalty file exists penalties = {} if self._args.penalty is not None: for line in self._args.penalty: line, _, comment = line.partition('#') line = line.strip() if line == '': continue rxnid, penalty = line.split(None, 1) penalties[rxnid] = float(penalty) model_extended, weights = create_extended_model( self._model, db_penalty=self._args.db_penalty, ex_penalty=self._args.ex_penalty, tp_penalty=self._args.tp_penalty, penalties=penalties) epsilon = self._args.epsilon core = set() if self._args.subset is None: for r in self._mm.reactions: if not self._mm.is_exchange(r): core.add(r) else: for line in self._args.subset: line = line.strip() if line == '': continue core.add(line) induced = fastgapfill(model_extended, core, weights=weights, epsilon=epsilon, solver=solver) for reaction_id in sorted(self._mm.reactions): rx = self._mm.get_reaction(reaction_id) rxt = rx.translated_compounds(compound_name) print('{}\t{}\t{}\t{}'.format(reaction_id, 'Model', 0, rxt)) for rxnid in sorted(induced, key=reaction_key): if self._mm.has_reaction(rxnid): continue rx = model_extended.get_reaction(rxnid) rxt = rx.translated_compounds(compound_name) print('{}\t{}\t{}\t{}'.format( rxnid, 'Add', weights.get(rxnid, 1), rxt))
<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.ObjectiveSense) Returns: The Result object for the solved LP problem """
# 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: self._remove_constr = []
<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 for the solved FBA problem. """
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 minimize changes in the flux distributions following model perturbation. Args: objective: The objective reaction that is maximized. Returns: Dictionary of fluxes for each reaction in the model. """
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 fluxes while keeping the objective flux at the maximum. Args: objective: The objective reaction that is maximized. Returns: A dictionary of all the reactions and their minimized fluxes. """
# 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._v_wt[objective] >= wt_obj_flux) self._prob.set_objective(self._z.sum(self._model.reactions)) result = self._solve(lp.ObjectiveSense.Minimize) fba_fluxes = {} for key in self._model.reactions: fba_fluxes[key] = 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_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 sum of the absolute values of the differences of wild type FBA solution and the knockout strain flux solution. This formulation bases the solution on the wild type fluxes that are specified by the user. If these wild type fluxes were calculated using FBA, then an arbitrary flux vector that optimizes the objective function is used. See [Segre`_02] for more information. Args: wt_fluxes: Dictionary of all the wild type fluxes. Use :meth:`.get_fba_flux(objective)` to return a dictionary of fluxes found by FBA. """
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 solution, such # that the difference between the wildtype flux is similar # to the knockout flux. constr.add( z_diff[f_reaction] >= f_value - v[f_reaction], f_value - v[f_reaction] >= -z_diff[f_reaction]) # If we minimize the sum of the z vector then we will minimize # the |vs_wt - vs| from above self._prob.set_objective(z_diff.sum(reactions)) self._solve(lp.ObjectiveSense.Minimize)
<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 minimizing the sum of the absolute values of the differences of wild type FBA solution and the knockout strain flux solution. Creates the constraint that the we select the optimal flux vector that is closest to the wildtype. This might still return an arbitrary flux vector the maximizes the objective function. Args: objective: Objective reaction for the model. wt_obj: The flux value for your wild type objective reactions. Can either use an expiremental value or on determined by FBA by using :meth:`.get_fba_obj_flux(objective)`. """
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 difference between the wildtype flux # is similar to the knockout flux. constr.add( z_diff[f_reaction] >= v_wt[f_reaction] - v[f_reaction], v_wt[f_reaction] - v[f_reaction] >= -z_diff[f_reaction]) # If we minimize the sum of the z vector then we will minimize # the |v_wt - v| from above self._prob.set_objective(z_diff.sum(reactions)) constr.add(self._v_wt[objective] >= wt_obj) self._solve(lp.ObjectiveSense.Minimize)
<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 function. The distance is minimized by minimizing the sum of (wild type - knockout)^2. Args: wt_fluxes: Dictionary of all the wild type fluxes that will be used to find a close MOMA solution. Fluxes can be expiremental or calculated using :meth: get_fba_flux(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])**2 self._prob.set_objective(obj_expr) self._solve(lp.ObjectiveSense.Minimize)
<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 quadratic objective function. The distance is minimized by minimizing the sum of (wild type - knockout)^2. Creates the constraint that the we select the optimal flux vector that is closest to the wildtype. This might still return an arbitrary flux vector the maximizes the objective function. Args: objective: Objective reaction for the model. wt_obj: The flux value for your wild type objective reactions. Can either use an expiremental value or on determined by FBA by using :meth:`.get_fba_obj_flux(objective)`. """
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(lp.ObjectiveSense.Minimize)
<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: # clean up after any error in on_connect self.disconnect() raise # run any user callbacks. right now the only internal callback # is for pubsub channel/pattern resubscription for callback in self._connect_callbacks: callback(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 _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): family, socktype, proto, canonname, socket_address = res sock = None try: sock = socket.socket(family, socktype, proto) # TCP_NODELAY sock.setsockopt(socket.IPPROTO_TCP,socket.TCP_NODELAY, 1) # TCP_KEEPALIVE if self.socket_keepalive: sock.setsockopt(socket.SOL_SOCKET,socket.SO_KEEPALIVE, 1) for k, v in iteritems(self.socket_keepalive_options): sock.setsockopt(socket.SOL_TCP, k, v) # set the socket_connect_timeout before we connect sock.settimeout(self.socket_connect_timeout) # connect sock.connect(socket_address) # set the socket_timeout now that we're connected sock.settimeout(self.socket_timeout) return sock except socket.error as _: err = _ if sock is not None: sock.close() if err is not None: raise err raise socket.error("socket.getaddrinfo returned an empty list")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 them from being encoded. command = args[0] if ' ' in command: args = tuple([Token(s) for s in command.split(' ')]) + args[1:] else: args = (Token(command),) + args[1:] args_output = SYM_EMPTY.join([ SYM_EMPTY.join(( b(str(len(k))), SYM_LF, k, SYM_LF )) for k in imap(self.encode, args) ]) output = "%s%s" % (args_output,SYM_LF) return 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 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 late resolution. :param loader: YAML loader. :type loader: yaml.loader.SafeLoader :param node: Document node. :type node: ScalarNode :return: Corresponding value stored in the ``env`` dictionary. :rtype: any """
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 ``DiffInfo`` objects. args: ``a=``\ *Record* The base object ``b=``\ *Record*\ \|\ *object* The 'other' object, which must be the same type as ``a``, unless ``options.duck_type`` is set. ``fs_a=``\ *FieldSelector\* The current diff context, prefixed to any returned ``base`` field in yielded ``DiffInfo`` objects. Defaults to an empty FieldSelector. ``fs_b=``\ *FieldSelector\* The ``other`` object context. This will differ from ``fs_a`` in the case of collections, where a value has moved slots. Defaults to an empty FieldSelector. ``options=``\ *DiffOptions\* A constructed ``DiffOptions`` object; a default one is created if not passed in. """
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 = FieldSelector(tuple()) fs_b = FieldSelector(tuple()) properties = ( type(a).properties if a is not _nothing else type(b).properties ) for propname in sorted(properties): prop = properties[propname] if options.is_filtered(prop, fs_a + propname): continue propval_a = options.normalize_object_slot( getattr(a, propname, _nothing), prop, a, ) propval_b = options.normalize_object_slot( getattr(b, propname, _nothing), prop, b, ) if propval_a is _nothing and propval_b is _nothing: # don't yield NO_CHANGE for fields missing on both sides continue one_side_nothing = (propval_a is _nothing) != (propval_b is _nothing) types_match = type(propval_a) == type(propval_b) comparable = ( isinstance(propval_a, COMPARABLE) or isinstance(propval_b, COMPARABLE) ) prop_fs_a = fs_a + [propname] prop_fs_b = fs_b + [propname] if comparable and ( types_match or options.duck_type or ( options.ignore_empty_slots and one_side_nothing ) ): if one_side_nothing: diff_types_found = set() for diff in _diff_iter( propval_a, propval_b, prop_fs_a, prop_fs_b, options, ): if one_side_nothing: if diff.diff_type != DiffTypes.NO_CHANGE: diff_types_found.add(diff.diff_type) else: yield diff if one_side_nothing: net_diff = None if diff_types_found: assert(len(diff_types_found) == 1) net_diff = tuple(diff_types_found)[0] elif options.unchanged: net_diff = DiffTypes.NO_CHANGE if net_diff: yield DiffInfo( diff_type=net_diff, base=prop_fs_a, other=prop_fs_b, ) elif one_side_nothing: yield DiffInfo( diff_type=( DiffTypes.ADDED if propval_a is _nothing else DiffTypes.REMOVED ), base=fs_a + [propname], other=fs_b + [propname], ) elif not options.items_equal(propval_a, propval_b): yield DiffInfo( diff_type=DiffTypes.MODIFIED, base=fs_a + [propname], other=fs_b + [propname], ) elif options.unchanged: yield DiffInfo( diff_type=DiffTypes.NO_CHANGE, base=fs_a + [propname], other=fs_b + [propname], )
<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 indicate that the value is not set. """
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 object the slot is in as well as the value. """
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) return self.normalize_slot(value, prop)