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 accessible_organisms(user, orgs):
"""Get the list of organisms accessible to a user, filtered by `orgs`""" |
permission_map = {
x['organism']: x['permissions']
for x in user.organismPermissions
if 'WRITE' in x['permissions'] or
'READ' in x['permissions'] or
'ADMINISTRATE' in x['permissions'] or
user.role == 'ADMIN'
}
if 'error' in orgs:
raise Exception("Err... |
<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(cls, host, public_key, private_key, verbose=0, use_cache=True):
""" Connect the client with the given host and the provided credentials. Parameters h... |
return cls(host, public_key, private_key, verbose, use_cache) |
<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_from_cli(cls, argv, use_cache=True):
""" Connect with data taken from a command line interface. Parameters argv: list Command line parameters (execut... |
argparse = cls._add_cytomine_cli_args(ArgumentParser())
params, _ = argparse.parse_known_args(args=argv)
log_level = params.verbose
if params.log_level is not None:
log_level = logging.getLevelName(params.log_level)
return cls.connect(params.host, params.public_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_url(host, provided_protocol=None):
""" Process the provided host and protocol to return them in a standardized way that can be subsequently used by Cy... |
protocol = "http" # default protocol
if host.startswith("http://"):
protocol = "http"
elif host.startswith("https://"):
protocol = "https"
elif provided_protocol is not None:
provided_protocol = provided_protocol.replace("://", "")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_crop(self, ims_host, filename, id_annot, id_storage, id_project=None, sync=False, protocol=None):
""" Upload the crop associated with an annotation as... |
if not protocol:
protocol = self._protocol
ims_host, protocol = self._parse_url(ims_host, protocol)
ims_host = "{}://{}".format(protocol, ims_host)
query_parameters = {
"annotation" : id_annot,
"storage": id_storage,
"cy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_comment(self, value):
""" Get a specific canned comment :type value: str :param value: Canned comment to show :rtype: dict :return: A dictionnary contai... |
comments = self.get_comments()
comments = [x for x in comments if x['comment'] == value]
if len(comments) == 0:
raise Exception("Unknown comment")
else:
return comments[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 arrow(ctx, apollo_instance, verbose, log_level):
"""Command line wrappers around Apollo functions. While this sounds unexciting, with arrow and jq you can ea... |
set_logging_level(log_level)
# We abuse this, knowing that calls to one will fail.
try:
ctx.gi = get_apollo_instance(apollo_instance)
except TypeError:
pass
# ctx.log("Could not access Galaxy instance configuration")
ctx.verbose = verbose |
<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_loads(data):
"""Load json data, allowing - to represent stdin.""" |
if data is None:
return ""
if data == "-":
return json.load(sys.stdin)
elif os.path.exists(data):
with open(data, 'r') as handle:
return json.load(handle)
else:
return json.loads(data) |
<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_queryset(self, **options):
""" Filters the list of log objects to display """ |
days = options.get('days')
queryset = TimelineLog.objects.order_by('-timestamp')
if days:
try:
start = timezone.now() - timedelta(days=days)
except TypeError:
raise CommandError("Incorrect 'days' parameter. 'days' must be a number of days.... |
<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_recipients(self, **options):
""" Figures out the recipients """ |
if options['recipients_from_setting']:
return settings.TIMELINE_DIGEST_EMAIL_RECIPIENTS
users = get_user_model()._default_manager.all()
if options['staff']:
users = users.filter(is_staff=True)
elif not options['all']:
users = users.filter(is_staff=Tr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_actions(self, actions):
"""Accepts an array of actions and returns an array of actions which match. This should be called before "matches?" and other ... |
results = list()
for action in actions:
if action in self.aliased_actions:
results.append(action)
for item in self.expand_actions(self.aliased_actions[action]):
results.append(item)
else:
results.append(action)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _software_params_to_argparse(parameters):
""" Converts a SoftwareParameterCollection into an ArgumentParser object. Parameters parameters: SoftwareParameterC... |
# Check software parameters
argparse = ArgumentParser()
boolean_defaults = {}
for parameter in parameters:
arg_desc = {"dest": parameter.name, "required": parameter.required, "help": ""} # TODO add help
if parameter.type == "Boolean":
default = _to_bool(parameter.defaultPar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Connect to the Cytomine server and switch to job connection Incurs dataflows """ |
run_by_ui = False
if not self.current_user.algo:
# If user connects as a human (CLI execution)
self._job = Job(self._project.id, self._software.id).save()
user_job = User().fetch(self._job.userJob)
self.set_credentials(user_job.publicKey, user_job.privat... |
<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, value):
""" Notify the Cytomine server of the job's end Incurs a dataflows """ |
if value is None:
status = Job.TERMINATED
status_comment = "Job successfully terminated"
else:
status = Job.FAILED
status_comment = str(value)[:255]
self._job.status = status
self._job.statusComment = status_comment
self._job.upd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_from_cli(args):
"""CLI entry point.""" |
parser = argparse.ArgumentParser(description="Generate Python classes from an Ecore model.")
parser.add_argument(
'--ecore-model',
'-e',
help="Path to Ecore XMI file.",
required=True
)
parser.add_argument(
'--out-folder',
'-o',
help="Path to direc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_uri_implementation(ecore_model_path):
"""Select the right URI implementation regarding the Ecore model path schema.""" |
if URL_PATTERN.match(ecore_model_path):
return pyecore.resources.resource.HttpURI
return pyecore.resources.URI |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_model(ecore_model_path):
"""Load a single Ecore model and return the root package.""" |
rset = pyecore.resources.ResourceSet()
uri_implementation = select_uri_implementation(ecore_model_path)
resource = rset.get_resource(uri_implementation(ecore_model_path))
return resource.contents[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 post(self, client_method, data, post_params=None, is_json=True):
"""Make a POST request""" |
url = self._wa.apollo_url + self.CLIENT_BASE + client_method
if post_params is None:
post_params = {}
headers = {
'Content-Type': 'application/json'
}
data.update({
'username': self._wa.username,
'password': self._wa.password,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, client_method, get_params, is_json=True):
"""Make a GET request""" |
url = self._wa.apollo_url + self.CLIENT_BASE + client_method
headers = {}
response = requests.get(url, headers=headers,
verify=self.__verify, params=get_params,
**self._request_args)
if response.status_code == 200:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can(user, action, subject):
"""Checks if a given user has the ability to perform the action on a subject :param user: A user object :param action: an action ... |
ability = Ability(user, get_authorization_method())
return ability.can(action, subject) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cannot(user, action, subject):
"""inverse of ``can``""" |
ability = Ability(user, get_authorization_method())
return ability.cannot(action, subject) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure(user, action, subject):
""" Similar to ``can`` but will raise a AccessDenied Exception if does not have access""" |
ability = Ability(user, get_authorization_method())
if ability.cannot(action, subject):
raise AccessDenied() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, dest_pattern="{id}.jpg", override=True, mask=False, alpha=False, bits=8, zoom=None, max_size=None, increase_area=None, contrast=None, gamma=None, c... |
if self.id is None:
raise ValueError("Cannot dump an annotation with no ID.")
pattern = re.compile("{(.*?)}")
dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_")), dest_pattern)
destination = os.path.dirname(dest_pattern)
filename... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, organism, sequence):
"""Set the sequence for subsequent requests. Mostly used in client scripts to avoid passing the sequence and organism on every ... |
return ctx.gi.annotations.set_sequence(organism, sequence) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path(self):
"""The path attribute returns a stringified, concise representation of the MultiFieldSelector. It can be reversed by the ``from_path`` constructo... |
if len(self.heads) == 1:
return _fmt_mfs_path(self.heads.keys()[0], self.heads.values()[0])
else:
return "(" + "|".join(
_fmt_mfs_path(k, v) for (k, v) in self.heads.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(self, obj):
"""Creates a copy of the passed object which only contains the parts which are pointed to by one of the FieldSelectors that were used to cons... |
ctor = type(obj)
if isinstance(obj, (list, ListCollection)):
if self.has_string:
raise TypeError(
"MultiFieldSelector has string in list collection context"
)
if self.has_none:
tail = self.heads[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 delete(self, obj, force=False):
"""Deletes all of the fields at the specified locations. args: ``obj=``\ *OBJECT* the object to remove the fields from ``forc... |
# TODO: this could be a whole lot more efficient!
if not force:
for fs in self:
try:
fs.get(obj)
except FieldSelectorException:
raise
for fs in self:
try:
fs.delete(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 reset_socat(use_sudo=False):
""" Finds and closes all processes of `socat`. :param use_sudo: Use `sudo` command. As Docker-Fabric does not run `socat` with `... |
output = stdout_result('ps -o pid -C socat', quiet=True)
pids = output.split('\n')[1:]
puts("Removing process(es) with id(s) {0}.".format(', '.join(pids)))
which = sudo if use_sudo else run
which('kill {0}'.format(' '.join(pids)), quiet=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 version():
""" Shows version information of the remote Docker service, similar to ``docker version``. """ |
output = docker_fabric().version()
col_len = max(map(len, output.keys())) + 1
puts('')
for k, v in six.iteritems(output):
fastprint('{0:{1}} {2}'.format(''.join((k, ':')), col_len, v), end='\n', flush=False)
fastprint('', flush=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 list_images(list_all=False, full_ids=False):
""" Lists images on the Docker remote host, similar to ``docker images``. :param list_all: Lists all images (e.g... |
images = docker_fabric().images(all=list_all)
_format_output_table(images, IMAGE_COLUMNS, full_ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_containers(list_all=True, short_image=True, full_ids=False, full_cmd=False):
""" Lists containers on the Docker remote host, similar to ``docker ps``. :... |
containers = docker_fabric().containers(all=list_all)
_format_output_table(containers, CONTAINER_COLUMNS, full_ids, full_cmd, short_image) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_networks(full_ids=False):
""" Lists networks on the Docker remote host, similar to ``docker network ls``. :param full_ids: Shows the full network ids. W... |
networks = docker_fabric().networks()
_format_output_table(networks, NETWORK_COLUMNS, full_ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_containers(**kwargs):
""" Removes all containers that have finished running. Similar to the ``prune`` functionality in newer Docker versions. """ |
containers = docker_fabric().cleanup_containers(**kwargs)
if kwargs.get('list_only'):
puts('Existing containers:')
for c_id, c_name in containers:
fastprint('{0} {1}'.format(c_id, c_name), 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 cleanup_images(remove_old=False, **kwargs):
""" Removes all images that have no name, and that are not references as dependency by any other named image. Sim... |
keep_tags = env.get('docker_keep_tags')
if keep_tags is not None:
kwargs.setdefault('keep_tags', keep_tags)
removed_images = docker_fabric().cleanup_images(remove_old=remove_old, **kwargs)
if kwargs.get('list_only'):
puts('Unused images:')
for image_name in removed_images:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_image(image, filename=None):
""" Saves a Docker image from the remote to a local files. For performance reasons, uses the Docker command line client on ... |
local_name = filename or '{0}.tar.gz'.format(image)
cli.save_image(image, local_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_image(filename, timeout=120):
""" Uploads an image from a local file to a Docker remote. Note that this temporarily has to extend the service timeout pe... |
c = docker_fabric()
with open(expand_path(filename), 'r') as f:
_timeout = c._timeout
c._timeout = timeout
try:
c.load_image(f)
finally:
c._timeout = _timeout |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff_iter(self, other, **kwargs):
"""Generator method which returns the differences from the invocant to the argument. args: ``other=``\ *Record*\ \|\ *Anyth... |
from normalize.diff import diff_iter
return diff_iter(self, other, **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 _parse_weights(weight_args, default_weight=0.6):
"""Parse list of weight assignments.""" |
weights_dict = {}
r_group_weight = default_weight
for weight_arg in weight_args:
for weight_assignment in weight_arg.split(','):
if '=' not in weight_assignment:
raise ValueError(
'Invalid weight assignment: {}'.format(weight_assignment))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _combine_transfers(self, result):
"""Combine multiple pair transfers into one.""" |
transfers = {}
for reaction_id, c1, c2, form in result:
key = reaction_id, c1, c2
combined_form = transfers.setdefault(key, Formula())
transfers[key] = combined_form | form
for (reaction_id, c1, c2), form in iteritems(transfers):
yield reaction_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 copy_resource(container, resource, local_filename, contents_only=True):
""" Copies a resource from a container to a compressed tarball and downloads it. :par... |
with temp_dir() as remote_tmp:
base_name = os.path.basename(resource)
copy_path = posixpath.join(remote_tmp, 'copy_tmp')
run(mkdir(copy_path, check_if_exists=True))
remote_name = posixpath.join(copy_path, base_name)
archive_name = 'container_{0}.tar.gz'.format(container)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_image(image, local_filename):
""" Saves a Docker image as a compressed tarball. This command line client method is a suitable alternative, if the Remove... |
r_name, __, i_name = image.rpartition('/')
i_name, __, __ = i_name.partition(':')
with temp_dir() as remote_tmp:
archive = posixpath.join(remote_tmp, 'image_{0}.tar.gz'.format(i_name))
run('docker save {0} | gzip --stdout > {1}'.format(image, archive), shell=False)
get(archive, loca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_name(s):
"""Decode names in ModelSEED files""" |
# Some names contain XML-like entity codes
return re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), 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 parse_compound_file(f, context=None):
"""Iterate over the compound entries in the given file""" |
f.readline() # Skip header
for lineno, row in enumerate(csv.reader(f, delimiter='\t')):
compound_id, names, formula = row[:3]
names = (decode_name(name) for name in names.split(',<br>'))
# ModelSEED sometimes uses an asterisk and number at
# the end of formulas. This seems to... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_parser(cls, parser):
"""Initialize argument parser""" |
subparsers = parser.add_subparsers(title='Search domain')
# Compound subcommand
parser_compound = subparsers.add_parser(
'compound', help='Search in compounds')
parser_compound.set_defaults(which='compound')
parser_compound.add_argument(
'--id', '-i', de... |
<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 search command.""" |
which_command = self._args.which
if which_command == 'compound':
self._search_compound()
elif which_command == 'reaction':
self._search_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 to_json(self, propval, extraneous=False, to_json_func=None):
"""This function calls the ``json_out`` function, if it was specified, otherwise continues with ... |
if self.json_out:
return self.json_out(propval)
else:
if not to_json_func:
from normalize.record.json import to_json
to_json_func = to_json
return to_json_func(propval, extraneous) |
<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_compound(s, global_compartment=None):
"""Parse a compound specification. If no compartment is specified in the string, the global compartment will be u... |
m = re.match(r'^\|(.*)\|$', s)
if m:
s = m.group(1)
m = re.match(r'^(.+)\[(\S+)\]$', s)
if m:
compound_id = m.group(1)
compartment = m.group(2)
else:
compound_id = s
compartment = global_compartment
return Compound(compound_id, compartment=compartment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_sparse(strategy, prob, obj_reaction, flux_threshold):
"""Find a random minimal network of model reactions. Given a reaction to optimize and a threshol... |
essential = set()
deleted = set()
for entity, deleted_reactions in strategy.iter_tests():
if obj_reaction in deleted_reactions:
logger.info(
'Marking entity {} as essential because the objective'
' reaction depends on this entity...'.format(entity))
... |
<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_sink_check(self, model, solver, threshold, implicit_sinks=True):
"""Run sink production check method.""" |
prob = solver.create_problem()
# Create flux variables
v = prob.namespace()
for reaction_id in model.reactions:
lower, upper = model.limits[reaction_id]
v.define([reaction_id], lower=lower, upper=upper)
# Build mass balance constraints
massbalan... |
<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_reaction_production_check(self, model, solver, threshold, implicit_sinks=True):
"""Run reaction production check method.""" |
prob = solver.create_problem()
# Create flux variables
v = prob.namespace()
for reaction_id in model.reactions:
lower, upper = model.limits[reaction_id]
v.define([reaction_id], lower=lower, upper=upper)
# Build mass balance constraints
massbalan... |
<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_linear_constraints(self, *relations):
"""Add constraints to the problem Each constraint is represented by a Relation, and the expression in that relation... |
constraints = []
for relation in relations:
if self._check_relation(relation):
constraints.append(Constraint(self, None))
else:
for name in self._add_constraints(relation):
constraints.append(Constraint(self, name))
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_objective(self, expression):
"""Set objective expression of the problem.""" |
if isinstance(expression, numbers.Number):
# Allow expressions with no variables as objective,
# represented as a number
expression = Expression(offset=expression)
linear = []
quad = []
# Reset previous objective.
for var in self._non_zero_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reset_problem_type(self):
"""Reset problem type to whatever is appropriate.""" |
# Only need to reset the type after the first solve. This also works
# around a bug in Cplex where get_num_binary() is some rare cases
# causes a segfault.
if self._solve_count > 0:
integer_count = 0
for func in (self._cp.variables.get_num_binary,
... |
<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):
"""Return value of expression.""" |
self._check_valid()
return super(Result, 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 _parse_formula(s):
"""Parse formula string.""" |
scanner = re.compile(r'''
(\s+) | # whitespace
(\(|\)) | # group
([A-Z][a-z]*) | # element
(\d+) | # number
([a-z]) | # variable
(\Z) | # end
(.) # error
''', re.DOTALL | re.VERBOSE)
def transform_subf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Be sure to implement this method when sub-classing, otherwise you will lose any specialization context.""" |
doppel = type(self)(
self.unpack, self.apply, self.collect, self.reduce,
apply_empty_slots=self.apply_empty_slots,
extraneous=self.extraneous,
ignore_empty_string=self.ignore_empty_string,
ignore_none=self.ignore_none,
visit_filter=self.vi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack(cls, value, value_type, visitor):
"""Unpack a value during a 'visit' args: ``value=``\ *object* The instance being visited ``value_type=``\ *RecordTyp... |
if issubclass(value_type, Collection):
try:
generator = value.itertuples()
except AttributeError:
if isinstance(value, value_type.colltype):
generator = value_type.coll_to_tuples(value)
else:
raise 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 apply(cls, value, prop, visitor):
"""'apply' is a general place to put a function which is called on every extant record slot. This is usually the most impor... |
return (
None if isinstance(value, (AttributeError, KeyError)) else
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 aggregate(self, mapped_coll_generator, coll_type, visitor):
"""Hook called for each normalize.coll.Collection, after mapping over each of the items in the co... |
return coll_type.tuples_to_coll(mapped_coll_generator, coerce=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 reduce(self, mapped_props, aggregated, value_type, visitor):
"""This reduction is called to combine the mapped slot and collection item values into a single ... |
reduced = None
if mapped_props:
reduced = dict((k.name, v) for k, v in mapped_props)
if issubclass(value_type, Collection) and aggregated is not None:
if all(visitor.is_filtered(prop) for prop in
value_type.properties.values()):
reduce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reflect(cls, X, **kwargs):
"""Reflect is for visitors where you are exposing some information about the types reachable from a starting type to an external s... |
if isinstance(X, type):
value = None
value_type = X
else:
value = X
value_type = type(X)
if not issubclass(value_type, Record):
raise TypeError("Cannot reflect on %s" % value_type.__name__)
visitor = cls.Visitor(
c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map(cls, visitor, value, value_type):
"""The common visitor API used by all three visitor implementations. args: ``visitor=``\ *Visitor* Visitor options inst... |
unpacked = visitor.unpack(value, value_type, visitor)
if unpacked == cls.StopVisiting or isinstance(
unpacked, cls.StopVisiting
):
return unpacked.return_value
if isinstance(unpacked, tuple):
props, coll = unpacked
else:
props, c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_fba_problem(model, tfba, solver):
"""Convenience function for returning the right FBA problem instance""" |
p = FluxBalanceProblem(model, solver)
if tfba:
p.add_thermodynamic()
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flux_balance(model, reaction, tfba, solver):
"""Run flux balance analysis on the given model. Yields the reaction id and flux value for each reaction in the ... |
fba = _get_fba_problem(model, tfba, solver)
fba.maximize(reaction)
for reaction in model.reactions:
yield reaction, fba.get_flux(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 flux_variability(model, reactions, fixed, tfba, solver):
"""Find the variability of each reaction while fixing certain fluxes. Yields the reaction id, and a ... |
fba = _get_fba_problem(model, tfba, solver)
for reaction_id, value in iteritems(fixed):
flux = fba.get_flux_var(reaction_id)
fba.prob.add_linear_constraints(flux >= value)
def min_max_solve(reaction_id):
for direction in (-1, 1):
yield fba.flux_bound(reaction_id, dire... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flux_minimization(model, fixed, solver, weights={}):
"""Minimize flux of all reactions while keeping certain fluxes fixed. The fixed reactions are given in a... |
fba = FluxBalanceProblem(model, solver)
for reaction_id, value in iteritems(fixed):
flux = fba.get_flux_var(reaction_id)
fba.prob.add_linear_constraints(flux >= value)
fba.minimize_l1()
return ((reaction_id, fba.get_flux(reaction_id))
for reaction_id in model.reactions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flux_randomization(model, threshold, tfba, solver):
"""Find a random flux solution on the boundary of the solution space. The reactions in the threshold dict... |
optimize = {}
for reaction_id in model.reactions:
if model.is_reversible(reaction_id):
optimize[reaction_id] = 2*random.random() - 1.0
else:
optimize[reaction_id] = random.random()
fba = _get_fba_problem(model, tfba, solver)
for reaction_id, value in iteritems(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def consistency_check(model, subset, epsilon, tfba, solver):
"""Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* ... |
fba = _get_fba_problem(model, tfba, solver)
subset = set(subset)
while len(subset) > 0:
reaction = next(iter(subset))
logger.info('{} left, checking {}...'.format(len(subset), reaction))
fba.maximize(reaction)
subset = set(reaction_id for reaction_id in subset
... |
<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_thermodynamic(self, em=1000):
"""Apply thermodynamic constraints to the model. Adding these constraints restricts the solution space to only contain solu... |
internal = set(r for r in self._model.reactions
if not self._model.is_exchange(r))
# Reaction fluxes
v = self._v
# Indicator variable
alpha = self._prob.namespace(internal, types=lp.VariableType.Binary)
# Delta mu is the stoichiometrically weig... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximize(self, reaction):
"""Solve the model by maximizing the given reaction. If reaction is a dictionary object, each entry is interpreted as a weight on t... |
self._prob.set_objective(self.flux_expr(reaction))
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 flux_bound(self, reaction, direction):
"""Return the flux bound of the reaction. Direction must be a positive number to obtain the upper bound or a negative ... |
try:
self.maximize({reaction: direction})
except FluxBalanceError as e:
if not e.result.unbounded:
raise
return direction * _INF
else:
return self.get_flux(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 _add_minimization_vars(self):
"""Add variables and constraints for L1 norm minimization.""" |
self._z = self._prob.namespace(self._model.reactions, lower=0)
# Define constraints
v = self._v.set(self._model.reactions)
z = self._z.set(self._model.reactions)
self._prob.add_linear_constraints(z >= v, v >= -z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minimize_l1(self, weights={}):
"""Solve the model by minimizing the L1 norm of the fluxes. If the weights dictionary is given, the weighted L1 norm if minimi... |
if self._z is None:
self._add_minimization_vars()
objective = self._z.expr(
(reaction_id, -weights.get(reaction_id, 1))
for reaction_id in self._model.reactions)
self._prob.set_objective(objective)
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 max_min_l1(self, reaction, weights={}):
"""Maximize flux of reaction then minimize the L1 norm. During minimization the given reaction will be fixed at the m... |
self.maximize(reaction)
if isinstance(reaction, dict):
reactions = list(reaction)
else:
reactions = [reaction]
# Save flux values before modifying the LP problem
fluxes = {r: self.get_flux(r) for r in reactions}
# Add constraints on the maximi... |
<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):
"""Solve the problem with the current objective.""" |
# Remove temporary constraints
while len(self._remove_constr) > 0:
self._remove_constr.pop().delete()
try:
self._prob.solve(lp.ObjectiveSense.Maximize)
except lp.SolverError as e:
raise_from(FluxBalanceError('Failed to solve: {}'.format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flux_expr(self, reaction):
"""Get LP expression representing the reaction flux.""" |
if isinstance(reaction, dict):
return self._v.expr(iteritems(reaction))
return self._v(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 get_flux(self, reaction):
"""Get resulting flux value for reaction.""" |
return self._prob.result.get_value(self._v(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 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.set_linear_objective(
(lp_name, expression.value(var))
for var, lp_name in iteritems(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 unbounded(self):
"""Whether the solution is unbounded""" |
self._check_valid()
return (self._problem._p.get_status() ==
qsoptex.SolutionStatus.UNBOUNDED) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _execute(job, f, o=None):
""" Executes a librsync "job" by reading bytes from `f` and writing results to `o` if provided. If `o` is omitted, the output is ig... |
# Re-use the same buffer for output, we will read from it after each
# iteration.
out = ctypes.create_string_buffer(RS_JOB_BLOCKSIZE)
while True:
block = f.read(RS_JOB_BLOCKSIZE)
buff = Buffer()
# provide the data block via input buffer.
buff.next_in = ctypes.c_char_p(bl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signature(f, s=None, block_size=RS_DEFAULT_BLOCK_LEN):
""" Generate a signature for the file `f`. The signature will be written to `s`. If `s` is omitted, a ... |
if s is None:
s = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+')
job = _librsync.rs_sig_begin(block_size, RS_DEFAULT_STRONG_LEN)
try:
_execute(job, f, s)
finally:
_librsync.rs_job_free(job)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delta(f, s, d=None):
""" Create a delta for the file `f` using the signature read from `s`. The delta will be written to `d`. If `d` is omitted, a temporary ... |
if d is None:
d = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+')
sig = ctypes.c_void_p()
try:
job = _librsync.rs_loadsig_begin(ctypes.byref(sig))
try:
_execute(job, s)
finally:
_librsync.rs_job_free(job)
r = _librsync.rs_build_h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch(f, d, o=None):
""" Patch the file `f` using the delta `d`. The patched file will be written to `o`. If `o` is omitted, a temporary file will be used. T... |
if o is None:
o = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+')
@patch_callback
def read_cb(opaque, pos, length, buff):
f.seek(pos)
size_p = ctypes.cast(length, ctypes.POINTER(ctypes.c_size_t)).contents
size = size_p.value
block = f.read(size)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_integer_tolerance(epsilon, v_max, min_tol):
"""Find appropriate integer tolerance for gap-filling problems.""" |
int_tol = min(epsilon / (10 * v_max), 0.1)
min_tol = max(1e-10, min_tol)
if int_tol < min_tol:
eps_lower = min_tol * 10 * v_max
logger.warning(
'When the maximum flux is {}, it is recommended that'
' epsilon > {} to avoid numerical issues with this'
' sol... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gapfind(model, solver, epsilon=0.001, v_max=1000, implicit_sinks=True):
"""Identify compounds in the model that cannot be produced. Yields all compounds that... |
prob = solver.create_problem()
# Set integrality tolerance such that w constraints are correct
min_tol = prob.integrality_tolerance.min
int_tol = _find_integer_tolerance(epsilon, v_max, min_tol)
if int_tol < prob.integrality_tolerance.value:
prob.integrality_tolerance.value = int_tol
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def float_constructor(loader, node):
"""Construct Decimal from YAML float encoding.""" |
s = loader.construct_scalar(node)
if s == '.inf':
return Decimal('Infinity')
elif s == '-.inf':
return -Decimal('Infinity')
elif s == '.nan':
return Decimal('NaN')
return Decimal(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 yaml_load(stream):
"""Load YAML file using safe loader.""" |
# Surprisingly, the CSafeLoader does not seem to be used by default.
# Check whether the CSafeLoader is available and provide a log message
# if it is not available.
global _HAS_YAML_LIBRARY
if _HAS_YAML_LIBRARY is None:
_HAS_YAML_LIBRARY = hasattr(yaml, 'CSafeLoader')
if not _HAS_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_id(entity, entity_type):
"""Check whether the ID is valid. First check if the ID is missing, and then check if it is a qualified string type, finally ... |
if entity is None:
raise ParseError('{} ID missing'.format(entity_type))
elif not isinstance(entity, string_types):
msg = '{} ID must be a string, id was {}.'.format(entity_type, entity)
if isinstance(entity, bool):
msg += (' You may have accidentally used an ID value that ... |
<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_compound(compound_def, context=None):
"""Parse a structured compound definition as obtained from a YAML file Returns a CompoundEntry.""" |
compound_id = compound_def.get('id')
_check_id(compound_id, 'Compound')
mark = FileMark(context, None, None)
return CompoundEntry(compound_def, mark) |
<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_compound_list(path, compounds):
"""Parse a structured list of compounds as obtained from a YAML file Yields CompoundEntries. Path can be given as a str... |
context = FilePathContext(path)
for compound_def in compounds:
if 'include' in compound_def:
file_format = compound_def.get('format')
include_context = context.resolve(compound_def['include'])
for compound in parse_compound_file(include_context, file_format):
... |
<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_compound_table_file(path, f):
"""Parse a tab-separated file containing compound IDs and properties The compound properties are parsed according to the ... |
context = FilePathContext(path)
for i, row in enumerate(csv.DictReader(f, delimiter=str('\t'))):
if 'id' not in row or row['id'].strip() == '':
raise ParseError('Expected `id` column in table')
props = {key: value for key, value in iteritems(row) if value != ''}
if 'char... |
<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_compound_file(path, format):
"""Open and parse reaction file based on file extension or given format Path can be given as a string or a context. """ |
context = FilePathContext(path)
# YAML files do not need to explicitly specify format
format = resolve_format(format, context.filepath)
if format == 'yaml':
logger.debug('Parsing compound file {} as YAML'.format(
context.filepath))
with context.open('r') as 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 parse_reaction_equation_string(equation, default_compartment):
"""Parse a string representation of a reaction equation. Converts undefined compartments to th... |
def _translate_compartments(reaction, compartment):
"""Translate compound with missing compartments.
These compounds will have the specified compartment in the output.
"""
left = (((c.in_compartment(compartment), v)
if c.compartment is None else (c, v))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_reaction_equation(equation_def, default_compartment):
"""Parse a structured reaction equation as obtained from a YAML file Returns a Reaction. """ |
def parse_compound_list(l, compartment):
"""Parse a list of reactants or metabolites"""
for compound_def in l:
compound_id = compound_def.get('id')
_check_id(compound_id, 'Compound')
value = compound_def.get('value')
if value 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 parse_reaction(reaction_def, default_compartment, context=None):
"""Parse a structured reaction definition as obtained from a YAML file Returns a ReactionEnt... |
reaction_id = reaction_def.get('id')
_check_id(reaction_id, 'Reaction')
reaction_props = dict(reaction_def)
# Parse reaction equation
if 'equation' in reaction_def:
reaction_props['equation'] = parse_reaction_equation(
reaction_def['equation'], default_compartment)
mark ... |
<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_list(path, reactions, default_compartment=None):
"""Parse a structured list of reactions as obtained from a YAML file Yields tuples of reactio... |
context = FilePathContext(path)
for reaction_def in reactions:
if 'include' in reaction_def:
include_context = context.resolve(reaction_def['include'])
for reaction in parse_reaction_file(
include_context, default_compartment):
yield reactio... |
<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_table_file(path, f, default_compartment):
"""Parse a tab-separated file containing reaction IDs and properties The reaction properties are par... |
context = FilePathContext(path)
for lineno, row in enumerate(csv.DictReader(f, delimiter=str('\t'))):
if 'id' not in row or row['id'].strip() == '':
raise ParseError('Expected `id` column in table')
props = {key: value for key, value in iteritems(row) if value != ''}
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_reaction_file(path, default_compartment=None):
"""Open and parse reaction file based on file extension Path can be given as a string or a context. """ |
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing reaction file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for reaction in parse_reaction_table_file(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_exchange(exchange_def, default_compartment):
"""Parse a structured exchange definition as obtained from a YAML file. Returns in iterator of compound, r... |
default_compartment = exchange_def.get('compartment', default_compartment)
for compound_def in exchange_def.get('compounds', []):
compartment = compound_def.get('compartment', default_compartment)
compound = Compound(compound_def['id'], compartment=compartment)
reaction = compound_def... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_exchange_list(path, exchange, default_compartment):
"""Parse a structured exchange list as obtained from a YAML file. Yields tuples of compound, reacti... |
context = FilePathContext(path)
for exchange_def in exchange:
if 'include' in exchange_def:
include_context = context.resolve(exchange_def['include'])
for exchange_compound in parse_exchange_file(
include_context, default_compartment):
yield... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.