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 synced(func):
'''
Decorator for functions that should be called synchronously from another thread
:param func: function to call
'''
def wrapper(self, *args, **kwargs):
'''
Actual wrapper for the synchronous function
'''
task = DataManagerTask(func, *args, **kwargs)
self.submit_task(task)
return task.get_results()
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def execute(self, dataman):
'''
run the task
:type dataman: :class:`~kitty.data.data_manager.DataManager`
:param dataman: the executing data manager
'''
self._event.clear()
try:
self._result = self._task(dataman, *self._args)
#
# We are going to re-throw this exception from get_results,
# so we are doing such a general eception handling at the point.
# however, we do want to print it here as well
#
except Exception as ex: # pylint: disable=W0703
self._exception = ex
KittyObject.get_logger().error(traceback.format_exc())
self._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 open(self):
'''
open the database
'''
self._connection = sqlite3.connect(self._dbname)
self._cursor = self._connection.cursor()
self._session_info = SessionInfoTable(self._connection, self._cursor)
self._reports = ReportsTable(self._connection, self._cursor) |
<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(self, key, data):
'''
set arbitrary data by key in volatile memory
:param key: key of the data
:param data: data to be stored
'''
if isinstance(data, dict):
self._volatile_data[key] = {k: v for (k, v) in data.items()}
else:
self._volatile_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 row_to_dict(self, row):
'''
translate a row of the current table to dictionary
:param row: a row of the current table (selected with \\*)
:return: dictionary of all fields
'''
res = {}
for i in range(len(self._fields)):
res[self._fields[i][0]] = row[i]
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self, test_id):
'''
get report by the test id
:param test_id: test id
:return: Report object
'''
self.select('*', 'test_id=?', [test_id])
row = self._cursor.fetchone()
if not row:
raise KeyError('No report with test id %s in the DB' % test_id)
values = self.row_to_dict(row)
content = self._deserialize_dict(values['content'])
return Report.from_dict(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _serialize_dict(cls, data):
'''
serializes a dictionary
:param data: data to serialize
'''
return b64encode(zlib.compress(cPickle.dumps(data, protocol=2))).decode() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _deserialize_dict(cls, data):
'''
deserializes a dictionary
:param data: data to deserialize
'''
return cPickle.loads(zlib.decompress(b64decode(data.encode()))) |
<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_sequence(self, sequence):
'''
Run a single sequence
'''
self._check_pause()
self._pre_test()
session_data = self.target.get_session_data()
self._test_info()
resp = None
for edge in sequence:
if edge.callback:
edge.callback(self, edge, resp)
session_data = self.target.get_session_data()
node = edge.dst
node.set_session_data(session_data)
resp = self._transmit(node)
return self._post_test() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _transmit(self, node):
'''
Transmit node data to target.
:type node: Template
:param node: node to transmit
:return: response if there is any
'''
payload = node.render().tobytes()
self._last_payload = payload
try:
return self.target.transmit(payload)
except Exception as e:
self.logger.error('Error in transmit: %s', e)
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _generate_rpc_method(self, method):
'''
Generate a function that performs rpc call
:param method: method name
:return: rpc function
'''
def _(**kwargs):
'''
always use named arguments
'''
msg_id = self.get_unique_msg_id()
params = encode_data(kwargs)
payload = {
'method': method,
'params': params,
'jsonrpc': '2.0',
'id': msg_id
}
response = requests.post(self.url, data=json.dumps(payload), headers=self.headers).json()
if ('error' in response):
if response['error']['code'] == JSONRPC_NO_RESULT:
return None
raise Exception('Got error from RPC server when called "%s" error: %s' % (method, response['error']))
if 'result' in response:
result = decode_data(response['result'])
return result
return _ |
<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_request(self):
'''
Parse the request
'''
self.req_method = 'unknown'
self.req_params = {}
self.req_rpc_version = '2.0'
self.req_id = 0
self.data = self.rfile.read(int(self.headers.get('content-length')))
data_dict = json.loads(self.data)
self.req_method = data_dict['method']
self.req_params = decode_data(data_dict['params'])
self.req_rpc_version = data_dict['jsonrpc']
self.req_id = data_dict['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 send_result(self, additional_dict):
'''
Send a result to the RPC client
:param additional_dict: the dictionary with the response
'''
self.send_response(200)
self.send_header("Content-type", "application/json")
response = {
'jsonrpc': self.req_rpc_version,
'id': self.req_id,
}
response.update(additional_dict)
jresponse = json.dumps(response)
self.send_header("Content-length", len(jresponse))
self.end_headers()
self.wfile.write(jresponse.encode()) |
<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_current_value(self, value):
'''
Sets the current value of the field
:param value: value to set
:return: rendered value
'''
self._current_value = value
self._current_rendered = self._encode_value(self._current_value)
return self._current_rendered |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mutate(self):
'''
Mutate the field
:rtype: boolean
:return: True if field the mutated
'''
self._initialize()
if self._exhausted():
return False
self._current_index += 1
self._mutate()
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 render(self, ctx=None):
'''
Render the current value of the field
:rtype: Bits
:return: rendered value
'''
self._initialize()
if not self.is_default():
self._current_rendered = self._encode_value(self._current_value)
return self._current_rendered |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reset(self):
'''
Reset the field to its default state
'''
self._current_index = -1
self._current_value = self._default_value
self._current_rendered = self._default_rendered
self.offset = 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 resolve_field(self, field):
'''
Resolve a field from name
:param field: name of the field to resolve
:rtype: BaseField
:return: the resolved field
:raises: KittyException if field could not be resolved
'''
if isinstance(field, BaseField):
return field
name = field
if name.startswith('/'):
return self.resolve_absolute_name(name)
resolved_field = self.scan_for_field(name)
if not resolved_field:
container = self.enclosing
if container:
resolved_field = container.resolve_field(name)
if not resolved_field:
raise KittyException('Could not resolve field by name (%s)' % name)
return resolved_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 stop(self):
'''
stop the thread, return after thread stopped
'''
self._stop_event.set()
if self._func_stop_event is not None:
self._func_stop_event.set()
self.join(timeout=1)
if self.isAlive():
print('Failed to stop thread') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _initialize(self):
'''
We override _initialize, as we want to resolve the field each time
'''
if self._field_name:
self._field = self.resolve_field(self._field_name)
if not self._field:
raise KittyException('Could not resolve field name %s' % self._field_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _calculate(self, field):
'''
We want to avoid trouble, so if the field is not enclosed by any other field,
we just return 0.
'''
encloser = field.enclosing
if encloser:
rendered = encloser.get_rendered_fields(RenderContext(self))
if field not in rendered:
value = len(rendered)
else:
value = rendered.index(field)
else:
value = 0
return 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 _calculate(self, field):
'''
If the offset is unknown, return 0
'''
base_offset = 0
if self.base_field is not None:
base_offset = self.base_field.offset
target_offset = self._field.offset
if (target_offset is None) or (base_offset is None):
return 0
return target_offset - base_offset |
<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_report(self):
'''
need to wrap get_report, since we need to parse the report
'''
report_dict = self._meta_get_report()
report = Report.from_dict(report_dict)
return report |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setup(self):
'''
Make sure the target is ready for fuzzing, including monitors and
controllers
'''
if self.controller:
self.controller.setup()
for monitor in self.monitors:
monitor.setup() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def teardown(self):
'''
Clean up the target once all tests are completed
'''
if self.controller:
self.controller.teardown()
for monitor in self.monitors:
monitor.teardown() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stop(self):
'''
Stop the fuzzing session
'''
self.logger.info('Stopping client fuzzer')
self._target_control_thread.stop()
self.target.signal_mutated()
super(ClientFuzzer, self).stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _should_fuzz_node(self, fuzz_node, stage):
'''
The matching stage is either the name of the last node, or ClientFuzzer.STAGE_ANY.
:return: True if we are in the correct model node
'''
if stage == ClientFuzzer.STAGE_ANY:
return True
if fuzz_node.name.lower() == stage.lower():
if self._index_in_path == len(self._fuzz_path) - 1:
return True
else:
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 get_mutation(self, stage, data):
'''
Get the next mutation, if in the correct stage
:param stage: current stage of the stack
:param data: a dictionary of items to pass to the model
:return: mutated payload if in apropriate stage, None otherwise
'''
payload = None
# Commented out for now: we want to return the same
# payload - while inside the same test
# if self._keep_running() and self._do_fuzz.is_set():
if self._keep_running():
fuzz_node = self._fuzz_path[self._index_in_path].dst
if self._should_fuzz_node(fuzz_node, stage):
fuzz_node.set_session_data(data)
payload = fuzz_node.render().tobytes()
self._last_payload = payload
else:
self._update_path_index(stage)
if payload:
self._notify_mutated()
self._requested_stages.append((stage, payload))
return payload |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def SInt64(value, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False):
'''Signed 64-bit field'''
return BitField(value, 64, signed=True, min_value=min_value, max_value=max_value, encoder=encoder, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def BE8(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''8-bit field, Big endian encoded'''
return UInt8(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def BE16(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''16-bit field, Big endian encoded'''
return UInt16(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def BE32(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''32-bit field, Big endian encoded'''
return UInt32(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def BE64(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''64-bit field, Big endian encoded'''
return UInt64(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def LE8(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''8-bit field, Little endian encoded'''
return UInt8(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def LE16(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''16-bit field, Little endian encoded'''
return UInt16(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def LE32(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''32-bit field, Little endian encoded'''
return UInt32(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def LE64(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''64-bit field, Little endian encoded'''
return UInt64(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eintr_retry(func, *args):
"""restart a system call interrupted by EINTR""" |
while True:
try:
return func(*args)
except (OSError, select.error) as e:
if e.args[0] != errno.EINTR:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serve_forever(self, poll_interval=0.5):
""" Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ |
self.__is_shut_down.clear()
try:
while not self.__shutdown_request:
r, w, e = _eintr_retry(select.select, [self], [], [], poll_interval)
if self in r:
self._handle_request_noblock()
finally:
self.__shutdown_request = False
self.__is_shut_down.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 _handle_request_noblock(self):
""" Handle one request, without blocking. """ |
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except:
self.handle_error(request, client_address)
self.shutdown_request(request) |
<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_request(self, request, client_address):
""" Call finish_request. """ |
self.finish_request(request, client_address)
self.shutdown_request(request) |
<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_request_thread(self, request, client_address):
""" Process the request. """ |
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
except Exception as e:
self.logger.error(e)
self.handle_error(request, client_address)
self.shutdown_request(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_error(self, request, client_address):
""" Add self.stop to make server stop """ |
self.logger.error('-' * 40)
self.logger.error('Exception happened during processing of request from %s:%s' % (client_address[0], client_address[1]))
self.logger.error(traceback.format_exc())
self.logger.error('-' * 40)
self.stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _restart_target(self):
""" Restart our Target. """ |
if self._server:
if self._server.returncode is None:
self._server.kill()
time.sleep(0.2)
self._server = subprocess.Popen("python session_server.py", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
time.sleep(0.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 clear(self):
'''
Set the report to its defaults.
This will clear the report, keeping only the name and setting the
failure status to the default.
'''
self._data_fields = {}
self._sub_reports = {}
self.set_status(Report.FAILED if self._default_failed else Report.PASSED)
self.add('name', self._name)
self.add('sub_reports', []) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def passed(self):
'''
Set the report status to PASSED
'''
self.set_status(Report.PASSED)
if 'reason' in self._data_fields:
del self._data_fields['reason'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def failed(self, reason=None):
'''
Set the test status to Report.FAILED, and set the failure reason
:param reason: failure reason (default: None)
'''
self.set_status(Report.FAILED)
if reason:
self.add('reason', reason) |
<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, reason=None):
'''
Set the test status to Report.ERROR, and set the error reason
:param reason: error reason (default: None)
'''
self.set_status(Report.ERROR)
if reason:
self.add('reason', reason) |
<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_status(self, new_status):
'''
Set the status of the report.
:param new_status: the new status of the report (either PASSED, FAILED or ERROR)
'''
if new_status not in Report.allowed_statuses:
raise Exception('status must be one of: %s' % (', '.join(Report.allowed_statuses)))
self._data_fields['status'] = new_status.lower() |
<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, key, value):
'''
Add an entry to the report
:param key: entry's key
:param value: the actual value
:example:
::
my_report.add('retry count', 3)
'''
if key in self.reserved_keys:
raise Exception('You cannot add the key %s directly, use %s' % (key, self.reserved_keys[key]))
if isinstance(value, Report):
self._sub_reports[key] = value
self._data_fields['sub_reports'].append(key)
else:
self._data_fields[key] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self, key):
'''
Get a value for a given key
:param key: entry's key
:return: corresponding value
'''
if key in self._data_fields:
return self._data_fields[key]
if key in self._sub_reports:
return self._sub_reports[key]
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_dict(self, encoding='base64'):
'''
Return a dictionary version of the report
:param encoding: required encoding for the string values (default: 'base64')
:rtype: dictionary
:return: dictionary representation of the report
'''
res = {}
for k, v in self._data_fields.items():
if isinstance(v, (bytes, bytearray, six.string_types)):
v = StrEncodeEncoder(encoding).encode(v).tobytes().decode()
res[k] = v
for k, v in self._sub_reports.items():
res[k] = v.to_dict(encoding)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_dict(cls, d, encoding='base64'):
'''
Construct a ``Report`` object from dictionary.
:type d: dictionary
:param d: dictionary representing the report
:param encoding: encoding of strings in the dictionary (default: 'base64')
:return: Report object
'''
report = Report(Report._decode(d['name'], encoding))
report.set_status(Report._decode(d['status'], encoding))
sub_reports = Report._decode(d['sub_reports'], encoding)
del d['sub_reports']
for k, v in d.items():
if k in sub_reports:
report.add(k, Report.from_dict(v))
else:
if k.lower() == 'status':
report.set_status(Report._decode(v, encoding))
else:
report.add(k, Report._decode(v, encoding))
return report |
<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_status(self):
'''
Get the status of the report and its sub-reports.
:rtype: str
:return: report status ('passed', 'failed' or 'error')
'''
status = self.get('status')
if status == Report.PASSED:
for sr_name in self._sub_reports:
sr = self._sub_reports[sr_name]
sr_status = sr.get_status()
reason = sr.get('reason')
if sr_status == Report.ERROR:
self.error(reason)
break
if sr_status == Report.FAILED:
self.failed(reason)
break
status = self.get('status')
return status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setup(self):
'''
Make sure the monitor is ready for fuzzing
'''
super(BaseMonitor, self).setup()
self.monitor_thread = LoopFuncThread(self._monitor_func)
self.monitor_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 teardown(self):
'''
cleanup the monitor data and
'''
self.monitor_thread.stop()
self.monitor_thread = None
super(BaseMonitor, self).teardown() |
<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_offset(self, offset):
'''
Set the absolute offset of current field,
if the field should have default value,
set the offset of the sub fields as well.
:param offset: absolute offset of this field (in bits)
'''
super(Container, self).set_offset(offset)
if self.is_default():
for field in self._fields:
field.set_offset(offset)
offset += len(field._current_rendered) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scan_for_field(self, field_key):
'''
Scan for a field in the container and its enclosed fields
:param field_key: name of field to look for
:return: field with name that matches field_key, None if not found
'''
if field_key == self.get_name():
return self
if field_key in self._fields_dict:
return self._fields_dict[field_key]
for field in self._fields:
if isinstance(field, Container):
resolved = field.scan_for_field(field_key)
if resolved:
return resolved
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 set_session_data(self, session_data):
'''
Set session data in the container enclosed fields
:param session_data: dictionary of session data
'''
if session_data:
for field in self._fields:
if isinstance(field, (Container, Dynamic)):
field.set_session_data(session_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 is_default(self):
'''
Checks if the field is in its default form
:return: True if field is in default form
'''
for field in self._fields:
if not field.is_default():
return False
return super(Container, self).is_default() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _mutate(self):
'''
Mutate enclosed fields
'''
for i in range(self._field_idx, len(self._fields)):
self._field_idx = i
if self._current_field().mutate():
return True
self._current_field().reset()
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 append_fields(self, new_fields):
'''
Add fields to the container
:param new_fields: fields to append
'''
for field in new_fields:
self.push(field)
if isinstance(field, Container):
self.pop() |
<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_info(self):
'''
Get info regarding the current fuzzed enclosed node
:return: info dictionary
'''
field = self._current_field()
if field:
info = field.get_info()
info['path'] = '%s/%s' % (self.name if self.name else '<no name>', info['path'])
else:
info = super(Container, self).get_info()
return info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pop(self):
'''
Remove a the top container from the container stack
'''
if not self._containers:
raise KittyException('no container to pop')
self._containers.pop()
if self._container():
self._container().pop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def copy(self):
'''
Copy the container, put an invalidated copy of the condition in the new container
'''
dup = super(Conditional, self).copy()
condition = self._condition.copy()
condition.invalidate(self)
dup._condition = condition
return dup |
<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, ctx=None):
'''
Only render if condition applies
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container
'''
if ctx is None:
ctx = RenderContext()
self._initialize()
if self in ctx:
self._current_rendered = self._in_render_value()
else:
ctx.push(self)
if self._evaluate_condition(ctx):
super(Conditional, self).render(ctx)
else:
self.set_current_value(empty_bits)
ctx.pop()
return self._current_rendered |
<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_times(self, min_times, max_times, step):
'''
Make sure that the arguments are valid
:raises: KittyException if not valid
'''
kassert.is_int(min_times)
kassert.is_int(max_times)
kassert.is_int(step)
if not((min_times >= 0) and (max_times > 0) and (max_times >= min_times) and (step > 0)):
raise KittyException('one of the checks failed: min_times(%d)>=0, max_times(%d)>0, max_times>=min_times, step > 0' % (min_times, max_times)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _rebuild_fields(self):
'''
We take the original fields and create subsets of them, each subset will be set into a container.
all the resulted containers will then replace the original _fields, since we inherit from OneOf each time only one of them will be mutated and used.
This is super ugly and dangerous, any idea how to implement it in a better way is welcome.
'''
# generate new lists
new_field_lists = []
field_list_len = self.min_elements
while not field_list_len > self.max_elements:
how_many = self.max_elements + 1 - field_list_len
i = 0
while i < how_many:
current = self.random.sample(self._fields, field_list_len)
if current not in new_field_lists:
new_field_lists.append(current)
i += 1
field_list_len += 1
# put each list in a container
new_containers = []
for i, fields in enumerate(new_field_lists):
# self.logger.info(fields)
dup_fields = [field.copy() for field in fields]
if self.get_name():
name = '%s_sublist_%d' % (self.get_name(), i)
else:
name = 'sublist_%d' % (i)
new_containers.append(Container(fields=dup_fields, encoder=self.subcontainer_encoder, name=name))
self.replace_fields(new_containers) |
<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_info(self):
'''
Get info regarding the current template state
:return: info dictionary
'''
self.render()
info = super(Template, self).get_info()
res = {}
res['name'] = self.get_name()
res['mutation'] = {
'current_index': self._current_index,
'total_number': self.num_mutations()
}
res['value'] = {
'rendered': {
'base64': b64encode(self._current_rendered.tobytes()).decode(),
'length_in_bytes': len(self._current_rendered.tobytes()),
}
}
res['hash'] = self.hash()
res['field'] = info
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def applies(self, container, ctx):
'''
Subclasses should not override `applies`, but instead they should override `_applies`, which has the same syntax as `applies`.
In the `_applies` method the condition is guaranteed to have a reference to the desired field, as `self._field`.
:type container: :class:`~kitty.model.low_level.container.Container`
:param container: the caller
:param ctx: rendering context in which applies was called
:return: True if condition applies, False otherwise
'''
self._get_ready(container)
return self._applies(container, ctx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_keypair(keysize, id, output):
"""Generate a paillier private key. Output as JWK to given output file. Use "-" to output the private key to stdout. See the extract command to extract the public component of the private key. Note: The default ID text includes the current time. """ |
log("Generating a paillier keypair with keysize of {}".format(keysize))
pub, priv = phe.generate_paillier_keypair(n_length=keysize)
log("Keys generated")
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
jwk_public = {
'kty': "DAJ",
'alg': "PAI-GN1",
"key_ops": ["encrypt"],
'n': phe.util.int_to_base64(pub.n),
'kid': "Paillier public key generated by pheutil on {}".format(date)
}
jwk_private = {
'kty': "DAJ",
'key_ops': ["decrypt"],
'p': phe.util.int_to_base64(priv.p),
'q': phe.util.int_to_base64(priv.q),
'pub': jwk_public,
'kid': "Paillier private key generated by pheutil on {}".format(date)
}
json.dump(jwk_private, output)
output.write('\n')
log("Private key written to {}".format(output.name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract(input, output):
"""Extract public key from private key. Given INPUT a private paillier key file as generated by generate, extract the public key portion to OUTPUT. Use "-" to output to stdout. """ |
log("Loading paillier keypair")
priv = json.load(input)
error_msg = "Invalid private key"
assert 'pub' in priv, error_msg
assert priv['kty'] == 'DAJ', error_msg
json.dump(priv['pub'], output)
output.write('\n')
log("Public key written to {}".format(output.name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt(public, plaintext, output=None):
"""Encrypt a number with public key. The PLAINTEXT input will be interpreted as a floating point number. Output will be a JSON object with a "v" attribute containing the ciphertext as a string, and "e" the exponent as a Number, where possible fixed at -32. Note if you are passing a negative number to encrypt, you will need to include a "--" between the public key and your plaintext. """ |
num = float(plaintext)
log("Loading public key")
publickeydata = json.load(public)
pub = load_public_key(publickeydata)
log("Encrypting: {:+.16f}".format(num))
enc = pub.encrypt(num)
serialised = serialise_encrypted(enc)
print(serialised, file=output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(private, ciphertext, output):
"""Decrypt ciphertext with private key. Requires PRIVATE key file and the CIPHERTEXT encrypted with the corresponding public key. """ |
privatekeydata = json.load(private)
assert 'pub' in privatekeydata
pub = load_public_key(privatekeydata['pub'])
log("Loading private key")
private_key_error = "Invalid private key"
assert 'key_ops' in privatekeydata, private_key_error
assert "decrypt" in privatekeydata['key_ops'], private_key_error
assert 'p' in privatekeydata, private_key_error
assert 'q' in privatekeydata, private_key_error
assert privatekeydata['kty'] == 'DAJ', private_key_error
_p = phe.util.base64_to_int(privatekeydata['p'])
_q = phe.util.base64_to_int(privatekeydata['q'])
private_key = phe.PaillierPrivateKey(pub, _p, _q)
log("Decrypting ciphertext")
enc = load_encrypted_number(ciphertext, pub)
out = private_key.decrypt(enc)
print(out, file=output) |
<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_encrypted(public, encrypted_a, encrypted_b, output):
"""Add two encrypted numbers together. """ |
log("Loading public key")
publickeydata = json.load(public)
pub = load_public_key(publickeydata)
log("Loading first encrypted number")
enc_a = load_encrypted_number(encrypted_a, pub)
log("Loading second encrypted number")
enc_b = load_encrypted_number(encrypted_b, pub)
log("Adding encrypted numbers together")
enc_result = enc_a + enc_b
serialised_result = serialise_encrypted(enc_result)
print(serialised_result, file=output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multiply_encrypted_to_plaintext(public, encrypted, plaintext, output):
"""Multiply encrypted num with unencrypted num. Requires a PUBLIC key file, a number ENCRYPTED with that public key also as a file, and the PLAINTEXT number to multiply. Creates a new encrypted number. """ |
log("Loading public key")
publickeydata = json.load(public)
pub = load_public_key(publickeydata)
log("Loading encrypted number")
enc = load_encrypted_number(encrypted, pub)
log("Loading unencrypted number")
num = float(plaintext)
log("Multiplying")
enc_result = enc * num
serialised_result = serialise_encrypted(enc_result)
print(serialised_result, file=output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypted_score(self, x):
"""Compute the score of `x` by multiplying with the encrypted model, which is a vector of `paillier.EncryptedNumber`""" |
score = self.intercept
_, idx = x.nonzero()
for i in idx:
score += x[0, i] * self.weights[i]
return score |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, n_iter, eta=0.01):
"""Linear regression for n_iter""" |
for _ in range(n_iter):
gradient = self.compute_gradient()
self.gradient_step(gradient, eta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_gradient(self):
"""Compute the gradient of the current model using the training set """ |
delta = self.predict(self.X) - self.y
return delta.dot(self.X) / len(self.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 encrypted_gradient(self, sum_to=None):
"""Compute and encrypt gradient. When `sum_to` is given, sum the encrypted gradient to it, assumed to be another vector of the same size """ |
gradient = self.compute_gradient()
encrypted_gradient = encrypt_vector(self.pubkey, gradient)
if sum_to is not None:
return sum_encrypted_vectors(sum_to, encrypted_gradient)
else:
return encrypted_gradient |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt_encoded(self, encoding, r_value):
"""Paillier encrypt an encoded value. Args: encoding: The EncodedNumber instance. r_value (int):
obfuscator for the ciphertext; by default (i.e. if *r_value* is None), a random value is used. Returns: EncryptedNumber: An encryption of *value*. """ |
# If r_value is None, obfuscate in a call to .obfuscate() (below)
obfuscator = r_value or 1
ciphertext = self.raw_encrypt(encoding.encoding, r_value=obfuscator)
encrypted_number = EncryptedNumber(self, ciphertext, encoding.exponent)
if r_value is None:
encrypted_number.obfuscate()
return encrypted_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 from_totient(public_key, totient):
"""given the totient, one can factorize the modulus The totient is defined as totient = (p - 1) * (q - 1), and the modulus is defined as modulus = p * q Args: public_key (PaillierPublicKey):
The corresponding public key totient (int):
the totient of the modulus Returns: the :class:`PaillierPrivateKey` that corresponds to the inputs Raises: ValueError: if the given totient is not the totient of the modulus of the given public key """ |
p_plus_q = public_key.n - totient + 1
p_minus_q = isqrt(p_plus_q * p_plus_q - public_key.n * 4)
q = (p_plus_q - p_minus_q) // 2
p = p_plus_q - q
if not p*q == public_key.n:
raise ValueError('given public key and totient do not match.')
return PaillierPrivateKey(public_key, p, q) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_decrypt(self, ciphertext):
"""Decrypt raw ciphertext and return raw plaintext. Args: ciphertext (int):
(usually from :meth:`EncryptedNumber.ciphertext()`) that is to be Paillier decrypted. Returns: int: Paillier decryption of ciphertext. This is a positive integer < :attr:`public_key.n`. Raises: TypeError: if ciphertext is not an int. """ |
if not isinstance(ciphertext, int):
raise TypeError('Expected ciphertext to be an int, not: %s' %
type(ciphertext))
decrypt_to_p = self.l_function(powmod(ciphertext, self.p-1, self.psquare), self.p) * self.hp % self.p
decrypt_to_q = self.l_function(powmod(ciphertext, self.q-1, self.qsquare), self.q) * self.hq % self.q
return self.crt(decrypt_to_p, decrypt_to_q) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def h_function(self, x, xsquare):
"""Computes the h-function as defined in Paillier's paper page 12, 'Decryption using Chinese-remaindering'. """ |
return invert(self.l_function(powmod(self.public_key.g, x - 1, xsquare),x), 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 crt(self, mp, mq):
"""The Chinese Remainder Theorem as needed for decryption. Returns the solution modulo n=pq. Args: mp(int):
the solution modulo p. mq(int):
the solution modulo q. """ |
u = (mq - mp) * self.p_inverse % self.q
return mp + (u * self.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 add(self, private_key):
"""Add a key to the keyring. Args: private_key (PaillierPrivateKey):
a key to add to this keyring. """ |
if not isinstance(private_key, PaillierPrivateKey):
raise TypeError("private_key should be of type PaillierPrivateKey, "
"not %s" % type(private_key))
self.__keyring[private_key.public_key] = private_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 ciphertext(self, be_secure=True):
"""Return the ciphertext of the EncryptedNumber. Choosing a random number is slow. Therefore, methods like :meth:`__add__` and :meth:`__mul__` take a shortcut and do not follow Paillier encryption fully - every encrypted sum or product should be multiplied by r ** :attr:`~PaillierPublicKey.n` for random r < n (i.e., the result is obfuscated). Not obfuscating provides a big speed up in, e.g., an encrypted dot product: each of the product terms need not be obfuscated, since only the final sum is shared with others - only this final sum needs to be obfuscated. Not obfuscating is OK for internal use, where you are happy for your own computer to know the scalars you've been adding and multiplying to the original ciphertext. But this is *not* OK if you're going to be sharing the new ciphertext with anyone else. So, by default, this method returns an obfuscated ciphertext - obfuscating it if necessary. If instead you set `be_secure=False` then the ciphertext will be returned, regardless of whether it has already been obfuscated. We thought that this approach, while a little awkward, yields a safe default while preserving the option for high performance. Args: be_secure (bool):
If any untrusted parties will see the returned ciphertext, then this should be True. Returns: an int, the ciphertext. If `be_secure=False` then it might be possible for attackers to deduce numbers involved in calculating this ciphertext. """ |
if be_secure and not self.__is_obfuscated:
self.obfuscate()
return self.__ciphertext |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrease_exponent_to(self, new_exp):
"""Return an EncryptedNumber with same value but lower exponent. If we multiply the encoded value by :attr:`EncodedNumber.BASE` and decrement :attr:`exponent`, then the decoded value does not change. Thus we can almost arbitrarily ratchet down the exponent of an `EncryptedNumber` - we only run into trouble when the encoded integer overflows. There may not be a warning if this happens. When adding `EncryptedNumber` instances, their exponents must match. This method is also useful for hiding information about the precision of numbers - e.g. a protocol can fix the exponent of all transmitted `EncryptedNumber` instances to some lower bound(s). Args: new_exp (int):
the desired exponent. Returns: EncryptedNumber: Instance with the same plaintext and desired exponent. Raises: ValueError: You tried to increase the exponent. """ |
if new_exp > self.exponent:
raise ValueError('New exponent %i should be more negative than '
'old exponent %i' % (new_exp, self.exponent))
multiplied = self * pow(EncodedNumber.BASE, self.exponent - new_exp)
multiplied.exponent = new_exp
return multiplied |
<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(cls, public_key, scalar, precision=None, max_exponent=None):
"""Return an encoding of an int or float. This encoding is carefully chosen so that it supports the same operations as the Paillier cryptosystem. If *scalar* is a float, first approximate it as an int, `int_rep`: scalar = int_rep * (:attr:`BASE` ** :attr:`exponent`), for some (typically negative) integer exponent, which can be tuned using *precision* and *max_exponent*. Specifically, :attr:`exponent` is chosen to be equal to or less than *max_exponent*, and such that the number *precision* is not rounded to zero. Having found an integer representation for the float (or having been given an int `scalar`), we then represent this integer as a non-negative integer < :attr:`~PaillierPublicKey.n`. Paillier homomorphic arithemetic works modulo :attr:`~PaillierPublicKey.n`. We take the convention that a number x < n/3 is positive, and that a number x > 2n/3 is negative. The range n/3 < x < 2n/3 allows for overflow detection. Args: public_key (PaillierPublicKey):
public key for which to encode (this is necessary because :attr:`~PaillierPublicKey.n` varies). scalar: an int or float to be encrypted. If int, it must satisfy abs(*value*) < :attr:`~PaillierPublicKey.n`/3. If float, it must satisfy abs(*value* / *precision*) << :attr:`~PaillierPublicKey.n`/3 (i.e. if a float is near the limit then detectable overflow may still occur) precision (float):
Choose exponent (i.e. fix the precision) so that this number is distinguishable from zero. If `scalar` is a float, then this is set so that minimal precision is lost. Lower precision leads to smaller encodings, which might yield faster computation. max_exponent (int):
Ensure that the exponent of the returned `EncryptedNumber` is at most this. Returns: EncodedNumber: Encoded form of *scalar*, ready for encryption against *public_key*. """ |
# Calculate the maximum exponent for desired precision
if precision is None:
if isinstance(scalar, int):
prec_exponent = 0
elif isinstance(scalar, float):
# Encode with *at least* as much precision as the python float
# What's the base-2 exponent on the float?
bin_flt_exponent = math.frexp(scalar)[1]
# What's the base-2 exponent of the least significant bit?
# The least significant bit has value 2 ** bin_lsb_exponent
bin_lsb_exponent = bin_flt_exponent - cls.FLOAT_MANTISSA_BITS
# What's the corresponding base BASE exponent? Round that down.
prec_exponent = math.floor(bin_lsb_exponent / cls.LOG2_BASE)
else:
raise TypeError("Don't know the precision of type %s."
% type(scalar))
else:
prec_exponent = math.floor(math.log(precision, cls.BASE))
# Remember exponents are negative for numbers < 1.
# If we're going to store numbers with a more negative
# exponent than demanded by the precision, then we may
# as well bump up the actual precision.
if max_exponent is None:
exponent = prec_exponent
else:
exponent = min(max_exponent, prec_exponent)
# Use rationals instead of floats to avoid overflow.
int_rep = round(fractions.Fraction(scalar)
* fractions.Fraction(cls.BASE) ** -exponent)
if abs(int_rep) > public_key.max_int:
raise ValueError('Integer needs to be within +/- %d but got %d'
% (public_key.max_int, int_rep))
# Wrap negative numbers by adding n
return cls(public_key, int_rep % public_key.n, exponent) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self):
"""Decode plaintext and return the result. Returns: an int or float: the decoded number. N.B. if the number returned is an integer, it will not be of type float. Raises: OverflowError: if overflow is detected in the decrypted number. """ |
if self.encoding >= self.public_key.n:
# Should be mod n
raise ValueError('Attempted to decode corrupted number')
elif self.encoding <= self.public_key.max_int:
# Positive
mantissa = self.encoding
elif self.encoding >= self.public_key.n - self.public_key.max_int:
# Negative
mantissa = self.encoding - self.public_key.n
else:
raise OverflowError('Overflow detected in decrypted number')
if self.exponent >= 0:
# Integer multiplication. This is exact.
return mantissa * self.BASE ** self.exponent
else:
# BASE ** -e is an integer, so below is a division of ints.
# Not coercing mantissa to float prevents some overflows.
try:
return mantissa / self.BASE ** -self.exponent
except OverflowError as e:
raise OverflowError(
'decoded result too large for a float') from e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrease_exponent_to(self, new_exp):
"""Return an `EncodedNumber` with same value but lower exponent. If we multiply the encoded value by :attr:`BASE` and decrement :attr:`exponent`, then the decoded value does not change. Thus we can almost arbitrarily ratchet down the exponent of an :class:`EncodedNumber` - we only run into trouble when the encoded integer overflows. There may not be a warning if this happens. This is necessary when adding :class:`EncodedNumber` instances, and can also be useful to hide information about the precision of numbers - e.g. a protocol can fix the exponent of all transmitted :class:`EncodedNumber` to some lower bound(s). Args: new_exp (int):
the desired exponent. Returns: EncodedNumber: Instance with the same value and desired exponent. Raises: ValueError: You tried to increase the exponent, which can't be done without decryption. """ |
if new_exp > self.exponent:
raise ValueError('New exponent %i should be more negative than'
'old exponent %i' % (new_exp, self.exponent))
factor = pow(self.BASE, self.exponent - new_exp)
new_enc = self.encoding * factor % self.public_key.n
return self.__class__(self.public_key, new_enc, new_exp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def powmod(a, b, c):
""" Uses GMP, if available, to do a^b mod c where a, b, c are integers. :return int: (a ** b) % c """ |
if a == 1:
return 1
if not HAVE_GMP or max(a, b, c) < _USE_MOD_FROM_GMP_SIZE:
return pow(a, b, c)
else:
return int(gmpy2.powmod(a, b, c)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extended_euclidean_algorithm(a, b):
"""Extended Euclidean algorithm Returns r, s, t such that r = s*a + t*b and r is gcd(a, b) See <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm> """ |
r0, r1 = a, b
s0, s1 = 1, 0
t0, t1 = 0, 1
while r1 != 0:
q = r0 // r1
r0, r1 = r1, r0 - q*r1
s0, s1 = s1, s0 - q*s1
t0, t1 = t1, t0 - q*t1
return r0, s0, t0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invert(a, b):
""" The multiplicitive inverse of a in the integers modulo b. :return int: x, where a * x == 1 mod b """ |
if HAVE_GMP:
s = int(gmpy2.invert(a, b))
# according to documentation, gmpy2.invert might return 0 on
# non-invertible element, although it seems to actually raise an
# exception; for consistency, we always raise the exception
if s == 0:
raise ZeroDivisionError('invert() no inverse exists')
return s
else:
r, s, _ = extended_euclidean_algorithm(a, b)
if r != 1:
raise ZeroDivisionError('invert() no inverse exists')
return s % b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getprimeover(N):
"""Return a random N-bit prime number using the System's best Cryptographic random source. Use GMP if available, otherwise fallback to PyCrypto """ |
if HAVE_GMP:
randfunc = random.SystemRandom()
r = gmpy2.mpz(randfunc.getrandbits(N))
r = gmpy2.bit_set(r, N - 1)
return int(gmpy2.next_prime(r))
elif HAVE_CRYPTO:
return number.getPrime(N, os.urandom)
else:
randfunc = random.SystemRandom()
n = randfunc.randrange(2**(N-1), 2**N) | 1
while not is_prime(n):
n += 2
return n |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def miller_rabin(n, k):
"""Run the Miller-Rabin test on n with at most k iterations Arguments: n (int):
number whose primality is to be tested k (int):
maximum number of iterations to run Returns: bool: If n is prime, then True is returned. Otherwise, False is returned, except with probability less than 4**-k. See <https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test> """ |
assert n > 3
# find r and d such that n-1 = 2^r × d
d = n-1
r = 0
while d % 2 == 0:
d //= 2
r += 1
assert n-1 == d * 2**r
assert d % 2 == 1
for _ in range(k): # each iteration divides risk of false prime by 4
a = random.randint(2, n-2) # choose a random witness
x = pow(a, d, n)
if x == 1 or x == n-1:
continue # go to next witness
for _ in range(1, r):
x = x*x % n
if x == n-1:
break # go to next witness
else:
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 is_prime(n, mr_rounds=25):
"""Test whether n is probably prime See <https://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests> Arguments: n (int):
the number to be tested mr_rounds (int, optional):
number of Miller-Rabin iterations to run; defaults to 25 iterations, which is what the GMP library uses Returns: bool: when this function returns False, `n` is composite (not prime); when it returns True, `n` is prime with overwhelming probability """ |
# as an optimization we quickly detect small primes using the list above
if n <= first_primes[-1]:
return n in first_primes
# for small dividors (relatively frequent), euclidean division is best
for p in first_primes:
if n % p == 0:
return False
# the actual generic test; give a false prime with probability 2⁻⁵⁰
return miller_rabin(n, mr_rounds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findCommunities(G):
""" Partition network with the Infomap algorithm. Annotates nodes with 'community' id and return number of communities found. """ |
infomapWrapper = infomap.Infomap("--two-level")
print("Building Infomap network from a NetworkX graph...")
for e in G.edges():
infomapWrapper.addLink(*e)
print("Find communities with Infomap...")
infomapWrapper.run();
tree = infomapWrapper.tree
print("Found %d top modules with codelength: %f" % (tree.numTopModules(), tree.codelength()))
communities = {}
for node in tree.leafIter():
communities[node.originalLeafIndex] = node.moduleIndex()
nx.set_node_attributes(G, name='community', values=communities)
return tree.numTopModules() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self):
"""Check if the bluetooth controller is available.""" |
try:
subprocess.check_output(["hcitool", "clock"],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
raise BackendError("'hcitool clock' returned error. Make sure "
"your bluetooth device is powered up with "
"'hciconfig hciX up'.")
except OSError:
raise BackendError("'hcitool' could not be found, make sure you "
"have bluez-utils installed.") |
<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_device(self):
"""Scan for bluetooth devices and return a DS4 device if found.""" |
for bdaddr, name in self.scan():
if name == "Wireless Controller":
self.logger.info("Found device {0}", bdaddr)
return BluetoothDS4Device.connect(bdaddr) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.