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 getSet(self, setID):
'''
Gets the information of one specific build using its Brickset set ID.
:param str setID: The ID of the build from Brickset.
:returns: A single Build object.
:rtype: :class:`brickfront.build.Build`
:raises brickfront.errors.InvalidSetID: If no ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getRecentlyUpdatedSets(self, minutesAgo):
'''
Gets the information of recently updated sets.
:param int minutesAgo: The amount of time ago that the set was updated.
:returns: A list of Build instances that were updated within the given time.
:rtype: list
.. warning::... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAdditionalImages(self, setID):
'''
Gets a list of URLs containing images of the set.
:param str setID: The ID of the set you want to grab the images for.
:returns: A list of URL strings.
:rtype: list
.. warning:: An empty list will be returned if there are no addi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getReviews(self, setID):
'''
Get the reviews for a set.
:param str setID: The ID of the set you want to get the reviews of.
:returns: A list of reviews.
:rtype: List[:class:`brickfront.review.Review`]
.. warning:: An empty list will be returned if there are no review... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def results(cls, function, group=None):
""" Returns a numpy nparray representing the benchmark results of a function in a group. """ |
return numpy.array(cls._results[group][function]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mixin_class(target, cls):
"""Mix cls content in target.""" |
for name, field in getmembers(cls):
Mixin.mixin(target, field, 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 mixin_function_or_method(target, routine, name=None, isbound=False):
"""Mixin a routine into the target. :param routine: routine to mix in target. :param str... |
function = None
if isfunction(routine):
function = routine
elif ismethod(routine):
function = get_method_function(routine)
else:
raise Mixin.MixInError(
"{0} must be a function or a method.".format(routine))
if name is Non... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mixin(target, resource, name=None):
"""Do the correct mixin depending on the type of input resource. - Method or Function: mixin_function_or_method. - class:... |
result = None
if ismethod(resource) or isfunction(resource):
result = Mixin.mixin_function_or_method(target, resource, name)
elif isclass(resource):
result = list()
for name, content in getmembers(resource):
if isclass(content):
... |
<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_mixins(target):
"""Tries to get back target in a no mixin consistent state. """ |
mixedins_by_name = Mixin.get_mixedins_by_name(target).copy()
for _name in mixedins_by_name: # for all named mixins
while True: # remove all mixins named _name
try:
Mixin.remove_mixin(target, _name)
except Mixin.MixInError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error403(error):
""" Custom 403 page. """ |
tb = error.traceback
if isinstance(tb, dict) and "name" in tb and "uuid" in tb:
return SimpleTemplate(PRIVATE_ACCESS_MSG).render(
name=error.traceback["name"],
uuid=error.traceback["uuid"]
)
return "Access denied!" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_trees(trees, path_composer):
""" Render list of `trees` to HTML. Args: trees (list):
List of :class:`.Tree`. path_composer (fn reference):
Function ... |
trees = list(trees) # by default, this is set
def create_pub_cache(trees):
"""
Create uuid -> DBPublication cache from all uuid's linked from `trees`.
Args:
trees (list): List of :class:`.Tree`.
Returns:
dict: {uuid: DBPublication}
"""
... |
<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_publications():
""" Return list of all publications in basic graphic HTML render. """ |
publications = search_publications(
DBPublication(is_public=True)
)
return SimpleTemplate(INDEX_TEMPLATE).render(
publications=publications,
compose_path=web_tools.compose_path,
delimiter=":",
) |
<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_theme(theme=None, for_code=None):
""" set md and code theme """ |
try:
if theme == 'default':
return
theme = theme or os.environ.get('AXC_THEME', 'random')
# all the themes from here:
themes = read_themes()
if theme == 'random':
rand = randint(0, len(themes)-1)
theme = themes.keys()[rand]
t = the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def style_ansi(raw_code, lang=None):
""" actual code hilite """ |
lexer = 0
if lang:
try:
lexer = get_lexer_by_name(lang)
except ValueError:
print col(R, 'Lexer for %s not found' % lang)
lexer = None
if not lexer:
try:
if guess_lexer:
lexer = pyg_guess_lexer(raw_code)
except:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrap(el, t, ind, pref):
""" Reasonably smart rewrapping checking punctuations """ |
global term_columns
cols = term_columns - len(ind + pref)
if el.tag == 'code' or len(t) <= cols:
return t
# wrapping:
# we want to keep existing linebreaks after punctuation
# marks. the others we rewrap:
puncs = ',', '.', '?', '!', '-', ':'
parts = []
origp = t.splitlines... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitor(args):
""" file monitor mode """ |
filename = args.get('MDFILE')
if not filename:
print col('Need file argument', 2)
raise SystemExit
last_err = ''
last_stat = 0
while True:
if not os.path.exists(filename):
last_err = 'File %s not found. Will continue trying.' % filename
else:
... |
<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_changed_file_cmd(cmd, fp, pretty):
""" running commands on changes. pretty the parsed file """ |
with open(fp) as f:
raw = f.read()
# go sure regarding quotes:
for ph in (dir_mon_filepath_ph, dir_mon_content_raw,
dir_mon_content_pretty):
if ph in cmd and not ('"%s"' % ph) in cmd \
and not ("'%s'" % ph) in cmd:
cmd = cmd.replace(ph, '"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitor_dir(args):
""" displaying the changed files """ |
def show_fp(fp):
args['MDFILE'] = fp
pretty = run_args(args)
print pretty
print "(%s)" % col(fp, L)
cmd = args.get('change_cmd')
if cmd:
run_changed_file_cmd(cmd, fp=fp, pretty=pretty)
ftree = {}
d = args.get('-M')
# was a change command giv... |
<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_args(args):
""" call the lib entry function with CLI args """ |
return main(filename = args.get('MDFILE')
,theme = args.get('-t', 'random')
,cols = args.get('-c')
,from_txt = args.get('-f')
,c_theme = args.get('-T')
,c_no_guess = args.get('-x')
,do_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 code(_, s, from_fenced_block = None, **kw):
""" md code AND ``` style fenced raw code ends here""" |
lang = kw.get('lang')
raw_code = s
if have_pygments:
s = style_ansi(raw_code, lang=lang)
# outest hir is 2, use it for fenced:
ind = ' ' * kw.get('hir', 2)
#if from_fenced_block: ... WE treat equal.
# shift to the far left, no matter the indent (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 bestfit_func(self, bestfit_x):
""" Returns y value """ |
if not self.bestfit_func:
raise KeyError("Do do_bestfit first")
return self.args["func"](self.fit_args, bestfit_x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_bestfit(self):
""" do bestfit using scipy.odr """ |
self.check_important_variables()
x = np.array(self.args["x"])
y = np.array(self.args["y"])
if self.args.get("use_RealData", True):
realdata_kwargs = self.args.get("RealData_kwargs", {})
data = RealData(x, y, **realdata_kwargs)
else:
data_kwarg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_in_longitude(lat, miles):
"""Given a latitude and a distance west, return the change in longitude.""" |
# Find the radius of a circle around the earth at given latitude.
r = earth_radius * math.cos(lat * degrees_to_radians)
return (miles / r) * radians_to_degrees |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
""" Close all connections that are set on this wire """ |
if self.connection_receive:
self.connection_receive.close()
if self.connection_respond:
self.connection_respond.close()
if self.connection_send:
self.connection_send.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_and_wait(self, path, message, timeout=0, responder=None):
""" Send a message and block until a response is received. Return response message """ |
message.on("response", lambda x,event_origin,source:None, once=True)
if timeout > 0:
ts = time.time()
else:
ts = 0
sent = False
while not message.response_received:
if not sent:
self.send(path, message)
sent ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wire(self, name, receive=None, send=None, respond=None, **kwargs):
""" Wires the link to a connection. Can be called multiple times to set up wires to differ... |
if hasattr(self, name) and name != "main":
raise AttributeError("cannot use '%s' as name for wire, attribute already exists")
if send:
self.log_debug("Wiring '%s'.send: %s" % (name, send))
if respond:
self.log_debug("Wiring '%s'.respond: %s" % (name, respon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
""" Cut all wires and disconnect all connections established on this link """ |
for name, wire in self.wires():
self.cut(name, disconnect=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 call(self, task, decorators=None):
""" Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's containe... |
if decorators is None:
decorators = []
task = self.apply_task_decorators(task, decorators)
data = task.get_data()
name = task.get_name()
result = self._inner_call(name, data)
task_result = RawTaskResult(task, result)
return self.apply_task_result_d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resource_context(fn):
""" Compose path to the ``resources`` directory for given `fn`. Args: fn (str):
Filename of file in ``resources`` directory. Returns:... |
return os.path.join(
os.path.dirname(__file__),
DES_DIR,
fn
) |
<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_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen):
""" Compose contract and create PDF. Args: firma (str):
firma pravni_forma (str):
pravni_form... |
contract_fn = _resource_context(
"Licencni_smlouva_o_dodavani_elektronickych_publikaci"
"_a_jejich_uziti.rst"
)
# load contract
with open(contract_fn) as f:
contract = f.read()#.decode("utf-8").encode("utf-8")
# make sure that `firma` has its heading mark
firma = firma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_tag(self, tag_func):
""" Creates a tag using the decorated func as the render function for the template tag node. The render function takes two argume... |
@wraps(tag_func)
def tag_wrapper(parser, token):
class RenderTagNode(template.Node):
def render(self, context):
return tag_func(context, token)
return RenderTagNode()
return self.tag(tag_wrapper) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inclusion_tag(self, name, context_class=Context, takes_context=False):
""" Replacement for Django's ``inclusion_tag`` which looks up device specific template... |
def tag_decorator(tag_func):
@wraps(tag_func)
def tag_wrapper(parser, token):
class InclusionTagNode(template.Node):
def render(self, context):
if not getattr(self, "nodelist", False):
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_list(self, params=None):
"""Lists all users within the tenant.""" |
uri = 'openstack/users'
if params:
uri += '?%s' % urllib.urlencode(params)
resp, body = self.get(uri)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_invite(self, username, email, roles):
""" Invite a user to the tenant. """ |
uri = 'openstack/users'
data = {
"username": username,
"email": email,
"roles": list(set(roles))
}
post_body = json.dumps(data)
resp, body = self.post(uri, body=post_body)
self.expected_success(200, resp.status)
body = json.lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revoke_user(self, user_id):
""" Revoke a user from the tenant This will remove pending or approved roles but will not not delete the user from Keystone. """ |
uri = 'openstack/users/%s' % user_id
try:
resp = self.delete(uri)
except AttributeError:
# note: this breaks. stacktask returns a string, not json.
return
self.expected_success(200, resp.status)
return rest_client.ResponseBody(resp, 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 get_tokens(self, filters={}):
""" Returns dict of tokens matching the provided filters """ |
uri = 'tokens'
if filters:
filters = {'filters': json.dumps(filters)}
uri += "?%s" % urllib.urlencode(filters, True)
resp, body = self.get(uri)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_submit(self, token_id, json_data={}):
""" Submits a given token, along with optional data """ |
uri = 'tokens/%s' % token_id
post_body = json.dumps(json_data)
resp, body = self.post(uri, post_body)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def approve_task(self, task_id):
""" Returns dict of tasks matching the provided filters """ |
uri = 'tasks/%s' % task_id
data = {"approved": True}
resp, body = self.post(uri, json.dumps(data))
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signup(self, project_name, email):
""" Signup for a new project. """ |
uri = 'openstack/sign-up'
data = {
"project_name": project_name,
"email": email,
}
post_body = json.dumps(data)
resp, body = self.post(uri, body=post_body)
self.expected_success(200, resp.status)
body = json.loads(body)
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 get_event(self, name, default=_sentinel):
""" Lookup an event by name. :param str item: Event name :return Event: Event instance under key """ |
if name not in self.events:
if self.create_events_on_access:
self.add_event(name)
elif default is not _sentinel:
return default
return self.events[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 _add_internal_event(self, name, send_event=False, internal_event_factory=None):
""" This is only here to ensure my constant hatred for Python 2's horrid vari... |
if not internal_event_factory:
internal_event_factory = self.internal_event_factory
return self.add_event(names, send_event=send_event, event_factory=internal_event_factory) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attach_handler_events(self, handler, events=None):
""" Search handler for methods named after events, attaching to event handlers as applicable. :param obje... |
if not events:
events = self
for name in events:
meth = getattr(handler, name, None)
if meth:
self.events[name] += meth |
<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(self, handler, send_event=True):
""" Remove handler instance and detach any methods bound to it from uninhibited. :param object handler: handler inst... |
for event in self:
event.remove_handlers_bound_to_instance(handler)
self.handlers.remove(handler)
if send_event:
self.on_handler_remove(handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fire(self, event, *args, **kwargs):
""" Fire event. call event's handlers using given arguments, return a list of results. :param str name: Event name :param... |
if not self._maybe_create_on_fire(event):
return
return self[event].fire(*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 ifire(self, event, *args, **kwargs):
""" Iteratively fire event, returning generator. Calls each handler using given arguments, upon iteration, yielding each... |
if not self._maybe_create_on_fire(event):
return
# Wrap the generator per item to force that this method be a generator
# Python 3.x of course has yield from, which would be great here.
# for x in self[event].ifire(*args, **kwargs)
# yield x
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 active(context, pattern_or_urlname, class_name='active', *args, **kwargs):
"""Based on a URL Pattern or name, determine if it is the current page. This is us... |
request = context.dicts[1].get('request')
try:
pattern = '^%s$' % reverse(pattern_or_urlname, args=args,
kwargs=kwargs)
except NoReverseMatch:
pattern = pattern_or_urlname
if request and re.search(pattern, request.path):
return class_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 run(sub_command, exit_handle=None, **options):
"""Run a command""" |
command = Command(sub_command, exit_handle)
return command.run(**options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __trim_extensions_dot(exts):
"""trim leading dots from extensions and drop any empty strings.""" |
if exts is None:
return None
res = []
for i in range(0, len(exts)):
if exts[i] == "":
continue
res.append(__trim_extension_dot(exts[i]))
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 load_just_in_time_genome_alignment(path, ref_spec, extensions=None, index_exts=None, fail_no_index=True, verbose=False):
"""Load a just-in-time genome alignm... |
if index_exts is None and fail_no_index:
raise ValueError("Failure on no index specified for loading genome " +
"alignment, but no index extensions specified")
extensions = __trim_extensions_dot(extensions)
index_exts = __trim_extensions_dot(index_exts)
partial_chrom_file... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __find_index(alig_file_pth, idx_extensions):
""" Find an index file for a genome alignment file in the same directory. :param alig_file_path: path to the ali... |
if idx_extensions is None:
return None
base, _ = os.path.splitext(alig_file_pth)
for idx_ext in idx_extensions:
candidate = base + os.extsep + idx_ext
if os.path.isfile(candidate):
return candidate
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 build_genome_alignment_from_directory(d_name, ref_spec, extensions=None, index_exts=None, fail_no_index=False):
""" build a genome aligment by loading all fi... |
if index_exts is None and fail_no_index:
raise ValueError("Failure on no index specified for loading genome " +
"alignment, but no index extensions specified")
blocks = []
for fn in os.listdir(d_name):
pth = os.path.join(d_name, fn)
if os.path.isfile(pth):
_, ext = os.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 build_genome_alignment_from_file(ga_path, ref_spec, idx_path=None, verbose=False):
""" build a genome alignment by loading from a single MAF file. :param ga_... |
blocks = []
if (idx_path is not None):
bound_iter = functools.partial(genome_alignment_iterator,
reference_species=ref_spec)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
factory = IndexedFile(None, bound_iter, hash_func)
factory.read_index(idx_path, ga_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 genome_alignment_iterator(fn, reference_species, index_friendly=False, verbose=False):
""" build an iterator for an MAF file of genome alignment blocks. :par... |
kw_args = {"reference_species": reference_species}
for e in maf.maf_iterator(fn, index_friendly=index_friendly,
yield_class=GenomeAlignmentBlock,
yield_kw_args=kw_args,
verbose=verbose):
yield e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_index(maf_strm, ref_spec):
"""Build an index for a MAF genome alig file and return StringIO of it.""" |
idx_strm = StringIO.StringIO()
bound_iter = functools.partial(genome_alignment_iterator,
reference_species=ref_spec)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
idx = IndexedFile(maf_strm, bound_iter, hash_func)
idx.write_index(idx_strm)
idx_strm.seek(0) # seek 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 update(self, addr, raw_addr, name=None, rssi=None):
"""Updates the collection of results with a newly received scan response. Args: addr (str):
Device hardw... |
if addr in self._devices:
# logger.debug('UPDATE scan result: {} / {}'.format(addr, name))
self._devices[addr].update(name, rssi)
return False
else:
self._devices[addr] = ScanResult(addr, raw_addr, name, rssi)
logger.debug('Scan 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 set_calibration(self, enabled, imus):
"""Set calibration state for attached IMUs. Args: enabled (bool):
True to apply calibration to IMU data (if available)... |
if len(imus) == 0:
imus = list(range(MAX_IMUS))
for i in imus:
if i < 0 or i >= MAX_IMUS:
logger.warn('Invalid IMU index {} in set_calibration'.format(i))
continue
self.imus[i]._use_calibration = enabled |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
"""Disconnect the dongle from this SK8. Simply closes the active BLE connection to the device represented by the current instance. Returns:... |
result = False
logger.debug('SK8.disconnect({})'.format(self.conn_handle))
if self.conn_handle >= 0:
logger.debug('Calling dongle disconnect')
result = self.dongle._disconnect(self.conn_handle)
self.conn_handle = -1
self.packets = 0
retur... |
<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_extana_callback(self, callback, data=None):
"""Register a callback for incoming data packets from the SK8-ExtAna board. This method allows you to pass in... |
self.extana_callback = callback
self.extana_callback_data = 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 enable_extana_streaming(self, include_imu=False, enabled_sensors=SENSOR_ALL):
"""Configures and enables sensor data streaming from the SK8-ExtAna device. By ... |
if not self.dongle._enable_extana_streaming(self, include_imu, enabled_sensors):
logger.warn('Failed to enable SK8-ExtAna streaming!')
return False
# have to add IMU #0 to enabled_imus if include_imu is True
if include_imu:
self.enabled_imus = [0]
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_extana_led(self, r, g, b, check_state=True):
"""Update the colour of the RGB LED on the SK8-ExtAna board. Args: r (int):
red channel, 0-255 g (int):
gr... |
r, g, b = map(int, [r, g, b])
if min([r, g, b]) < LED_MIN or max([r, g, b]) > LED_MAX:
logger.warn('RGB channel values must be {}-{}'.format(LED_MIN, LED_MAX))
return False
if check_state and (r, g, b) == self.led_state:
return True
# internally r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_imu_callback(self, callback, data=None):
"""Register a callback for incoming IMU data packets. This method allows you to pass in a callbable which will b... |
self.imu_callback = callback
self.imu_callback_data = 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 enable_imu_streaming(self, enabled_imus, enabled_sensors=SENSOR_ALL):
"""Configures and enables IMU sensor data streaming. NOTE: only one streaming mode can ... |
imus_enabled = 0
for imu in enabled_imus:
imus_enabled |= (1 << imu)
if enabled_sensors == 0:
logger.warn('Not enabling IMUs, no sensors enabled!')
return False
if not self.dongle._enable_imu_streaming(self, imus_enabled, enabled_sensors):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_imu_streaming(self):
"""Disable IMU streaming for this device. Returns: True on success, False if an error occurred. """ |
self.enabled_imus = []
# reset IMU data state
for imu in self.imus:
imu.reset()
return self.dongle._disable_imu_streaming(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_battery_level(self):
"""Reads the battery level descriptor on the device. Returns: int. If successful this will be a positive value representing the curr... |
battery_level = self.get_characteristic_handle_from_uuid(UUID_BATTERY_LEVEL)
if battery_level is None:
logger.warn('Failed to find handle for battery level')
return None
level = self.dongle._read_attribute(self.conn_handle, battery_level)
if level is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_name(self, cached=True):
"""Returns the SK8 device BLE name. Args: cached (bool):
if True, returns the locally cached copy of the name. If this i... |
if cached and self.name is not None:
return self.name
device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME)
if device_name is None:
logger.warn('Failed to find handle for device name')
return None
self.name = self.dongle._read_att... |
<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_device_name(self, new_name):
"""Sets a new BLE device name for this SK8. Args: new_name (str):
the new device name as an ASCII string, max 20 characters... |
device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME)
if device_name is None:
logger.warn('Failed to find handle for device name')
return False
if len(new_name) > MAX_DEVICE_NAME_LEN:
logger.error('Device name exceeds maximum leng... |
<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_firmware_version(self, cached=True):
"""Returns the SK8 device firmware version. Args: cached (bool):
if True, returns the locally cached copy of the fi... |
if cached and self.firmware_version != 'unknown':
return self.firmware_version
firmware_version = self.get_characteristic_handle_from_uuid(UUID_FIRMWARE_REVISION)
if firmware_version is None:
logger.warn('Failed to find handle for firmware version')
return N... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_service(self, uuid):
"""Lookup information about a given GATT service. Args: uuid (str):
a string containing the hex-encoded service UUID Returns: None ... |
if uuid in self.services:
return self.services[uuid]
if pp_hex(uuid) in self.services:
return self.services[pp_hex(uuid)]
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 get_polling_override(self):
"""Get the current polling override value in milliseconds. See :meth:`set_polling_override` for more information. Returns: None o... |
polling_override = self.get_characteristic_handle_from_uuid(UUID_POLLING_OVERRIDE)
if polling_override is None:
logger.warn('Failed to find handle for polling override')
return None
override_ms = self.dongle._read_attribute(self.conn_handle, polling_override, 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 set_polling_override(self, override):
"""Set the sensor polling timer override value in milliseconds. Due to the time it takes to poll all the sensors on up ... |
polling_override = self.get_characteristic_handle_from_uuid(UUID_POLLING_OVERRIDE)
if polling_override is None:
logger.warn('Failed to find handle for device name')
return False
if self.dongle._write_attribute(self.conn_handle, polling_override, struct.pack('B',... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(self, address, hard_reset=False):
"""Open the serial connection to a dongle at the supplied address. Args: address (str):
the serial port address of th... |
self.address = address
if hard_reset:
# TODO (needs more work to be usable)
# if not Dongle._hard_reset(address):
# return False
# time.sleep(2.0)
pass
# TODO timeout not working if opened on valid, non Bluegiga port
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 find_dongle_port():
"""Convenience method which attempts to find the port where a BLED112 dongle is connected. This relies on the `pyserial.tools.list_ports.... |
logger.debug('Attempting to find Bluegiga dongle...')
# TODO this will probably only work on Windows at the moment
ports = list(serial.tools.list_ports.grep('Bluegiga'))
if len(ports) == 0:
logger.debug('No Bluegiga-named serial ports discovered')
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 reset(self):
"""Attempts to reset the dongle to a known state. When called, this method will reset the internal state of the object, and disconnect any activ... |
logger.debug('resetting dongle state')
self._clear()
if self.api is not None:
self._set_state(Dongle._STATE_RESET)
self.api.ble_cmd_gap_set_mode(gap_discoverable_mode['gap_non_discoverable'], gap_connectable_mode['gap_non_connectable'])
self._wait_for_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 set_reconnect_parameters(self, interval, attempts, restore_state=True):
"""Sets the behaviour of the automatic reconnect feature. When a connected SK8 is dis... |
self._reconnect_attempts = max(0, attempts)
self._reconnect_interval = max(0, interval)
self._reconnect_restore_state = restore_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 scan_and_connect(self, devnames, timeout=DEF_TIMEOUT, calibration=True):
"""Scan for and then connect to a set of one or more SK8s. This method is intended t... |
responses = self.scan_devices(devnames, timeout)
for dev in devnames:
if dev not in responses:
logger.error('Failed to find device {} during scan'.format(dev))
return (False, [])
return self.connect([responses.get_device(dev) for dev in devnames], c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin_scan(self, callback=None, interval=DEF_SCAN_INTERVAL, window=DEF_SCAN_WINDOW):
"""Begins a BLE scan and returns immediately. Using this method you can ... |
# TODO validate params and current state
logger.debug('configuring scan parameters')
self.api.ble_cmd_gap_set_scan_parameters(interval, window, 1)
self._set_state(self._STATE_CONFIGURE_SCAN)
self.api.ble_cmd_gap_discover(1) # any discoverable devices
self._wait_for_sta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, devicelist, calibration=True):
"""Establish a connection to one or more SK8 devices. Given a list of 1 or more :class:`ScanResult` objects, thi... |
if not isinstance(devicelist, list):
devicelist = [devicelist]
logger.debug('Connecting to {} devices'.format(len(devicelist)))
if len(devicelist) > self.supported_connections:
logging.error('Dongle firmware supports max {} connections, {} device connections requested!'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_direct(self, device, calibration=True):
"""Establish a connection to a single SK8. Args: device: either a :class:`ScanResult` or a plain hardware add... |
# convert string address into a ScanResult if needed
if not isinstance(device, ScanResult):
if isinstance(device, str):
device = ScanResult(device, fmt_addr_raw(device))
elif isinstance(device, unicode):
device = device.encode('ascii')
... |
<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_supported_connections(self):
"""Returns the number of supported simultaneous BLE connections. The BLED112 is capable of supporting up to 8 simultaneous B... |
if self.supported_connections != -1:
return self.supported_connections
if self.api is None:
return -1
self._set_state(self._STATE_DONGLE_COMMAND)
self.api.ble_cmd_system_get_connections()
self._wait_for_state(self._STATE_DONGLE_COMMAND)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def httpapi_request(client, **params) -> 'Response': """Send a request to AniDB HTTP API. https://wiki.anidb.net/w/HTTP_API_Definition """ |
return requests.get(
_HTTPAPI,
params={
'client': client.name,
'clientver': client.version,
'protover': 1,
**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 unpack_xml(text) -> ET.ElementTree: """Unpack an XML string from AniDB API.""" |
etree: ET.ElementTree = ET.parse(io.StringIO(text))
_check_for_errors(etree)
return etree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_for_errors(etree: ET.ElementTree):
"""Check AniDB response XML tree for errors.""" |
if etree.getroot().tag == 'error':
raise APIError(etree.getroot().text) |
<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_fields(lines, delim, searches, match_lineno=1, **kwargs):
"""Return generator of fields matching `searches`. Parameters lines : iterable Provides lin... |
keep_idx = []
for lineno, line in lines:
if lineno < match_lineno or delim not in line:
if lineno == match_lineno:
raise WcutError('Delimter not found in line {}'.format(
match_lineno))
yield [line]
continue
fields = line.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_fields(fields, searches, ignore_case=False, wholename=False, complement=False):
"""Return fields that match searches. Parameters fields : iterable sear... |
if ignore_case:
fields = [f.lower() for f in fields]
searches = [s.lower() for s in searches]
if wholename:
match_found = _complete_match
else:
match_found = _partial_match
fields = [(i, field) for i, field in enumerate(fields)]
matched = []
for search, (idx, fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(cls, dbname):
"""Create a new connection to the SQLite3 database. :param dbname: The database name :type dbname: str """ |
test_times_schema = """
CREATE TABLE IF NOT EXISTS test_times (
file text,
module text,
class text,
func text,
elapsed float
)
"""
setup_times_schema = """
CREATE TABLE IF NOT EXISTS setup_times (
file ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(cls, dbname="perfdump"):
"""Returns the singleton connection to the SQLite3 database. :param dbname: The database name :type dbname: str """ |
try:
return cls.connection
except:
cls.connect(dbname)
return cls.connection |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def before_scenario(context, scenario):
"""Prepare a fresh environment for each scenario.""" |
# Prepare a new temporary directory.
context.directory = testfixtures.TempDirectory(create=True)
context.old_cwd = os.getcwd()
context.new_cwd = context.directory.path
# Move into our new working directory.
os.chdir(context.new_cwd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def after_scenario(context, scenario):
"""Leave the environment fresh after each scenario.""" |
# Move back into the original working directory.
os.chdir(context.old_cwd)
# Delete all content generated by the test.
context.directory.cleanup() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, name):
"""Get a parameter object by name. :param name: Name of the parameter object. :type name: str :return: The parameter. :rtype: Parameter """ |
parameter = next((p for p in self.parameters if p.name == name), None)
if parameter is None:
raise LookupError("Cannot find parameter '" + name + "'.")
return parameter |
<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_parameter(self, name, value, meta=None):
"""Add a parameter to the parameter list. :param name: New parameter's name. :type name: str :param value: New p... |
parameter = Parameter(name, value)
if meta: parameter.meta = meta
self.parameters.append(parameter) |
<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_file(self, path):
"""Load a YAML file with parameter data and other metadata. :param path: Path to YAML file. :type path: str The data in the YAML file ... |
data = yaml.load(open(path, 'r'))
for key in self.property_keys:
if key in data: setattr(self, key, data[key])
self.parameters = self.parameter_list(data['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 parameter_list(data):
"""Create a list of parameter objects from a dict. :param data: Dictionary to convert to parameter list. :type data: dict :return: Para... |
items = []
for item in data:
param = Parameter(item['name'], item['value'])
if 'meta' in item: param.meta = item['meta']
items.append(param)
return 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 add_blueprint(self, blueprint, **options):
""" Specify a blueprint to be registered with the application. Additional options will be passed to :meth:`~Flask.... |
instance = werkzeug.utils.import_string(blueprint)
self._blueprints.append((instance, options)) |
<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_extension(self, extension):
""" Specify a broadway extension to initialise .. code-block:: python factory = Factory() factory.add_extension('broadway_sql... |
instance = werkzeug.utils.import_string(extension)
if hasattr(instance, 'register'):
instance.register(self)
self._extensions.append(instance) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def newkeys(nbits=1024):
""" Create a new pair of public and private key pair to use. """ |
pubkey, privkey = rsa.newkeys(nbits, poolsize=1)
return pubkey, privkey |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt(self, binary, use_sign=True):
""" Encrypt binary data. **中文文档** - 发送消息时只需要对方的pubkey - 如需使用签名, 则双方都需要持有对方的pubkey """ |
token = rsa.encrypt(binary, self.his_pubkey) # encrypt it
if use_sign:
self.sign = rsa.sign(binary, self.my_privkey, "SHA-1") # sign it
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(self, token, signature=None):
""" Decrypt binary data. **中文文档** - 接收消息时只需要自己的privkey - 如需使用签名, 则双方都需要持有对方的pubkey """ |
binary = rsa.decrypt(token, self.my_privkey)
if signature:
rsa.verify(binary, signature, self.his_pubkey)
return binary |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True):
""" Encrypt a file using rsa. RSA for big file encryption is very slow. For... |
path, output_path = files.process_dst_overwrite_args(
src=path, dst=output_path, overwrite=overwrite,
src_to_dst_func=files.get_encrpyted_path,
)
with open(path, "rb") as infile, open(output_path, "wb") as outfile:
encrypt_bigfile(infile, outfile, self.his_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True):
""" Decrypt a file using rsa. """ |
path, output_path = files.process_dst_overwrite_args(
src=path, dst=output_path, overwrite=overwrite,
src_to_dst_func=files.get_decrpyted_path,
)
with open(path, "rb") as infile, open(output_path, "wb") as outfile:
decrypt_bigfile(infile, outfile, self.my_pr... |
<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_subcommands(self):
"""Print the subcommand part of the help.""" |
lines = ["Call"]
lines.append('-'*len(lines[-1]))
lines.append('')
lines.append("> jhubctl <subcommand> <resource-type> <resource-name>")
lines.append('')
lines.append("Subcommands")
lines.append('-'*len(lines[-1]))
lines.append('')
for name, sub... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.