def Ch5_33(): # Diffie-Hellman print("Welcome, I am starting on your computation of a ^ b mod m") a = 2988348162058574136915891421498819466320163312926952423791023078876139 b = 2351399303373464486466122544523690094744975233415544072992656881240319 m = 10 ** 40 print(pow(a, b, m)) print("Now I am starting on the actual challenge. See if we get the same key in both cases.") p=0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff g = 2 a = secrets.randbelow(p) b = secrets.randbelow(p) ga = pow(g, a, p) gb = pow(g, b, p) s1 = pow(ga, b, p) s2 = pow(gb, a, p) print("s1 = ", s1 ) print("s2 = ", s2)
def Ch5_39(): # RSA p = secrets.randbelow(10000) q = secrets.randbelow(10000) n = p * q; phi = (p-1)*(q-1) e = 3 d = invmod(e, phi) print("d = ", d)
def make_problem(): op = secrets.randbelow(4) a = secrets.randbelow(1000) b = secrets.randbelow(1000) problem = "" answer = 0 if op == 0: problem = "multiply {} and {}".format(a, b) answer = a * b elif op == 1: problem = "divide {} by {}".format(a, b) answer = round(a / b, 8) elif op == 2: problem = "add {} and {}".format(a, b) answer = a + b elif op == 3: problem = "subtract {} from {}".format(a, b) answer = b - a return problem, answer
from tkinter import * from tinyec import registry import secrets import os import cmath import mysql.connector mydb = mysql.connector.connect(host="localhost", user="******", passwd="", database="mydatabase1", auth_plugin="mysql_native_password") mycursor = mydb.cursor() curve = registry.get_curve('secp192r1') p = curve.g #server extracting r1 from zn* r1 = secrets.randbelow(curve.field.n) #print(f"r1: {r1}") R1 = r1 * p #tag extracting r2 from zn* and calculating R2 r2 = secrets.randbelow(curve.field.n) R2 = r2 * p #handling GUI of the server main = Tk() main.geometry("500x500") main.title("My Server") img = ImageTk.PhotoImage(file="logo2.jpg") photoL = Label(main, image=img) photoL.pack(pady=5) frame = Frame(main) sc = Scrollbar(frame) msgs = Listbox(frame, width=100, height=10, yscrollcommand=sc.set)
def genRandomPaths(initialPaths): paths = initialPaths[:] while paths: i = secrets.randbelow(len(paths)) paths[i], paths[-1] = paths[-1], paths[i] yield paths.pop()
# secrs/secr_rand.py import secrets # utils print(secrets.choice('Choose one of these words'.split())) print(secrets.randbelow(10 ** 6)) print(secrets.randbits(32)) # tokens print(secrets.token_bytes(16)) print(secrets.token_hex(32)) print(secrets.token_urlsafe(32)) # compare digests against timing attacks secrets.compare_digest('abc123', 'abc123') """ $ python secr_rand.py one 504156 3172492450 b'\xda\x863\xeb\xbb|\x8fk\x9b\xbd\x14Q\xd4\x8d\x15}' 9f90fd042229570bf633e91e92505523811b45e1c3a72074e19bbeb2e5111bf7 bl4qz_Av7QNvPEqZtKsLuTOUsNLFmXW3O03pn50leiY """
def randrange(bound: int) -> int: """Return a random integer k such that 1 <= k < bound, uniformly distributed across that range.""" # secrets.randbelow(bound) returns a random int: 0 <= r < bound, # hence transformations: return secrets.randbelow(bound - 1) + 1
def test_failed_contract_cancellation(web3, chain): _hashed_data_groups = [] accuracy_criteria = 9950 # 99.50% w_scale = 1000 # Scale up weights by 1000x b_scale = 1000 # Scale up biases by 1000x dbg.dprint("Start amount bal[0]: " + str(web3.eth.getBalance(web3.eth.accounts[0]))) danku, _ = chain.provider.get_or_deploy_contract('Danku') offer_account = web3.eth.accounts[1] solver_account = web3.eth.accounts[2] # Fund contract web3.eth.sendTransaction({ 'from': offer_account, 'to': danku.address, 'value': web3.toWei(1, "ether") }) # Check that offerer was deducted bal = web3.eth.getBalance(offer_account) # Deduct reward amount (1 ETH) and gas cost (21040 wei) assert bal == 999998999999999999978960 wallet_amount = 1000000000000000000000000 # minus the reward amount scd = SampleHalfDividedDataset(training_percentage=0.8) scd.generate_nonce() scd.sha_all_data_groups() dbg.dprint("All data groups: " + str(scd.data)) dbg.dprint("All nonces: " + str(scd.nonce)) # Initialization step 1 dbg.dprint("Hashed data groups: " + str(scd.hashed_data_group)) dbg.dprint("Hashed Hex data groups: " + str(list(map(lambda x: "0x" + x.hex(), scd.hashed_data_group)))) # Keep track of all block numbers, so we can send them in time # Start at a random block between 0-1000 chain.wait.for_block(randbelow(1000)) dbg.dprint("Starting block: " + str(web3.eth.blockNumber)) init1_tx = danku.transact().init1(scd.hashed_data_group, accuracy_criteria, offer_account) chain.wait.for_receipt(init1_tx) init1_block_number = web3.eth.blockNumber dbg.dprint("Init1 block: " + str(init1_block_number)) submission_t = danku.call().submission_stage_block_size() # get submission timeframe evaluation_t = danku.call().evaluation_stage_block_size() # get evaluation timeframe test_reveal_t = danku.call().reveal_test_data_groups_block_size() # get revealing testing dataset timeframe # Initialization step 2 # Get data group indexes chain.wait.for_block(init1_block_number + 1) dgi = [] init2_block_number = web3.eth.blockNumber dbg.dprint("Init2 block: " + str(init2_block_number)) for i in range(scd.num_data_groups): dgi.append(i) dbg.dprint("Data group indexes: " + str(dgi)) init2_tx = danku.transact().init2() chain.wait.for_receipt(init2_tx) # Can only access one element of a public array at a time training_partition = list(map(lambda x: danku.call().training_partition(x),\ range(scd.num_train_data_groups))) testing_partition = list(map(lambda x: danku.call().testing_partition(x),\ range(scd.num_test_data_groups))) # get partitions dbg.dprint("Training partition: " + str(training_partition)) dbg.dprint("Testing partition: " + str(testing_partition)) scd.partition_dataset(training_partition, testing_partition) # Initialization step 3 # Time to reveal the training dataset training_nonces = [] training_data = [] for i in training_partition: training_nonces.append(scd.nonce[i]) # Pack data into a 1-dimension array # Since the data array is too large, we're going to send them in single data group chunks train_data = scd.pack_data(scd.train_data) test_data = scd.pack_data(scd.test_data) init3_tx = [] for i in range(len(training_partition)): start = i*scd.dps*scd.partition_size end = start + scd.dps*scd.partition_size dbg.dprint("(" + str(training_partition[i]) + ") Train data,nonce: " + str(train_data[start:end]) + "," + str(scd.train_nonce[i])) init3_tx.append(danku.transact().init3(train_data[start:end], scd.train_nonce[i])) chain.wait.for_receipt(init3_tx[i]) init3_block_number = web3.eth.blockNumber dbg.dprint("Init3 block: " + str(init3_block_number)) try: # try cancelling contract after init3() danku.transact().cancel_contract() except Exception: pass # contract termination should fail contract_finalized = danku.call().contract_terminated() assert contract_finalized == False bal = web3.eth.getBalance(solver_account) # Verify that the solver account didn't receive the reward amount assert bal == 1000000000000000000000000 bal = web3.eth.getBalance(offer_account) # Verify the offer account didn't get refunded the reward amount assert bal == 999998999999999999978960
def test_create_folder_error(foss_server: str, foss: Fossology): parent = Folder(secrets.randbelow(1000), "NonFolder", "", foss.rootFolder) responses.add(responses.POST, f"{foss_server}/api/v1/folders", status=404) with pytest.raises(FossologyApiError) as excinfo: foss.create_folder(parent, "TestFolderNoParent") assert "Unable to create folder TestFolderNoParent" in str(excinfo.value)
def random_instance(plants, customers): open_cost = [randbelow(15 * plants) for _ in range(plants)] service_cost = [[ randbelow(10 * (plants + customers)) for _ in range(plants) ] for _ in range(customers)] return open_cost, service_cost
def test_single_solver_refunded_contract(web3, chain): _hashed_data_groups = [] accuracy_criteria = 9950 # 99.50% w_scale = 1000 # Scale up weights by 1000x b_scale = 1000 # Scale up biases by 1000x dbg.dprint("Start amount bal[0]: " + str(web3.eth.getBalance(web3.eth.accounts[0]))) danku, _ = chain.provider.get_or_deploy_contract('Danku') offer_account = web3.eth.accounts[1] solver_account = web3.eth.accounts[2] # Fund contract web3.eth.sendTransaction({ 'from': offer_account, 'to': danku.address, 'value': web3.toWei(1, "ether") }) # Check that offerer was deducted bal = web3.eth.getBalance(offer_account) # Deduct reward amount (1 ETH) and gas cost (21040 wei) assert bal == 999998999999999999978960 wallet_amount = 1000000000000000000000000 # minus the reward amount scd = SampleHalfDividedDataset(training_percentage=0.8) scd.generate_nonce() scd.sha_all_data_groups() dbg.dprint("All data groups: " + str(scd.data)) dbg.dprint("All nonces: " + str(scd.nonce)) # Initialization step 1 dbg.dprint("Hashed data groups: " + str(scd.hashed_data_group)) dbg.dprint("Hashed Hex data groups: " + str(list(map(lambda x: "0x" + x.hex(), scd.hashed_data_group)))) # Keep track of all block numbers, so we can send them in time # Start at a random block between 0-1000 chain.wait.for_block(randbelow(1000)) dbg.dprint("Starting block: " + str(web3.eth.blockNumber)) init1_tx = danku.transact().init1(scd.hashed_data_group, accuracy_criteria, offer_account) chain.wait.for_receipt(init1_tx) init1_block_number = web3.eth.blockNumber dbg.dprint("Init1 block: " + str(init1_block_number)) submission_t = danku.call().submission_stage_block_size() # get submission timeframe evaluation_t = danku.call().evaluation_stage_block_size() # get evaluation timeframe test_reveal_t = danku.call().reveal_test_data_groups_block_size() # get revealing testing dataset timeframe # Initialization step 2 # Get data group indexes chain.wait.for_block(init1_block_number + 1) dgi = [] init2_block_number = web3.eth.blockNumber dbg.dprint("Init2 block: " + str(init2_block_number)) for i in range(scd.num_data_groups): dgi.append(i) dbg.dprint("Data group indexes: " + str(dgi)) init2_tx = danku.transact().init2() chain.wait.for_receipt(init2_tx) # Can only access one element of a public array at a time training_partition = list(map(lambda x: danku.call().training_partition(x),\ range(scd.num_train_data_groups))) testing_partition = list(map(lambda x: danku.call().testing_partition(x),\ range(scd.num_test_data_groups))) # get partitions dbg.dprint("Training partition: " + str(training_partition)) dbg.dprint("Testing partition: " + str(testing_partition)) scd.partition_dataset(training_partition, testing_partition) # Initialization step 3 # Time to reveal the training dataset training_nonces = [] training_data = [] for i in training_partition: training_nonces.append(scd.nonce[i]) # Pack data into a 1-dimension array # Since the data array is too large, we're going to send them in single data group chunks train_data = scd.pack_data(scd.train_data) test_data = scd.pack_data(scd.test_data) init3_tx = [] for i in range(len(training_partition)): start = i*scd.dps*scd.partition_size end = start + scd.dps*scd.partition_size dbg.dprint("(" + str(training_partition[i]) + ") Train data,nonce: " + str(train_data[start:end]) + "," + str(scd.train_nonce[i])) init3_tx.append(danku.transact().init3(train_data[start:end], scd.train_nonce[i])) chain.wait.for_receipt(init3_tx[i]) init3_block_number = web3.eth.blockNumber dbg.dprint("Init3 block: " + str(init3_block_number)) # Get the training data from the contract contract_train_data_length = danku.call().get_train_data_length() contract_train_data = [] for i in range(contract_train_data_length): for j in range(scd.dps): contract_train_data.append(danku.call().train_data(i,j)) contract_train_data = scd.unpack_data(contract_train_data) dbg.dprint("Contract training data: " + str(contract_train_data)) il_nn = 2 hl_nn = [] ol_nn = 2 # Train a neural network with contract data nn = NeuralNetwork(il_nn, hl_nn, ol_nn) contract_train_data = nn.binary_2_one_hot(contract_train_data) nn.load_train_data(contract_train_data) nn.init_network() nn.train() trained_weights = nn.weights trained_biases = nn.bias dbg.dprint("Trained weights: " + str(trained_weights)) dbg.dprint("Trained biases: " + str(trained_biases)) packed_trained_weights = nn.pack_weights(trained_weights) dbg.dprint("Packed weights: " + str(packed_trained_weights)) packed_trained_biases = nn.pack_biases(trained_biases) dbg.dprint("Packed biases: " + str(packed_trained_biases)) int_packed_trained_weights = scale_packed_data(packed_trained_weights,\ w_scale) dbg.dprint("Packed integer weights: " + str(int_packed_trained_weights)) int_packed_trained_biases = scale_packed_data(packed_trained_biases,\ b_scale) dbg.dprint("Packed integer biases: " + str(int_packed_trained_biases)) dbg.dprint("Solver address: " + str(solver_account)) # Submit the solution to the contract submit_tx = danku.transact().submit_model(solver_account, il_nn, ol_nn, hl_nn,\ int_packed_trained_weights, int_packed_trained_biases) chain.wait.for_receipt(submit_tx) # Get submission index ID submission_id = danku.call().get_submission_id(solver_account, il_nn,\ ol_nn, hl_nn, int_packed_trained_weights, int_packed_trained_biases) dbg.dprint("Submission ID: " + str(submission_id)) # Wait until the submission period ends chain.wait.for_block(init3_block_number + submission_t) # Reveal the testing dataset after the submission period ends reveal_tx = [] for i in range(len(testing_partition)): start = i*scd.dps*scd.partition_size end = start + scd.dps*scd.partition_size dbg.dprint("(" + str(testing_partition[i]) + ") Test data,nonce: " + str(test_data[start:end]) + "," + str(scd.test_nonce[i])) reveal_tx.append(danku.transact().reveal_test_data(test_data[start:end], scd.test_nonce[i])) chain.wait.for_receipt(reveal_tx[i]) # Wait until the test reveal period ends chain.wait.for_block(init3_block_number + submission_t + test_reveal_t) # Evaluate the submitted solution eval_tx = danku.transact().evaluate_model(submission_id) # Wait until the evaluation period ends chain.wait.for_block(init3_block_number + submission_t + test_reveal_t + evaluation_t) bal2 = web3.eth.getBalance(offer_account) # Finalize the contract final_tx = danku.transact().finalize_contract() contract_finalized = danku.call().contract_terminated() dbg.dprint("Contract finalized: " + str(contract_finalized)) assert contract_finalized == True # Get best submission accuracy & ID best_submission_accuracy = danku.call().best_submission_accuracy() best_submission_index = danku.call().best_submission_index() dbg.dprint("Best submission ID: " + str(best_submission_index)) dbg.dprint("Best submission accuracy: " + str(best_submission_accuracy)) l_nn = [il_nn] + hl_nn + [ol_nn] input_layer = train_data[:2] hidden_layers = [0] * sum(hl_nn) output_layer = [0] * ol_nn weights = int_packed_trained_weights biases = int_packed_trained_biases # Test forward fwd_pass2 = danku.call().forward_pass2(l_nn, input_layer, hidden_layers, output_layer, weights, biases) dbg.dprint("Test input: " + str(train_data[:2])) dbg.dprint("Expected output: " + str(train_data[2])) dbg.dprint("local nn prediction: " + str(nn.predict([train_data[:2]]))) dbg.dprint("forward_pass2: " + str(fwd_pass2)) bal = web3.eth.getBalance(solver_account) # Verify that the solver account didn't receive the reward amount assert bal == 1000000000000000000000000 bal = web3.eth.getBalance(offer_account) # Verify the offer account got refunded the reward amount assert bal == 999999999999999999978960
import datetime import sys import os import shutil from time import sleep import secrets rootDir = "." while 1 == 1: for dirName, subdirList, fileList in os.walk(rootDir): for fName in fileList: changeflag = 0 if '.xml' in fName or '.html' in fName: inName = os.path.join(dirName, fName) if 'target' in inName: pass else: infile = open(inName, "r", errors='ignore') for line in infile: print(line, end='') sleep(0.025) infile.close() sleep(secrets.randbelow(100) / 1000)
def select_random(name_list, name_dict): for i in range(100): n = secrets.randbelow(len(name_dict)) name_dict[name_list[n]] += 1 return name_dict
def random(num): return ''.join([alphabet[secrets.randbelow(len(alphabet))] for i in range(num)])
async def cycler(ev): """ :param ev: The event object referenced in the event. :type ev: sigma.core.mechanics.event.SigmaEvent """ raffle_coll = ev.db[ev.db.db_nam].Raffles while True: if ev.bot.is_ready(): # noinspection PyBroadException try: now = arrow.utcnow().float_timestamp raffles = await raffle_coll.find({ 'end': { '$lt': now }, 'active': True }).to_list(None) if raffles: for raffle in raffles: cid = raffle.get('channel') aid = raffle.get('author') mid = raffle.get('message') icon = raffle.get('icon') title = raffle.get('title') color = raffle.get('color') channel = await ev.bot.get_channel(cid) if channel: await raffle_coll.update_one( raffle, {'$set': { 'active': False }}) message = await channel.fetch_message(mid) if message: custom_emote = icon.startswith( '<:') and icon.endswith('>') if custom_emote: emote = get_matching_emote( message.guild, icon) if emote: icon = emote.name contestants = [] reactions = message.reactions for reaction in reactions: rem_nam = str(reaction.emoji) custom_rem = rem_nam.startswith( '<:') and rem_nam.endswith('>') if custom_rem: rem_emote = get_matching_emote( message.guild, rem_nam) if rem_emote: rem = rem_emote.name else: rem = None else: rem = reaction.emoji if rem: if rem == icon: async for user in reaction.users(): if not user.bot: contestants.append(user) break if contestants: automatic = raffle.get('automatic', False) if automatic: if not (aid in ev.bot.cfg.dsc.owners or aid == ev.bot.user.id): automatic = False contestants = extra_shuffle(contestants) draw_count = min( len(contestants), raffle.get('draw_count', 1)) for _ in range(draw_count): winner = contestants.pop( secrets.randbelow( len(contestants))) amen = f'<@{aid}>' wmen = f'<@{winner.id}>' ender = '' if title[ -1] in string.punctuation else '!' win_text = f'{raffle.get("icon")} Hey {amen}, {wmen} won your raffle!' win_embed = discord.Embed(color=color) win_title = f'{winner.name} won {title.lower()}{ender}' if automatic: await auto_award( ev, winner, raffle) win_embed.set_footer( text= 'The reward has been automatically transferred.' ) win_embed.set_author( name=win_title, icon_url=user_avatar(winner)) await channel.send(win_text, embed=win_embed) ev.log.info( f'{winner} won {aid}\'s raffle {raffle.get("id")} in {cid}.' ) except Exception as e: ev.log.error(e) pass await asyncio.sleep(1)
embeds.append(embed) await self.bot.paginator.Paginator(extras=embeds).paginate(ctx) @has_char() @is_class("Thief") @user_cooldown(3600) @commands.command() @locale_doc async def steal(self, ctx): _("""[Thief Only] Steal money!""") if (buildings := await self.bot.get_city_buildings(ctx.character_data["guild"])): bonus = buildings["thief_building"] * 5 else: bonus = 0 if secrets.randbelow(100) in range( 1, self.bot.get_class_grade_from(ctx.character_data["class"], "Thief") * 8 + 1 + bonus, ): async with self.bot.pool.acquire() as conn: usr = await conn.fetchrow( 'SELECT "user", "money" FROM profile WHERE "money">=10 AND "user"!=$1 ORDER BY RANDOM() LIMIT 1;', ctx.author.id, ) if usr["user"] in self.bot.owner_ids: return await ctx.send( _("You attempted to steal from a bot VIP, but the bodyguards caught you." ))
keyDetails = json.load(key_file) key_file.close() nonce = bytes.fromhex(keyDetails['nonce']) authTag = bytes.fromhex(keyDetails['authTag']) ciphertextPubKey = ec.Point(self.curve, keyDetails['x'], keyDetails['y']) privateKey = int(keyDetails['privateKey']) decryptedMsg = self.decrypt_helper(cipher_bytes, nonce, authTag, ciphertextPubKey, privateKey) return decryptedMsg if __name__ == "__main__": ecc = Cipher() msg = b'This is a test' print("original msg:", msg) privateKey = secrets.randbelow(0xAAAAAAAAAAAAAAAAAAA) publicKey = ecc.get_public_key(privateKey) ciphertext, nonce, authTag, ciphertextPubKey = ecc.encrypt_helper( msg, publicKey) print("encrypted msg:", ciphertext) decryptedMsg = ecc.decrypt_helper(ciphertext, nonce, authTag, ciphertextPubKey, privateKey) print("decrypted msg:", decryptedMsg)
def random_str(): # Generate a random size string rand_str = '' for i in range(0, 1 + secrets.randbelow(25)): rand_str += string.ascii_lowercase[secrets.randbelow(26)] # each char is a random downcase letter [a-z] return rand_str
def random_discount_rate(): id_lst = [] range_limit = Goods.objects.all().count() while True: val = secrets.randbelow(range_limit) if val in id_lst: continue elif val == 0: continue else: id_lst.append(val) if len(id_lst) == 200: break s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 = SaleInfo.objects.all()[:10] for index, id in enumerate(id_lst): if index < 20: print('5-----------------------------------', index) goods = Goods.objects.get(id=id) goods.sales = s1 goods.save() elif index >= 20 and index < 40: print('10---------------', index) goods = Goods.objects.get(id=id) goods.sales = s2 goods.save() elif index >= 40 and index < 60: print('15-----------', index) goods = Goods.objects.get(id=id) goods.sales = s3 goods.save() elif index >= 60 and index < 80: print('20------------', index) goods = Goods.objects.get(id=id) goods.sales = s4 goods.save() elif index >= 80 and index < 100: print('25-----------', index) goods = Goods.objects.get(id=id) goods.sales = s5 goods.save() elif index >= 100 and index < 120: print('30-----------', index) goods = Goods.objects.get(id=id) goods.sales = s6 goods.save() elif index >= 120 and index < 140: print('35-----------', index) goods = Goods.objects.get(id=id) goods.sales = s7 goods.save() elif index >= 140 and index < 160: print('40-----------', index) goods = Goods.objects.get(id=id) goods.sales = s8 goods.save() elif index >= 160 and index < 180: print('45-----------', index) goods = Goods.objects.get(id=id) goods.sales = s9 goods.save() elif index >= 180 and index < 200: print('50-----------', index) goods = Goods.objects.get(id=id) goods.sales = s10 goods.save()
@has_god() @user_cooldown(86_400) @commands.command() @locale_doc async def pray(self, ctx): _("""Pray to your deity to gain favor.""") if (rand := secrets.randbelow(3)) == 0: message = secrets.choice([ _("They obviously didn't like your prayer!"), _("Noone heard you!"), _("Your voice has made them screw off."), _("Even a donkey would've been a better follower than you."), ]) val = 0 elif rand == 1: val = secrets.randbelow(500) + 1 message = secrets.choice([ _("„Rather lousy, but okay“, they said."), _("You were a little sleepy."), _("They were a little amused about your singing."), _("Hearing the same prayer over and over again made them tired." ), ]) await self.bot.pool.execute( 'UPDATE profile SET "favor"="favor"+$1 WHERE "user"=$2;', val, ctx.author.id, ) elif rand == 2: val = secrets.randbelow(500) + 500 message = secrets.choice([
def test_successful_contract_cancellation(web3, chain): _hashed_data_groups = [] accuracy_criteria = 9950 # 99.50% w_scale = 1000 # Scale up weights by 1000x b_scale = 1000 # Scale up biases by 1000x dbg.dprint("Start amount bal[0]: " + str(web3.eth.getBalance(web3.eth.accounts[0]))) danku, _ = chain.provider.get_or_deploy_contract('Danku') offer_account = web3.eth.accounts[1] solver_account = web3.eth.accounts[2] # Fund contract web3.eth.sendTransaction({ 'from': offer_account, 'to': danku.address, 'value': web3.toWei(1, "ether") }) # Check that offerer was deducted bal = web3.eth.getBalance(offer_account) # Deduct reward amount (1 ETH) and gas cost (21040 wei) assert bal == 999998999999999999978960 wallet_amount = 1000000000000000000000000 # minus the reward amount scd = SampleHalfDividedDataset(training_percentage=0.8) scd.generate_nonce() scd.sha_all_data_groups() dbg.dprint("All data groups: " + str(scd.data)) dbg.dprint("All nonces: " + str(scd.nonce)) # Initialization step 1 dbg.dprint("Hashed data groups: " + str(scd.hashed_data_group)) dbg.dprint("Hashed Hex data groups: " + str(list(map(lambda x: "0x" + x.hex(), scd.hashed_data_group)))) # Keep track of all block numbers, so we can send them in time # Start at a random block between 0-1000 chain.wait.for_block(randbelow(1000)) dbg.dprint("Starting block: " + str(web3.eth.blockNumber)) init1_tx = danku.transact().init1(scd.hashed_data_group, accuracy_criteria, offer_account) chain.wait.for_receipt(init1_tx) init1_block_number = web3.eth.blockNumber dbg.dprint("Init1 block: " + str(init1_block_number)) submission_t = danku.call().submission_stage_block_size() # get submission timeframe evaluation_t = danku.call().evaluation_stage_block_size() # get evaluation timeframe test_reveal_t = danku.call().reveal_test_data_groups_block_size() # get revealing testing dataset timeframe # Initialization step 2 # Get data group indexes chain.wait.for_block(init1_block_number + 1) dgi = [] init2_block_number = web3.eth.blockNumber dbg.dprint("Init2 block: " + str(init2_block_number)) for i in range(scd.num_data_groups): dgi.append(i) dbg.dprint("Data group indexes: " + str(dgi)) init2_tx = danku.transact().init2() chain.wait.for_receipt(init2_tx) # Cancel contract before init3() danku.transact().cancel_contract() contract_finalized = danku.call().contract_terminated() assert contract_finalized == True dbg.dprint("Contract finalized: " + str(contract_finalized)) bal = web3.eth.getBalance(solver_account) # Verify that the solver account didn't receive the reward amount assert bal == 1000000000000000000000000 bal = web3.eth.getBalance(offer_account) # Verify the offer account got refunded the reward amount assert bal == 999999999999999999978960
#!/usr/bin/env python3 import argparse import uuid import secrets parser = argparse.ArgumentParser() parser.add_argument('--months', type=int, required=True) parser.add_argument('--stocks', type=int, required=True) args = parser.parse_args() months = args.months stocks = args.stocks print(months) print(stocks) for s in range(stocks): print(f"Shady-Co-{s}") print(" ".join([str(secrets.randbelow(4950) + 1) for m in range(months)]))
def test_create_folder_no_parent(foss: Fossology): parent = Folder(secrets.randbelow(1000), "Parent", "", 0) with pytest.raises(AuthorizationError) as excinfo: foss.create_folder(parent, "FossFolderNoParent") assert f"Folder creation in folder {parent.id} not authorized" in str(excinfo.value)
random.seed(1) print(random.random()) print(random.randint(1, 10)) random.seed(2) print(random.random()) print(random.randint(1, 10)) random.seed(1) print(random.random()) # same as seed 1 print(random.randint(1, 10)) random.seed(2) print(random.random()) # same as seed 2 print(random.randint(1, 10)) print() import secrets # used for security purposes, takes longer time x = secrets.randbelow(10) # random int from 0 to 9, upper bound not included print(x) y = secrets.randbits(5) # return a binary representation of an int with given number of bits # e.g. 10001, which is 17 print(y) my_list = list("ABCDEFG") z = secrets.choice(my_list) print(z) print() import numpy as np p = np.random.rand(3) # a np array of length n with random float from 0 to 1 print(p) p = np.random.rand(3, 3) # a np array of provided args shape with random float from 0 to 1 print(p) q = np.random.randint(0, 10, 3) # a np array of length n with random int from 0 to 10, upper bound not included
def vector_sum_magnitude(magnitude1, theta1, magnitude2, theta2): return math.sqrt(magnitude1**2 + magnitude2**2 + 2 * magnitude1 * magnitude2 * math.cos(theta2 - theta1)) def vector_sum_angle(magnitude1, theta1, magnitude2, theta2): return theta1 + math.atan2( magnitude2 * math.sin(theta2 - theta1), magnitude1 + magnitude2 * math.cos(theta2 - theta1)) # Let's add random walk vectors! All same length, but random direction polar_vectors = [] for w in range(walker_count): polar_vectors.append([(vector_magnitude, secrets.randbelow(361)) for i in range(polar_vector_count)]) # oh no all these vectors stack on top of one another # we have to convert them all into bector from origin if we want to plot them rmax = 0 magnitudes = [] thetas = [] for w in range(walker_count): latest_vector = (0, 0) magnitude = [0] theta = [0] for v in polar_vectors[w]: r = vector_sum_magnitude(latest_vector[0], latest_vector[1], v[0], v[1])
def r_change(self): loc = sec.randbelow(self.__size) self.__r_modify(loc)
def cycle(self): # cannot update dict while iterating so add children after loop new_len = len(self.organisms) - 1 new_organism_keys = [] new_organism_stats = [] all_stats = {} for o in self.organisms: all_stats[o] = self.organisms[o].get_stats() # take top half sorted_stats = sorted(all_stats.items(), key=lambda x: x[1]) #pdb.set_trace() for o in self.organisms: #pdb.set_trace() stats = self.organisms[o].get_stats() #print(o) if (stats == None): # organism is not accounted for continue if (stats == 0): # kill off organisms with no traits print("No organism") continue # find organism relative position p = 0 while (sorted_stats[p][0] != o): p = p + 1 #pdb.set_trace() if (p >= len(sorted_stats) / 2.0): new_len = new_len + 1 new_organism_keys.append(new_len) new_organism_stats.append(self.organisms[o].stats) #self.organisms[len(self.organisms)+1] = Organisms(self.traits) """ if(stats >= self.traits/2): # asexually create new children new_len = new_len + 1 new_organism_keys.append(new_len) new_organism_stats.append(self.organisms[o].stats) #self.organisms[len(self.organisms)+1] = Organisms(self.traits) """ # events that can kill rand = secrets.randbelow(101) if (rand > 90): for s in self.organisms[o].stats: self.organisms[o].stats[s] = 0 continue # add new children n = 0 #pdb.set_trace() while (n < len(new_organism_keys)): self.organisms[new_organism_keys[n]] = Organisms(self.traits) self.organisms[new_organism_keys[n]].child(new_organism_stats[n]) # potentially mutate new children for bit in self.organisms[new_organism_keys[n]].stats: rand_mut = secrets.randbelow(101) if (rand_mut > 80): # flip bits print("Mutated O=" + str(new_organism_keys[n])) if (self.organisms[new_organism_keys[n]].stats[bit] == 1): self.organisms[new_organism_keys[n]].stats[bit] = 0 else: self.organisms[new_organism_keys[n]].stats[bit] = 1 n = n + 1 continue for k in self.organisms: print("Organism: " + str(k) + " Traits: " + str(self.organisms[k].stats))
def __r_nucleo(self): return Nucleo(sec.randbelow(len(Nucleo))).name
async def trivia(cmd, message, args): global trivia_cache if not cmd.bot.cool_down.on_cooldown(cmd.name, message.author): if message.author.id not in ongoing_list: ongoing_list.append(message.author.id) allotted_time = 20 if not trivia_cache: trivia_api_url = 'https://opentdb.com/api.php?amount=50' async with aiohttp.ClientSession() as session: async with session.get(trivia_api_url) as number_get: number_response = await number_get.read() data = json.loads(number_response) trivia_cache += data['results'] data = trivia_cache.pop(secrets.randbelow(len(trivia_cache))) cmd.bot.cool_down.set_cooldown(cmd.name, message.author, 30) question = data['question'] question = ftfy.fix_text(question) category = data['category'] correct_answer = data['correct_answer'] correct_answer = ftfy.fix_text(correct_answer) incorrect_answers = data['incorrect_answers'] difficulty = data['difficulty'] kud_reward = awards.get(difficulty) or '10' choice_list = [correct_answer] + incorrect_answers choice_list = shuffle_questions(choice_list) choice_number = 0 choice_lines = [] for choice in choice_list: choice_number += 1 choice_line = f'[{choice_number}] {choice}' choice_lines.append(choice_line) choice_text = '\n'.join(choice_lines) choice_text = ftfy.fix_text(choice_text) if difficulty == 'easy': starter = 'An' else: starter = 'A' question_embed = discord.Embed(color=0xF9F9F9, title='❔ Here\'s a question!') question_embed.description = f'{starter} {difficulty} one from the {category} category.' question_embed.add_field(name='Question', value=question, inline=False) question_embed.add_field(name='Choices', value=f'```py\n{choice_text}\n```', inline=False) question_embed.set_footer( text='Input the number of your chosen answer.') question_embed.set_author(name=message.author.display_name, icon_url=user_avatar(message.author)) await message.channel.send(embed=question_embed) def check_answer(msg): if message.channel.id == msg.channel.id: if message.author.id == msg.author.id: try: int(msg.content) number = True except ValueError: number = False if number or (msg.content.title() in choice_list): correct = True else: correct = False else: correct = False else: correct = False return correct try: answer_message = await cmd.bot.wait_for('message', check=check_answer, timeout=allotted_time) try: answer_index = int(answer_message.content) - 1 except ValueError: answer_index = None correct_index = get_correct_index(choice_list, correct_answer) if answer_index == correct_index or answer_message.content.lower( ) == correct_answer.lower(): cmd.db.add_currency(answer_message.author, message.guild, kud_reward) author = answer_message.author.display_name currency = cmd.bot.cfg.pref.currency win_title = f'🎉 Correct, {author}, it was {correct_answer}. You won {kud_reward} {currency}!' final_embed = discord.Embed(color=0x77B255, title=win_title) else: lose_title = f'💣 Ooh, sorry, it was {correct_answer}...' final_embed = discord.Embed(color=0x262626, title=lose_title) await message.channel.send(embed=final_embed) except asyncio.TimeoutError: timeout_title = f'🕙 Time\'s up! It was {correct_answer}...' timeout_embed = discord.Embed(color=0x696969, title=timeout_title) await message.channel.send(embed=timeout_embed) if message.author.id in ongoing_list: ongoing_list.remove(message.author.id) else: ongoing_error = discord.Embed( color=ERROR, title='❗ There is one already ongoing.') await message.channel.send(embed=ongoing_error) else: timeout = cmd.bot.cool_down.get_cooldown(cmd.name, message.author) on_cooldown = discord.Embed( color=0xccffff, title=f'❄ On cooldown for another {timeout} seconds.') await message.channel.send(embed=on_cooldown)
import secrets from django.core.files.uploadedfile import InMemoryUploadedFile from django.http import QueryDict from imagekit.utils import get_cache from imagekit.models import ProcessedImageField import hashlib from openbook_common.utils.model_loaders import get_post_model r = lambda: secrets.randbelow(255) def normalise_request_data(request_data): """ request.data is a QueryDict if multiform request and dict if JSON request This normalises the data :param request_data: :return: """ if not request_data: return {} if isinstance(request_data, QueryDict): return request_data.dict() return {**request_data} def nomalize_usernames_in_request_data(request_data): normalize_list_value_in_request_data(list_name='usernames', request_data=request_data)
def test_randbelow(self): # Test randbelow. for i in range(2, 10): self.assertIn(secrets.randbelow(i), range(i)) self.assertRaises(ValueError, secrets.randbelow, 0) self.assertRaises(ValueError, secrets.randbelow, -1)
def sign(self, message): k = secrets.randbelow(self.q-1) r = pow(self.g, k, self.p) % self.q s = (modinv(k, self.q) * (int(SHA1(message), 16) + self.x * r)) % self.q return [r, s, self.p, self.q, self.g, self.y]
b1 = 0.5 in_put = np.random.rand(1, 4) in_put = np.array(in_put, dtype=np.float64) hidden = np.random.rand(4, 4) hidden = np.array(hidden, dtype=np.float64) output = np.random.rand(3, 4) output = np.array(output, dtype=np.float64) res = np.random.rand(1, 3) res = np.array(res, dtype=np.float64) ErrorTab = [] dec = 0.0 # zbiór treningowy for i in range(100000): # warstwa wejścia RandRow = randbelow(120) #rd.randint(0,7) in_put = data[RandRow, [0, 1, 2, 3]] neuronArray(data[RandRow, [4]]) # warstwa ukrytwa hidden_out = function(in_put.dot(hidden.transpose()).transpose() + dec) out_out = function(hidden_out.dot(output.transpose()).transpose() + dec) # warstwa wyjścia diff_out = ((-1) * np.subtract(res, out_out)) * (out_out * (1 - out_out)) diffCalcOut = (diff_out * (np.vstack( (hidden_out, hidden_out, hidden_out)).transpose())).transpose() diffCalcOut = (output - (b1 * diffCalcOut)) # korekty diff_hid = (diff_out.dot(output)) * (hidden_out * (1 - hidden_out))
def rand_range(lower_inclusive: int, upper_exclusive: int) -> Callable[[], int]: return lambda: lower_inclusive + secrets.randbelow(upper_exclusive - lower_inclusive)
def _generate_id(): # from: https://messenger.klinkerapps.com/resources/js/helper.js MAGIC = 922337203685477 return randbelow(MAGIC - 1) + 1 # between 1 and MAGIC
def __init__(self, size_x, size_y): self.x = randbelow(size_x) self.y = randbelow(size_y)