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 alloc_data(self, value):
""" Allocate a piece of data that will be included in the shellcode body. Arguments: string type. Returns: ~pwnypack.types.Offset: The offset used to address the data. """
|
if isinstance(value, six.binary_type):
return self._alloc_data(value)
elif isinstance(value, six.text_type):
return self._alloc_data(value.encode('utf-8') + b'\0')
else:
raise TypeError('No idea how to encode %s' % repr(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 compile(self, ops):
""" Translate a list of operations into its assembler source. Arguments: ops(list):
A list of shellcode operations. Returns: str: The assembler source code that implements the shellcode. """
|
def _compile():
code = []
for op in ops:
if isinstance(op, SyscallInvoke):
code.extend(self.syscall(op))
elif isinstance(op, LoadRegister):
code.extend(self.reg_load(op.register, op.value))
elif isinstance(op, str):
code.extend(op.split('\n'))
else:
raise ValueError('No idea how to assemble "%s"' % repr(op))
return ['\t%s' % line for line in code]
# We do 2 passes to make sure all data is allocated so buffers point at the right offset.
_compile()
return '\n'.join(self.finalize(self.data_finalizer(_compile(), self.data))) + '\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 assemble(self, ops):
""" Assemble a list of operations into executable code. Arguments: ops(list):
A list of shellcode operations. Returns: bytes: The executable code that implements the shellcode. """
|
return pwnypack.asm.asm(self.compile(ops), target=self.target)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_nearest_index(arr, value):
"""For a given value, the function finds the nearest value in the array and returns its index."""
|
arr = np.array(arr)
index = (abs(arr-value)).argmin()
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 kill(self):
""" Shut down the socket immediately. """
|
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_eof(self, echo=None):
""" Read until the channel is closed. Args: echo(bool):
Whether to write the read data to stdout. Returns: bytes: The read data. """
|
d = b''
while True:
try:
d += self.read(1, echo)
except EOFError:
return d
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_until(self, s, echo=None):
""" Read until a certain string is encountered.. Args: s(bytes):
The string to wait for. echo(bool):
Whether to write the read data to stdout. Returns: bytes: The data up to and including *s*. Raises: EOFError: If the channel was closed. """
|
s_len = len(s)
buf = self.read(s_len, echo)
while buf[-s_len:] != s:
buf += self.read(1, echo)
return buf
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, data, echo=None):
""" Write data to channel. Args: data(bytes):
The data to write to the channel. echo(bool):
Whether to echo the written data to stdout. Raises: EOFError: If the channel was closed before all data was sent. """
|
if echo or (echo is None and self.echo):
sys.stdout.write(data.decode('latin1'))
sys.stdout.flush()
self.channel.write(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 writeline(self, line=b'', sep=b'\n', echo=None):
""" Write a byte sequences to the channel and terminate it with carriage return and line feed. Args: line(bytes):
The line to send. sep(bytes):
The separator to use after each line. echo(bool):
Whether to echo the written data to stdout. Raises: EOFError: If the channel was closed before all data was sent. """
|
self.writelines([line], sep, echo)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interact(self):
""" Interact with the socket. This will send all keyboard input to the socket and input from the socket to the console until an EOF occurs. """
|
sockets = [sys.stdin, self.channel]
while True:
ready = select.select(sockets, [], [])[0]
if sys.stdin in ready:
line = sys.stdin.readline().encode('latin1')
if not line:
break
self.write(line)
if self.channel in ready:
self.read(1, echo=True)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_possible_importers(file_uris, current_doc=None):
""" Return all the importer objects that can handle the specified files. Possible imports may vary depending on the currently active document """
|
importers = []
for importer in IMPORTERS:
if importer.can_import(file_uris, current_doc):
importers.append(importer)
return importers
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_import(self, file_uris, current_doc=None):
""" Check that the specified file looks like a PDF """
|
if len(file_uris) <= 0:
return False
for uri in file_uris:
uri = self.fs.safe(uri)
if not self.check_file_type(uri):
return False
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_doc(self, file_uris, docsearch, current_doc=None):
""" Import the specified PDF file """
|
doc = None
docs = []
pages = []
file_uris = [self.fs.safe(uri) for uri in file_uris]
imported = []
for file_uri in file_uris:
if docsearch.is_hash_in_index(PdfDoc.hash_file(self.fs, file_uri)):
logger.info("Document %s already found in the index. Skipped"
% (file_uri))
continue
doc = PdfDoc(self.fs, docsearch.rootdir)
logger.info("Importing doc '%s' ..." % file_uri)
error = doc.import_pdf(file_uri)
if error:
raise Exception("Import of {} failed: {}".format(
file_uri, error
))
imported.append(file_uri)
docs.append(doc)
pages += [p for p in doc.pages]
return ImportResult(
imported_file_uris=imported,
select_doc=doc, new_docs=docs,
new_docs_pages=pages,
stats={
_("PDF"): len(imported),
_("Document(s)"): len(imported),
_("Page(s)"): len(pages),
}
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_import(self, file_uris, current_doc=None):
""" Check that the specified file looks like a directory containing many pdf files """
|
if len(file_uris) <= 0:
return False
try:
for file_uri in file_uris:
file_uri = self.fs.safe(file_uri)
for child in self.fs.recurse(file_uri):
if self.check_file_type(child):
return True
except GLib.GError:
pass
return False
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_import(self, file_uris, current_doc=None):
""" Check that the specified file looks like an image supported by PIL """
|
if len(file_uris) <= 0:
return False
for file_uri in file_uris:
file_uri = self.fs.safe(file_uri)
if not self.check_file_type(file_uri):
return False
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xor(key, data):
""" Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or bytes):
The key to xor ``data`` with. data(bytes):
The data to perform the xor operation on. Returns: bytes: The result of the exclusive or operation. Examples: b'DGFA' b'ABCD' b'15-=51)19=%5=9!)!%=-%!9!)-' b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' """
|
if type(key) is int:
key = six.int2byte(key)
key_len = len(key)
return b''.join(
six.int2byte(c ^ six.indexbytes(key, i % key_len))
for i, c in enumerate(six.iterbytes(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 caesar(shift, data, shift_ranges=('az', 'AZ')):
""" Apply a caesar cipher to a string. The caesar cipher is a substition cipher where each letter in the given alphabet is replaced by a letter some fixed number down the alphabet. You can define the alphabets that will be shift by specifying one or more shift ranges. The characters will than be shifted within the given ranges. Args: shift(int):
The shift to apply. data(str):
The string to apply the cipher to. shift_ranges(list of str):
Which alphabets to shift. Returns: str: The string with the caesar cipher applied. Examples: 'Fmdofqsa' 'Pwnypack' 'FMDOpack' '`g^iFqsA' """
|
alphabet = dict(
(chr(c), chr((c - s + shift) % (e - s + 1) + s))
for s, e in map(lambda r: (ord(r[0]), ord(r[-1])), shift_ranges)
for c in range(s, e + 1)
)
return ''.join(alphabet.get(c, c) for c in 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 enhex(d, separator=''):
""" Convert bytes to their hexadecimal representation, optionally joined by a given separator. Args: d(bytes):
The data to convert to hexadecimal representation. separator(str):
The separator to insert between hexadecimal tuples. Returns: str: The hexadecimal representation of ``d``. Examples: '70776e797061636b' '70 77 6e 79 70 61 63 6b' """
|
v = binascii.hexlify(d).decode('ascii')
if separator:
return separator.join(
v[i:i+2]
for i in range(0, len(v), 2)
)
else:
return 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 xor_app(parser, cmd, args):
# pragma: no cover """ Xor a value with a key. """
|
parser.add_argument(
'-d', '--dec',
help='interpret the key as a decimal integer',
dest='type',
action='store_const',
const=int
)
parser.add_argument(
'-x', '--hex',
help='interpret the key as an hexadecimal integer',
dest='type',
action='store_const',
const=lambda v: int(v, 16)
)
parser.add_argument('key', help='the key to xor the value with')
parser.add_argument('value', help='the value to xor, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
if args.type is not None:
args.key = args.type(args.key)
return xor(args.key, pwnypack.main.binary_value_or_stdin(args.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 caesar_app(parser, cmd, args):
# pragma: no cover """ Caesar crypt a value with a key. """
|
parser.add_argument('shift', type=int, help='the shift to apply')
parser.add_argument('value', help='the value to caesar crypt, read from stdin if omitted', nargs='?')
parser.add_argument(
'-s', '--shift-range',
dest='shift_ranges',
action='append',
help='specify a character range to shift (defaults to a-z, A-Z)'
)
args = parser.parse_args(args)
if not args.shift_ranges:
args.shift_ranges = ['az', 'AZ']
return caesar(args.shift, pwnypack.main.string_value_or_stdin(args.value), args.shift_ranges)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rot13_app(parser, cmd, args):
# pragma: no cover """ rot13 encrypt a value. """
|
parser.add_argument('value', help='the value to rot13, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return rot13(pwnypack.main.string_value_or_stdin(args.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 enb64_app(parser, cmd, args):
# pragma: no cover """ base64 encode a value. """
|
parser.add_argument('value', help='the value to base64 encode, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return enb64(pwnypack.main.binary_value_or_stdin(args.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 deb64_app(parser, cmd, args):
# pragma: no cover """ base64 decode a value. """
|
parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return deb64(pwnypack.main.string_value_or_stdin(args.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 enhex_app(parser, cmd, args):
# pragma: no cover """ hex encode a value. """
|
parser.add_argument('value', help='the value to hex encode, read from stdin if omitted', nargs='?')
parser.add_argument(
'--separator', '-s',
default='',
help='the separator to place between hex tuples'
)
args = parser.parse_args(args)
return enhex(pwnypack.main.binary_value_or_stdin(args.value), args.separator)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dehex_app(parser, cmd, args):
# pragma: no cover """ hex decode a value. """
|
parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return dehex(pwnypack.main.string_value_or_stdin(args.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 enurlform_app(parser, cmd, args):
# pragma: no cover """ encode a series of key=value pairs into a query string. """
|
parser.add_argument('values', help='the key=value pairs to URL encode', nargs='+')
args = parser.parse_args(args)
return enurlform(dict(v.split('=', 1) for v in args.values))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deurlform_app(parser, cmd, args):
# pragma: no cover """ decode a query string into its key value pairs. """
|
parser.add_argument('value', help='the query string to decode')
args = parser.parse_args(args)
return ' '.join('%s=%s' % (key, value) for key, values in deurlform(args.value).items() for value in values)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frequency_app(parser, cmd, args):
# pragma: no cover """ perform frequency analysis on a value. """
|
parser.add_argument('value', help='the value to analyse, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
data = frequency(six.iterbytes(pwnypack.main.binary_value_or_stdin(args.value)))
return '\n'.join(
'0x%02x (%c): %d' % (key, chr(key), value)
if key >= 32 and chr(key) in string.printable else
'0x%02x ---: %d' % (key, value)
for key, value in data.items()
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error(self, err=None):
"""Update the circuit breaker with an error event."""
|
if self.state == 'half-open':
self.test_fail_count = min(self.test_fail_count + 1, 16)
self.errors.append(self.clock())
if len(self.errors) > self.maxfail:
time = self.clock() - self.errors.pop(0)
if time < self.time_unit:
if time == 0:
time = 0.0001
self.log.debug('error rate: %f errors per second' % (
float(self.maxfail) / time))
self.open(err)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context(self, id):
"""Return a circuit breaker for the given ID."""
|
if id not in self.circuits:
self.circuits[id] = self.factory(self.clock, self.log.getChild(id),
self.error_types, self.maxfail,
self.reset_timeout,
self.time_unit,
backoff_cap=self.backoff_cap,
with_jitter=self.with_jitter)
return self.circuits[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 shell(_parser, cmd, args):
# pragma: no cover """ Start an interactive python interpreter with pwny imported globally. """
|
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
group = parser.add_mutually_exclusive_group()
group.set_defaults(shell=have_bpython and 'bpython' or (have_IPython and 'ipython' or 'python'))
if have_bpython:
group.add_argument(
'--bpython',
action='store_const',
dest='shell',
const='bpython',
help='Use the bpython interpreter'
)
if have_IPython:
group.add_argument(
'--ipython',
action='store_const',
dest='shell',
const='ipython',
help='Use the IPython interpreter'
)
group.add_argument(
'--python',
action='store_const',
dest='shell',
const='python',
help='Use the default python interpreter'
)
args = parser.parse_args(args)
import pwny
pwny_locals = dict(
(key, getattr(pwny, key))
for key in dir(pwny)
if not key.startswith('__') and not key == 'shell'
)
if args.shell == 'bpython':
from bpython import embed
embed(pwny_locals, banner=BANNER)
elif args.shell == 'ipython':
from IPython import start_ipython
start_ipython(
argv=['--ext=pwnypack.ipython_ext'],
)
else:
import code
code.interact(BANNER, local=pwny_locals)
|
<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_sequence(self):
"""Return the sorted StopTimes for this trip."""
|
return sorted(
self.stop_times(),
key=lambda x:int(x.get('stop_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 getGestureAndSegments(points):
""" Returns a list of tuples. The first item in the tuple is the directional integer, and the second item is a tuple of integers for the start and end indexes of the points that make up the stroke. """
|
strokes, strokeSegments = _identifyStrokes(points)
return list(zip(strokes, strokeSegments))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def levenshteinDistance(s1, s2):
""" Returns the Levenshtein Distance between two strings, `s1` and `s2` as an integer. http://en.wikipedia.org/wiki/Levenshtein_distance The Levenshtein Distance (aka edit distance) is how many changes (i.e. insertions, deletions, substitutions) have to be made to convert one string into another. For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits: kitten -> sitten -> sittin -> sitting """
|
singleLetterMapping = {DOWNLEFT: '1', DOWN:'2', DOWNRIGHT:'3',
LEFT:'4', RIGHT:'6',
UPLEFT:'7', UP:'8', UPRIGHT:'9'}
len1 = len([singleLetterMapping[letter] for letter in s1])
len2 = len([singleLetterMapping[letter] for letter in s2])
matrix = list(range(len1 + 1)) * (len2 + 1)
for i in range(len2 + 1):
matrix[i] = list(range(i, i + len1 + 1))
for i in range(len2):
for j in range(len1):
if s1[j] == s2[i]:
matrix[i+1][j+1] = min(matrix[i+1][j] + 1, matrix[i][j+1] + 1, matrix[i][j])
else:
matrix[i+1][j+1] = min(matrix[i+1][j] + 1, matrix[i][j+1] + 1, matrix[i][j] + 1)
return matrix[len2][len1]
|
<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_localised_form(model, form, exclude=None):
""" This is a factory function that creates a form for a model with internationalised field. The model should be decorated with the L10N decorater. """
|
newfields = {}
for localized_field in model.localized_fields:
# get the descriptor, which contains the form field
default_field_descriptor = getattr(model, localized_field)
# See if we've got overridden fields in a custom form.
if hasattr(form, 'declared_fields'):
form_field = form.declared_fields.get(
localized_field, default_field_descriptor.form_field)
else:
form_field = default_field_descriptor.form_field
# wrap the widget to show the origin of the value;
# either database, catalog or fallback.
if type(form_field.widget) is not WidgetWrapper:
form_field.widget = WidgetWrapper(form_field.widget)
newfields[localized_field] = form_field
if hasattr(form, 'Meta'):
setattr(form.Meta, 'model', model)
else:
newfields['Meta'] = type('Meta', tuple(), {'model':model})
newfields['localized_fields'] = model.localized_fields
return ModelFormMetaclass(model.__name__, (LocalisedForm, form), newfields)
|
<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, commit=True):
""" Override save method to also save the localised fields. """
|
# set the localised fields
for localized_field in self.instance.localized_fields:
setattr(self.instance, localized_field, self.cleaned_data[localized_field])
return super(LocalisedForm, self).save(commit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_unique(self):
""" Validates the uniqueness of fields, but also handles the localized_fields. """
|
form_errors = []
try:
super(LocalisedForm, self).validate_unique()
except ValidationError as e:
form_errors += e.messages
# add unique validation for the localized fields.
localized_fields_checks = self._get_localized_field_checks()
bad_fields = set()
field_errors, global_errors = self._perform_unique_localized_field_checks(localized_fields_checks)
bad_fields.union(field_errors)
form_errors.extend(global_errors)
for field_name in bad_fields:
del self.cleaned_data[field_name]
if form_errors:
# Raise the unique together errors since they are considered
# form-wide.
raise ValidationError(form_errors)
|
<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_localized_field_checks(self):
""" Get the checks we must perform for the localized fields. """
|
localized_fields_checks = []
for localized_field in self.instance.localized_fields:
if self.cleaned_data.get(localized_field) is None:
continue
f = getattr(self.instance.__class__, localized_field, None)
if f and f.unique:
if f.unique:
local_name = get_real_fieldname(localized_field, self.language)
localized_fields_checks.append((localized_field, local_name))
return localized_fields_checks
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _perform_unique_localized_field_checks(self, unique_checks):
""" Do the checks for the localized fields. """
|
bad_fields = set()
form_errors = []
for (field_name, local_field_name) in unique_checks:
lookup_kwargs = {}
lookup_value = self.cleaned_data[field_name]
# ModelChoiceField will return an object instance rather than
# a raw primary key value, so convert it to a pk value before
# using it in a lookup.
lookup_value = getattr(lookup_value, 'pk', lookup_value)
lookup_kwargs[str(local_field_name)] = lookup_value
qs = self.instance.__class__._default_manager.filter(**lookup_kwargs)
# Exclude the current object from the query if we are editing an
# instance (as opposed to creating a new one)
if self.instance.pk is not None:
qs = qs.exclude(pk=self.instance.pk)
# This cute trick with extra/values is the most efficient way to
# tell if a particular query returns any results.
if qs.extra(select={'a': 1}).values('a').order_by():
self._errors[field_name] = ErrorList([self.unique_error_message([field_name])])
bad_fields.add(field_name)
return bad_fields, form_errors
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_missing_modules():
""" look for dependency that setuptools cannot check or that are too painful to install with setuptools """
|
missing_modules = []
for module in MODULES:
try:
__import__(module[1])
except ImportError:
missing_modules.append(module)
return missing_modules
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_response(self, request, response):
""" If ``request.session was modified``, or if the configuration is to save the session every time, save the changes and set a session cookie. """
|
try:
modified = request.session.modified
except AttributeError:
pass
else:
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Save the session data and refresh the client cookie.
request.session.save()
response.set_cookie(settings.SESSION_COOKIE_NAME,
request.session.session_key, max_age=max_age,
expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None)
return response
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(cls, collection, skip=None, limit=None):
""" Returns all documents of the collection :param collection Collection instance :param skip The number of documents to skip in the query :param limit The maximal amount of documents to return. The skip is applied before the limit restriction. :returns Document list """
|
kwargs = {
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='all', collection=collection, multiple=True,
**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 update_by_example(cls, collection, example_data, new_value, keep_null=False, wait_for_sync=None, limit=None):
""" This will find all documents in the collection that match the specified example object, and partially update the document body with the new value specified. Note that document meta-attributes such as _id, _key, _from, _to etc. cannot be replaced. Note: the limit attribute is not supported on sharded collections. Using it will result in an error. Returns result dict of the request. :param collection Collection instance :param example_data An example document that all collection documents are compared against. :param new_value A document containing all the attributes to update in the found documents. :param keep_null This parameter can be used to modify the behavior when handling null values. Normally, null values are stored in the database. By setting the keepNull parameter to false, this behavior can be changed so that all attributes in data with null values will be removed from the updated document. :param wait_for_sync if set to true, then all removal operations will instantly be synchronised to disk. If this is not specified, then the collection's default sync behavior will be applied. :param limit an optional value that determines how many documents to update at most. If limit is specified but is less than the number of documents in the collection, it is undefined which of the documents will be updated. :returns dict """
|
kwargs = {
'newValue': new_value,
'options': {
'keepNull': keep_null,
'waitForSync': wait_for_sync,
'limit': limit,
}
}
return cls._construct_query(name='update-by-example',
collection=collection, example=example_data, result=False,
**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 remove_by_example(cls, collection, example_data, wait_for_sync=None, limit=None):
""" This will find all documents in the collection that match the specified example object. Note: the limit attribute is not supported on sharded collections. Using it will result in an error. The options attributes waitForSync and limit can given yet without an ecapsulation into a json object. But this may be deprecated in future versions of arango Returns result dict of the request. :param collection Collection instance :param example_data An example document that all collection documents are compared against. :param wait_for_sync if set to true, then all removal operations will instantly be synchronised to disk. If this is not specified, then the collection's default sync behavior will be applied. :param limit an optional value that determines how many documents to replace at most. If limit is specified but is less than the number of documents in the collection, it is undefined which of the documents will be replaced. """
|
kwargs = {
'options': {
'waitForSync': wait_for_sync,
'limit': limit,
}
}
return cls._construct_query(name='remove-by-example',
collection=collection, example=example_data, result=False,
**kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_by_example_hash(cls, collection, index_id, example_data, allow_multiple=False, skip=None, limit=None):
""" This will find all documents matching a given example, using the specified hash index. :param collection Collection instance :param index_id ID of the index which should be used for the query :param example_data The example document :param allow_multiple If the query can return multiple documents :param skip The number of documents to skip in the query :param limit The maximal amount of documents to return. The skip is applied before the limit restriction. :returns Single document / Document list """
|
kwargs = {
'index': index_id,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='by-example-hash',
collection=collection, example=example_data, multiple=allow_multiple,
**kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_by_example_skiplist(cls, collection, index_id, example_data, allow_multiple=True, skip=None, limit=None):
""" This will find all documents matching a given example, using the specified skiplist index. :param collection Collection instance :param index_id ID of the index which should be used for the query :param example_data The example document :param allow_multiple If the query can return multiple documents :param skip The number of documents to skip in the query :param limit The maximal amount of documents to return. The skip is applied before the limit restriction. :returns Single document / Document list """
|
kwargs = {
'index': index_id,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='by-example-skiplist',
collection=collection, example=example_data, multiple=allow_multiple,
**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 range(cls, collection, attribute, left, right, closed, index_id, skip=None, limit=None):
""" This will find all documents within a given range. In order to execute a range query, a skip-list index on the queried attribute must be present. :param collection Collection instance :param attribute The attribute path to check :param left The lower bound :param right The upper bound :param closed If true, use interval including left and right, otherwise exclude right, but include left :param index_id ID of the index which should be used for the query :param skip The number of documents to skip in the query :param limit The maximal amount of documents to return. The skip is applied before the limit restriction. :returns Document list """
|
kwargs = {
'index': index_id,
'attribute': attribute,
'left': left,
'right': right,
'closed': closed,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='range',
collection=collection, multiple=True,
**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 fulltext(cls, collection, attribute, example_text, index_id, skip=None, limit=None):
""" This will find all documents from the collection that match the fulltext query specified in query. In order to use the fulltext operator, a fulltext index must be defined for the collection and the specified attribute. :param collection Collection instance :param attribute The attribute path to check :param example_text Text which should be used to search :param index_id ID of the index which should be used for the query :param skip The number of documents to skip in the query :param limit The maximal amount of documents to return. The skip is applied before the limit restriction. :returns Document list """
|
kwargs = {
'index': index_id,
'attribute': attribute,
'query': example_text,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='fulltext',
collection=collection, multiple=True,
**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 near(cls, collection, latitude, longitude, index_id, distance=None, skip=None, limit=None):
""" The default will find at most 100 documents near the given coordinate. The returned list is sorted according to the distance, with the nearest document being first in the list. If there are near documents of equal distance, documents are chosen randomly from this set until the limit is reached. In order to use the near operator, a geo index must be defined for the collection. This index also defines which attribute holds the coordinates for the document. If you have more then one geo-spatial index, you can use the geo field to select a particular index. :param collection Collection instance :param latitude The latitude of the coordinate :param longitude The longitude of the coordinate :param index_id ID of the index which should be used for the query :param distance If given, the attribute key used to return the distance to the given coordinate. If specified, distances are returned in meters. :param skip The number of documents to skip in the query :param limit The maximal amount of documents to return. The skip is applied before the limit restriction. :returns Document list """
|
kwargs = {
'geo': index_id,
'latitude': latitude,
'longitude': longitude,
'distance': distance,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='near',
collection=collection, multiple=True,
**kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_pwm_values(self, brightness=None, color=None):
""" Get the pwm values for a specific state of the led. If a state argument is omitted, current value is used. :param brightness: The brightness of the state. :param color: The color of the state. :return: The pwm values. """
|
if brightness is None:
brightness = self.brightness
if color is None:
color = self.color
return [(x / 255) * brightness for x in self._rgb_to_rgbw(color)]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rgb_to_rgbw(color):
""" Convert a RGB color to a RGBW color. :param color: The RGB color. :return: The RGBW color. """
|
# Get the maximum between R, G, and B
max_value = max(color)
# If the maximum value is 0, immediately return pure black.
if max_value == 0:
return [0] * 4
# Figure out what the color with 100% hue is
multiplier = 255 / max_value
hue_red = color.R * multiplier
hue_green = color.G * multiplier
hue_blue = color.B * multiplier
# Calculate the whiteness (not strictly speaking luminance)
max_hue = max(hue_red, hue_green, hue_blue)
min_hue = min(hue_red, hue_green, hue_blue)
luminance = ((max_hue + min_hue) / 2 - 127.5) * 2 / multiplier
# Calculate the output values
r = max(0, min(255, int(color.R - luminance)))
g = max(0, min(255, int(color.G - luminance)))
b = max(0, min(255, int(color.B - luminance)))
w = max(0, min(255, int(luminance)))
return [r, g, b, 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 from_uri(cls, reactor, uri):
"""Return an AMQEndpoint instance configured with the given AMQP uri. @see: https://www.rabbitmq.com/uri-spec.html """
|
uri = URI.fromBytes(uri.encode(), defaultPort=5672)
kwargs = {}
host = uri.host.decode()
if "@" in host:
auth, host = uri.netloc.decode().split("@")
username, password = auth.split(":")
kwargs.update({"username": username, "password": password})
vhost = uri.path.decode()
if len(vhost) > 1:
vhost = vhost[1:] # Strip leading "/"
kwargs["vhost"] = vhost
params = parse_qs(uri.query)
kwargs.update({name.decode(): value[0].decode() for name, value in params.items()})
if "heartbeat" in kwargs:
kwargs["heartbeat"] = int(kwargs["heartbeat"])
return cls(reactor, host, uri.port, **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 _authenticate(self, client):
"""Perform AMQP authentication."""
|
yield client.authenticate(
self._username, self._password, mechanism=self._auth_mechanism)
returnValue(client)
|
<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_plain(self):
'''Create a BlockText from the captured lines and clear _text.'''
if self._text:
self._blocks.append(BlockText('\n'.join(self._text)))
self._text.clear()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step(self):
"""Apply the current stage of the transition based on current time."""
|
if self.cancelled or self.finished:
return
if not self.pwm_stages:
self._finish()
return
if self.duration == 0:
progress = 1
else:
run_time = time.time() - self._start_time
progress = max(0, min(1, run_time / self.duration))
self.stage_index = math.ceil((len(self.pwm_stages) - 1) * progress)
stage = self.pwm_stages[self.stage_index]
self._driver.set_pwm(stage)
if progress == 1:
self._finish()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _finish(self):
"""Mark transition as finished and execute callback."""
|
self.finished = True
if self._callback:
self._callback(self)
self._finish_event.set()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def send(self, message, level=Level.NOTICE):
"Send a syslog message to remote host using UDP or TCP"
data = "<%d>%s" % (level + self.facility*8, message)
if self.protocol == 'UDP':
self.socket.sendto(data.encode('utf-8'), (self.host, self.port))
else:
self.socket.send(data.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 sync(self, graph_commons):
"""Synchronize local and remote representations."""
|
if self['id'] is None:
return
remote_graph = graph_commons.graphs(self['id'])
# TODO: less forceful, more elegant
self.edges = remote_graph.edges
self.nodes = remote_graph.nodes
self.node_types = remote_graph.node_types
self.edge_types = remote_graph.edge_types
self._edges = dict((edge['id'], edge) for edge in self.edges)
self._nodes = dict((node['id'], node) for node in self.nodes)
self._node_types = dict((t['id'], t) for t in self.node_types)
self._edge_types = dict((t['id'], t) for t in self.edge_types)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, transition):
""" Queue a transition for execution. :param transition: The transition """
|
self._transitions.append(transition)
if self._thread is None or not self._thread.isAlive():
self._thread = threading.Thread(target=self._transition_loop)
self._thread.setDaemon(True)
self._thread.start()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _transition_loop(self):
"""Execute all queued transitions step by step."""
|
while self._transitions:
start = time.time()
for transition in self._transitions:
transition.step()
if transition.finished:
self._transitions.remove(transition)
time_delta = time.time() - start
sleep_time = max(0, self.MIN_STEP_TIME - time_delta)
time.sleep(sleep_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 _update_pwm(self):
"""Update the pwm values of the driver regarding the current state."""
|
if self._is_on:
values = self._get_pwm_values()
else:
values = [0] * len(self._driver.pins)
self._driver.set_pwm(values)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transition(self, duration, is_on=None, **kwargs):
""" Transition to the specified state of the led. If another transition is already running, it is aborted. :param duration: The duration of the transition. :param is_on: The on-off state to transition to. :param kwargs: The state to transition to. """
|
self._cancel_active_transition()
dest_state = self._prepare_transition(is_on, **kwargs)
total_steps = self._transition_steps(**dest_state)
state_stages = [self._transition_stage(step, total_steps, **dest_state)
for step in range(total_steps)]
pwm_stages = [self._get_pwm_values(**stage)
for stage in state_stages]
callback = partial(self._transition_callback, is_on)
self._active_transition = Transition(self._driver, duration,
state_stages, pwm_stages,
callback)
TransitionManager().execute(self._active_transition)
return self._active_transition
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _transition_callback(self, is_on, transition):
""" Callback that is called when a transition has ended. :param is_on: The on-off state to transition to. :param transition: The transition that has ended. """
|
# Update state properties
if transition.state_stages:
state = transition.state_stages[transition.stage_index]
if self.is_on and is_on is False:
# If led was turned off, set brightness to initial value
# so that the brightness is restored when it is turned on again
state['brightness'] = self.brightness
self.set(is_on=is_on, cancel_transition=False, **state)
self._active_transition = 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 _interpolate(start, end, step, total_steps):
""" Interpolate a value from start to end at a given progress. :param start: The start value. :param end: The end value. :param step: The current step. :param total_steps: The total number of steps. :return: The interpolated value at the given progress. """
|
diff = end - start
progress = step / (total_steps - 1)
return start + progress * diff
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance(cls, hostname=None, auth=None, protocol=None, port=None, database=None):
""" This method is called from everywhere in the code which accesses the database. If one of the parameters is set, these variables are overwritten for all others. """
|
if cls.class_instance is None:
if hostname is None and auth is None and protocol is None and port is None and database is None:
cls.class_instance = Client(hostname='localhost')
else:
cls.class_instance = Client(hostname=hostname, auth=auth, protocol=protocol, port=port, database=database)
else:
if hostname is not None:
cls.class_instance.hostname = hostname
if protocol is not None:
cls.class_instance.hostname = protocol
if port is not None:
cls.class_instance.hostname = port
if database is not None:
cls.class_instance.database = database
if auth is not None:
cls.class_instance.auth = auth
cls.class_instance._create_api()
return cls.class_instance
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collection(self, name):
""" Returns a collection with the given name :param name Collection name :returns Collection """
|
return Collection(
name=name,
api_resource=self.api.collection(name),
api=self.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 create(cls, name, users=None):
""" Creates database and sets itself as the active database. :param name Database name :returns Database """
|
api = Client.instance().api
database_data = {
'name': name,
'active': True,
}
if isinstance(users, list) or isinstance(users, tuple):
database_data['users'] = users
data = api.database.post(data=database_data)
db = Database(
name=name,
api=api,
kwargs=data
)
Client.instance().set_database(name=name)
return db
|
<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_all(cls):
""" Returns an array with all databases :returns Database list """
|
api = Client.instance().api
data = api.database.get()
database_names = data['result']
databases = []
for name in database_names:
db = Database(name=name, api=api)
databases.append(db)
return databases
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(cls, name):
""" Destroys the database. """
|
client = Client.instance()
new_current_database = None
if client.database != name:
new_current_database = name
# Deletions are only possible from the system database
client.set_database(name=SYSTEM_DATABASE)
api = client.api
api.database(name).delete()
if new_current_database:
client.set_database(name=new_current_database)
|
<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_collection(self, name, type=2):
""" Shortcut to create a collection :param name Collection name :param type Collection type (2 = document / 3 = edge) :returns Collection """
|
return Collection.create(name=name, database=self.name, type=type)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(cls, name):
""" Destroys collection. :param name Collection name """
|
api = Client.instance().api
api.collection(name).delete()
|
<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):
""" Updates only waitForSync and journalSize """
|
data = {
'waitForSync': self.waitForSync,
'journalSize': self.journalSize,
}
self.resource(self.name).properties.put(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):
""" Retrieves all properties again for the collection and sets the attributes. """
|
data = self.resource(self.name).properties.get()
self.set_data(**data)
return 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_figures(self):
""" Returns figures about the collection. """
|
data = self.resource(self.name).figures.get()
return data['figures']
|
<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_edge(self, from_doc, to_doc, edge_data={}):
""" Creates edge document. :param from_doc Document from which the edge comes :param to_doc Document to which the edge goes :param edge_data Extra data for the edge :returns Document """
|
return Edge.create(
collection=self,
from_doc=from_doc,
to_doc=to_doc,
edge_data=edge_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 documents(self):
""" Returns all documents of this collection. :returns Document list """
|
document_list = []
document_uri_list = self.api.document.get(collection=self.name)['documents']
for document_uri in document_uri_list:
splitted_uri = document_uri.split('/')
document_key = splitted_uri[-1]
document_id = "%s/%s" % (self.name, document_key)
doc = Document(
id=document_id,
key=document_key,
collection=self,
api=self.api
)
document_list.append(doc)
return document_list
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, collection):
""" Creates document object without really creating it in the collection. :param collection Collection instance :returns Document """
|
api = Client.instance().api
doc = Document(
id='',
key='',
collection=collection.name,
api=api,
)
return doc
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve(self):
""" Retrieves all data for this document and saves it. """
|
data = self.resource(self.id).get()
self.data = data
return 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 save(self):
""" If its internal state is loaded than it will only updated the set properties but otherwise it will create a new document. """
|
# TODO: Add option force_insert
if not self.is_loaded and self.id is None or self.id == '':
data = self.resource.post(data=self.data, collection=self.collection)
self.id = data['_id']
self.key = data['_key']
self.revision = data['_rev']
self.is_loaded = True
else:
data = self.resource(self.id).patch(data=self.data)
self.revision = data['_rev']
|
<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, key):
""" Returns attribute value. :param key :returns value """
|
if not self.is_loaded:
self.retrieve()
self.is_loaded = True
if self.has(key=key):
return self.data[key]
else:
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 _to_raw_pwm(self, values):
""" Convert uniform pwm values to raw, driver-specific values. :param values: The uniform pwm values (0.0-1.0). :return: Converted, driver-specific pwm values. """
|
return [self._to_single_raw_pwm(values[i])
for i in range(len(self._pins))]
|
<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_uniform_pwm(self, values):
""" Convert raw pwm values to uniform values. :param values: The raw pwm values. :return: Converted, uniform pwm values (0.0-1.0). """
|
return [self._to_single_uniform_pwm(values[i])
for i in range(len(self._pins))]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def steps(self, start, end):
""" Get the maximum number of steps the driver needs for a transition. :param start: The start value as uniform pwm value (0.0-1.0). :param end: The end value as uniform pwm value (0.0-1.0). :return: The maximum number of steps. """
|
if not 0 <= start <= 1:
raise ValueError('Values must be between 0 and 1.')
if not 0 <= end <= 1:
raise ValueError('Values must be between 0 and 1.')
raw_start = self._to_single_raw_pwm(start)
raw_end = self._to_single_raw_pwm(end)
return abs(raw_start - raw_end)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def numa_nodemask_to_set(mask):
""" Convert NUMA nodemask to Python set. """
|
result = set()
for i in range(0, get_max_node() + 1):
if __nodemask_isset(mask, i):
result.add(i)
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 set_to_numa_nodemask(mask):
""" Conver Python set to NUMA nodemask. """
|
result = nodemask_t()
__nodemask_zero(result)
for i in range(0, get_max_node() + 1):
if i in mask:
__nodemask_set(result, i)
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 get_interleave_mask():
""" Get interleave mask for current thread. @return: node mask @rtype: C{set} """
|
nodemask = nodemask_t()
bitmask = libnuma.numa_get_interleave_mask()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bitmask)
return numa_nodemask_to_set(nodemask)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind(nodemask):
""" Binds the current thread and its children to the nodes specified in nodemask. They will only run on the CPUs of the specified nodes and only be able to allocate memory from them. @param nodemask: node mask @type nodemask: C{set} """
|
mask = set_to_numa_nodemask(nodemask)
bitmask = libnuma.numa_allocate_nodemask()
libnuma.copy_nodemask_to_bitmask(byref(mask), bitmask)
libnuma.numa_bind(bitmask)
libnuma.numa_bitmask_free(bitmask)
|
<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_preferred(node):
""" Sets the preferred node for the current thread to node. The preferred node is the node on which memory is preferably allocated before falling back to other nodes. The default is to use the node on which the process is currently running (local policy). @param node: node idx @type node: C{int} """
|
if node < 0 or node > get_max_node():
raise ValueError(node)
libnuma.numa_set_preferred(node)
|
<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_membind(nodemask):
""" Sets the memory allocation mask. The thread will only allocate memory from the nodes set in nodemask. @param nodemask: node mask @type nodemask: C{set} """
|
mask = set_to_numa_nodemask(nodemask)
tmp = bitmask_t()
tmp.maskp = cast(byref(mask), POINTER(c_ulong))
tmp.size = sizeof(nodemask_t) * 8
libnuma.numa_set_membind(byref(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_membind():
""" Returns the mask of nodes from which memory can currently be allocated. @return: node mask @rtype: C{set} """
|
bitmask = libnuma.numa_get_membind()
nodemask = nodemask_t()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bitmask)
return numa_nodemask_to_set(nodemask)
|
<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_run_on_node_mask(nodemask):
""" Runs the current thread and its children only on nodes specified in nodemask. They will not migrate to CPUs of other nodes until the node affinity is reset with a new call to L{set_run_on_node_mask}. @param nodemask: node mask @type nodemask: C{set} """
|
mask = set_to_numa_nodemask(nodemask)
tmp = bitmask_t()
tmp.maskp = cast(byref(mask), POINTER(c_ulong))
tmp.size = sizeof(nodemask_t) * 8
if libnuma.numa_run_on_node_mask(byref(tmp)) < 0:
raise RuntimeError()
|
<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_run_on_node_mask():
""" Returns the mask of nodes that the current thread is allowed to run on. @return: node mask @rtype: C{set} """
|
bitmask = libnuma.numa_get_run_node_mask()
nodemask = nodemask_t()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bitmask)
return numa_nodemask_to_set(nodemask)
|
<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_distance(node1, node2):
""" Reports the distance in the machine topology between two nodes. The factors are a multiple of 10. It returns 0 when the distance cannot be determined. A node has distance 10 to itself. Reporting the distance requires a Linux kernel version of 2.6.10 or newer. @param node1: node idx @type node1: C{int} @param node2: node idx @type node2: C{int} @rtype: C{int} """
|
if node1 < 0 or node1 > get_max_node():
raise ValueError(node1)
if node2 < 0 or node2 > get_max_node():
raise ValueError(node2)
return libnuma.numa_distance(node1, node2)
|
<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_affinity(pid):
""" Returns the affinity mask of the process whose ID is pid. @param pid: process PID (0 == current process) @type pid: C{int} @return: set of CPU ids @rtype: C{set} """
|
cpuset = cpu_set_t()
result = set()
libnuma.sched_getaffinity(pid, sizeof(cpu_set_t), byref(cpuset))
for i in range(0, sizeof(cpu_set_t)*8):
if __CPU_ISSET(i, cpuset):
result.add(i)
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 set_affinity(pid, cpuset):
""" Sets the CPU affinity mask of the process whose ID is pid to the value specified by mask. If pid is zero, then the calling process is used. @param pid: process PID (0 == current process) @type pid: C{int} @param cpuset: set of CPU ids @type cpuset: C{set} """
|
_cpuset = cpu_set_t()
__CPU_ZERO(_cpuset)
for i in cpuset:
if i in range(0, sizeof(cpu_set_t) * 8):
__CPU_SET(i, _cpuset)
if libnuma.sched_setaffinity(pid, sizeof(cpu_set_t), byref(_cpuset)) < 0:
raise RuntimeError()
|
<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, namespace):
'''Render template lines.
Note: we only need to parse the namespace if we used variables in
this part of the template.
'''
return self._text.format_map(namespace.dictionary) \
if self._need_format else self._text
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _assert_is_color(value):
""" Assert that the given value is a valid brightness. :param value: The value to check. """
|
if not isinstance(value, tuple) or len(value) != 3:
raise ValueError("Color must be a RGB tuple.")
if not all(0 <= x <= 255 for x in value):
raise ValueError("RGB values of color must be between 0 and 255.")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(cls, id):
""" Deletes an index with id :param id string/document-handle """
|
api = Client.instance().api
api.index(id).delete()
|
<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):
""" Creates this index in the collection if it hasn't been already created """
|
api = Client.instance().api
index_details = {
'type': self.index_type_obj.type_name
}
extra_index_attributes = self.index_type_obj.get_extra_attributes()
for extra_attribute_key in extra_index_attributes:
extra_attribute_value = extra_index_attributes[extra_attribute_key]
index_details[extra_attribute_key] = extra_attribute_value
query_parameters = {
'collection': self.collection.name,
}
result = api.index.post(data=index_details, **query_parameters)
self.index_type_obj.is_new = result['isNewlyCreated']
self.index_type_obj.id = result['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 _compile(cls, lines):
'''Return macro or block name from the current line.'''
m = cls.RE_PASTE.match(lines.current)
if m is None:
raise MacroBlockUsageError(
'Incorrect macro or block usage at line {}, {}\nShould be '
'something like: #my_macro'.format(lines.pos, lines.current))
return m.group(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.