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 __singleIntersect(self, e):
""" Get a list of GenomicRegions produced by subtracting e from self. :return: a list of regions that represent the result of subtracting e from self. The list might be empty if self is totally contained in e, or may contain two elements if e is totally contained in self. otherwise there'll be one element. """ |
if e.chrom != self.chrom or e.end < self.start or e.start > self.end:
# no intersection
return [copy.copy(self)]
if e.start <= self.start and e.end >= self.end:
# whole self is removed.
return []
if e.start > self.start and e.end < self.end:
# splits self in two
r1 = copy.copy(self)
r2 = copy.copy(self)
r1.end = e.start
r2.start = e.end
return [r1, r2]
if e.start <= self.start:
# cuts off start of self
r = copy.copy(self)
r.start = e.end
return [r]
if e.end >= self.end:
# cuts off end of self
r = copy.copy(self)
r.end = e.start
return [r]
# oops, we screwed up if we got to here..
raise GenomicIntervalError("fatal error - failed BED subtraction of " +
str(e) + " from " + str(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 subtract(self, es):
""" Subtract the BED elements in es from self. :param es: a list of BED elements (or anything with chrom, start, end) :return: a list of BED elements which represent what is left of self after the subtraction. This might be an empty list. """ |
workingSet = [self]
for e in es:
newWorkingSet = []
for w in workingSet:
newWorkingSet += w.__singleIntersect(e)
workingSet = newWorkingSet
return workingSet |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sizeOfOverlap(self, e):
""" Get the size of the overlap between self and e. :return: the number of bases that are shared in common between self and e. """ |
# no overlap
if not self.intersects(e):
return 0
# complete inclusion..
if e.start >= self.start and e.end <= self.end:
return len(e)
if self.start >= e.start and self.end <= e.end:
return len(self)
# partial overlap
if e.start > self.start:
return (self.end - e.start)
if self.start > e.start:
return (e.end - self.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 intersects(self, e):
""" Check whether e intersects self. :return: true if this elements intersects the element e """ |
if self.chrom != e.chrom:
return False
if e.start >= self.start and e.start < self.end:
return True
if e.end > self.start and e.end <= self.end:
return True
if e.start < self.start and e.end > self.end:
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 isPositiveStrand(self):
""" Check if this genomic region is on the positive strand. :return: True if this element is on the positive strand """ |
if self.strand is None and self.DEFAULT_STRAND == self.POSITIVE_STRAND:
return True
return self.strand == self.POSITIVE_STRAND |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isNegativeStrand(self):
""" Check if this genomic interval is on the negative strand. :return: True if this element is on the negative strand """ |
if self.strand is None and self.DEFAULT_STRAND == self.NEGATIVE_STRAND:
return True
return self.strand == self.NEGATIVE_STRAND |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_center(self, size):
""" Tranform self so it is centered on the same spot, but has new size. If the region grows, the extra nucleotides will be distributed evenly to the 5' and 3' side of the current region if possible. If the extra is odd, the 3' side will get the extra one. Similarly, if the resize shrinks the interval, bases will be removed from the 5' and 3' sides equally; if the number to remove is odd, the extra one will be removed from the 3' side. :param size: size of the region after transformation. """ |
if size < 1:
raise GenomicIntervalError("Cannot resize genomic interval to " +
str(size) + " bases; must be at least 1 " +
"base in length")
if size == len(self):
return
elif size > len(self):
extra = size - len(self)
extra_5_prime = extra / 2
extra_3_prime = extra / 2 if extra % 2 == 0 else (extra / 2) + 1
assert(extra_5_prime + extra_3_prime == extra)
self.start = (self.start - extra_5_prime if self.isPositiveStrand()
else self.start - extra_3_prime)
self.end = (self.end + extra_3_prime if self.isPositiveStrand()
else self.end + extra_5_prime)
else:
less = len(self) - size
less_5_prime = less / 2
less_3_prime = less / 2 if less % 2 == 0 else (less / 2) + 1
assert(less_5_prime + less_3_prime == less)
self.start = (self.start + less_5_prime if self.isPositiveStrand()
else self.start + less_3_prime)
self.end = (self.end - less_3_prime if self.isPositiveStrand()
else self.end - less_5_prime) |
<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_model(self, request, obj, form, change):
""" If the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``, send a notification email to the user being saved if their ``active`` status has changed to ``True``. If the ``ACCOUNTS_VERIFICATION_REQUIRED`` setting is ``True``, send a verification email instead. """ |
must_send_verification_mail_after_save = False
if change and settings.ACCOUNTS_APPROVAL_REQUIRED:
if obj.is_active and not User.objects.get(id=obj.id).is_active:
if settings.ACCOUNTS_VERIFICATION_REQUIRED:
# Accounts verification requires an inactive account
obj.is_active = False
# The token generated by send_verification_mail()
# must match the _saved_ User object,
# so postpone send_verification_mail() until later
must_send_verification_mail_after_save = True
else:
send_approved_mail(request, obj)
super(UserProfileAdmin, self).save_model(request, obj, form, change)
if must_send_verification_mail_after_save:
user = User.objects.get(id=obj.id)
send_verification_mail(request, user, "signup_verify") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy(self, machine):
"""Deploy service.""" |
log.debug("machine id: %s." % machine)
path = self.path + "/machines"
value, metadata = yield self.client.get(path)
machines = json.loads(value)
machines.append(machine)
yield self.client.set(path, json.dumps(machines)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self):
"""Add service definition to hierarchy.""" |
yield self.client.create(self.path)
yield self.client.create(self.path + "/type", self.name)
yield self.client.create(self.path + "/state")
yield self.client.create(self.path + "/machines", "[]")
log.debug("registered service '%s' at %s." % (self.name, self.path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _insert_cache(self, key, val, read):
'''
Does an insert into the cache such that the cache
will have an updated entry for the key,value,read
tuple. Any changes to those values will both update
the local cache and queue any required writes to the
database.
'''
if key != None and self.stringify_keys:
key = str(key)
cval = self._cache.get(key)
if cval == None:
self._cur_size += 1
if cval == None or val != cval:
self._cache[key] = val
# Force a write if it's a write or if it's
# unclear that the item was modified
if not self.read_only and (not self._immutable_vals or not read):
self._wqueue.add(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 _sync_writes(self):
'''
Flushes the write queue
'''
for key in self._wqueue:
val = self._cache[key]
self._database[key] = val
del self._wqueue
self._wqueue = set()
self._database.sync() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def drop_cache(self):
'''
Drops all changes in the cache.
'''
del self._cache
self._cache = {}
del self._wqueue
self._wqueue = set()
self._cur_size = 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 update(self, *args, **kwargs):
'''
Updates the set to include all arguments passed in. If the keyword
argument preprocess is passed, then each element is preprocessed
before being added.
'''
preprocess = kwargs.get('preprocess')
for s in args:
for e in s:
self._dict_set(preprocess(e) if preprocess else e, True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_episode_number(episode: Episode) -> int: """Get the episode number. The episode number is unique for an anime and episode type, but not across episode types for the same anime. """ |
match = _NUMBER_SUFFIX.search(episode.epno)
return int(match.group(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 get_episode_title(episode: Episode) -> int: """Get the episode title. Japanese title is prioritized. """ |
for title in episode.titles:
if title.lang == 'ja':
return title.title
else:
return episode.titles[0].title |
<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_element_text(element, match, default=None):
"""Find a matching subelement and return its text. If default is given, return it if a matching subelement is not found. Otherwise, ValueError is raised. """ |
child = element.find(match)
try:
return child.text
except AttributeError:
if default is not None:
return default
else:
raise MissingElementError(element, 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 _unpack_episode(element: ET.Element):
"""Unpack Episode from episode XML element.""" |
return Episode(
epno=element.find('epno').text,
type=int(element.find('epno').get('type')),
length=int(element.find('length').text),
titles=tuple(_unpack_episode_title(title)
for title in element.iterfind('title')),
) |
<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_episode_title(element: ET.Element):
"""Unpack EpisodeTitle from title XML element.""" |
return EpisodeTitle(title=element.text,
lang=element.get(f'{XML}lang')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self):
"""Validate the resource using its voluptuous schema""" |
try:
# update _resource to have default values from the schema
self._resource = self.schema(self._resource)
except MultipleInvalid as e:
errors = [format_error(err, self.resource_type) for err in e.errors]
raise exceptions.ValidationError({'errors': errors})
yield self.check_unique() |
<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(self):
""" Save the resource It's better to use the create, updated & delete methods intsead of modifying an instance and calling save, because then we call the can_create, can_update & can_delete methods to check whether a user is permitted to make the changes. """ |
yield self.validate()
db = self.db_client()
saved = yield db.save_doc(self._resource)
# Allow couch to create Document IDs
if '_id' not in self._resource:
self._resource['_id'] = saved['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 save_subresource(self, subresource):
""" Save the sub-resource NOTE: Currently assumes subresources are stored within a dictionary, keyed with the subresource's ID """ |
data = deepcopy(subresource._resource)
data.pop('id', None)
data.pop(self.resource_type + '_id', None)
subresources = getattr(self, subresource.parent_key, {})
subresources[subresource.id] = data
setattr(self, subresource.parent_key, subresources)
yield self._save() |
<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, user):
"""Delete a resource""" |
if user:
can_delete = yield self.can_delete(user)
else:
can_delete = False
if not can_delete:
raise exceptions.Unauthorized('User may not delete the resource')
doc = {
'_id': self.id,
'_deleted': True
}
try:
doc['_rev'] = self._rev
except AttributeError:
pass
db = self.db_client()
yield db.save_doc(doc)
self._resource = doc |
<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_subresource(self, subresource):
""" Delete the sub-resource NOTE: Currently assumes subresources are stored within a dictionary, keyed with the subresource's ID """ |
subresources = getattr(self, subresource.parent_key, {})
del subresources[subresource.id]
yield self._save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def state(self):
"""Get the Document's state""" |
state = self._resource.get('state', self.default_state)
if state in State:
return state
else:
return getattr(State, state) |
<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_parent(self):
""" Get the parent resource from the database The get, create & update methods will populate the parent for you. Use this method in the cases where parent has not been populated. """ |
if not self._parent:
self._parent = yield self.parent_resource.get(self.parent_id)
raise Return(self._parent) |
<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_resources(cls):
"""Get a list of parent resources, starting from the Document""" |
parent = cls.parent_resource
parents = [parent]
try:
while True:
parent = parent.parent_resource
parents.append(parent)
except AttributeError:
pass
parents.reverse()
return parents |
<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(cls, user, **kwargs):
"""If parent resource is not an editable state, should not be able to create.""" |
parent_id = kwargs.get(cls.parent_resource.resource_type + '_id')
try:
parent = yield cls.parent_resource.get(parent_id)
except couch.NotFound:
msg = 'Parent {} with id {} not found'.format(
cls.parent_resource.resource_type,
parent_id)
raise exceptions.ValidationError(msg)
if not parent.editable:
err = 'Cannot create child of {} resource'.format(parent.state.name)
raise exceptions.Unauthorized(err)
resource = yield super(SubResource, cls).create(user, **kwargs)
resource._parent = parent
raise Return(resource) |
<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, user, **kwargs):
"""If parent resource is not an editable state, should not be able to update""" |
yield self.get_parent()
if not self.parent.editable:
err = 'Cannot update child of {} resource'.format(self.parent.state.name)
raise exceptions.Unauthorized(err)
yield super(SubResource, self).update(user, **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 _save(self):
"""Save the sub-resource within the parent resource""" |
yield self.validate()
try:
self._parent = yield self.parent_resource.get(self.parent_id)
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resource_type,
self.parent_id)
raise exceptions.ValidationError(msg)
yield self._parent.save_subresource(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 delete(self, user):
"""Delete a sub-resource""" |
if user:
can_delete = yield self.can_delete(user)
else:
can_delete = False
if not can_delete:
raise exceptions.Unauthorized('User may not delete the resource')
try:
parent = yield self.get_parent()
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resource_type,
self.parent_id)
raise exceptions.ValidationError(msg)
yield parent.delete_subresource(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 state(self):
""" Get the SubResource state If the parents state has a higher priority, then it overrides the SubResource state ..note:: This assumes that self.parent is populated """ |
state = self._resource.get('state', self.default_state)
if state not in State:
state = getattr(State, state)
if not self.parent:
raise Exception('Unable to check the parent state')
parent_state = self.parent.state
return max([state, parent_state], key=attrgetter('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 schedule_tasks(self):
""" Get all the tasks for a release. :param release_id: int, release id number. :returns: deferred that when fired returns a list of Munch (dict-like) objects representing all tasks. """ |
url = 'api/v6/releases/%d/schedule-tasks' % self.id
tasks = yield self.connection._get(url)
defer.returnValue(munchify(tasks)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def task_date(self, task_re):
""" Get a datetime.date object for the last task that matches a regex. :param task_re: regex, eg re.compile('Development Freeze'). See txproductpages.milestones for some useful regex constants to pass in here. :returns: deferred that when fired returns a datetime.date object :raises: TaskNotFoundException if no tasks matched. """ |
tasks = yield self.schedule_tasks()
task_date = None
for task in tasks:
if task_re.match(task['name']):
(y, m, d) = task['date_finish'].split('-')
task_date = date(int(y), int(m), int(d))
if task_date:
defer.returnValue(task_date)
raise TaskNotFoundException() |
<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(self, event = None):
"""Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.""" |
for section in self.config.sections():
# Run through the sections to check all the option values:
for option, o in self.config.config[section].items():
# Check the actual values against the validators and complain if necessary:
if not o['include']:
continue # This value is hidden, so there's no control for it.
control = self._controls[section][option] # Get the actual control for GetValue
try:
value = type(o['value'])(control.GetValue()) # Try and convert the value
except ValueError as msg:
self.displayError(section, option, str(msg)) # Woops, something went wrong
return False # Tells self.onOk not to close the window
problem = None # Set up the problem variable.
try:
problem = o['validate'](value) # See if it passes the test
except Exception as e:
problem = str(e) # The lambda raised an exception.
if problem:
self.displayError(section, option, problem) # It didn't
return False # Tells self.onOk not to close the window
self.config.set(section, option, value) # All clear
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 _detect_notebook():
""" This isn't 100% correct but seems good enough Returns ------- bool True if it detects this is a notebook, otherwise False. """ |
try:
from IPython import get_ipython
from ipykernel import zmqshell
except ImportError:
return False
kernel = get_ipython()
return isinstance(kernel, zmqshell.ZMQInteractiveShell) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xlim(self, low, high):
"""Set xaxis limits Parameters low : number high : number Returns ------- Chart """ |
self.chart['xAxis'][0]['min'] = low
self.chart['xAxis'][0]['max'] = high
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 ylim(self, low, high):
"""Set yaxis limits Parameters low : number high : number index : int, optional Returns ------- Chart """ |
self.chart['yAxis'][0]['min'] = low
self.chart['yAxis'][0]['max'] = high
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 get_val(source, extract=None, transform=None):
"""Extract a value from a source, transform and return it.""" |
if extract is None:
raw_value = source
else:
raw_value = extract(source)
if transform is None:
return raw_value
else:
return transform(raw_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 get_obj(source, extract=None, child_transform=None, transform=None):
"""Maps an object based on a key->extractor child_transform dict.""" |
if extract is None:
obj = source
else:
obj = extract(source)
if child_transform is None:
data = obj
else:
data = dict()
for k, v in child_transform.items():
try:
data[k] = v(obj)
except Exception as ex:
raise Exception("An error occurred with child {0}".format(k)) from ex
if transform is None:
return data
else:
return transform(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_lst(source, extract=None, transform=None):
"""Extract a list from a source, transform each item, and return the result.""" |
if extract is None:
raw_list = source
else:
raw_list = extract(source)
if transform is None:
return raw_list
else:
tlist = []
for idx, item in enumerate(raw_list):
try:
tlist.append(transform(item))
except Exception as ex:
raise Exception("An error occurred with item #{0}".format(idx)) from ex
return tlist |
<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_composition(source, *fxns):
"""Compose several extractors together, on a source.""" |
val = source
for fxn in fxns:
val = fxn(val)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_flattened(dct, names, path_joiner="_"):
"""Flatten a child dicts, whose resulting keys are joined by path_joiner. E.G. { "valuation": { "currency": "USD", "amount": "100" } } -> { "valuation_currency": "USD", "valuation_amount": "100" } """ |
new_dct = dict()
for key, val in dct.items():
if key in names:
child = {path_joiner.join(k): v for k, v in flatten_dict(val, (key, ))}
new_dct.update(child)
else:
new_dct[key] = dct[key]
return new_dct |
<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_hoisted(dct, child_name):
"""Pulls all of a child's keys up to the parent, with the names unchanged.""" |
child = dct[child_name]
del dct[child_name]
dct.update(child)
return dct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def obj(extract=None, child_transform=None, transform=None):
"""Returns a partial of get_obj that only needs a source argument.""" |
return lambda source: get_obj(source, extract, child_transform, transform) |
<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_xml_attr(source, name, path=None):
"""Get the XML attribute with name from source. If path is not Mone, it will instead get the XML attribute with name from the child indicated by path. """ |
if path is None:
return source.attrib[name]
else:
return get_xml_attr(get_xml_child(source, path), 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 get_xml_text(source, path=None):
"""Get the text of the XML node. If path is not None, it will get the text of the descendant of source indicated by path. """ |
if path is None:
return source.text
else:
return get_xml_text(get_xml_child(source, path)) |
<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_xml_child(source, path):
"""Get the first descendant of source identified by path. Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict). """ |
if isinstance(path, (tuple, list)):
return source.find(*path)
else:
return source.find(path) |
<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_xml_children(source, path):
"""Get all the descendants of source identified by path. Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict). """ |
if isinstance(path, (tuple, list)):
return source.findall(*path)
else:
return source.findall(path) |
<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_json_val(source, path, *, ignore_bad_path=False):
"""Get the nested value identified by the json path, rooted at source.""" |
try:
return JP.find(source, path)
except JP.JSONPathError as ex:
if ignore_bad_path:
return None
else:
raise |
<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_val(path, *, ignore_bad_path=False):
"""Returns a partial of get_json_val that only needs a source argument.""" |
return lambda source: get_json_val(source, path, ignore_bad_path=ignore_bad_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_defs(self, def_list, **kwargs):
""" Registers a list of Rml defintions objects Args: ----- def_list: list of objects defining the rml definitons """ |
for item in def_list:
if isinstance(item, tuple):
self.register_rml_def(*item, **kwargs)
elif isinstance(item, dict):
cp_kwargs = kwargs.copy()
item.update(kwargs)
self.register_rml_def(**item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_rml_def(self, location_type, location, filename=None, **kwargs):
""" Registers the rml file locations for easy access Args: ----- location_type: ['package_all', 'package_file', 'directory', 'filepath'] location: The correlated location string based on the location_type filename: Optional, associated with 'package_file' location_type kwargs: ------- include_subfolders: Boolean """ |
if location_type == 'directory':
self.register_directory(location, **kwargs)
elif location_type == 'filepath':
if not os.path.exists(location):
raise OSError("File not found", location)
if os.path.isfile(location):
self.register_rml(location)
elif filename:
new_loc = os.path.join(location, filename)
if not os.path.exists(new_loc):
raise OSError("File not found", new_loc)
elif os.path.isfile(new_loc):
self.register_rml(new_loc)
else:
raise OSError("File not found", location)
elif location_type.startswith('package'):
pkg_path = \
importlib.util.find_spec(\
location).submodule_search_locations[0]
if location_type.endswith('_all'):
self.register_directory(pkg_path, **kwargs)
elif location_type.endswith('_file'):
filepath = os.path.join(pkg_path, filename)
self.register_rml(filepath, **kwargs)
else:
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_rml(self, filepath, **kwargs):
""" Registers the filepath for an rml mapping Args: ----- filepath: the path the rml file """ |
name = os.path.split(filepath)[-1]
if name in self.rml_maps and self.rml_maps[name] != filepath:
raise Exception("RML name already registered. Filenames must be "
"unique.",
(self.rml_maps[name], filepath))
self.rml_maps[name] = filepath |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_directory(self, dirpath, **kwargs):
""" Registers all of the files in the the directory path """ |
kwargs['file_extensions'] = kwargs.get("file_extensions",
self.rdf_formats)
files = list_files(file_directory=dirpath, **kwargs)
for fileinfo in files:
self.register_rml(fileinfo[-1], **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 make_processor(self, name, mappings, processor_type, **kwargs):
""" Instantiates a RmlProcessor and registers it in the manager Args: ----- name: the name to register the processor mappings: the list RML mapping definitions to use processor_type: the name of the RML processor to use """ |
from .processor import Processor
if self.processors.get(name):
raise LookupError("processor has already been created")
if isinstance(mappings, list):
mappings = [self.get_rml(item) for item in mappings]
else:
mappings = [self.get_rml(mappings)]
self.processors[name] = Processor[processor_type](mappings, **kwargs)
self.processors[name].name = name
return self.processors[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 get_processor(self, name, mappings=None, processor_type=None, **kwargs):
""" Returns the specified RML Processor """ |
try:
return self.processors[name]
except KeyError:
return self.make_processor(name,
mappings,
processor_type,
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_rml(self, rml_name, rtn_format="filepath"):
""" returns the rml mapping filepath rml_name(str):
Name of the rml mapping to retrieve rtn_format: ['filepath', 'data'] """ |
try:
rml_path = self.rml_maps[rml_name]
except KeyError:
if rml_name in self.rml_maps.values() or os.path.exists(rml_name):
rml_path = rml_name
else:
raise LookupError("rml_name '%s' is not registered" % rml_name)
if rtn_format == "data":
with open(rml_path, "rb") as fo:
return fo.read()
return rml_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def filename(self, index):
'''
Get the absolute filename corresponding to a key; run the
key_transformer on the key and do a few other small things.
:raises TypeError: if the key_transformer returns something other than
a :py:class:`tuple` of :py:class:`strings <str>`
:raises KeyError: if the key_transformer returns an empty path
:returns: the filename
:rtype: str
'''
subpath = self.key_transformer.to_path(index)
if not isinstance(subpath, tuple):
msg = 'subpath is a %s, but it should be a tuple.'
raise TypeError(msg % type(subpath).__name__)
elif len(subpath) == 0:
raise KeyError('You specified an empty key.')
elif not all(isinstance(x, str) for x in subpath):
msg = 'Elements of subpath should all be str; here is subpath:\n%s' % repr(subpath)
raise TypeError(msg)
return os.path.join(self.base_directory, *safe_path(subpath)) + self.extension |
<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_filename(self, filename):
'''
Convert an absolute filename into key.
'''
i = len(self.base_directory)
if filename[:i] != self.base_directory:
raise ValueError('Filename needs to start with "%s";\nyou passed "%s".' % (self.base_directory, filename))
if filename.endswith(self.extension):
if len(self.extension) > 0:
j = -len(self.extension)
else:
j = None
return self.key_transformer.from_path(tuple(filename[i:j].strip('/').split('/'))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(self, spin, data):
""" The function which uses irc rfc regex to extract the basic arguments from the msg. """ |
data = data.decode(self.encoding)
field = re.match(RFC_REG, data)
if not field:
return
prefix = self.extract_prefix(field.group('prefix'))
command = field.group('command').upper()
args = self.extract_args(field.group('arguments'))
spawn(spin, command, *(prefix + args)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_prefix(self, prefix):
""" It extracts an irc msg prefix chunk """ |
field = re.match(PREFIX_REG, prefix if prefix else '')
return (prefix,) if not field else field.group(1, 2, 3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_args(self, data):
""" It extracts irc msg arguments. """ |
args = []
data = data.strip(' ')
if ':' in data:
lhs, rhs = data.split(':', 1)
if lhs: args.extend(lhs.rstrip(' ').split(' '))
args.append(rhs)
else:
args.extend(data.split(' '))
return tuple(args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_ctcp(self, spin, nick, user, host, target, msg):
""" it is used to extract ctcp requests into pieces. """ |
# The ctcp delimiter token.
DELIM = '\001'
if not msg.startswith(DELIM) or not msg.endswith(DELIM):
return
ctcp_args = msg.strip(DELIM).split(' ')
spawn(spin, ctcp_args[0], (nick, user, host, target, msg), *ctcp_args[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 patch(self, spin, header, *args):
""" It spawns DCC TYPE as event. """ |
spawn(spin, 'DCC %s' % args[0], header, *args[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 print_commands(self, out=sys.stdout):
'''
utility method to print commands
and descriptions for @BotFather
'''
cmds = self.list_commands()
for ck in cmds:
if ck.printable:
out.write('%s\n' % ck) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, uri, **kw):
""" The money maker. """ |
expect = kw.pop("expect", [])
mime_body = kw.pop("mime_body", None)
headers = kw.pop("headers", {})
data = kw.pop("data", None)
if mime_body:
mimevalues = self.mimeobjects.get(mime_body.__class__)
if not mimevalues:
raise ClientException(
("Cannot handle object of type "
"{0!r}").format(mime_body.__class__))
mapping = mimevalues[0]
document_type, mimetype, validator = mapping
data = document_type.render(validator, mime_body)
headers["Content-Type"] = mimetype
if uri[0] != '/':
uri = '/' + uri
url = "{self.scheme}://{self.host}{uri}".format(self=self, uri=uri)
response = self.session.request(
method, url,
headers=headers,
data=data,
**kw)
content_type = response.headers.get("Content-Type")
if content_type is None or not response.content:
return response, None
mimetype, opts = werkzeug.http.parse_options_header(content_type)
if mimetype not in self.mimetypes:
raise ClientException(
"Cannot handle response type: {0}".format(mimetype))
document_type, document_class, validator = self.mimetypes.get(mimetype)
if expect and document_class not in expect:
raise ClientException(
"Unexpected response type: {0}".format(mimetype))
try:
obj = document_type.parse(validator,
document_class,
response.content)
except MimeValidationError as e:
raise ClientException(
"Response format invalid: {0}".format(str(e)))
except:
log.error(
"Failed to parse content of type: {0}".format(mimetype),
exc_info=sys.exc_info())
raise ClientException(
"Failed to parse content of type: {0}".format(mimetype))
return response, 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 update_user(self, username, profile, owner_privkey):
""" Update profile_hash on blockchain """ |
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'profile': profile,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_tx = resp['unsigned_tx']
except:
return resp
dht_resp = write_dht_profile(profile)
dht_resp = dht_resp[0]
if not dht_resp['status'] == 'success':
return {"error": "DHT write failed"}
# sign all unsigned inputs
signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)
return self.broadcast_transaction(signed_tx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer_user(self, username, transfer_address, owner_privkey):
""" Transfer name on blockchain """ |
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'transfer_address': transfer_address,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_tx = resp['unsigned_tx']
except:
return resp
# sign all unsigned inputs
signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)
return self.broadcast_transaction(signed_tx) |
<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(controller_id, name):
"""Turn class into a kervi controller""" |
def _decorator(cls):
class _ControllerClass(cls, Controller):
def __init__(self):
Controller.__init__(self, controller_id, name)
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinstance(prop, KerviValue):
if prop.is_input:
self.inputs._add_internal(key, prop)
else:
self.outputs._add_internal(key, prop)
cls.__init__(self)
return _ControllerClass
return _decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def input(input_id, name, value_class=NumberValue):
"""Add input to controller""" |
def _init():
return value_class(
name,
input_id=input_id,
is_input=True,
index=-1
)
def _decorator(cls):
setattr(cls, input_id, _init())
return cls
return _decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(output_id, name, value_class=NumberValue):
"""Add output to controller""" |
def _init():
return value_class(
name,
input_id=output_id,
is_input=False,
index=-1
)
def _decorator(cls):
setattr(cls, output_id, _init())
return cls
return _decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _subset(subset, superset):
"""True if subset is a subset of superset. :param dict subset: subset to compare. :param dict superset: superset to compare. :return: True iif all pairs (key, value) of subset are in superset. :rtype: bool """ |
result = True
for k in subset:
result = k in superset and subset[k] == superset[k]
if not result:
break
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def button_with_image(size='medium', icon=None, text=None, title=None, button=False, name=None, target=False, disabled=False, extra_css=None, modal=None, data_target='#modal', viewname=None, next=None, extra_href=False, href=False, fancyajax=False, viewargs=[], **kwargs):
""" Output a button using Bingo's button html. @param size: The size that refers to the icon css class. @param icon: A css class that refers to an icon - for example 'send_mail' @param text: Text to display on the button @param title: Title parameter for the button or if button=False the data-tip for an a tag. @param button: If true a button tag will be returned. @param name: A name for the button @param target: A target for the a tag @param disabled: If true, css class 'disabled' will be added to the container div. @param extra_css: A string of extra css classes. @param model: If True the class 'model' is placed on the a tag. @param viewname: The django viewname as defined in a urls.py file. @param **kwargs: Remaining keyword args are supplied to django.core.urlresolvers.reverse @param next: If specified ?next=[NEXT] will be appended to any generated link. @return string """ |
html = '<div class="button-std'
if disabled:
html += ' disabled'
html += '">'
if button:
html += '<button type="submit" name="%s" value="%s" class="%s">' % (name, title, icon)
if icon:
html += '<span class="icon-%s icon-%s-%s"></span>' % (size, size, icon)
html += '<span>%s</span></button>' % (title)
else:
html += '<a class="%s' % (icon)
if fancyajax:
html += ' fancybox fancybox.ajax'
if extra_css:
html += ' %s' % (extra_css)
html += '"'
if modal:
html += ' role="button" data-toggle="modal" data-remoteinbody="false"'
if data_target:
html += ' data-target="#modal"'
if fancyajax:
html += ' data-spinner-append="1"'
if viewname:
html += ' href="%s' % (reverse(viewname, args=viewargs, kwargs=kwargs))
elif href:
html += ' href="%s' % (href)
if viewname or href:
if next:
if next.startswith('/'):
html += '?next=%s' % next
else:
html += '?next=%s' % reverse(next)
if extra_href:
html += extra_href
html += '"'
if not title and text:
title = text
if title:
html += ' data-tip="%s"' % (title)
if target:
html += ' target="%s"' % (target)
html += '>'
if icon:
html += '<span class="icon-%s icon-%s-%s"></span>' % (size, size, icon)
if text:
html += '<span class="title">%s</span>' % (text)
html += '</a></div>'
return html |
<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():
""" Initialize the arguments parser. """ |
parser = argparse.ArgumentParser(
description="Automated development environment initialization")
parser.add_argument('--version', action='version',
version='%(prog)s ' + __version__)
subparsers = parser.add_subparsers(title="commands")
# List command
parser_list = subparsers.add_parser("list",
help="list all the available environment types")
# New command
parser_new = subparsers.add_parser("new",
help="define a new environment type")
parser_new.add_argument("environment", help="name for the environment")
# Remove command
parser_remove = subparsers.add_parser("remove",
help="remove an environment type from the configuration file")
parser_remove.add_argument("environment", help="name of the environment")
# Show command
parser_show = subparsers.add_parser("show",
help="show the commands performed for a specific environment")
parser_show.add_argument("environment", help="name of the environment")
# Start command
parser_start = subparsers.add_parser("start",
help="start a new environment")
parser_start.add_argument("environment", help="name of the environment")
parser_start.add_argument("path", nargs="?",
help="path in which to initialize the environment")
return parser |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_env(environment):
""" Create a new environment in the configuration and ask the user for the commands for this specific environment. """ |
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if environment in parser.sections():
print("Environment '%s' already exists" % environment)
return
print("Please introduce (in order) the commands for '%s'\n" % environment)
print("Press RETURN to end command and RETURN with empty line to finish\n")
commands = []
cmd = ""
while True:
try:
cmd = raw_input("> ")
if not cmd:
break
commands.append(cmd)
except KeyboardInterrupt:
return
parser.add_section(environment)
parser.set(environment, "cmd", "\n".join(commands))
write_config(parser)
print("Added environment '%s'" % environment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_env(environment):
""" Remove an environment from the configuration. """ |
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if not parser.remove_section(environment):
print("Unknown environment type '%s'" % environment)
return
write_config(parser)
print("Removed environment '%s'" % environment) |
<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_env(environment):
""" Show the commands for a given environment. """ |
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
try:
commands = parser.get(environment, "cmd").split("\n")
except KeyError:
print("Unknown environment type '%s'" % environment)
return
print("Environment: %s\n" % environment)
for cmd in commands:
print(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 start_env(environment, path):
""" Initialize a new environment in specified directory. If path does not exist, will try to create the directory structure recursively. If the path is not provided, will use current working directory. """ |
parser = read_config()
if environment not in parser.sections():
print("Unknown environment type '%s'" % environment)
return
if path and not os.path.isdir(path):
try:
os.makedirs(path)
except os.error:
print("Could not create directory structure")
return
init_path = path if path else os.getcwd()
commands = parser.get(environment, "cmd").split("\n")
print("Working in directory: " + init_path)
for cmd in commands:
proc = subprocess.Popen(cmd , cwd=init_path, shell=True)
proc.wait()
print("Initialized '%s' environment" % environment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_config():
""" Read the configuration file and parse the different environments. Returns: ConfigParser object """ |
if not os.path.isfile(CONFIG):
with open(CONFIG, "w"):
pass
parser = ConfigParser()
parser.read(CONFIG)
return parser |
<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_action(action, parsed):
""" Parse the action to execute. """ |
if action == "list":
list_env()
elif action == "new":
new_env(parsed.environment)
elif action == "remove":
remove_env(parsed.environment)
elif action == "show":
show_env(parsed.environment)
elif action == "start":
start_env(parsed.environment, parsed.path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_pdf(rst_content, style_text, header=None, footer=FOOTER):
""" Create PDF file from `rst_content` using `style_text` as style. Optinally, add `header` or `footer`. Args: rst_content (str):
Content of the PDF file in restructured text markup. style_text (str):
Style for the :mod:`rst2pdf` module. header (str, default None):
Header which will be rendered to each page. footer (str, default FOOTER):
Footer, which will be rendered to each page. See :attr:`FOOTER` for details. Returns: obj: StringIO file instance containing PDF file. """ |
out_file_obj = StringIO()
with NamedTemporaryFile() as f:
f.write(style_text)
f.flush()
pdf = _init_pdf(f.name, header, footer)
# create PDF
pdf.createPdf(text=rst_content, output=out_file_obj, compressed=True)
# rewind file pointer to begin
out_file_obj.seek(0)
return out_file_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def define_parameters(**parameters):
"""Get a list of parameters to pass to AWS boto call.""" |
params = []
for key, value in parameters.items():
param = dict(ParameterKey=key, ParameterValue=value)
params.append(param)
return params |
<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(self):
"""Deploy a cluster on Amazon's EKS Service configured for Jupyterhub Deployments. """ |
steps = [
(self.create_role, (), {}),
(self.create_vpc, (), {}),
(self.create_cluster, (), {}),
(self.create_node_group, (), {}),
(self.create_spot_nodes, (), {}),
(self.create_utilities, (), {}),
]
# Execute creation.
for step in tqdm.tqdm(steps, ncols=70):
method, args, kwargs = step
method(*args, **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 delete(self):
"""Delete a running cluster.""" |
stacks = [
self.utilities_name,
self.spot_nodes_name,
self.node_group_name,
self.cluster_name,
self.vpc_name,
self.role_name
]
# Execute creation.
for stack in tqdm.tqdm(stacks, ncols=70):
self.delete_stack(stack) |
<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_template(self, template_name, **parameters):
"""Pull templates from the AWS templates folder""" |
template_path = pathlib.Path(self.template_dir).joinpath(template_name)
return get_template(template_path, **parameters) |
<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_stack(self, stack_name):
"""Teardown a stack.""" |
get_stack(stack_name)
CLIENT.delete_stack(
StackName=stack_name
)
DELETE_WAITER.wait(StackName=stack_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 create_stack( self, stack_name, stack_template_name, parameters=None, capabilities=None ):
"""Create a stack using Amazon's Cloud formation""" |
# Build template_path
stack_template_path = pathlib.Path(
self.template_dir).joinpath(stack_template_name)
# Create stack
create_stack(
stack_name,
stack_template_path,
parameters=parameters,
capabilities=capabilities
) |
<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_vpc(self):
"""Create a virtual private cloud on Amazon's Web services configured for deploying JupyterHubs. """ |
self.create_stack(
self.vpc_name,
'amazon-eks-vpc.yaml',
parameters=define_parameters(
VpcBlock="10.42.0.0/16",
Subnet01Block="10.42.1.0/24",
Subnet02Block="10.42.2.0/24",
Subnet03Block="10.42.3.0/24"
)
) |
<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_cluster(self):
"""Creates a cluster on Amazon EKS . """ |
self.create_stack(
self.cluster_name,
'amazon-eks-cluster.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
ControlPlaneSecurityGroup=self.security_groups,
Subnets=self.subnet_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 create_node_group(self):
"""Create on-demand node group on Amazon EKS. """ |
self.create_stack(
self.node_group_name,
'amazon-eks-nodegroup.yaml',
capabilities=['CAPABILITY_IAM'],
parameters=define_parameters(
ClusterName=self.cluster_name,
ClusterControlPlaneSecurityGroup=self.security_groups,
Subnets=self.subnet_ids,
VpcId=self.vpc_ids,
KeyName=self.ssh_key_name,
NodeAutoScalingGroupMaxSize="1",
NodeVolumeSize="100",
NodeImageId="ami-0a54c984b9f908c81",
NodeGroupName=f"{self.name} OnDemand Nodes"
)
) |
<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_spot_nodes(self):
"""Create spot nodes. """ |
self.create_stack(
self.spot_nodes_name,
'amazon-spot-nodes.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
Subnets=self.subnet_ids,
NodeInstanceProfile=self.node_instance_profile,
NodeInstanceRole=self.node_instance_role,
NodeSecurityGroup=self.node_security_group,
)
) |
<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_utilities(self):
"""Create utitilies stack. """ |
self.create_stack(
self.utilities_name,
'amazon-utilities.yaml',
parameters=define_parameters(
Subnets=self.subnet_ids,
NodeSecurityGroup=self.node_security_group
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debugtoolbar_middleware_factory(app, handler):
"""Setup Debug middleware.""" |
dbtb = app.ps.debugtoolbar
@asyncio.coroutine
def debugtoolbar_middleware(request):
"""Integrate to application."""
# Check for debugtoolbar is enabled for the request
if not dbtb.cfg.enabled or any(map(request.path.startswith, dbtb.cfg.exclude)):
return (yield from handler(request))
remote_host, remote_port = request.transport.get_extra_info('peername')
for host in dbtb.cfg.hosts:
if ip.ip_address(remote_host) in ip.ip_network(host):
break
else:
return (yield from handler(request))
# Initialize a debugstate for the request
state = DebugState(app, request)
dbtb.history[state.id] = state
context_switcher = state.wrap_handler(handler)
# Make response
try:
response = yield from context_switcher(handler(request))
state.status = response.status
except HTTPException as exc:
response = exc
state.status = response.status
except Exception as exc:
# Store traceback for unhandled exception
state.status = 500
if not dbtb.cfg.intercept_exc:
raise
tb = get_traceback(
info=sys.exc_info(), skip=1, show_hidden_frames=False,
ignore_system_exceptions=True, exc=exc)
dbtb.exceptions[tb.id] = request['pdbt_tb'] = tb
for frame in tb.frames:
dbtb.frames[id(frame)] = frame
response = Response(text=tb.render_full(request), content_type='text/html')
# Intercept http redirect codes and display an html page with a link to the target.
if dbtb.cfg.intercept_redirects and response.status in REDIRECT_CODES \
and 'Location' in response.headers:
response = yield from app.ps.jinja2.render(
'debugtoolbar/redirect.html', response=response)
response = Response(text=response, content_type='text/html')
yield from state.process_response(response)
if isinstance(response, Response) and response.content_type == 'text/html' and \
RE_BODY.search(response.body):
return (yield from dbtb.inject(state, response))
return response
return debugtoolbar_middleware |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self, app):
"""Setup the plugin and prepare application.""" |
super(Plugin, self).setup(app)
if 'jinja2' not in app.plugins:
raise PluginException('The plugin requires Muffin-Jinja2 plugin installed.')
self.cfg.prefix = self.cfg.prefix.rstrip('/') + '/'
self.cfg.exclude.append(self.cfg.prefix)
# Setup debugtoolbar templates
app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates'))
self.cfg.panels += list(self.cfg.additional_panels)
panels_ = []
for panel in self.cfg.panels:
if isinstance(panel, str):
mod, _, panel = panel.partition(':')
mod = importlib.import_module(mod)
panel = eval(panel or 'DebugPanel', mod.__dict__)
panels_.append(panel)
self.cfg.panels = panels_
# Setup debugtoolbar static files
app.router.register_route(StaticRoute(
'debugtoolbar.static',
self.cfg.prefix + 'static/',
op.join(PLUGIN_ROOT, 'static')))
app.register(self.cfg.prefix + 'sse', name='debugtoolbar.sse')(self.sse)
app.register(
self.cfg.prefix + 'exception', name='debugtoolbar.exception')(self.exception)
app.register(
self.cfg.prefix + 'execute', name='debugtoolbar.execute')(self.execute)
app.register(
self.cfg.prefix + 'source', name='debugtoolbar.source')(self.source)
app.register(
self.cfg.prefix.rstrip('/'),
self.cfg.prefix,
self.cfg.prefix + '{request_id}', name='debugtoolbar.request')(self.view)
app['debugtoolbar'] = {}
app['debugtoolbar']['pdbt_token'] = uuid.uuid4().hex
self.history = app['debugtoolbar']['history'] = utils.History(50)
self.exceptions = app['debugtoolbar']['exceptions'] = utils.History(50)
self.frames = app['debugtoolbar']['frames'] = utils.History(100) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject(self, state, response):
""" Inject Debug Toolbar code to response body. """ |
html = yield from self.app.ps.jinja2.render(
'debugtoolbar/inject.html',
static_path=self.cfg.prefix + 'static',
toolbar_url=self.cfg.prefix + state.id,
)
html = html.encode(state.request.charset or 'utf-8')
response.body = RE_BODY.sub(html + b'</body>', response.body)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view(self, request):
""" Debug Toolbar. """ |
auth = yield from self.authorize(request)
if not auth:
raise HTTPForbidden()
request_id = request.match_info.get('request_id')
state = self.history.get(request_id, None)
response = yield from self.app.ps.jinja2.render(
'debugtoolbar/toolbar.html',
debugtoolbar=self,
state=state,
static_path=self.cfg.prefix + 'static',
panels=state and state.panels or [],
global_panels=self.global_panels,
request=state and state.request or None,
)
return Response(text=response, content_type='text/html') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_dict(self, info_dict):
"""Replaces empty content with 'NA's""" |
for key, value in info_dict.items():
if not value:
info_dict[key] = "NA"
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_addresses(email_string_list):
""" Converts a string containing comma separated email addresses into a list of email addresses. """ |
return [f for f in [s.strip() for s in email_string_list.split(",")] if 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 subject_template(template, context):
""" Loads and renders an email subject template, returning the subject string. """ |
subject = loader.get_template(template).render(Context(context))
return " ".join(subject.splitlines()).strip() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.