code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
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) | def failed(self, reason=None) | Set the test status to Report.FAILED, and set the failure reason
:param reason: failure reason (default: None) | 5.526941 | 2.782223 | 1.98652 |
'''
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) | def error(self, reason=None) | Set the test status to Report.ERROR, and set the error reason
:param reason: error reason (default: None) | 6.231572 | 2.865736 | 2.17451 |
'''
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... | 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) | 3.559582 | 2.672451 | 1.331954 |
'''
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, us... | 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) | 4.358831 | 2.507502 | 1.738316 |
'''
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 | def get(self, key) | Get a value for a given key
:param key: entry's key
:return: corresponding value | 4.294322 | 2.903847 | 1.478839 |
'''
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():
... | 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 | 3.827471 | 2.613504 | 1.464498 |
'''
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['nam... | 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 | 2.897503 | 2.285706 | 1.267662 |
'''
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_repor... | def get_status(self) | Get the status of the report and its sub-reports.
:rtype: str
:return: report status ('passed', 'failed' or 'error') | 3.240853 | 2.340652 | 1.384594 |
'''
Make sure the monitor is ready for fuzzing
'''
super(BaseMonitor, self).setup()
self.monitor_thread = LoopFuncThread(self._monitor_func)
self.monitor_thread.start() | def setup(self) | Make sure the monitor is ready for fuzzing | 8.166111 | 4.042429 | 2.0201 |
'''
cleanup the monitor data and
'''
self.monitor_thread.stop()
self.monitor_thread = None
super(BaseMonitor, self).teardown() | def teardown(self) | cleanup the monitor data and | 10.724062 | 6.386257 | 1.679241 |
'''
:return: a copy of the container
'''
dup = super(Container, self).copy()
dup._fields = [field.copy() for field in self._fields]
dup._fields_dict = {field.get_name(): field for field in dup._fields if field.get_name() is not None}
dup._containers = []
f... | def copy(self) | :return: a copy of the container | 3.33606 | 3.054133 | 1.09231 |
'''
:rtype: int
:return: hash of the container
'''
hashed = super(Container, self).hash()
for f in self._fields:
f_hashed = f.hash()
hashed = khash(hashed + f_hashed)
return hashed | def hash(self) | :rtype: int
:return: hash of the container | 5.078002 | 3.996672 | 1.270558 |
'''
:return: number of mutations in the container
'''
self._initialize()
res = super(Container, self).num_mutations()
return res | def num_mutations(self) | :return: number of mutations in the container | 8.126109 | 4.964565 | 1.636822 |
'''
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container
'''
self._initialize()
render_count = 1
if ctx is None:
ctx = RenderContext()
if self._need_second_pass:
... | def render(self, ctx=None) | :param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container | 4.500278 | 3.601419 | 1.249585 |
'''
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():
... | 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) | 7.008432 | 2.682554 | 2.612597 |
'''
Reset the state of the container and its internal fields
'''
super(Container, self).reset()
for field in self._fields:
field.reset()
self._field_idx = 0 | def reset(self) | Reset the state of the container and its internal fields | 6.632251 | 3.433505 | 1.931627 |
'''
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_... | 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 | 2.874047 | 1.82204 | 1.577379 |
'''
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) | def set_session_data(self, session_data) | Set session data in the container enclosed fields
:param session_data: dictionary of session data | 5.850775 | 3.096312 | 1.889595 |
'''
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() | def is_default(self) | Checks if the field is in its default form
:return: True if field is in default form | 5.840049 | 3.339364 | 1.748851 |
'''
Prepare to run (if not ready)
'''
num = 0
for field in self._fields:
field._initialize()
self._need_second_pass |= field._need_second_pass
for field in self._fields:
num += field.num_mutations()
self._calculate_mutations(num... | def _init(self) | Prepare to run (if not ready) | 8.838924 | 6.105817 | 1.447624 |
'''
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 | def _mutate(self) | Mutate enclosed fields | 6.319129 | 4.227699 | 1.494697 |
'''
:param name: name of field to get
:return: direct sub-field with the given name
:raises: :class:`~kitty.core.KittyException` if no direct subfield with this name
'''
if name in self._fields_dict:
return self._fields_dict[name]
raise KittyException(... | def get_field_by_name(self, name) | :param name: name of field to get
:return: direct sub-field with the given name
:raises: :class:`~kitty.core.KittyException` if no direct subfield with this name | 5.342761 | 2.397299 | 2.228659 |
'''
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() | def append_fields(self, new_fields) | Add fields to the container
:param new_fields: fields to append | 5.422048 | 3.907085 | 1.387748 |
'''
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
'''
if ctx is None:
ctx = RenderContext()
ctx.push(self)
result = []
for f in self._fields:
if len(f.render(c... | def get_rendered_fields(self, ctx=None) | :param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered | 3.76248 | 2.362536 | 1.59256 |
'''
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:
... | def get_info(self) | Get info regarding the current fuzzed enclosed node
:return: info dictionary | 6.617679 | 3.677948 | 1.799286 |
'''
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() | def pop(self) | Remove a the top container from the container stack | 10.049918 | 5.411751 | 1.857055 |
'''
Add a field to the container, if the field is a Container itself, it should be poped() when done pushing into it
:param field: BaseField to push
'''
kassert.is_of_types(field, BaseField)
container = self._container()
field.enclosing = self
if isinstan... | def push(self, field) | Add a field to the container, if the field is a Container itself, it should be poped() when done pushing into it
:param field: BaseField to push | 5.792693 | 3.232908 | 1.79179 |
'''
:rtype: int
:return: hash of the container
'''
hashed = super(ForEach, self).hash()
return khash(hashed + self._mutated_field.hash()) | def hash(self) | :rtype: int
:return: hash of the container | 13.185617 | 9.601387 | 1.373303 |
'''
Reset the state of the container and its internal fields
:param reset_mutated: should reset the mutated field too (default: True)
'''
super(ForEach, self).reset()
if reset_mutated:
self._mutated_field.reset() | def reset(self, reset_mutated=True) | Reset the state of the container and its internal fields
:param reset_mutated: should reset the mutated field too (default: True) | 5.999692 | 2.635894 | 2.276151 |
'''
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
'''
res = []
if ctx is None:
ctx = RenderContext()
if self._evaluate_condition(ctx):
ctx.push(self)
res =... | def get_rendered_fields(self, ctx=None) | :param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered | 4.267408 | 2.709932 | 1.574729 |
'''
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 | def copy(self) | Copy the container, put an invalidated copy of the condition in the new container | 10.413318 | 3.858274 | 2.698957 |
'''
:rtype: int
:return: hash of the container
'''
hashed = super(Conditional, self).hash()
return khash(hashed, self._condition.hash()) | def hash(self) | :rtype: int
:return: hash of the container | 9.843451 | 6.945713 | 1.417198 |
'''
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:
... | 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 | 6.29534 | 3.551591 | 1.772541 |
'''
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container, padded if needed
'''
super(Pad, self).render(ctx)
self.set_current_value(self._pad_buffer(self._current_rendered))
return self._curren... | def render(self, ctx=None) | :param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container, padded if needed | 8.351328 | 3.323041 | 2.513158 |
'''
:rtype: int
:return: hash of the container
'''
hashed = super(Pad, self).hash()
return khash(hashed, self._pad_length, self._pad_data) | def hash(self) | :rtype: int
:return: hash of the container | 9.099562 | 6.758224 | 1.346443 |
'''
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)):
... | def _check_times(self, min_times, max_times, step) | Make sure that the arguments are valid
:raises: KittyException if not valid | 3.266326 | 2.44398 | 1.336478 |
'''
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container, repeated
'''
self._initialize()
times = self._min_times
if self._mutating() and self._in_repeat_stage():
times += (self._c... | def render(self, ctx=None) | :param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container, repeated | 10.214563 | 5.555305 | 1.838704 |
'''
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
'''
times = self._min_times
if self._mutating() and self._in_repeat_stage():
times += (self._current_index) * self._step
return s... | def get_rendered_fields(self, ctx=None) | :param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered | 9.761345 | 6.014159 | 1.623061 |
'''
:rtype: int
:return: hash of the container
'''
hashed = super(Repeat, self).hash()
return khash(hashed, self._min_times, self._max_times, self._step, self._repeats) | def hash(self) | :rtype: int
:return: hash of the container | 7.150967 | 5.618357 | 1.272786 |
'''
Render only the mutated field (or the first one if not in mutation)
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container
'''
if ctx is None:
ctx = RenderContext()
ctx.push(sel... | def render(self, ctx=None) | Render only the mutated field (or the first one if not in mutation)
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container | 5.954213 | 2.804898 | 2.122791 |
'''
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
'''
if ctx is None:
ctx = RenderContext()
ctx.push(self)
current = self._fields[self._field_idx]
res = current.get_render... | def get_rendered_fields(self, ctx=None) | :param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered | 4.54933 | 2.858563 | 1.591475 |
'''
Render only a single field (see class docstring for more details)
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container
'''
if ctx is None:
ctx = RenderContext()
ctx.push(self)... | def render(self, ctx=None) | Render only a single field (see class docstring for more details)
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container | 4.270265 | 2.903851 | 1.470553 |
'''
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... | 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 impleme... | 4.837975 | 2.383839 | 2.029489 |
'''
Reset the state of the container and its internal fields
'''
super(TakeFrom, self).reset()
self.random.seed(self.seed * self.max_elements + self.min_elements) | def reset(self) | Reset the state of the container and its internal fields | 11.901283 | 6.168174 | 1.929466 |
'''
:rtype: int
:return: hash of the container
'''
hashed = super(TakeFrom, self).hash()
return khash(hashed, self.min_elements, self.max_elements, self.seed) | def hash(self) | :rtype: int
:return: hash of the container | 8.61068 | 6.660174 | 1.292861 |
'''
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,
... | def get_info(self) | Get info regarding the current template state
:return: info dictionary | 4.644556 | 3.849368 | 1.206576 |
'''
:param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container
'''
super(Trunc, self).render(ctx)
self._current_value = self._current_rendered
self._current_rendered = self._current_rendered[:self._... | def render(self, ctx=None) | :param ctx: rendering context in which the method was called
:rtype: `Bits`
:return: rendered value of the container | 6.227097 | 3.184348 | 1.955533 |
'''
:rtype: int
:return: hash of the container
'''
hashed = super(Trunc, self).hash()
return khash(hashed, self._max_size) | def hash(self) | :rtype: int
:return: hash of the container | 11.11286 | 8.019924 | 1.385656 |
'''
:param container: the container that tries to invalidate the condition
'''
self._get_ready(container)
field_name = self._field.get_name()
if field_name is None:
raise KittyException('Cannot invalidate field without name')
self._field_name = field_n... | def invalidate(self, container) | :param container: the container that tries to invalidate the condition | 7.085989 | 4.920944 | 1.439965 |
'''
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_l... | 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.Conta... | 9.070117 | 1.547605 | 5.860745 |
'''
:rtype: int
:return: hash of the condition
'''
hashed = super(Compare, self).hash()
return khash(hashed, self._comp_value, self._comp_type) | def hash(self) | :rtype: int
:return: hash of the condition | 8.734194 | 6.332614 | 1.37924 |
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_op... | 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. | 2.74264 | 2.728807 | 1.005069 |
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)) | 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. | 6.113165 | 5.890621 | 1.037779 |
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) | 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 t... | 5.806433 | 5.735622 | 1.012346 |
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'], priv... | def decrypt(private, ciphertext, output) | Decrypt ciphertext with private key.
Requires PRIVATE key file and the CIPHERTEXT encrypted with
the corresponding public key. | 2.918039 | 2.989194 | 0.976196 |
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("Addin... | def add_encrypted(public, encrypted_a, encrypted_b, output) | Add two encrypted numbers together. | 2.94558 | 2.741836 | 1.07431 |
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
... | 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. | 3.88222 | 3.483373 | 1.1145 |
n_datasets = 2
for d in range(1, n_datasets + 1):
if not os.path.isdir('enron%d' % d):
URL = url[d-1]
print("Downloading %d/%d: %s" % (d, n_datasets, URL))
folderzip = 'enron%d.zip' % d
with urlopen(URL) as remotedata:
with open(fol... | def download_data() | Download two sets of Enron1 spam/ham e-mails if they are not here
We will use the first as trainset and the second as testset.
Return the path prefix to us to load the data from disk. | 3.248063 | 3.030486 | 1.071796 |
print("Importing dataset from disk...")
path = 'enron1/ham/'
ham1 = [open(path + f, 'r', errors='replace').read().strip(r"\n")
for f in os.listdir(path) if os.path.isfile(path + f)]
path = 'enron1/spam/'
spam1 = [open(path + f, 'r', errors='replace').read().strip(r"\n")
... | def preprocess_data() | Get the Enron e-mails from disk.
Represent them as bag-of-words.
Shuffle and split train/test. | 2.001433 | 1.951459 | 1.025609 |
score = self.intercept
_, idx = x.nonzero()
for i in idx:
score += x[0, i] * self.weights[i]
return score | def encrypted_score(self, x) | Compute the score of `x` by multiplying with the encrypted model,
which is a vector of `paillier.EncryptedNumber` | 4.608332 | 5.330652 | 0.864497 |
print("Loading data")
diabetes = load_diabetes()
y = diabetes.target
X = diabetes.data
# Add constant to emulate intercept
X = np.c_[X, np.ones(X.shape[0])]
# The features are already preprocessed
# Shuffle
perm = np.random.permutation(X.shape[0])
X, y = X[perm, :], y[perm]... | def get_data(n_clients) | Import the dataset via sklearn, shuffle and split train/test.
Return training, target lists for `n_clients` and a holdout test set | 2.368969 | 2.358215 | 1.00456 |
for _ in range(n_iter):
gradient = self.compute_gradient()
self.gradient_step(gradient, eta) | def fit(self, n_iter, eta=0.01) | Linear regression for n_iter | 3.733062 | 4.586977 | 0.813839 |
delta = self.predict(self.X) - self.y
return delta.dot(self.X) / len(self.X) | def compute_gradient(self) | Compute the gradient of the current model using the training set | 4.642603 | 4.019639 | 1.15498 |
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 | 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 | 3.085436 | 3.498046 | 0.882046 |
p = q = n = None
n_len = 0
while n_len != n_length:
p = getprimeover(n_length // 2)
q = p
while q == p:
q = getprimeover(n_length // 2)
n = p * q
n_len = n.bit_length()
public_key = PaillierPublicKey(n)
private_key = PaillierPrivateKey(public... | def generate_paillier_keypair(private_keyring=None, n_length=DEFAULT_KEYSIZE) | Return a new :class:`PaillierPublicKey` and :class:`PaillierPrivateKey`.
Add the private key to *private_keyring* if given.
Args:
private_keyring (PaillierPrivateKeyring): a
:class:`PaillierPrivateKeyring` on which to store the private
key.
n_length: key size in bits.
Returns:... | 2.266173 | 2.4059 | 0.941924 |
if not isinstance(plaintext, int):
raise TypeError('Expected int type plaintext but got: %s' %
type(plaintext))
if self.n - self.max_int <= plaintext < self.n:
# Very large plaintext, take a sneaky shortcut using inverses
neg_plai... | def raw_encrypt(self, plaintext, r_value=None) | Paillier encryption of a positive integer plaintext < :attr:`n`.
You probably should be using :meth:`encrypt` instead, because it
handles positive and negative ints and floats.
Args:
plaintext (int): a positive integer < :attr:`n` to be Paillier
encrypted. Typically this ... | 5.141583 | 4.995429 | 1.029258 |
if isinstance(value, EncodedNumber):
encoding = value
else:
encoding = EncodedNumber.encode(self, value, precision)
return self.encrypt_encoded(encoding, r_value) | def encrypt(self, value, precision=None, r_value=None) | Encode and Paillier encrypt a real number *value*.
Args:
value: an int or float to be encrypted.
If int, it must satisfy abs(*value*) < :attr:`n`/3.
If float, it must satisfy abs(*value* / *precision*) <<
:attr:`n`/3
(i.e. if a float is near the limit t... | 4.64605 | 4.214241 | 1.102464 |
# 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:
encryp... | 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*. | 5.814976 | 4.811801 | 1.208482 |
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 Paillier... | 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
... | 3.132493 | 3.34284 | 0.937075 |
if not isinstance(encrypted_number, EncryptedNumber):
raise TypeError('Expected encrypted_number to be an EncryptedNumber'
' not: %s' % type(encrypted_number))
if self.public_key != encrypted_number.public_key:
raise ValueError('encrypted_num... | def decrypt_encoded(self, encrypted_number, Encoding=None) | Return the :class:`EncodedNumber` decrypted from *encrypted_number*.
Args:
encrypted_number (EncryptedNumber): an
:class:`EncryptedNumber` with a public key that matches this
private key.
Encoding (class): A class to use instead of :class:`EncodedNumber`, the
... | 3.948947 | 3.268414 | 1.208215 |
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(ci... | 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`.
... | 3.532613 | 3.519472 | 1.003734 |
return invert(self.l_function(powmod(self.public_key.g, x - 1, xsquare),x), x) | def h_function(self, x, xsquare) | Computes the h-function as defined in Paillier's paper page 12,
'Decryption using Chinese-remaindering'. | 16.556591 | 12.13914 | 1.363901 |
u = (mq - mp) * self.p_inverse % self.q
return mp + (u * self.p) | 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. | 9.760673 | 8.877318 | 1.099507 |
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 | def add(self, private_key) | Add a key to the keyring.
Args:
private_key (PaillierPrivateKey): a key to add to this keyring. | 3.092777 | 2.587301 | 1.195368 |
relevant_private_key = self.__keyring[encrypted_number.public_key]
return relevant_private_key.decrypt(encrypted_number) | def decrypt(self, encrypted_number) | Return the decrypted & decoded plaintext of *encrypted_number*.
Args:
encrypted_number (EncryptedNumber): encrypted against a known public
key, i.e., one for which the private key is on this keyring.
Returns:
the int or float that *encrypted_number* was holding. N.B. if... | 7.012901 | 5.282915 | 1.327468 |
if be_secure and not self.__is_obfuscated:
self.obfuscate()
return self.__ciphertext | 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:`~PaillierP... | 6.122099 | 8.856503 | 0.691255 |
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
... | 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... | 4.329906 | 3.575859 | 1.210871 |
r = self.public_key.get_random_lt_n()
r_pow_n = powmod(r, self.public_key.n, self.public_key.nsquare)
self.__ciphertext = self.__ciphertext * r_pow_n % self.public_key.nsquare
self.__is_obfuscated = True | def obfuscate(self) | Disguise ciphertext by multiplying by r ** n with random r.
This operation must be performed for every `EncryptedNumber`
that is sent to an untrusted party, otherwise eavesdroppers
might deduce relationships between this and an antecedent
`EncryptedNumber`.
For example::
... | 4.915112 | 4.437598 | 1.107606 |
encoded = EncodedNumber.encode(self.public_key, scalar,
max_exponent=self.exponent)
return self._add_encoded(encoded) | def _add_scalar(self, scalar) | Returns E(a + b), given self=E(a) and b.
Args:
scalar: an int or float b, to be added to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~PaillierPublicKey.n` ** 2.
Raises:... | 11.495105 | 12.240195 | 0.939128 |
if self.public_key != encoded.public_key:
raise ValueError("Attempted to add numbers encoded against "
"different public keys!")
# In order to add two numbers, their exponents must match.
a, b = self, encoded
if a.exponent > b.exponent:
... | def _add_encoded(self, encoded) | Returns E(a + b), given self=E(a) and b.
Args:
encoded (EncodedNumber): an :class:`EncodedNumber` to be added
to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~Paillie... | 6.178184 | 5.443032 | 1.135063 |
if self.public_key != other.public_key:
raise ValueError("Attempted to add numbers encrypted against "
"different public keys!")
# In order to add two numbers, their exponents must match.
a, b = self, other
if a.exponent > b.exponent:
... | def _add_encrypted(self, other) | Returns E(a + b) given E(a) and E(b).
Args:
other (EncryptedNumber): an `EncryptedNumber` to add to self.
Returns:
EncryptedNumber: E(a + b), calculated by taking the product
of E(a) and E(b) modulo :attr:`~PaillierPublicKey.n` ** 2.
Raises:
ValueErro... | 3.880917 | 3.533183 | 1.09842 |
if not isinstance(plaintext, int):
raise TypeError('Expected ciphertext to be int, not %s' %
type(plaintext))
if plaintext < 0 or plaintext >= self.public_key.n:
raise ValueError('Scalar out of bounds: %i' % plaintext)
if self.public_key.n - sel... | def _raw_mul(self, plaintext) | Returns the integer E(a * plaintext), where E(a) = ciphertext
Args:
plaintext (int): number by which to multiply the
`EncryptedNumber`. *plaintext* is typically an encoding.
0 <= *plaintext* < :attr:`~PaillierPublicKey.n`
Returns:
int: Encryption of the prod... | 3.830436 | 3.682315 | 1.040225 |
# 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
# Wha... | 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 som... | 5.198955 | 4.984787 | 1.042964 |
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 - ... | 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. | 5.624382 | 5.205249 | 1.080521 |
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
... | 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... | 3.465155 | 3.850158 | 0.900003 |
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)) | 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 | 4.753076 | 4.283771 | 1.109554 |
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 | 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> | 1.286196 | 1.42856 | 0.900344 |
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 ZeroDivisionErr... | def invert(a, b) | The multiplicitive inverse of a in the integers modulo b.
:return int: x, where a * x == 1 mod b | 4.724941 | 4.804534 | 0.983434 |
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 = ran... | 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 | 3.228407 | 2.903934 | 1.111736 |
assert n >= 0
if n == 0:
return 0
i = n.bit_length() >> 1 # i = floor( (1 + floor(log_2(n))) / 2 )
m = 1 << i # m = 2^i
#
# Fact: (2^(i + 1))^2 > n, so m has at least as many bits
# as the floor of the square root of n.
#
# Proof: (2^(i+1))^2 = 2^(2i + 2) >= 2^(flo... | def improved_i_sqrt(n) | taken from
http://stackoverflow.com/questions/15390807/integer-square-root-in-python
Thanks, mathmandan | 3.919852 | 3.860782 | 1.0153 |
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 w... | 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 ... | 3.143853 | 3.254876 | 0.96589 |
# 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 ... | 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
... | 11.76515 | 12.463901 | 0.943938 |
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.n... | def findCommunities(G) | Partition network with the Infomap algorithm.
Annotates nodes with 'community' id and return number of communities found. | 4.560814 | 4.12239 | 1.106352 |
try:
subprocess.check_output(["hcitool", "clock"],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
raise BackendError("'hcitool clock' returned error. Make sure "
"your bluetooth device is... | def setup(self) | Check if the bluetooth controller is available. | 4.859101 | 3.953403 | 1.229093 |
try:
res = subprocess.check_output(["hcitool", "scan", "--flush"],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
raise BackendError("'hcitool scan' returned error. Make sure "
"y... | def scan(self) | Scan for bluetooth devices. | 4.535132 | 4.022546 | 1.127428 |
for bdaddr, name in self.scan():
if name == "Wireless Controller":
self.logger.info("Found device {0}", bdaddr)
return BluetoothDS4Device.connect(bdaddr) | def find_device(self) | Scan for bluetooth devices and return a DS4 device if found. | 10.884939 | 5.650607 | 1.926331 |
log_msg = True
while True:
if log_msg:
self.logger.info("Scanning for devices")
try:
device = self.find_device()
if device:
yield device
log_msg = True
else:
... | def devices(self) | Wait for new DS4 devices to appear. | 3.332456 | 3.133299 | 1.063561 |
@wraps(self.callback)
def callback():
os.read(self.timer, 8)
repeat = self.callback(*args, **kwargs)
if not repeat:
self.stop()
spec = timerfd.itimerspec(self.interval, self.interval)
timerfd.settime(self.timer, 0, spec)
... | def start(self, *args, **kwargs) | Starts the timer.
If the callback returns True the timer will be restarted. | 4.976084 | 4.527676 | 1.099037 |
if not isinstance(fd, int):
fd = fd.fileno()
self.callbacks[fd] = callback
self.epoll.register(fd, EPOLLIN) | def add_watcher(self, fd, callback) | Starts watching a non-blocking fd for data. | 3.435199 | 3.130661 | 1.097276 |
if not isinstance(fd, int):
fd = fd.fileno()
if fd not in self.callbacks:
return
self.callbacks.pop(fd, None)
self.epoll.unregister(fd) | def remove_watcher(self, fd) | Stops watching a fd. | 3.064345 | 2.876165 | 1.065427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.