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 delete_all_secrets(cls, user, client_id):
"""Delete all of the client's credentials""" |
can_delete = yield cls(client_id=client_id).can_delete(user)
if not can_delete:
raise exceptions.Unauthorized('User may not delete {} secrets'
.format(client_id))
results = yield cls.view.get(key=client_id, include_docs=True)
if re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendContact(self, context={}):
""" Send contact form message to single or multiple recipients """ |
for recipient in self.recipients:
super(ContactFormMail, self).__init__(recipient, self.async)
self.sendEmail('contactForm', 'New contact form message', context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proxify_elt(elt, bases=None, _dict=None, public=False):
"""Proxify input elt. :param elt: elt to proxify. :param bases: elt class base classes. If None, use ... |
# ensure _dict is a dictionary
proxy_dict = {} if _dict is None else _dict.copy()
# set of proxified attribute names which are proxified during bases parsing
# and avoid to proxify them twice during _dict parsing
proxified_attribute_names = set()
# ensure bases is a tuple of types
if bases... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proxify_routine(routine, impl=None):
"""Proxify a routine with input impl. :param routine: routine to proxify. :param impl: new impl to use. If None, use rou... |
# init impl
impl = routine if impl is None else impl
is_method = ismethod(routine)
if is_method:
function = get_method_function(routine)
else:
function = routine
# flag which indicates that the function is not a pure python function
# and has to be wrapped
wrap_functi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compilecode(function, name, impl, args, varargs, kwargs):
"""Get generated code. :return: function proxy generated code. :rtype: str """ |
newcodestr, generatedname, impl_name = _generatecode(
function=function, name=name, impl=impl,
args=args, varargs=varargs, kwargs=kwargs
)
try:
__file__ = getfile(function)
except TypeError:
__file__ = '<string>'
# compile newcodestr
code = compile(newcodestr,... |
<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_proxy(elt, bases=None, _dict=None):
"""Get proxy from an elt. If elt implements the proxy generator method (named ``__getproxy__``), use it instead of us... |
# try to find an instance proxy generator
proxygenerator = getattr(elt, __GETPROXY__, None)
# if a proxy generator is not found, use this module
if proxygenerator is None:
if isroutine(elt):
result = proxify_routine(elt)
else: # in case of object, result is a Proxy
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proxified_elt(proxy):
"""Get proxified element. :param proxy: proxy element from where get proxified element. :return: proxified element. None if proxy is no... |
if ismethod(proxy):
proxy = get_method_function(proxy)
result = getattr(proxy, __PROXIFIED__, None)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_proxy(elt):
"""Return True if elt is a proxy. :param elt: elt to check such as a proxy. :return: True iif elt is a proxy. :rtype: bool """ |
if ismethod(elt):
elt = get_method_function(elt)
result = hasattr(elt, __PROXIFIED__)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ajax_login_required(view_func):
"""Handle non-authenticated users differently if it is an AJAX request.""" |
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
response = http.HttpResponse()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ajax_only(view_func):
"""Required the view is only accessed via AJAX.""" |
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view_func(request, *args, **kwargs)
else:
return http.HttpResponseBadRequest()
return _wrapped_view |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def anonymous_required(func=None, url=None):
"""Required that the user is not logged in.""" |
url = url or "/"
def _dec(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
return redirect(url)
else:
return view_func(request, *args, **k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def secure(view_func):
"""Handles SSL redirect on the view level.""" |
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if not request.is_secure():
redirect = _redirect(request, True)
if redirect:
# Redirect might be None if SSL is not enabled
return redirect
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_int(n):
""" Encodes an int as a variable length signed 29-bit integer as defined by the spec. @param n: The integer to be encoded @return: The encoded... |
global ENCODED_INT_CACHE
try:
return ENCODED_INT_CACHE[n]
except KeyError:
pass
if n < MIN_29B_INT or n > MAX_29B_INT:
raise OverflowError("Out of range")
if n < 0:
n += 0x20000000
bytes = ''
real_value = None
if n > 0x1fffff:
real_value = 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 writeBoolean(self, value):
""" Writes a Boolean value. @type value: C{bool} @param value: A C{Boolean} value determining which byte is written. If the parame... |
if not isinstance(value, bool):
raise ValueError("Non-boolean value found")
if value is True:
self.stream.write_uchar(1)
else:
self.stream.write_uchar(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 writeMultiByte(self, value, charset):
""" Writes a multibyte string to the datastream using the specified character set. @type value: C{str} @param value: Th... |
if type(value) is unicode:
value = value.encode(charset)
self.stream.write(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 writeUTF(self, value):
""" Writes a UTF-8 string to the data stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed ... |
buf = util.BufferedByteStream()
buf.write_utf8_string(value)
bytes = buf.getvalue()
self.stream.write_ushort(len(bytes))
self.stream.write(bytes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readMultiByte(self, length, charset):
""" Reads a multibyte string of specified length from the data stream using the specified character set. @type length: ... |
#FIXME nick: how to work out the code point byte size (on the fly)?
bytes = self.stream.read(length)
return unicode(bytes, charset) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readUTF(self):
""" Reads a UTF-8 string from the data stream. The string is assumed to be prefixed with an unsigned short indicating the length in bytes. @rt... |
length = self.stream.read_ushort()
return self.stream.read_utf8_string(length) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readBytes(self):
""" Reads and returns a utf-8 encoded byte array. """ |
length, is_reference = self._readLength()
if is_reference:
return self.context.getString(length)
if length == 0:
return ''
result = self.stream.read(length)
self.context.addString(result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readString(self):
""" Reads and returns a string from the stream. """ |
length, is_reference = self._readLength()
if is_reference:
result = self.context.getString(length)
return self.context.getStringForBytes(result)
if length == 0:
return ''
result = self.stream.read(length)
self.context.addString(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 readDate(self):
""" Read date from the stream. The timezone is ignored as the date is always in UTC. """ |
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
return self.context.getObject(ref >> 1)
ms = self.stream.read_double()
result = util.get_datetime(ms / 1000.0)
if self.timezone_offset is not None:
result += self.timezone_offset
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 readArray(self):
""" Reads an array from the stream. @warning: There is a very specific problem with AMF3 where the first three bytes of an encoded empty C{d... |
size = self.readInteger(False)
if size & REFERENCE_BIT == 0:
return self.context.getObject(size >> 1)
size >>= 1
key = self.readBytes()
if key == '':
# integer indexes only -> python list
result = []
self.context.addObject(resu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getClassDefinition(self, ref):
""" Reads class definition from the stream. """ |
is_ref = ref & REFERENCE_BIT == 0
ref >>= 1
if is_ref:
class_def = self.context.getClassByReference(ref)
return class_def
name = self.readBytes()
alias = None
if name == '':
name = pyamf.ASObject
try:
alias = 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 readObject(self):
""" Reads an object from the stream. """ |
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
obj = self.context.getObject(ref >> 1)
if obj is None:
raise pyamf.ReferenceError('Unknown reference %d' % (ref >> 1,))
if self.use_proxies is True:
obj = self.readProxy(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 readXML(self):
""" Reads an xml object from the stream. @return: An etree interface compatible object @see: L{xml.set_default_interface} """ |
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
return self.context.getObject(ref >> 1)
xmlstring = self.stream.read(ref >> 1)
x = xml.fromstring(xmlstring)
self.context.addObject(x)
return 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 readByteArray(self):
""" Reads a string of data from the stream. Detects if the L{ByteArray} was compressed using C{zlib}. @see: L{ByteArray} @note: This is ... |
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
return self.context.getObject(ref >> 1)
buffer = self.stream.read(ref >> 1)
try:
buffer = zlib.decompress(buffer)
compressed = True
except zlib.error:
compressed = 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 writeBoolean(self, n):
""" Writes a Boolean to the stream. """ |
t = TYPE_BOOL_TRUE
if n is False:
t = TYPE_BOOL_FALSE
self.stream.write(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 writeInteger(self, n):
""" Writes an integer to the stream. @type n: integer data @param n: The integer data to be encoded to the AMF3 data stream. """ |
if n < MIN_29B_INT or n > MAX_29B_INT:
self.writeNumber(float(n))
return
self.stream.write(TYPE_INTEGER)
self.stream.write(encode_int(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 writeNumber(self, n):
""" Writes a float to the stream. @type n: C{float} """ |
self.stream.write(TYPE_NUMBER)
self.stream.write_double(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 writeProxy(self, obj):
""" Encodes a proxied object to the stream. @since: 0.6 """ |
proxy = self.context.getProxyForObject(obj)
self.writeObject(proxy, is_proxy=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 writeObject(self, obj, is_proxy=False):
""" Writes an object to the stream. """ |
if self.use_proxies and not is_proxy:
self.writeProxy(obj)
return
self.stream.write(TYPE_OBJECT)
ref = self.context.getObjectReference(obj)
if ref != -1:
self._writeInteger(ref << 1)
return
self.context.addObject(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 writeXML(self, n):
""" Writes a XML string to the data stream. @type n: L{ET<xml.ET>} @param n: The XML Document to be encoded to the AMF3 data stream. """ |
self.stream.write(TYPE_XMLSTRING)
ref = self.context.getObjectReference(n)
if ref != -1:
self._writeInteger(ref << 1)
return
self.context.addObject(n)
self.serialiseString(xml.tostring(n).encode('utf-8')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def v1_tag_associate(request, tags, tag):
'''Associate an HTML element with a tag.
The association should be a JSON serialized object on the
request body. Here is an example association that should
make the object's structure clear:
.. code-block:: python
{
"url": "http://exam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def v1_tag_list(tags, tag=''):
'''List all direct children tags of the given parent.
If no parent is specified, then list all top-level tags.
The JSON returned for ``/dossier/v1/tags/list/foo/bar``
might look like this:
.. code-block:: python
{
'children': [
{... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def v1_tag_suggest(request, tags, prefix, parent=''):
'''Provide fast suggestions for tag components.
This yields suggestions for *components* of a tag and a given
prefix. For example, given the tags ``foo/bar/baz`` and
``fob/bob``, here are some example completions (ordering may be
different):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def v1_stream_id_associations(tags, stream_id):
'''Retrieve associations for a given stream_id.
The associations returned have the exact same structure as defined
in the ``v1_tag_associate`` route with one addition: a ``tag``
field contains the full tag name for the association.
'''
stream_id =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def v1_url_associations(tags, url):
'''Retrieve associations for a given URL.
The associations returned have the exact same structure as defined
in the ``v1_tag_associate`` route with one addition: a ``tag``
field contains the full tag name for the association.
'''
url = urllib.unquote_plus(url... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def v1_tag_associations(tags, tag):
'''Retrieve associations for a given tag.
The associations returned have the exact same structure as defined
in the ``v1_tag_associate`` route with one addition: a ``tag``
field contains the full tag name for the association.
'''
tag = tag.decode('utf-8').str... |
<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_all(self):
'''Deletes all tag data.
This does not destroy the ES index, but instead only
deletes all tags with the configured doc types.
'''
try:
self.conn.indices.delete_mapping(
index=self.index, doc_type=self.type_tag)
except Tra... |
<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_mappings(self):
'Create the field type mapping.'
created1 = self._create_tag_mapping()
created2 = self._create_assoc_mapping()
return created1 or created2 |
<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_last_traceback():
"""Retrieve the last traceback as an `unicode` string.""" |
import traceback
from StringIO import StringIO
tb = StringIO()
traceback.print_exc(file=tb)
return to_unicode(tb.getvalue()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(file_name, data):
"""Encode and write a Hip file.""" |
with open(file_name, 'w') as f:
f.write(encode(data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, thread_uuid, uuid):
""" Get one thread member.""" |
members = (v for v in self.list(thread_uuid) if v.get('userUuid') == uuid)
for i in members:
self.log.debug(i)
return i
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 delete(self, wg_uuid, uuid):
""" Delete one thread member.""" |
url = "%(base)s/%(wg_uuid)s/members/%(uuid)s" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid,
'uuid': uuid
}
return self.core.delete(url) |
<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_from_cli():
""" Perform an update instigated from a CLI. """ |
arg_parser = argparse.ArgumentParser(
description='Read and write properties in a wp-config.php file. '
'Include a --value argument to set the value, omit it to '
'read the value of the specified key.',
prog='python -m wpconfigr')
arg_parser.add_argumen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def manage_file_analysis(args: argparse.Namespace, filename: str, data: object) -> None: """ Take care of the analysis of a datafile """ |
key = DataStore.hashfile(filename)
print('Analyzing {} --> {}'.format(filename, key))
if data.check_key(key): # if exists in database, prepopulate
fit = LineFit(filename, data=data.get_data(key))
else:
fit = LineFit(filename)
if args.time:
noise, curvature, rnge, domn = fit... |
<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_args() -> argparse.Namespace: """ Get program arguments. """ |
parser = argparse.ArgumentParser(prog='python3 linefit.py',
description=('Parameterize and analyze '
'usability of conduit edge data'))
parser.add_argument('files', metavar='F', type=str, nargs='*',
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 get_keys(self) -> typing.List[str]: """ Return list of SHA512 hash keys that exist in datafile :return: list of keys """ |
keys = []
for key in self.data.keys():
if key not in ['__header__', '__version__', '__globals__']:
keys.append(key)
return 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 check_key(self, key: str) -> bool: """ Checks if key exists in datastore. True if yes, False if no. :param: SHA512 hash key :return: whether or key not exists... |
keys = self.get_keys()
return key in 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 get_traindata(self) -> np.ndarray: """ Pulls all available data and concatenates for model training :return: 2d array of points """ |
traindata = None
for key, value in self.data.items():
if key not in ['__header__', '__version__', '__globals__']:
if traindata is None:
traindata = value[np.where(value[:, 4] != 0)]
else:
traindata = np.concatenate((tra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printdata(self) -> None: """ Prints data to stdout """ |
np.set_printoptions(threshold=np.nan)
print(self.data)
np.set_printoptions(threshold=1000) |
<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, key: str, data: np.ndarray) -> None: """ Update entry in datastore """ |
self.data[key] = 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 update1(self, key: str, data: np.ndarray, size: int) -> None: """ Update one entry in specific record in datastore """ |
print(data)
if key in self.get_keys():
self.data[key][data[0]] = data
else:
newdata = np.zeros((size, 6))
newdata[data[0]] = data
self.data[key] = newdata |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hashfile(name: str) -> str: """ Gets a hash of a file using block parsing http://stackoverflow.com/questions/3431825/generating-a-md5-checksum-of-a-file Using... |
hasher = hashlib.sha512()
with open(name, 'rb') as openfile:
for chunk in iter(lambda: openfile.read(4096), b''):
hasher.update(chunk)
return hasher.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadedges(self) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray, float, np.ndarray]: """ Attempts to intelligently load the .mat file and take average of ... |
data = sco.loadmat(self.filename)
datakeys = [k for k in data.keys()
if ('right' in k) or ('left' in k) or ('edge' in k)]
averagedata = ((data[datakeys[0]] + data[datakeys[1]]) / 2)
try:
times = (data['times'] - data['times'].min())[0]
except 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 plot_file(self, name: str=None, time: int=None) -> None: """ Plot specific time for provided datafile. If no time provided, will plot middle. :param: savefile... |
if not time:
time = int(len(self.times) / 2)
if not name:
name = './img/' + self.filename + '.png'
yhat, residuals, residual_mean, noise = self._get_fit(time)
plt.figure()
plt.scatter(self.domain, self.averagedata[:, time], alpha=0.2)
plt.plot(yha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gaussian_function(self, datalength: int, values: np.ndarray, height: int, index: int) -> np.ndarray: """ i'th Regression Model Gaussian :param: len(x) :param... |
return height * np.exp(-(1 / (self.spread_number * datalength)) *
(values - ((datalength / self.function_number) * index)) ** 2) |
<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_fit(self, time: int) -> typing.Tuple[np.ndarray, np.ndarray, float, float]: """ Fit regression model to data :param: time (column of data) :return: predi... |
rawdata = self.averagedata[:, time]
domain = np.arange(len(rawdata))
datalength = len(domain)
coefficients = np.zeros((datalength, self.function_number + 2))
coefficients[:, 0] = 1
coefficients[:, 1] = domain
for i in range(self.function_number):
coef... |
<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_noise(self, residuals: np.ndarray) -> float: """ Determine Noise of Residuals. :param: residuals :return: noise """ |
return np.mean(np.abs(residuals)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze(self, time: int=None) -> typing.Tuple[float, float, int, int]: """ Determine noise, curvature, range, and domain of specified array. :param: pixel to ... |
if not time:
time = int(len(self.times) / 2)
if self.domains[time] == 0:
yhat, residuals, mean_residual, error = self._get_fit(time)
yhat_p = self.ddiff(yhat)
yhat_pp = self.ddiff(yhat_p)
noise = self._get_noise(residuals)
curvatur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze_full(self) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ Determine noise, curvature, range, and domain of specified data. Like ... |
if self.noises[0] == 0:
timelength = len(self.times)
for i in tqdm(range(timelength)):
self.analyze(time=i)
return self.noises, self.curves, self.ranges, self.domains |
<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_algo(self, args: argparse.Namespace, algo: str) -> object: """ Returns machine learning algorithm based on arguments """ |
if algo == 'nn':
return NearestNeighbor(args.nnk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_fitspace(self, name: str, X: np.ndarray, y: np.ndarray, clf: object) -> None: """ Plot 2dplane of fitspace """ |
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
h = 0.01 # Mesh step size
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def train(self, traindata: np.ndarray) -> None: """ Trains on dataset """ |
self.clf.fit(traindata[:, 1:5], traindata[:, 5]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(self, predictdata: np.ndarray) -> np.ndarray: """ predict given points """ |
return self.clf.predict(predictdata) |
<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_to(self, service_name, **kwargs):
""" Shortcut method to make instantiating the ``Connection`` classes easier. Forwards ``**kwargs`` like region, key... |
service_class = self.get_connection(service_name)
return service_class.connect_to(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, **kwargs):
""" Create a ``FormEntry`` instance and related ``FieldEntry`` instances for each form field. """ |
entry = super(FormForForm, self).save(commit=False)
entry.form = self.form
entry.entry_time = now()
entry.save()
entry_fields = entry.fields.values_list("field_id", flat=True)
new_entry_fields = []
for field in self.form_fields:
field_key = "field_%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 email_to(self):
""" Return the value entered for the first field of type ``forms.EmailField``. """ |
for field in self.form_fields:
if issubclass(fields.CLASSES[field.field_type], forms.EmailField):
return self.cleaned_data["field_%s" % field.id]
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 columns(self):
""" Returns the list of selected column names. """ |
fields = [f.label for f in self.form_fields
if self.cleaned_data["field_%s_export" % f.id]]
if self.cleaned_data["field_0_export"]:
fields.append(self.entry_time_name)
return fields |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Close the Marquise context, ensuring data is flushed and spool files are closed. This should always be closed explicitly, as there's no guara... |
if self.marquise_ctx is None:
self.__debug("Marquise handle is already closed, will do nothing.")
# Multiple close() calls are okay.
return
self.__debug("Shutting down Marquise handle spooling to %s and %s" % (self.spool_path_points, self.spool_path_contents))
... |
<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_source(self, address, metadata_dict):
"""Pack the `metadata_dict` for an `address` into a data structure and ship it to the spool file. Arguments: add... |
if self.marquise_ctx is None:
raise ValueError("Attempted to write to a closed Marquise handle.")
self.__debug("Supplied address: %s" % address)
# Sanity check the input, everything must be UTF8 strings (not
# yet confirmed), no Nonetypes or anything stupid like that.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_db_fields(self, obj):
""" Return list of database dictionaries, which are used as indexes for each attributes. Args: cached (bool, default True):
Use c... |
for field in obj.indexes:
yield field, self._zeo_key(field) |
<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_obj_properties(self, pub, name="pub"):
""" Make sure, that `pub` has the right interface. Args: pub (obj):
Instance which will be checked. name (str)... |
if not hasattr(pub, "indexes"):
raise InvalidType("`%s` doesn't have .indexes property!" % name)
if not pub.indexes:
raise InvalidType("`%s.indexes` is not set!" % name)
if not hasattr(pub, "project_key"):
raise InvalidType(
"`%s` doesn't ha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _put_into_indexes(self, obj):
""" Put publication into all indexes. Attr: obj (obj):
Indexable object. Raises: UnindexableObject: When there is no index (pr... |
no_of_used_indexes = 0
for field_name, db_index in list(self._get_db_fields(obj)):
attr_value = getattr(obj, field_name)
if attr_value is None: # index only by set attributes
continue
container = db_index.get(attr_value, None)
if contai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def store_object(self, obj):
""" Save `obj` into database and into proper indexes. Attr: obj (obj):
Indexable object. Raises: InvalidType: When the `obj` doesn'... |
self._check_obj_properties(obj)
with transaction.manager:
self._put_into_indexes(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 _get_subset_matches(self, query):
""" Yield publications, at indexes defined by `query` property values. Args: query (obj):
Object implementing proper inter... |
for field_name, db_index in self._get_db_fields(query):
attr = getattr(query, field_name)
if attr is None: # don't use unset attributes
continue
results = db_index.get(attr, OOTreeSet())
if results:
yield results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap_measure(individual_group_measure_process, group_measure, loaded_processes):
""" Creates a function on a state_collection, which creates analysis_collec... |
def wrapped_measure(state_collection,overriding_parameters=None,loggers=None):
if loggers == None:
loggers = funtool.logger.set_default_loggers()
if loaded_processes != None :
if group_measure.grouping_selectors != None:
for grouping_selector_name in group_me... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getAWSAccountID():
'''
Print an instance's AWS account number or 0 when not in EC2
'''
link = "http://169.254.169.254/latest/dynamic/instance-identity/document"
try:
conn = urllib2.urlopen(url=link, timeout=5)
except urllib2.URLError:
return '0'
jsonData = json.loads(conn.read())
return json... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readInstanceTag(instanceID, tagName="Name", connection=None):
""" Load a tag from EC2 :param str instanceID: Instance ID to read the tag on :param str tagNam... |
assert isinstance(instanceID, basestring), ("instanceID must be a string but is %r" % instanceID)
assert isinstance(tagName, basestring), ("tagName must be a string but is %r" % tagName)
if not connection:
# Assume AWS credentials are in the environment or the instance is using an IAM role
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 readMyEC2Tag(tagName, connection=None):
""" Load an EC2 tag for the running instance & print it. :param str tagName: Name of the tag to read :param connectio... |
assert isinstance(tagName, basestring), ("tagName must be a string but is %r" % tagName)
# Load metadata. if == {} we are on localhost
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
if not connection:
# Assume AWS credentials are in the environment or the instance 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 ver_to_tuple(value):
""" Convert version like string to a tuple of integers. """ |
return tuple(int(_f) for _f in re.split(r'\D+', value) if _f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def increment_name(self, name, i):
""" takes something like test.txt and returns test1.txt """ |
if i == 0:
return name
if '.' in name:
split = name.split('.')
split[-2] = split[-2] + str(i)
return '.'.join(split)
else:
return name + str(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 save_local_metadata(self):
""" save all the exposed variables to a json file """ |
# save to the set local path and add .json
with open(self.filepath + '.json', 'w+') as outfile:
json.dump(self._prep_metadata(), outfile, indent=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_forward(num_steps):
"""Moves the pen forward a few steps in the direction that its "turtle" is facing. Arguments: num_steps - a number like 20. A bigger... |
assert int(num_steps) == num_steps, "move_forward() only accepts integers, but you gave it " + str(num_steps)
_make_cnc_request("move.forward./" + str(num_steps))
state['turtle'].forward(num_steps) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, v):
"""Add a new value.""" |
self._vals_added += 1
if self._mean is None:
self._mean = v
self._mean = self._mean + ((v - self._mean) / float(self._vals_added)) |
<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_trees_by_chrom(blocks, verbose=False):
""" Construct set of interval trees from an iterable of genome alignment blocks. :return: a dictionary indexed ... |
if verbose:
sys.stderr.write("separating blocks by chromosome... ")
by_chrom = {}
for b in blocks:
if b.chrom not in by_chrom:
by_chrom[b.chrom] = []
by_chrom[b.chrom].append(b)
if verbose:
sys.stderr.write("done\n")
if verbose:
sys.stderr.write("building interval trees by chromoso... |
<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_column_absolute(self, position, miss_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS, species=None):
""" return a column from the block as dictionary index... |
if position < self.start or position >= self.end:
raise ValueError("getting column at genomic locus " + self._chrom + " " +
str(position) + " failed; locus is outside of genome " +
"alignment block")
rel_coord = self.sequence_to_alignment_coords(self.referen... |
<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_column(self, chrom, position, missing_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS, species=None):
"""Get the alignment column at the specified chromoso... |
blocks = self.get_blocks(chrom, position, position + 1)
if len(blocks) == 0:
raise NoSuchAlignmentColumnError("Request for column on chrom " +
chrom + " at position " +
str(position) + " not possible; " +
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorate_instance_methods(obj, decorator, includes=None, excludes=None):
"""Decorator instance methods of an object. :param obj: Python object whose instance... |
class InstanceMethodDecorator(object):
def __getattribute__(self, name):
value = obj.__getattribute__(name)
if excludes and name in excludes:
return value
if includes and name not in includes:
return value
if inspect.ismethod(v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reraise(clazz):
""" Decorator catching every exception that might be raised by wrapped function and raise another exception instead. Exception initially rais... |
def _decorator(f):
@functools.wraps(f)
def _wrap(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
raise clazz(e), None, sys.exc_info()[2]
return _wrap
return _decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getListOfBases():
""" This function is here mainly for purposes of unittest Returns: list of str: Valid bases as they are used as URL parameters in links at ... |
downer = Downloader()
data = downer.download(ALEPH_URL + "/F/?func=file&file_name=base-list")
dom = dhtmlparser.parseString(data.lower())
# from default aleph page filter links containing local_base in their href
base_links = filter(
lambda x: "href" in x.params and "local_base" in x.param... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def searchInAleph(base, phrase, considerSimilar, field):
""" Send request to the aleph search engine. Request itself is pretty useless, but it can be later used ... |
downer = Downloader()
if field.lower() not in VALID_ALEPH_FIELDS:
raise InvalidAlephFieldException("Unknown field '" + field + "'!")
param_url = Template(SEARCH_URL_TEMPLATE).substitute(
PHRASE=quote_plus(phrase), # urlencode phrase
BASE=base,
FIELD=field,
SIMILAR... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def downloadRecords(search_result, from_doc=1):
""" Download `MAX_RECORDS` documents from `search_result` starting from `from_doc`. Attr: search_result (dict):
... |
downer = Downloader()
if "set_number" not in search_result:
return []
# set numbers should be probably aligned to some length
set_number = str(search_result["set_number"])
if len(set_number) < 6:
set_number = (6 - len(set_number)) * "0" + set_number
# download all no_records
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDocumentIDs(aleph_search_result, number_of_docs=-1):
""" Get IDs, which can be used as parameters for other functions. Args: aleph_search_result (dict):
... |
downer = Downloader()
if "set_number" not in aleph_search_result:
return []
# set numbers should be probably aligned to some length
set_number = str(aleph_search_result["set_number"])
if len(set_number) < 6:
set_number = (6 - len(set_number)) * "0" + set_number
# limit number... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _index_item(self, uri, num, batch_num):
""" queries the triplestore for an item sends it to elasticsearch """ |
data = RdfDataset(get_all_item_data(uri, self.namespace),
uri).base_class.es_json()
self.batch_data[batch_num].append(data)
self.count += 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 share_with_org(project_ids, org, access_level, suppress_email_notification=False):
""" Shares one or more DNAnexus projects with an organization. Args: proje... |
for p in project_ids:
dxpy.api.project_invite(object_id=p,input_params={"invitee": org,"level": access_level,"suppressEmailNotification": suppress_email_notification}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_url(url):
""" Takes a URL string and returns its protocol and server """ |
# Verify that the protocol makes sense. We shouldn't guess!
if not RE_PROTOCOL_SERVER.match(url):
raise Exception("URL should begin with `protocol://domain`")
protocol, server, path, _, _, _ = urlparse.urlparse(url)
return protocol, server |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def record_event(self, event):
"""Records the ``KindleEvent`` `event` in the store """ |
with open(self._path, 'a') as file_:
file_.write(str(event) + '\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_events(self):
"""Returns a list of all ``KindleEvent``s held in the store """ |
with open(self._path, 'r') as file_:
file_lines = file_.read().splitlines()
event_lines = [line for line in file_lines if line]
events = []
for event_line in event_lines:
for event_cls in (AddEvent, SetReadingEvent, ReadEvent,
Se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self, value):
"""Set parameter name. :param str value: name value. """ |
if isinstance(value, string_types):
match = Parameter._PARAM_NAME_COMPILER_MATCHER(value)
if match is None or match.group() != value:
value = re_compile(value)
self._name = value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.