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 set_property(self, key, value):
"""Set a property on the document. Calling code should use this method to add and modify properties on the document instead o... |
if key in self.RESERVED_ATTRIBUTE_NAMES:
return
self.o[key] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_property(self, key):
"""Remove a property from the document. Calling code should use this method to remove properties on the document instead of modif... |
if key in self.RESERVED_ATTRIBUTE_NAMES:
raise KeyError(key)
del self.o[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 link(self, href, **kwargs):
"""Retuns a new link relative to this resource.""" |
return link.Link(dict(href=href, **kwargs), self.base_uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_link(self, rel=None, href=lambda _: True):
"""Deletes links from the document. Calling code should use this method to remove links instead of modyfyin... |
if not LINKS_KEY in self.o:
return
links = self.o[LINKS_KEY]
if rel is None:
for rel in list(links.keys()):
self.delete_link(rel, href)
return
if callable(href):
href_filter = href
else:
href_filter = ... |
<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_object(cls, o, base_uri=None, parent_curies=None, draft=AUTO):
"""Returns a new ``Document`` based on a JSON object or array. Arguments: - ``o``: a dict... |
if isinstance(o, list):
return [cls.from_object(x, base_uri, parent_curies, draft)
for x in o]
return cls(o, base_uri, parent_curies, draft) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def empty(cls, base_uri=None, draft=AUTO):
"""Returns an empty ``Document``. Arguments: - ``base_uri``: optional URL used as the basis when expanding relative UR... |
return cls.from_object({}, base_uri=base_uri, draft=draft) |
<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_embedded(self, rel=None, href=lambda _: True):
"""Removes an embedded resource from this document. Calling code should use this method to remove embed... |
if EMBEDDED_KEY not in self.o:
return
if rel is None:
for rel in list(self.o[EMBEDDED_KEY].keys()):
self.delete_embedded(rel, href)
return
if rel not in self.o[EMBEDDED_KEY]:
return
if callable(href):
url_fil... |
<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_curie(self, name):
"""Removes a CURIE. The CURIE link with the given name is removed from the document. """ |
curies = self.o[LINKS_KEY][self.draft.curies_rel]
if isinstance(curies, dict) and curies['name'] == name:
del self.o[LINKS_KEY][self.draft.curies_rel]
return
for i, curie in enumerate(curies):
if curie['name'] == name:
del curies[i]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mask_left(self, n_seq_bases, mask="S"):
""" Return a new cigar with cigar string where the first `n_seq_bases` are soft-masked unless they are already hard-m... |
cigs = list(self.items())
new_cigs = []
c, cum_len = self.cigar, 0
for i, (l, op) in enumerate(cigs):
if op in Cigar.read_consuming_ops:
cum_len += l
if op == "H":
cum_len += l
new_cigs.append(cigs[i])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mask_right(self, n_seq_bases, mask="S"):
""" Return a new cigar with cigar string where the last `n_seq_bases` are soft-masked unless they are already hard-m... |
return Cigar(Cigar(self._reverse_cigar()).mask_left(n_seq_bases, mask)._reverse_cigar()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runner(test_command, work_dir=None):
""" Internal test job runner context manager. Run the test_command in a subprocess and instantiates 2 FlushStreamThread,... |
process = subprocess.Popen(test_command, bufsize=0, shell=True,
cwd=work_dir,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
with flush_stream_threads(process):
try:
yield process
finally:
if process.poll() i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill(self, sig=signal.SIGTERM):
""" Terminate the test job. Kill the subprocess if it was spawned, abort the spawning process otherwise. This information can... |
while self.is_alive():
self.killed = True
time.sleep(POLLING_DELAY) # "Was a process spawned?" polling
if not self.spawned:
continue # Either self.run returns or runner yields
if self.process.poll() is None: # It's running
self.pro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loader(schema, validator=CerberusValidator, update=None):
"""Create a load function based on schema dict and Validator class. :param schema: a Cerberus schem... |
if not issubclass(validator, CerberusValidator):
raise TypeError(
"Validator must be a subclass of more.cerberus.CerberusValidator"
)
return partial(load, schema, validator, update) |
<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(self, rectangle, data):
"""Draws the signature mark. Note that this draws OUTSIDE the rectangle we're given. If cropping is involved, then this obviou... |
size = (1.0 - 2.0*self.margin) * rectangle.h
offset = self.margin * rectangle.h
per_mark = 1.0 / float(self.total)
bottom = offset + size * float(self.index) * per_mark
top = bottom + per_mark * size
c = data['output']
with c:
c.translate(rectangle.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def projected_inverse(L):
""" Supernodal multifrontal projected inverse. The routine computes the projected inverse .. math:: Y = P(L^{-T}L^{-1}) where :math:`L`... |
assert isinstance(L, cspmatrix) and L.is_factor is True, "L must be a cspmatrix factor"
n = L.symb.n
snpost = L.symb.snpost
snptr = L.symb.snptr
chptr = L.symb.chptr
chidx = L.symb.chidx
relptr = L.symb.relptr
relidx = L.symb.relidx
blkptr = L.symb.blkptr
blkval = L.blkval
... |
<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_system_args(subparsers):
"""Append the parser arguments for the 'system' commands""" |
system_parser = subparsers.add_parser("system", help='Available commands: \'info\'')
system_subparsers = system_parser.add_subparsers(help='System commands')
# system info arguments
info_parser = system_subparsers.add_parser('info', help='Get system status information')
info_parser.add_argument('-... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_info(user):
"""Get the user information """ |
user = api.get_user(user)
current = api.get_current_user()
if api.is_anonymous():
return {
"username": current.getUserName(),
"authenticated": False,
"roles": current.getRoles(),
"api_url": api.url_for("plone.jsonapi.routes.users", username="current"... |
<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(context, request, username=None):
"""Plone users route """ |
user_ids = []
# Don't allow anonymous users to query a user other than themselves
if api.is_anonymous():
username = "current"
# query all users if no username was given
if username is None:
user_ids = api.get_member_ids()
elif username == "current":
current_user = api.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perm(A, p):
""" Symmetric permutation of a symmetric sparse matrix. :param A: :py:class:`spmatrix` :param p: :py:class:`matrix` or :class:`list` of length `A... |
assert isinstance(A,spmatrix), "argument must be a sparse matrix"
assert A.size[0] == A.size[1], "A must be a square matrix"
assert A.size[0] == len(p), "length of p must be equal to the order of A"
return A[p,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 enable_shuffle(self, value=None):
"""Enable shuffle mode """ |
if value is None:
value = not self.shuffled
spotifyconnect.Error.maybe_raise(lib.SpPlaybackEnableShuffle(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 enable_repeat(self, value=None):
"""Enable repeat mode """ |
if value is None:
value = not self.repeated
spotifyconnect.Error.maybe_raise(lib.SpPlaybackEnableRepeat(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 detect(self, obj):
"""Identifies the HAL draft level of a given JSON object.""" |
links = obj.get(LINKS_KEY, {})
for detector in [LATEST, DRAFT_3]:
if detector.draft.curies_rel in links:
return detector.detect(obj)
return LATEST.detect(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 to_list(thing):
""" converts an object to a list [1] [1, 2, 3] ['a', 'b', 'c'] [{'a': 1, 'b': 2}] [] ['a', 'b', 'c'] [''] [] ['[]'] ['a', 'b', 'c'] """ |
if thing is None:
return []
if isinstance(thing, set):
return list(thing)
if isinstance(thing, types.StringTypes):
if thing.startswith("["):
# handle a list inside a string coming from the batch navigation
return ast.literal_eval(thing)
if not (is_list(th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pluck(col, key, default=None):
""" Extracts a list of values from a collection of dictionaries ['moe', 'larry', 'curly'] It only works with collections Trace... |
if not (is_list(col) or is_tuple(col)):
fail("First argument must be a list or tuple")
def _block(dct):
if not is_dict(dct):
return []
return dct.get(key, default)
return map(_block, col) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename(dct, mapping):
""" Rename the keys of a dictionary with the given mapping {'AAA': 1, 'BBB': 2} """ |
def _block(memo, key):
if key in dct:
memo[mapping[key]] = dct[key]
return memo
else:
return memo
return reduce(_block, mapping, omit(dct, *mapping.keys())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alias(col, mapping):
""" Returns a collection of dictionaries with the keys renamed according to the mapping [{'edition': 1, 'isbn': 1}, {'edition': 2, 'isbn... |
if not is_list(col):
col = [col]
def _block(dct):
return rename(dct, mapping)
return map(_block, col) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first(thing, n=0):
""" get the first element of a list 1 [1, 2, 3] [1, 2, 3, 4, 5] {'key': 'value'} 'a' '' [''] '' False '' """ |
n = to_int(n)
if is_list(thing) or is_tuple(thing):
if len(thing) == 0:
return None
if n > 0:
return thing[0:n]
return thing[0]
return thing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def discover(ignore_list=[], max_wait=30, loop=None):
"""List STB in the network.""" |
stbs = []
try:
async with timeout(max_wait, loop=loop):
def responses_callback(notify):
"""Queue notify messages."""
_LOGGER.debug("Found: %s", notify.ip_address)
stbs.append(notify.ip_address)
mr_protocol = await install_mediaroo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_cmd(self, cmd, loop=None):
"""Send remote command to STB.""" |
_LOGGER.info("Send cmd = %s", cmd)
if cmd not in COMMANDS and cmd not in range(0, 999):
_LOGGER.error("Unknown command")
raise PyMediaroomError("Unknown commands")
keys = []
if cmd in range(0, 999):
for character in str(cmd):
keys.ap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notify_callback(self, notify):
"""Process State from NOTIFY message.""" |
_LOGGER.debug(notify)
if notify.ip_address != self.stb_ip:
return
if notify.tune:
self._state = State.PLAYING_LIVE_TV
self.tune_src = notify.tune['@src']
try:
if notify.stopped:
self._state = State.STOPPED
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Main thread function. """ |
if not hasattr(self, 'queue'):
raise RuntimeError("Audio queue is not intialized.")
chunk = None
channel = None
self.keep_listening = True
while self.keep_listening:
if chunk is None:
try:
frame = self.queue.get(timeout=queue_timeout)
chunk = pygame.sndarray.make_sound(frame)
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 search(self, query):
"""search the catalog """ |
logger.info("Catalog query={}".format(query))
# Support to set the catalog as a request parameter
catalogs = _.to_list(req.get("catalog", None))
if catalogs:
return senaiteapi.search(query, catalog=catalogs)
# Delegate to the search API of Bika LIMS
return s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_index(self, name):
"""get an index by name TODO: Combine indexes of relevant catalogs depending on the portal_type which is searched for. """ |
catalog = self.get_catalog()
index = catalog._catalog.getIndex(name)
logger.debug("get_index={} of catalog '{}' --> {}".format(
name, catalog.__name__, index))
return index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_index_value(self, value, index):
"""Convert the value for a given index """ |
# ZPublisher records can be passed to the catalog as is.
if isinstance(value, HTTPRequest.record):
return value
if isinstance(index, basestring):
index = self.get_index(index)
if index.id == "portal_type":
return filter(lambda x: x, _.to_list(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 make_query(self, **kw):
"""create a query suitable for the catalog """ |
query = kw.pop("query", {})
query.update(self.get_request_query())
query.update(self.get_custom_query())
query.update(self.get_keyword_query(**kw))
sort_on, sort_order = self.get_sort_spec()
if sort_on and "sort_on" not in query:
query.update({"sort_on": so... |
<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_request_query(self):
"""Checks the request for known catalog indexes and converts the values to fit the type of the catalog index. :param catalog: The ca... |
query = {}
# only known indexes get observed
indexes = self.catalog.get_indexes()
for index in indexes:
# Check if the request contains a parameter named like the index
value = req.get(index)
# No value found, continue
if value is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_custom_query(self):
"""Extracts custom query keys from the index. Parameters which get extracted from the request: `q`: Passes the value to the `Searchab... |
query = {}
# searchable text queries
q = req.get_query()
if q:
query["SearchableText"] = q
# physical path queries
path = req.get_path()
if path:
query["path"] = {'query': path, 'depth': req.get_depth()}
# special handling for 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 get_keyword_query(self, **kw):
"""Generates a query from the given keywords. Only known indexes make it into the generated query. :returns: Catalog query :rt... |
query = dict()
# Only known indexes get observed
indexes = self.catalog.get_indexes()
# Handle additional keyword parameters
for k, v in kw.iteritems():
# handle uid in keywords
if k.lower() == "uid":
k = "UID"
# handle porta... |
<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_sort_spec(self):
"""Build sort specification """ |
all_indexes = self.catalog.get_indexes()
si = req.get_sort_on(allowed_indexes=all_indexes)
so = req.get_sort_order()
return si, so |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trsm(self,B,trans='N'):
r""" Solves a triangular system of equations with multiple righthand sides. Computes .. math:: B &:= L^{-1} B \text{ if trans is 'N'}... |
if trans=='N':
cp.trsm(self._L0,B)
pftrsm(self._V,self._L,self._B,B,trans='N')
elif trans=='T':
pftrsm(self._V,self._L,self._B,B,trans='T')
cp.trsm(self._L0,B,trans='T')
elif type(trans) is str:
raise ValueError("trans must be... |
<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_to_reportlab_canvas(rl_canvas, papersize_tuple, layout):
"""Renders the given layout manager on a page of the given canvas.""" |
rl_canvas.setPageSize(papersize_tuple)
layout.render(
Rectangle(0, 0, *papersize_tuple),
dict(output=ReportlabOutput(rl_canvas))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_basic(r, username, password):
"""Attaches HTTP Basic Authentication to the given Request object. Arguments should be considered non-positional. """ |
username = str(username)
password = str(password)
auth_s = b64encode('%s:%s' % (username, password))
r.headers['Authorization'] = ('Basic %s' % auth_s)
return 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 http_digest(r, username, password):
"""Attaches HTTP Digest Authentication to the given Request object. Arguments should be considered non-positional. """ |
def handle_401(r):
"""Takes the given response and tries digest-auth, if needed."""
s_auth = r.headers.get('www-authenticate', '')
if 'digest' in s_auth.lower():
last_nonce = ''
nonce_count = 0
chal = parse_dict_header(s_auth.replace('Digest ', ''))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(t):
"""Given an auth tuple, return an expanded version.""" |
if not t:
return t
else:
t = list(t)
# Make sure they're passing in something.
assert len(t) >= 2
# If only two items are passed in, assume HTTPBasic.
if (len(t) == 2):
t.insert(0, 'basic')
# Allow built-in string referenced auths.
if isinstance(t[0], basestr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def action(context, request, action=None, resource=None, uid=None):
"""Various HTTP POST actions """ |
# allow to set the method via the header
if action is None:
action = request.get_header("HTTP_X_HTTP_METHOD_OVERRIDE", "CREATE").lower()
# Fetch and call the action function of the API
func_name = "{}_items".format(action)
action_func = getattr(api, func_name, None)
if action_func is ... |
<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_help_html():
"""Build the help HTML using the shared resources.""" |
remove_from_help = ["not-in-help", "copyright"]
if sys.platform in ["win32", "cygwin"]:
remove_from_help.extend(["osx", "linux"])
elif sys.platform == "darwin":
remove_from_help.extend(["linux", "windows", "linux-windows"])
else:
remove_from_help.extend(["osx", "windows"])
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 help_box():
"""A simple HTML help dialog box using the distribution data files.""" |
style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
dialog_box = wx.Dialog(None, wx.ID_ANY, HELP_TITLE,
style=style, size=(620, 450))
html_widget = HtmlHelp(dialog_box, wx.ID_ANY)
html_widget.page = build_help_html()
dialog_box.ShowModal()
dialog_box.Destroy() |
<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_frame(self, outdata, frames, timedata, status):
""" Callback function for the audio stream. Don't use directly. """ |
if not self.keep_listening:
raise sd.CallbackStop
try:
chunk = self.queue.get_nowait()
# Check if the chunk contains the expected number of frames
# The callback function raises a ValueError otherwise.
if chunk.shape[0] == frames:
outdata[:] = chunk
else:
outdata.fill(0)
except Empt... |
<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_component_product(self, other):
"""Returns the component product of this vector and the given other vector.""" |
return Point(self.x * other.x, self.y * other.y) |
<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_normalized(self):
"""Returns a vector of unit length, unless it is the zero vector, in which case it is left as is.""" |
magnitude = self.get_magnitude()
if magnitude > 0:
magnitude = 1.0 / magnitude
return Point(self.x * magnitude, self.y * magnitude)
else:
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_rotated(self, angle):
"""Rotates this vector through the given anti-clockwise angle in radians.""" |
ca = math.cos(angle)
sa = math.sin(angle)
return Point(self.x*ca-self.y*sa, self.x*sa+self.y*ca) |
<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_magnitude(self):
"""Returns the magnitude of this vector.""" |
return math.sqrt(self.x*self.x + self.y*self.y) |
<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_magnitude_squared(self):
"""Returns the square of the magnitude of this vector.""" |
return self.x*self.x + self.y*self.y |
<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_scalar_product(self, other):
"""Returns the scalar product of this vector with the given other vector.""" |
return self.x*other.x+self.y*other.y |
<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_angle_between(self, other):
"""Returns the smallest angle between this vector and the given other vector.""" |
# The scalar product is the sum of the squares of the
# magnitude times the cosine of the angle - so normalizing the
# vectors first means the scalar product is just the cosine of
# the angle.
normself = self.get_normalized()
normother = other.get_normalized()
sp... |
<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_minimum(self, other):
"""Updates this vector so its components are the lower of its current components and those of the given other value.""" |
return Point(min(self.x, other.x), min(self.y, other.y)) |
<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_maximum(self, other):
"""Updates this vector so its components are the higher of its current components and those of the given other value.""" |
return Point(max(self.x, other.x), max(self.y, other.y)) |
<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_random(min_pt, max_pt):
"""Returns a random vector in the given range.""" |
result = Point(random.random(), random.random())
return result.get_component_product(max_pt - min_pt) + min_pt |
<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_data(self):
"""Returns the x, y, w, h, data as a tuple.""" |
return self.x, self.y, self.w, self.h |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which _get_default_tempdir will try.""" |
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# Failing that, try OS-specific locations.
if _os.name == 'nt':
dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]... |
<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_default_tempdir():
"""Calculate the default directory to use for temporary files. This routine should be called exactly once. We determine whether or no... |
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
for dir in dirlist:
if dir != _os.curdir:
dir = _os.path.abspath(dir)
# Try only a few names per directory.
for seq in range(100):
name = next(namer)
filename = _os.path.join(dir,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_candidate_names():
"""Common setup sequence for all user-callable interfaces.""" |
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence()
finally:
_once_lock.release()
return _name_sequence |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mkstemp_inner(dir, pre, suf, flags):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, pre + name + suf)
try:
fd = _os.open(file, flags, 0o600)
return (fd, _os.path.abspath(file))
except FileExistsError:
continue # try aga... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gettempdir():
"""Accessor for tempfile.tempdir.""" |
global tempdir
if tempdir is None:
_once_lock.acquire()
try:
if tempdir is None:
tempdir = _get_default_tempdir()
finally:
_once_lock.release()
return tempdir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mkdtemp(suffix="", prefix=template, dir=None):
"""User-callable function to create and return a unique temporary directory. The return value is the pathname ... |
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, prefix + name + suffix)
try:
_os.mkdir(file, 0o700)
return file
except FileExistsError:
co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def syr2(X, u, v, alpha = 1.0, beta = 1.0, reordered=False):
r""" Computes the projected rank 2 update of a cspmatrix X .. math:: X := \alpha*P(u v^T + v u^T) + ... |
assert X.is_factor is False, "cspmatrix factor object"
symb = X.symb
n = symb.n
snptr = symb.snptr
snode = symb.snode
blkval = X.blkval
blkptr = symb.blkptr
relptr = symb.relptr
snrowidx = symb.snrowidx
sncolptr = symb.sncolptr
if symb.p is not None and reordered is 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 _ensure_5args(func):
""" Conditionally wrap function to ensure 5 input arguments Parameters func: callable with four or five positional arguments Returns ---... |
if func is None:
return None
self_arg = 1 if inspect.ismethod(func) else 0
if len(inspect.getargspec(func)[0]) == 5 + self_arg:
return func
if len(inspect.getargspec(func)[0]) == 4 + self_arg:
return lambda t, y, J, dfdt, fy=None: func(t, y, J, dfdt)
else:
raise 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 shadow_normal_module(cls, mod_name=None):
""" Shadow a module with an instance of LazyModule :param mod_name: Name of the module to shadow. By default this i... |
if mod_name is None:
frame = inspect.currentframe()
try:
mod_name = frame.f_back.f_locals['__name__']
finally:
del frame
orig_mod = sys.modules[mod_name]
lazy_mod = cls(orig_mod.__name__, orig_mod.__doc__, orig_mod)
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 lazily(self, name, callable, args):
""" Load something lazily """ |
self._lazy[name] = callable, args
self._all.add(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 immediate(self, name, value):
""" Load something immediately """ |
setattr(self, name, value)
self._all.add(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 parse_dimension(text):
""" Parses the given text into one dimension and returns its equivalent size in points. The numbers provided can be integer or decimal... |
size, unit = _split_dimension(text)
factor = _unit_lookup[unit]
return size*factor |
<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_dimensions(text):
""" Parses a set of dimensions into tuple of values representing the sizes in points. The dimensions that this method supports are ex... |
components = _dimension_separator.split(text)
if len(components) == 0:
raise DimensionError("No dimensions found in string.")
# Split each component into size and units
pairs = []
units = 0
for component in components:
value, unit = _split_dimension(component)
pairs.app... |
<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_dimension(text):
""" Returns the number and unit from the given piece of text as a pair. (1, 'pt') (1, 'pt') (1, 'pt') (1, 'pt') (1, 'pt') (3, None) (... |
match = _dimension_finder.match(text)
if not match:
raise DimensionError("Can't parse dimension '%s'." % text)
number = match.group(1)
unit = match.group(4)
if '.' in number:
return (float(number), unit)
else:
return (int(number), unit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue(self, value):
""" Sets the audioqueue. Parameters value : queue.Queue The buffer from which audioframes are received. """ |
if not isinstance(value, Queue):
raise TypeError("queue is not a Queue object")
self._queue = 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_minimum_size(self, data):
"""Returns the minimum size of the managed element, as long as it is larger than any manually set minima.""" |
size = self.element.get_minimum_size(data)
return datatypes.Point(
max(size.x, self.min_width),
max(size.y, self.min_height)
) |
<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(self, rect, data):
"""Draws the managed element in the correct alignment.""" |
# We can't use our get minimum size, because that enforces
# the size limits.
size = self.element.get_minimum_size(data)
# Assume we're bottom left at our natural size.
x = rect.x
y = rect.y
w = size.x
h = size.y
extra_width = rect.w - w
... |
<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_copy_without_data(G):
"""Return a copy of the graph G with all the data removed""" |
H = nx.Graph()
for i in H.nodes_iter():
H.node[i] = {}
return H |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(stuff, filename, verbose=True, protocol=3):
"""Store an object to file by pickling Parameters stuff : object to be pickled filename : path verbose : boo... |
filename = os.path.normcase(filename)
dir_path = os.path.dirname(filename)
if not os.path.exists(dir_path): os.makedirs(dir_path)
with open(filename, 'wb') as f:
p = pickle.Pickler(f, protocol=protocol)
p.dump(stuff)
if verbose:
print('Written {} items to pickled binary 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 load(filename):
"""Retrieve a pickled object Parameter --------- filename : path Return ------ object Unpickled object """ |
filename = os.path.normcase(filename)
try:
with open(filename, 'rb') as f:
u = pickle.Unpickler(f)
return u.load()
except IOError:
raise LogOpeningError('No file found for %s' % filename, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign_envelope(envelope, key_file):
"""Sign the given soap request with the given key""" |
doc = etree.fromstring(envelope)
body = get_body(doc)
queue = SignQueue()
queue.push_and_mark(body)
security_node = ensure_security_header(doc, queue)
security_token_node = create_binary_security_token(key_file)
signature_node = Signature(
xmlsec.TransformExclC14N, xmlsec.Transfor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_envelope(reply, key_file):
"""Verify that the given soap request is signed with the certificate""" |
doc = etree.fromstring(reply)
node = doc.find(".//{%s}Signature" % xmlsec.DSigNs)
if node is None:
raise CertificationError("No signature node found")
dsigCtx = xmlsec.DSigCtx()
xmlsec.addIDs(doc, ['Id'])
signKey = xmlsec.Key.load(key_file, xmlsec.KeyDataFormatPem)
signKey.name = o... |
<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_key_info_node(security_token):
"""Create the KeyInfo node for WSSE. Note that this currently only supports BinarySecurityTokens Example of the generat... |
key_info = etree.Element(ns_id('KeyInfo', ns.dsns))
sec_token_ref = etree.SubElement(
key_info, ns_id('SecurityTokenReference', ns.wssens))
sec_token_ref.set(
ns_id('TokenType', ns.wssens), security_token.get('ValueType'))
reference = etree.SubElement(sec_token_ref, ns_id('Reference',... |
<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_binary_security_token(key_file):
"""Create the BinarySecurityToken node containing the x509 certificate. """ |
node = etree.Element(
ns_id('BinarySecurityToken', ns.wssens),
nsmap={ns.wssens[0]: ns.wssens[1]})
node.set(ns_id('Id', ns.wsuns), get_unique_id())
node.set('EncodingType', ns.wssns[1] + 'Base64Binary')
node.set('ValueType', BINARY_TOKEN_TYPE)
with open(key_file) as fh:
cer... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_security_header(envelope, queue):
"""Insert a security XML node if it doesn't exist otherwise update it. """ |
(header,) = HEADER_XPATH(envelope)
security = SECURITY_XPATH(header)
if security:
for timestamp in TIMESTAMP_XPATH(security[0]):
queue.push_and_mark(timestamp)
return security[0]
else:
nsmap = {
'wsu': ns.wsuns[1],
'wsse': ns.wssens[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 checkParametersInputFile(filename):
"""Check the do_x3dna output file and return list of parameters present in the file. """ |
fin = open(filename, 'r')
line = fin.readline()
line2 = fin.readline()
fin.close()
temp = re.split('\s+', line)
temp2 = re.split('\s+', line2)
if temp[0] == '#Minor':
return groovesParameters
if temp[0] == '#Shift':
return baseStepParameters
if temp[0] == '#X-dis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setParametersFromFile(dna, filename, parameters=None, bp=None):
"""Read a specific parameter from the do_x3dna output file. It automatically load the input p... |
gotParameterList = False
param_type = None
# In case of none try to determine from file
if parameters is None:
parameters = checkParametersInputFile(filename)
if parameters is None:
raise AssertionError(" Cannot determine the parameters name from file {0}.".format(filename... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def frenet_serret(xyz):
''' Frenet-Serret Space Curve Invariants
Taken from "Diffusion Imaging in Python" `DiPy package<http://nipy.org/dipy/>`_
Calculates the 3 vector and 2 scalar invariants of a space curve defined by vectors r = (x,y,z). If z is omitted (i.e. the array xyz has shape (N,2), then the 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 read_param_file(FileName, parameters, bp, bp_range, word=False, startBP=1):
""" Read parameters from do_x3dna file. It is the main function, which is used to... |
sys.stdout.write("\nReading file : %s\n" % FileName)
sys.stdout.flush()
def get_frame_data(block, parameters, bp_idx):
block = np.array(block).T
temp_data = (block[parameters, :])[:, bp_idx].copy()
return temp_data
def get_time(line):
dummy, temp_time = line.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 _set_time(self, time):
""" Set time in both class and hdf5 file """ |
if len(self.time) == 0 :
self.time = np.array(time)
if self.h5 is not None:
self.h5.create_dataset('time', self.time.shape, dtype=self.time.dtype, data=self.time, compression="gzip", shuffle=True, scaleoffset=3)
else:
if(len(time) != len(self.time)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_mask(self, mask):
""" Set mask array in both class and hdf5 file """ |
self.mask = mask.copy()
if self.h5 is not None:
if 'mask' in self.h5:
self.h5.pop('mask')
self.h5.create_dataset('mask', mask.shape, dtype=self.mask.dtype, data=mask, compression="gzip", shuffle=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_helical_axis(self, filename, step_range=False, step=None):
""" To read and set local helical-axis positions from an input file. Parameters filename : str... |
if (step_range):
if not isinstance(step, list):
raise AssertionError("type %s is not list" % type(step))
if (len(step) > 2):
print (
"ERROR: Range for helical axis should be list of two numbers, e.g. step=[1, 20] \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 loop(self, value):
""" Indicates whether the playback should loop. Parameters value : bool True if playback should loop, False if not. """ |
if not type(value) == bool:
raise TypeError("can only be True or False")
self._loop = 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 reset(self):
""" Resets the player and discards loaded data. """ |
self.clip = None
self.loaded_file = None
self.fps = None
self.duration = None
self.status = UNINITIALIZED
self.clock.reset()
self.loop_count = 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 load_media(self, mediafile, play_audio=True):
""" Loads a media file to decode. If an audiostream is detected, its parameters will be stored in a dicti... |
if not mediafile is None:
if os.path.isfile(mediafile):
self.clip = VideoFileClip(mediafile, audio=play_audio)
self.loaded_file = os.path.split(mediafile)[1]
## Timing variables
# Clip duration
self.duration = self.clip.duration
self.clock.max_duration = self.clip.duration
logger.deb... |
<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_audiorenderer(self, renderer):
""" Sets the SoundRenderer object. This should take care of processing the audioframes set in audioqueue. Parameters... |
if not hasattr(self, 'audioqueue') or self.audioqueue is None:
raise RuntimeError("No video has been loaded, or no audiostream "
"was detected.")
if not isinstance(renderer, SoundRenderer):
raise TypeError("Invalid renderer object. Not a subclass of "
"SoundRenderer")
self.soundrenderer = renderer
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Stops the video stream and resets the clock. """ |
logger.debug("Stopping playback")
# Stop the clock
self.clock.stop()
# Set plauyer status to ready
self.status = READY |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seek(self, value):
""" Seek to the specified time. Parameters value : str or int The time to seek to. Can be any of the following formats: """ |
# Pause the stream
self.pause()
# Make sure the movie starts at 1s as 0s gives trouble.
self.clock.time = max(0.5, value)
logger.debug("Seeking to {} seconds; frame {}".format(self.clock.time,
self.clock.current_frame))
if self.audioformat:
self.__calculate_audio_frames()
# Resume the stream
sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __calculate_audio_frames(self):
""" Aligns audio with video. This should be called for instance after a seeking operation or resuming from a pause. """ |
if self.audioformat is None:
return
start_frame = self.clock.current_frame
totalsize = int(self.clip.audio.fps*self.clip.audio.duration)
self.audio_times = list(range(0, totalsize,
self.audioformat['buffersize'])) + [totalsize]
# Remove audio segments up to the starting frame
del(self.audio_times[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 __render(self):
""" Main render loop. Checks clock if new video and audio frames need to be rendered. If so, it passes the frames to functions that tak... |
# Render first frame
self.__render_videoframe()
# Start videoclock with start of this thread
self.clock.start()
logger.debug("Started rendering loop.")
# Main rendering loop
while self.status in [PLAYING,PAUSED]:
current_frame_no = self.clock.current_frame
# Check if end of clip has been reache... |
<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_videoframe(self):
""" Retrieves a new videoframe from the stream. Sets the frame as the __current_video_frame and passes it on to __videorende... |
new_videoframe = self.clip.get_frame(self.clock.time)
# Pass it to the callback function if this is set
if callable(self.__videorenderfunc):
self.__videorenderfunc(new_videoframe)
# Set current_frame to current frame (...)
self.__current_videoframe = new_videoframe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.