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 record_id(self, record, type_=None, selector=None):
"""Retrieve an object identifier from the given record; if it is an alien class, and the type is provided... |
pk = record_id(record, type_, selector, self.normalize_object_slot)
return pk |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fastcc(model, epsilon, solver):
"""Check consistency of model reactions. Yield all reactions in the model that are not part of the consistent subset. Args: m... |
reaction_set = set(model.reactions)
subset = set(reaction_id for reaction_id in reaction_set
if model.limits[reaction_id].lower >= 0)
logger.info('Checking {} irreversible reactions...'.format(len(subset)))
logger.debug('|J| = {}, J = {}'.format(len(subset), subset))
p = Fastcore... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fastcc_is_consistent(model, epsilon, solver):
"""Quickly check whether model is consistent Return true if the model is consistent. If it is only necessary to... |
for reaction in fastcc(model, epsilon, solver):
return False
return 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 fastcc_consistent_subset(model, epsilon, solver):
"""Return consistent subset of model. The largest consistent subset is returned as a set of reaction names.... |
reaction_set = set(model.reactions)
return reaction_set.difference(fastcc(model, epsilon, solver)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fastcore(model, core, epsilon, solver, scaling=1e5, weights={}):
"""Find a flux consistent subnetwork containing the core subset. The result will contain the... |
consistent_subset = set()
reaction_set = set(model.reactions)
subset = core - model.reversible
logger.debug('|J| = {}, J = {}'.format(len(subset), subset))
penalty_set = reaction_set - core
logger.debug('|P| = {}, P = {}'.format(len(penalty_set), penalty_set))
p = FastcoreProblem(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 lp7(self, reaction_subset):
"""Approximately maximize the number of reaction with flux. This is similar to FBA but approximately maximizing the number of rea... |
if self._zl is None:
self._add_maximization_vars()
positive = set(reaction_subset) - self._flipped
negative = set(reaction_subset) & self._flipped
v = self._v.set(positive)
zl = self._zl.set(positive)
cs = self._prob.add_linear_constraints(v >= zl)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lp10(self, subset_k, subset_p, weights={}):
"""Force reactions in K above epsilon while minimizing support of P. This program forces reactions in subset K to... |
if self._z is None:
self._add_minimization_vars()
positive = set(subset_k) - self._flipped
negative = set(subset_k) & self._flipped
v = self._v.set(positive)
cs = self._prob.add_linear_constraints(v >= self._epsilon)
self._temp_constr.extend(cs)
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 find_sparse_mode(self, core, additional, scaling, weights={}):
"""Find a sparse mode containing reactions of the core subset. Return an iterator of the suppo... |
if len(core) == 0:
return
self.lp7(core)
k = set()
for reaction_id in core:
flux = self.get_flux(reaction_id)
if self.is_flipped(reaction_id):
flux *= -1
if flux >= self._epsilon:
k.add(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 flip(self, reactions):
"""Flip the specified reactions.""" |
for reaction in reactions:
if reaction in self._flipped:
self._flipped.remove(reaction)
else:
self._flipped.add(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 _jaccard_similarity(f1, f2, weight_func):
"""Calculate generalized Jaccard similarity of formulas. Returns the weighted similarity value or None if there is ... |
elements = set(f1)
elements.update(f2)
count, w_count, w_total = 0, 0, 0
for element in elements:
mi = min(f1.get(element, 0), f2.get(element, 0))
mx = max(f1.get(element, 0), f2.get(element, 0))
count += mi
w = weight_func(element)
w_count += w * mi
w_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict_compound_pairs_iterated( reactions, formulas, prior=(1, 43), max_iterations=None, element_weight=element_weight):
"""Predict reaction pairs using ite... |
prior_alpha, prior_beta = prior
reactions = dict(reactions)
pair_reactions = {}
possible_pairs = Counter()
for reaction_id, equation in iteritems(reactions):
for (c1, _), (c2, _) in product(equation.left, equation.right):
spair = tuple(sorted([c1.name, c2.name]))
po... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict_compound_pairs(reaction, compound_formula, pair_weights={}, weight_func=element_weight):
"""Predict compound pairs for a single reaction. Performs gr... |
def score_func(inst1, inst2):
score = _jaccard_similarity(
inst1.formula, inst2.formula, weight_func)
if score is None:
return None
pair = inst1.compound.name, inst2.compound.name
pair_weight = pair_weights.get(pair, 1.0)
return pair_weight * score
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_get(option_name):
""" Helper to access a Juju config option when charmhelpers is not available. :param str option_name: Name of the config option to g... |
try:
raw = subprocess.check_output(['config-get', option_name, '--format=yaml'])
return yaml.load(raw.decode('UTF-8'))
except ValueError:
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 fetch(which=None, mirror_url=None, resources_yaml='resources.yaml', force=False, reporthook=None):
""" Attempt to fetch all resources for a charm. :param lis... |
resources = _load(resources_yaml, None)
if reporthook is None:
reporthook = lambda r: juju_log('Fetching %s' % r, level='INFO')
_fetch(resources, which, mirror_url, force, reporthook)
failed = _invalid(resources, which)
if failed:
juju_log('Failed to fetch resource%s: %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 rate(wait=MIN_WAIT, reps=REPS):
""" Rate limit a command function. :param wait: How long to wait between commands. :param reps: How many times to send a comm... |
def decorator(function):
""" Decorator function.
:returns: Wrapper.
"""
def wrapper(self, *args, **kwargs):
""" Wrapper.
:param args: Passthrough positional arguments.
:param kwargs: Passthrough keyword arguments.
"""
sav... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on(self, state):
""" Turn on or off. :param state: True (on) or False (off). """ |
self._on = state
cmd = self.command_set.off()
if state:
cmd = self.command_set.on()
self.send(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flash(self, duration=0.0):
""" Flash a group. :param duration: How quickly to flash (in seconds). """ |
for _ in range(2):
self.on = not self.on
time.sleep(duration) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, cmd):
""" Send a command to the bridge. :param cmd: List of command bytes. """ |
self._bridge.send(cmd, wait=self.wait, reps=self.reps) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enqueue(self, pipeline):
""" Start a pipeline. :param pipeline: Start this pipeline. """ |
copied = Pipeline().append(pipeline)
copied.group = self
self._queue.put(copied) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wait(self, duration, steps, commands):
""" Compute wait time. :param duration: Total time (in seconds). :param steps: Number of steps. :param commands: Numb... |
wait = ((duration - self.wait * self.reps * commands) / steps) - \
(self.wait * self.reps * self._bridge.active)
return max(0, wait) |
<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(cls, name, definition, output_dir):
""" Dispatch to the right subclass based on the definition. """ |
if 'url' in definition:
return URLResource(name, definition, output_dir)
elif 'pypi' in definition:
return PyPIResource(name, definition, output_dir)
else:
return Resource(name, definition, output_dir) |
<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 the pipeline queue. The pipeline queue will run forever. """ |
while True:
self._event.clear()
self._queue.get().run(self._event) |
<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, stop):
""" Run the pipeline. :param stop: Stop event """ |
_LOGGER.info("Starting a new pipeline on group %s", self._group)
self._group.bridge.incr_active()
for i, stage in enumerate(self._pipe):
self._execute_stage(i, stage, stop)
_LOGGER.info("Finished pipeline on group %s", self._group)
self._group.bridge.decr_active() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, pipeline):
""" Append a pipeline to this pipeline. :param pipeline: Pipeline to append. :returns: This pipeline. """ |
for stage in pipeline.pipe:
self._pipe.append(stage)
return 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 _add_stage(self, name):
""" Add stage methods at runtime. Stage methods all follow the same pattern. :param name: Stage name. """ |
def stage_func(self, *args, **kwargs):
""" Stage function.
:param args: Positional arguments.
:param kwargs: Keyword arguments.
:return: Pipeline (for method chaining).
"""
self._pipe.append(Stage(name, args, kwargs))
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 _execute_stage(self, index, stage, stop):
""" Execute a pipeline stage. :param index: Stage index. :param stage: Stage object. """ |
if stop.is_set():
_LOGGER.info("Stopped pipeline on group %s", self._group)
return
_LOGGER.info(" -> Running stage '%s' on group %s", stage, self._group)
if stage.name == 'on':
self._group.on = True
elif stage.name == 'off':
self._group.on... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repeat(self, index, stage, stop):
""" Repeat a stage. :param index: Stage index. :param stage: Stage object to repeat. :param iterations: Number of iteratio... |
times = None
if 'iterations' in stage.kwargs:
times = stage.kwargs['iterations'] - 1
stages_back = 1
if 'stages' in stage.kwargs:
stages_back = stage.kwargs['stages']
i = 0
while i != times:
if stop.is_set():
break
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def brightness(self, brightness):
""" Set the brightness. :param brightness: Value to set (0.0-1.0). """ |
try:
cmd = self.command_set.brightness(brightness)
self.send(cmd)
self._brightness = brightness
except AttributeError:
self._setter('_brightness', brightness,
self._dimmest, self._brightest,
self._to_brigh... |
<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_brightness(self, brightness):
""" Step to a given brightness. :param brightness: Get to this brightness. """ |
self._to_value(self._brightness, brightness,
self.command_set.brightness_steps,
self._dimmer, self._brighter) |
<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_value(self, current, target, max_steps, step_down, step_up):
""" Step to a value :param current: Current value. :param target: Target value. :param max_s... |
for _ in range(steps(current, target, max_steps)):
if (current - target) > 0:
step_down()
else:
step_up() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dimmest(self):
""" Group brightness as dim as possible. """ |
for _ in range(steps(self.brightness, 0.0,
self.command_set.brightness_steps)):
self._dimmer() |
<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_repo(self, repo_name, items):
""" Build up repos `name` - Name of this repo. `items` - List of paths to rpm. """ |
juicer.utils.Log.log_debug("[CART:%s] Adding %s items to repo '%s'" % \
(self.cart_name, len(items), repo_name))
# We can't just straight-away add all of `items` to the
# repo. `items` may be composed of a mix of local files, local
# directories, 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 load(self, json_file):
""" Build a cart from a json file """ |
cart_file = os.path.join(CART_LOCATION, json_file)
try:
cart_body = juicer.utils.read_json_document(cart_file)
except IOError as e:
juicer.utils.Log.log_error('an error occured while accessing %s:' %
cart_file)
raise JuicerError(e.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 sign_items(self, sign_with):
""" Sign the items in the cart with a GPG key. After everything is collected and signed all the cart items are issued a refresh(... |
cart_items = self.items()
item_paths = [item.path for item in cart_items]
sign_with(item_paths)
for item in cart_items:
item.refresh() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_remotes(self, force=False):
""" Pull down all non-local items and save them into remotes_storage. """ |
connectors = juicer.utils.get_login_info()[0]
for repo, items in self.iterrepos():
repoid = "%s-%s" % (repo, self.current_env)
for rpm in items:
# don't bother syncing down if it's already in the pulp repo it needs to go to
if not rpm.path.startsw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def items(self):
""" Build and return a list of all items in this cart """ |
cart_items = []
for repo, items in self.iterrepos():
cart_items.extend(items)
return cart_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 arg(*args, **kwargs):
""" Decorator to add args to subcommands. """ |
def _arg(f):
if not hasattr(f, '_subcommand_args'):
f._subcommand_args = []
f._subcommand_args.append((args, kwargs))
return f
return _arg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def argset(name, *args, **kwargs):
""" Decorator to add sets of required mutually exclusive args to subcommands. """ |
def _arg(f):
if not hasattr(f, '_subcommand_argsets'):
f._subcommand_argsets = {}
f._subcommand_argsets.setdefault(name, []).append((args, kwargs))
return f
return _arg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resources(argv=sys.argv[1:]):
""" Juju CLI subcommand for dispatching resources subcommands. """ |
eps = iter_entry_points('jujuresources.subcommands')
ep_map = {ep.name: ep.load() for ep in eps}
parser = argparse.ArgumentParser()
if '--description' in argv:
print('Manage and mirror charm resources')
return 0
subparsers = {}
subparser_factory = parser.add_subparsers()
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 fetch(opts):
""" Create a local mirror of one or more resources. """ |
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name))
if opts.verbose:
backend.VERBOSE = True
_fetch(resources, opts.resource_names, opts.mirror_url, opts.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 verify(opts):
""" Verify that one or more resources were downloaded successfully. """ |
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
invalid = _invalid(resources, opts.resource_names)
if not invalid:
if not opts.quiet:
print("All resources successfully downloaded")
return 0
else:
if not opts.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 resource_path(opts):
""" Return the full path to a named resource. """ |
resources = _load(opts.resources, opts.output_dir)
if opts.resource_name not in resources:
sys.stderr.write('Invalid resource name: {}\n'.format(opts.resource_name))
return 1
print(resources[opts.resource_name].destination) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serve(opts):
""" Run a light-weight HTTP server hosting previously mirrored resources """ |
resources = _load(opts.resources, opts.output_dir)
opts.output_dir = resources.output_dir # allow resources.yaml to set default output_dir
if not os.path.exists(opts.output_dir):
sys.stderr.write("Resources dir '{}' not found. Did you fetch?\n".format(opts.output_dir))
return 1
backen... |
<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_temperature(self, temperature):
""" Step to a given temperature. :param temperature: Get to this temperature. """ |
self._to_value(self._temperature, temperature,
self.command_set.temperature_steps,
self._warmer, self._cooler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _warmest(self):
""" Group temperature as warm as possible. """ |
for _ in range(steps(self.temperature, 0.0,
self.command_set.temperature_steps)):
self._warmer() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _coolest(self):
""" Group temperature as cool as possible. """ |
for _ in range(steps(self.temperature, 1.0,
self.command_set.temperature_steps)):
self._cooler() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ip_to_array(ipaddress):
"""Convert a string representing an IPv4 address to 4 bytes.""" |
res = []
for i in ipaddress.split("."):
res.append(int(i))
assert len(res) == 4
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def int_to_array(i, length=2):
"""Convert an length byte integer to an array of bytes.""" |
res = []
for dummy in range(0, length):
res.append(i & 0xff)
i = i >> 8
return reversed(res) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop internal color pattern playing """ |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('p'), 0, 0, 0, 0, 0, 0, 0]
return self.write(buf); |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def savePattern(self):
"""Save internal RAM pattern to flash """ |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('W'), 0xBE, 0xEF, 0xCA, 0xFE, 0, 0, 0]
return self.write(buf); |
<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_repo(self, repo_name=None, feed=None, envs=[], checksum_type="sha256", query='/repositories/'):
""" `repo_name` - Name of repository to create `feed` ... |
data = {'display_name': repo_name,
'notes': {
'_repo-type': 'rpm-repo',
}
}
juicer.utils.Log.log_debug("Create Repo: %s", repo_name)
for env in envs:
if juicer.utils.repo_exists_p(repo_name, self.connectors[en... |
<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(self, login=None, password=None, user_name=None, envs=[], query='/users/'):
""" `login` - Login or username for user `password` - Plain text pass... |
login = login.lower()
data = {'login': login,
'password': password[0],
'name': user_name}
juicer.utils.Log.log_debug("Create User: %s ('%s')", login, user_name)
for env in envs:
if envs.index(env) != 0 and juicer.utils.env_same_host(env, en... |
<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_repo(self, repo_name=None, envs=[], query='/repositories/'):
""" `repo_name` - Name of repository to delete Delete repo in specified environments """ |
orphan_query = '/content/orphans/rpm/'
juicer.utils.Log.log_debug("Delete Repo: %s", repo_name)
for env in self.args.envs:
if not juicer.utils.repo_exists_p(repo_name, self.connectors[env], env):
juicer.utils.Log.log_info("repo `%s` doesn't exist in %s... skipping!"... |
<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_user(self, login=None, envs=[], query='/users/'):
""" `login` - Login or username of user to delete Delete user in specified environments """ |
juicer.utils.Log.log_debug("Delete User: %s", login)
for env in envs:
if envs.index(env) != 0 and juicer.utils.env_same_host(env, envs[envs.index(env) - 1]):
juicer.utils.Log.log_info("environment `%s` shares a host with environment `%s`... skipping!",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_repo(self, repo_name=None, envs=[], query='/repositories/'):
""" Sync repository in specified environments """ |
juicer.utils.Log.log_debug(
"Sync Repo %s In: %s" % (repo_name, ",".join(envs)))
data = {
'override_config': {
'verify_checksum': 'true',
'verify_size': 'true'
},
}
for env in envs:
url = "%s%s-%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 list_repos(self, envs=[], query='/repositories/'):
""" List repositories in specified environments """ |
juicer.utils.Log.log_debug(
"List Repos In: %s", ", ".join(envs))
repo_lists = {}
for env in envs:
repo_lists[env] = []
for env in envs:
_r = self.connectors[env].get(query)
if _r.status_code == Constants.PULP_GET_OK:
... |
<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_users(self, envs=[], query="/users/"):
""" List users in specified environments """ |
juicer.utils.Log.log_debug(
"List Users In: %s", ", ".join(envs))
for env in envs:
juicer.utils.Log.log_info("%s:" % (env))
_r = self.connectors[env].get(query)
if _r.status_code == Constants.PULP_GET_OK:
for user in juicer.utils.load_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def role_add(self, role=None, login=None, envs=[], query='/roles/'):
""" `login` - Login or username of user to add to `role` `role` - Role to add user to Add us... |
data = {'login': self.args.login}
juicer.utils.Log.log_debug(
"Add Role '%s' to '%s'", role, login)
for env in self.args.envs:
if not juicer.utils.role_exists_p(role, self.connectors[env]):
juicer.utils.Log.log_info("role `%s` doesn't exist in %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 show_user(self, login=None, envs=[], query='/users/'):
""" `login` - Login or username of user Show user in specified environments """ |
juicer.utils.Log.log_debug("Show User: %s", login)
# keep track of which iteration of environment we're in
count = 0
for env in self.args.envs:
count += 1
juicer.utils.Log.log_info("%s:", env)
if not juicer.utils.user_exists_p(login, self.connector... |
<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_roles(self, envs=[], query='/roles/'):
""" List roles in specified environments """ |
juicer.utils.Log.log_debug("List Roles %s", ", ".join(envs))
count = 0
for env in envs:
count += 1
rcount = 0
juicer.utils.Log.log_info("%s:", env)
_r = self.connectors[env].get(query)
if _r.status_code == Constants.PULP_GET_OK:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_user(self, login=None, user_name=None, password=None, envs=[], query='/users/'):
""" `login` - Login or username of user to update `user_name` - Updat... |
juicer.utils.Log.log_debug("Update user information %s" % login)
login = login.lower()
data = {'delta': {}}
if not user_name and not password:
raise JuicerError("Error: --name or --password must be present")
if user_name:
data['delta']['name'] = user_... |
<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(self):
"""Calculates what you need to do to make a pulp repo match a juicer repo def""" |
j_cs = self.j['checksum_type']
j_feed = self.j['feed']
p_cs = self.p['checksum_type']
p_feed = self.p['feed']
# checksum is a distributor property
# Is the pulp checksum wrong?
if not p_cs == j_cs:
juicer.utils.Log.log_debug("Pulp checksum_type does... |
<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_prefixes(self, conf):
"""Set the graphite key prefixes :param dict conf: The configuration data """ |
if conf.get('legacy_namespace', 'y') in self.TRUE_VALUES:
self.count_prefix = 'stats_counts'
self.count_suffix = ''
self.gauge_prefix = 'stats.gauges'
self.timer_prefix = 'stats.timers'
self.rate_prefix = 'stats'
self.rate_suffix = ''
... |
<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_batches(self, items):
"""given a list yield list at most self.max_batch_size in size""" |
for i in xrange(0, len(items), self.max_batch_size):
yield items[i:i + self.max_batch_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 report_stats(self, payload, is_retry=False):
""" Send data to graphite host :param payload: Data to send to graphite """ |
if self.debug:
if self.pickle_proto:
print "reporting pickled stats"
else:
print "reporting stats -> {\n%s}" % payload
try:
graphite = socket.socket()
with eventlet.Timeout(self.graphite_timeout, True):
grap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stats_flush(self):
""" Periodically flush stats to graphite """ |
while True:
try:
eventlet.sleep(self.flush_interval)
if self.debug:
print "seen %d stats so far." % self.stats_seen
print "current counters: %s" % self.counters
if self.pickle_proto:
payload ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pickle_payload(self):
"""obtain stats payload in batches of pickle format""" |
tstamp = int(time.time())
payload = []
for item in self.counters:
payload.append(("%s.%s%s" % (self.rate_prefix, item,
self.rate_suffix),
(tstamp,
self.counters[item] / self.flush_inte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plain_payload(self):
"""obtain stats payload in plaintext format""" |
tstamp = int(time.time())
payload = []
for item in self.counters:
payload.append('%s.%s%s %s %s\n' % (self.rate_prefix,
item,
self.rate_suffix,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_gauge(self, key, fields):
""" Process a received gauge event :param key: Key of timer :param fields: Received fields """ |
try:
self.gauges[key] = float(fields[0])
if self.stats_seen >= maxint:
self.logger.info("hit maxint, reset seen counter")
self.stats_seen = 0
self.stats_seen += 1
except Exception as err:
self.logger.info("error decoding ga... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_timer(self, key, fields):
""" Process a received timer event :param key: Key of timer :param fields: Received fields """ |
try:
if key not in self.timers:
self.timers[key] = []
self.timers[key].append(float(fields[0]))
if self.stats_seen >= maxint:
self.logger.info("hit maxint, reset seen counter")
self.stats_seen = 0
self.stats_seen +=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_counter(self, key, fields):
""" Process a received counter event :param key: Key of counter :param fields: Received fields """ |
sample_rate = 1.0
try:
if len(fields) is 3:
if self.ratecheck.match(fields[2]):
sample_rate = float(fields[2].lstrip("@"))
else:
raise Exception("bad sample rate.")
counter_value = float(fields[0] or 1) * (1... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_timer_key(self, key, tstamp, stack, pickled=False):
"""Append the plain text graphite :param str key: The timer key to process :param int tstamp: The... |
self.timers[key].sort()
values = {'count': len(self.timers[key]),
'low': min(self.timers[key]),
'high': max(self.timers[key]),
'total': sum(self.timers[key])}
values['mean'] = values['low']
nth_percentile = 'upper_%i' % self.pct_thre... |
<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_recvd(self, data):
""" Decode and process the data from a received event. :param data: Data to decode and process. """ |
bits = data.split(':')
if len(bits) == 2:
key = self.keycheck.sub('_', bits[0])
fields = bits[1].split("|")
field_count = len(fields)
if field_count >= 2:
processor = self.processors.get(fields[1])
if processor:
... |
<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_usage(self):
""" Build usage string from argparser args. """ |
parser = argparse.ArgumentParser()
parser.prog = 'juju-resources {}'.format(self.object_name)
for set_name, set_args in getattr(self.object, '_subcommand_argsets', {}).items():
for ap_args, ap_kwargs in set_args:
parser.add_argument(*ap_args, **ap_kwargs)
for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_group_address(addr):
"""Parse KNX group addresses and return the address as an integer. This allows to convert x/x/x and x/x address syntax to a numeri... |
if addr is None:
raise KNXException("No address given")
res = None
if re.match('[0-9]+$', addr):
res = int(addr)
match = re.match("([0-9]+)/([0-9]+)$", addr)
if match:
main = match.group(1)
sub = match.group(2)
res = int(main) * 2048 + int(sub)
match... |
<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, name, value):
"""Set the cached value for the given name""" |
old_val = self.values.get(name)
if old_val != value:
self.values[name] = value
return True
else:
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 sanitize(self):
"""Sanitize all fields of the KNX message.""" |
self.repeat = self.repeat % 2
self.priority = self.priority % 4
self.src_addr = self.src_addr % 0x10000
self.dst_addr = self.dst_addr % 0x10000
self.multicast = self.multicast % 2
self.routing = self.routing % 8
self.length = self.length % 16
for i in ran... |
<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_frame(self):
"""Convert the object to its frame format.""" |
self.sanitize()
res = []
res.append((1 << 7) + (1 << 4) + (self.repeat << 5) +
(self.priority << 2))
res.append(self.src_addr >> 8)
res.append(self.src_addr % 0x100)
res.append(self.dst_addr >> 8)
res.append(self.dst_addr % 0x100)
res.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_frame(cls, frame):
"""Create a KNXMessage object from the frame format.""" |
message = cls()
# Check checksum first
checksum = 0
for i in range(0, len(frame) - 1):
checksum += frame[i]
if (checksum % 0x100) != frame[len(frame) - 1]:
raise KNXException('Checksum error in frame {}, '
'expected {} but... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assemble_remotes(resource):
""" Using the specified input resource, assemble a list of rpm URLS. This function will, when given a remote package url, directo... |
resource_type = classify_resource_type(resource)
if resource_type is None:
juicer.utils.Log.log_debug("Could not classify or find the input resource.")
return []
elif resource_type == REMOTE_PKG_TYPE:
return [resource]
elif resource_type == REMOTE_INDEX_TYPE:
return par... |
<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_resource_type(resource):
""" Determine if the specified resource is remote or local. We can handle three remote resource types from the command line... |
if is_remote_package(resource):
juicer.utils.Log.log_debug("Classified %s as a remote package" % resource)
return REMOTE_PKG_TYPE
elif is_directory_index(resource):
juicer.utils.Log.log_debug("Classified %s as a directory index" % resource)
return REMOTE_INDEX_TYPE
elif exis... |
<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_remote_package(resource):
""" Classify the input resource as a remote RPM or not. """ |
remote_regexp = re.compile(r"^https?://(.+).rpm$", re.I)
result = remote_regexp.match(resource)
if result is not None:
juicer.utils.Log.log_debug("%s matches remote package regexp" % resource)
return True
else:
juicer.utils.Log.log_debug("%s doesn't match remote package regexp"... |
<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_index(resource):
""" Classify the input resource as a directory index or not. """ |
remote_regexp = re.compile(r"^https?://(.+)/?$", re.I)
result = remote_regexp.match(resource)
if result is not None:
juicer.utils.Log.log_debug("%s matches directory index regexp" % resource)
return True
else:
juicer.utils.Log.log_debug("%s doesn't match directory index regexp"... |
<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_input_file(resource):
""" Parse input file into remote packages and excluded data. In addition to garbage, excluded data includes directory indexes for... |
input_resource = open(resource, 'r').read()
remotes_list = [url for url in input_resource.split()]
juicer.utils.Log.log_debug("Input file parsed into: %s\n" % str(remotes_list))
remote_packages = [pkg for pkg in remotes_list if is_remote_package(pkg) is True]
juicer.utils.Log.log_debug("remote_pa... |
<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_directory_index(directory_index):
""" Retrieve a directory index and make a list of the RPMs listed. """ |
# Normalize our URL style
if not directory_index.endswith('/'):
directory_index = directory_index + '/'
site_index = urllib2.urlopen(directory_index)
parsed_site_index = bs(site_index)
rpm_link_tags = parsed_site_index.findAll('a', href=re.compile(r'.*rpm$'))
# Only save the HREF attr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kelvin_to_rgb(kelvin):
""" Convert a color temperature given in kelvin to an approximate RGB value. :param kelvin: Color temp in K :return: Tuple of (r, g, b... |
temp = kelvin / 100.0
# Calculate Red:
if temp <= 66:
red = 255
else:
red = 329.698727446 * ((temp - 60) ** -0.1332047592)
# Calculate Green:
if temp <= 66:
green = 99.4708025861 * math.log(temp) - 161.1195681661
else:
green = 288.1221695283 * ((temp - 60)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def white(self):
""" Set color to white. """ |
self._color = RGB_WHITE
cmd = self.command_set.white()
self.send(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def brightness(self, brightness):
""" Set the group brightness. :param brightness: Brightness in decimal percent (0.0-1.0). """ |
if brightness < 0 or brightness > 1:
raise ValueError("Brightness must be a percentage "
"represented as decimal 0-1.0")
self._brightness = brightness
cmd = self.command_set.brightness(brightness)
self.send(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hue(self, hue):
""" Set the group hue. :param hue: Hue in decimal percent (0.0-1.0). """ |
if hue < 0 or hue > 1:
raise ValueError("Hue must be a percentage "
"represented as decimal 0-1.0")
self._hue = hue
cmd = self.command_set.hue(hue)
self.send(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_updates(self):
""" Send updated to the KNX bus. """ |
d = datetime.now()
if self.timeaddr:
self.tunnel.group_write(self.timeaddr,
time_to_knx(d))
if self.dateaddr:
self.tunnel.group_write(self.dateaddr,
date_to_knx(d))
if self.datetimeaddr:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updater_loop(self):
""" Main loop that should run in the background. """ |
self.updater_running = True
while (self.updater_running):
self.send_updates()
sleep(self.updateinterval) |
<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_updater_in_background(self):
""" Starts a thread that runs the updater in the background. """ |
thread = threading.Thread(target=self.updater_loop())
thread.daemon = True
thread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parent_dir(path):
'''Return the parent of a directory.'''
return os.path.abspath(os.path.join(path, os.pardir, os.pardir, '_build')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, path):
""" Update the attributes of this CartItem. """ |
self._reset()
self.path = path
self._refresh_synced()
if self.is_synced:
self._refresh_path()
self._refresh_signed()
self._refresh_nvr() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_to(self, destination):
""" Sync an RPM from a REMOTE to a LOCAL path. Returns True if the item required a sync, False if it already existed locally. TOD... |
rpm = RPM(self.path)
rpm.sync(destination)
if rpm.modified:
juicer.utils.Log.log_debug("Source RPM modified. New 'path': %s" % rpm)
self.update(rpm.path)
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 _refresh_synced(self):
""" Update our is_synced attribute accordingly. """ |
if self.path.startswith('http'):
juicer.utils.Log.log_debug("%s is not synced" % self.path)
self.is_synced = False
else:
juicer.utils.Log.log_debug("%s is synced" % self.path)
self.is_synced = 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 _refresh_path(self):
""" Does it exist? Can we read it? Is it an RPM? """ |
# Unsynced items are remote so we can't check some of their
# properties yet
if os.path.exists(self.path):
try:
i = open(self.path, 'r')
i.close()
juicer.utils.Log.log_debug("Successfully read item at: %s" % self.path)
exce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _refresh_nvr(self):
""" Refresh our name-version-release attributes. """ |
rpm_info = juicer.utils.rpm_info(self.path)
self.name = rpm_info['name']
self.version = rpm_info['version']
self.release = rpm_info['release'] |
<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(self):
""" Used during update operations and when initialized. """ |
self.path = ''
self.version = ''
self.release = ''
self.is_signed = False
self.is_synced = False
self.rpm = 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 add_bridge(self, bridge):
""" Add bridge groups. :param bridge: Add groups from this bridge. """ |
for group in bridge.groups:
self._groups[group.name] = group |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.