Exemplo n.º 1
0
def simul(discipline, rho, k, seed):
    if seed == "-1":
        seed = None
    master = Master()
    results_w, results_w_icl, results_w_icu, \
        results_w_vars, results_w_vars_icl, results_w_vars_icu, \
        results_nq, results_nq_icl, results_nq_icu, \
        results_nq_vars, results_nq_vars_icl, results_nq_vars_icu, \
        execution_time = master.webmain(discipline, rho, k, seed)
    execution_time = "Execution time: {0:.2f} seconds".format(execution_time)
    discipline = "FCFS" if discipline == 1 else "LCFS"
    return render_template("simulation.html",
                           discipline=discipline,
                           rho=rho,
                           results_w=json.dumps(results_w),
                           results_w_icl=json.dumps(results_w_icl),
                           results_w_icu=json.dumps(results_w_icu),
                           results_w_vars=json.dumps(results_w_vars),
                           results_w_vars_icl=json.dumps(results_w_vars_icl),
                           results_w_vars_icu=json.dumps(results_w_vars_icu),
                           results_nq=json.dumps(results_nq),
                           results_nq_icl=json.dumps(results_nq_icl),
                           results_nq_icu=json.dumps(results_nq_icu),
                           results_nq_vars=json.dumps(results_nq_vars),
                           results_nq_vars_icl=json.dumps(results_nq_vars_icl),
                           results_nq_vars_icu=json.dumps(results_nq_vars_icu),
                           execution_time=execution_time)
    def test_two_particles_can_be_far_away(self):
        master = Master(100, 1)
        master.create_nanoparticles_and_ligands(2, 10, 10, 1)
        master.agents[0].position = np.array([1, 1, 1])
        position = np.array([50, 50, 50])

        self.assertTrue(master._check_space_available_nanoparticle(position))
Exemplo n.º 3
0
def main():
	master=Master()
	master.start()	
	master.join()
	#run()
	print "Server is dead"	
	return 0
Exemplo n.º 4
0
 def __init__(self):
     Master.__init__(self)
     #self.proxy = {}
     self.params = {}
     #self.params['proxy_ip'] = { 'https': 'socks5://127.0.0.1:9050',}
     self.proxy_list = self.initProxies()
     self.params['return_error_page'] = 1
    def test_correct_number_of_nanoparticles_are_created(self):
        master = Master(100, 1)
        master.create_nanoparticles_and_ligands(10, 1, 1, 1)
        self.assertEqual(10, master.number_of_nanoparticles)

        agents = [i for i in master.agents if isinstance(i, Nanoparticle)]
        self.assertEqual(10, len(agents))
 def test_no_nanoparticles_are_touching(self):
     master = Master(1000, 1)
     master.create_nanoparticles_and_ligands(100, 10, 10, 1)
     positions = [i.position for i in master.agents]
     combs = combinations(positions, 2)
     distance = [np.linalg.norm(a - b) for (a, b) in combs]
     self.assertTrue(all([i > 22 for i in distance]))
Exemplo n.º 7
0
def test_mult():
    key_cipher = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                           for j in range(4)],
                          dtype=GF2int)
    v1 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                   for j in range(4)],
                  dtype=GF2int)
    v2 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                   for j in range(4)],
                  dtype=GF2int)
    sub = Master.get_one_sub(key_cipher)

    shares1 = Master.get_shares(v1, sub)
    shares2 = Master.get_shares(v2, sub)
    sub.initShares(shares1)
    for s, mini in enumerate(sub.minicircuits):
        mini.state2 = shares2[s]

    sub.multiply(inputs1=[mini.state2 for mini in sub.minicircuits])

    reconstruct = Master.reconstructShares(sub)
    if not np.array_equal(v1 * v2, reconstruct):
        return 0
    else:
        return 1
def main():

    master = Master()
    logging.basicConfig(filename='work.log', level=logging.DEBUG)

    #Init by filling root
    for i in range(0, ROOTCOUNT):
        master.AddRoot(randint(18, 21), 1024)

    #Init
    for i in range(1000):
        #print "Adding node"
        retval = ADD(master)
        #if retval == 2:
        #    print "Added as root"
        #elif retval == 1:
        #    print "Added to some root"
        if retval == 0:
            print "Failed????"

    while True:
        #0 - Insrt
        #1 - Delete
        #2 - Nothing
        #Decide what to do
        choice = randint(0, 2)
        if choice == 0:
            ADD(master)
        elif choice == 1:
            DEL(master)
        else:
            time.sleep(1)
    def test_two_particles_cannot_be_in_same_positions(self):
        master = Master(100, 1)
        master.create_nanoparticles_and_ligands(2, 10, 10, 1)
        master.agents[0].position = np.array([1, 1, 1])
        position = np.array([1, 1, 1])

        self.assertFalse(master._check_space_available_nanoparticle(position))
 def test_correct_number_ligands_are_created(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(100, 10, 1, 1)
     self.assertEqual(master.ligand_length, 1)
     self.assertEqual(master.number_of_ligands, 10)
     ligands = [i.ligands for i in master.agents]
     for l in ligands:
         self.assertEqual(10, len(l))
Exemplo n.º 11
0
def preprocesse_file(name):
    with open(name) as fobj:
        lines = fobj.readlines()
    pool = Master()
    results = [x for x in pool.do(lines, preprocessing) if (x is not None) and (len(x) > 2)]
    with open("./preprocessing/"+ name.split("/")[-1], "w") as file:
        file.write(" \n".join(results))
    return "./preprocessing/"+ name.split("/")[-1]
 def test_no_nanoparticles_outside_area(self):
     master = Master(1000, 1)
     master.create_nanoparticles_and_ligands(100, 10, 10, 1)
     positions = [i.position for i in master.agents]
     self.assertTrue(
         all([(i[0] < 1000 and i[1] < 1000 and i[2] < 1000)
              for i in positions]))
     self.assertTrue(
         all([(i[0] > 0 and i[1] > 0 and i[2] > 0) for i in positions]))
Exemplo n.º 13
0
def validate_file(name):
    with open(name) as fobj:
        lines = fobj.readlines()
    master = Master()
    results = master.do(lines, valid_line)
    print(results)
    print(any(results))
    answer = any(results)
    return answer
Exemplo n.º 14
0
def assignMasterSlave(robot1, robot2):

    if robot1.type == robot2.type:
        printc("On ne peut pas permuter 2 " + robot2.type, 'Fail')

    if robot1.type == "Slave":
        slave = Slave(robot1.s, robot1.hostname)
        master = Master(robot2.s, robot2.hostname)
    else:
        slave = Slave(robot2.s, robot2.hostname)
        master = Master(robot1.s, robot1.hostname)
    return master, slave
 def test_no_receptor_bases_outside_area(self):
     for _ in range(100):
         master = Master(500, 1)
         master.create_nanoparticles_and_ligands(100, 10, 10, 1)
         positions = [
             i.base_position for i in master.agents
             if isinstance(i, Receptor)
         ]
         self.assertTrue(
             all([(i[0] < 1000 and i[1] < 1000 and i[2] < 1000)
                  for i in positions]))
         self.assertTrue(
             all([(i[0] > 0 and i[1] > 0 and i[2] > 0) for i in positions]))
Exemplo n.º 16
0
def test_AES():
    # INIT KEYS AND PLAINTEXT

    key1 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)
    key2 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)
    key3 = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                     for j in range(4)],
                    dtype=GF2int)

    key1 = "".join(format(y, '02x') for x in key1 for y in x)
    key2 = "".join(format(y, '02x') for x in key2 for y in x)
    key3 = "".join(format(y, '02x') for x in key3 for y in x)

    key_cipher = np.array([[GF2int(0) for i in range(4)] for j in range(4)],
                          dtype=GF2int)
    plain_text = np.array([[GF2int(0) for i in range(4)] for j in range(4)],
                          dtype=GF2int)

    plain_text_str = "".join(format(y, '02x') for x in plain_text for y in x)
    key_cipher_str = "".join(format(y, '02x') for x in key_cipher for y in x)

    aes_ref = AES.new(key_cipher_str)
    cipher_ref_str = aes_ref.encrypt(plain_text_str).encode("hex")
    W = aes.ExpandRoundKey(key_cipher)
    master = Master(key_cipher, 4)
    keys = [key1, key2, key3]
    sub = SubCircuit(
        np.array([
            MiniCircuit(keys[s % 3], keys[(s + 1) % 3], W) for s in range(3)
        ]))

    randomness = sub.getCorrRandom()
    shares = [Secret(), Secret(), Secret()]
    for s in range(0, 3):
        shares[s].alpha = randomness[s]
        shares[s].x = plain_text + randomness[(s - 1) % 3]
    W = aes.ExpandRoundKey(key_cipher)
    sub.initShares(shares)
    sub.AES()

    shared = master.reconstructShares(sub)

    state = aes.AES(key_cipher, plain_text)
    if (not np.array_equal(state, shared)):
        return 0
    else:
        return 1
Exemplo n.º 17
0
def main():

    GPIO.setmode(GPIO.BOARD)

    GPIO.setup(16, GPIO.IN)

    m = Master()

    if GPIO.input(16) == GPIO.HIGH:
        print("Stromlimit erreicht")

    while True:
        m.work()
        time.sleep(0.1)
Exemplo n.º 18
0
    def __init__(self, ip_address, orders_file_path):
        super(Daemon, self).__init__()

        self.__commands = Commands(orders_file_path)

        self.__master = Master(0, "00:00:00:00:00:00", ip_address, "0", 0)

        self.__master.add_stack(Stack(0,0))

        self.__udp_comm = CommunicatorUDP(42666, self.__master.get_ip_address())

        self.__udp_comm.open_communication()
        print("Master listening on {}:{}".format(ip_address, 42666))
        
        self.__i2c_comm = CommunicatorI2C()
Exemplo n.º 19
0
 def loop_Validator(self):
     with open("./pids/validator.pid", "w") as fobj:
         fobj.write(str(os.getpid()))
     workers = Master()
     redis_connector = RedisWrapper()
     worker = ValidatorService(redis_connector, workers, validate_file)
     worker.start_loop()
Exemplo n.º 20
0
 def loop_Preprocessor(self):
     with open("./pids/preprocessing.pid", "w") as fobj:
         fobj.write(str(os.getpid()))
     workers = Master()
     redis_connector = RedisWrapper()
     worker = PeprocessService(redis_connector, workers, preprocesse_file)
     worker.start_loop()
Exemplo n.º 21
0
 def loop_SessionGenerator(self):
     with open("./pids/sessions.pid", "w") as fobj:
         fobj.write(str(os.getpid()))
     workers = Master()
     redis_connector = RedisWrapper()
     worker = SessionGeneratorService(redis_connector, workers,
                                      SessionGeneratorWorker().generate)
     worker.start_loop()
 def __init__(self, clientId, data, verifykey, apiEndPoint):
     self.message = data
     self.sessionkey = verifykey
     self.apiEndPoint = apiEndPoint
     self.splitUrl = apiEndPoint.split('/')
     self.auth = Authentication()
     self.master = Master()
     self.admin = Admin()
     self.role = roleManage()
     self.attendance = attendanceManage()
     self.project = projectManage()
     self.labourer = labbourerManage()
     self.labclass = labourerClass()
     self.shift = shiftManage()
     self.log = Logger()
     self.paymentDesk = paymentDesk()
     self.clientId = clientId
Exemplo n.º 23
0
def binding_energy():
    print('Binding Energy -------------')
    d = np.linspace(5, 25, 5).tolist()
    data = {}
    means = []
    errors = []
    time_data = []
    for i in d:
        variable_finals = []
        for _ in range(3):
            number_of_seconds = 1  # i.e. 1 hour = 3600 seconds
            model = Master(dimension=1000,
                           binding_energy=int(i),
                           time_unit=10e-3,
                           number_of_receptors=2,
                           receptor_length=100,
                           number_of_nanoparticles=1,
                           nanoparticle_radius=50,
                           number_of_ligands=2,
                           ligand_length=7,
                           binding_distance=4,
                           receptor_radius=3,
                           ligand_radius=3,
                           cell_diffusion_coef=1)
            model.create_receptors()  # 100 nm for receptor
            model.create_nanoparticles_and_ligands(
            )  # 1-2 nm for ligand  # 95 particles
            print(
                f'{model.dimension/1000} μm\u00b3 system, {model.binding_energy} binding energy, {model.number_of_nanoparticles} Nanoparticles,\n'
                f'{model.nanoparticle_radius} nm Nanoparticle Radius, {model.number_of_ligands} Ligands, Ligand length {model.ligand_length} nm,\n'
                f'{model.number_of_receptors} Receptors, {model.receptor_length} nm Receptor length, {model.binding_distance} Binding distance'
            )
            model.run(steps=number_of_seconds)  # 3600 for 1 hour
            print(f'The surface coverage is {model.surface_coverage}')
            variable_finals.append(model.surface_coverage)
            time_data.append(np.array(model.coverage))
        mean_time = np.mean(time_data, axis=0)
        error_time = np.std(time_data, axis=0)
        data[f'{model.binding_energy} KT binding energy '] = np.array(
            [list(range(0, model.time + 1)), mean_time, error_time])
        mean_coverage = np.mean(np.array(variable_finals))
        print(f'The mean surface coverage is {mean_coverage}')
        errors.append(np.std(np.array(variable_finals)))
        means.append(np.mean(np.array(variable_finals)))
    plt.xlabel('Time (milliseconds)')
    plt.ylabel('Surface Coverage')
    for key, value in data.items():
        plt.plot(value[0], value[1], label=key)
        plt.fill_between(value[0],
                         value[1] - value[2],
                         value[1] + value[2],
                         alpha=0.2)
    plt.legend()
    plt.show()
    second_variable_plot('Binding energy (kt)', 'Surface Coverage', d, means,
                         errors)
Exemplo n.º 24
0
    def loop_Apriori(self):

        with open("./pids/apriory.pid", "w") as fobj:
            fobj.write(str(os.getpid()))

        workers = Master()
        redis_connector = RedisWrapper()
        worker = AprioriService(redis_connector, workers, None)
        worker.start_loop()
Exemplo n.º 25
0
def test_addKey():
    key_cipher = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                           for j in range(4)],
                          dtype=GF2int)
    v = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                  for j in range(4)],
                 dtype=GF2int)
    sub = Master.get_one_sub(key_cipher)

    shares = Master.get_shares(v, sub)
    sub.initShares(shares)
    sub.addKey(0)
    reconstruct = Master.reconstructShares(sub)

    if not np.array_equal(v + key_cipher, reconstruct):
        return 0
    else:
        return 1
Exemplo n.º 26
0
def test_Sbox():
    key_cipher = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                           for j in range(4)],
                          dtype=GF2int)
    v = np.array([[GF2int(randint(0, 255)) for i in range(4)]
                  for j in range(4)],
                 dtype=GF2int)
    sub = Master.get_one_sub(key_cipher)

    shares = Master.get_shares(v, sub)
    sub.initShares(shares)
    sub.SubBytes()
    reconstruct = Master.reconstructShares(sub)
    if not np.array_equal(np.array(sbox[np.array(v, dtype=int)], dtype=GF2int),
                          reconstruct):
        return 0
    else:
        return 1
Exemplo n.º 27
0
def main():
    master = Master()
    master.start()
    master.join()
    #run()
    print "Server is dead"
    return 0
 def test_all_receptors_have_correct_length(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(10, 1, 1, 1)
     master.create_receptors(10, 1)
     [
         self.assertEqual(1, a.receptor_length) for a in master.agents
         if isinstance(a, Receptor)
     ]
 def test_two_particles_can_be_really_close_without_touching(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(2, 10, 10, 1)
     master.agents[0].position = np.array([1, 1, 1])
     position = np.array([23, 1, 1])
     self.assertTrue(master._check_space_available_nanoparticle(position))
     x = 22 / np.sqrt(3) + 1
     position = np.array([x, x, x])
     self.assertTrue(master._check_space_available_nanoparticle(position))
 def test_two_particles_cannot_be_touching(self):
     master = Master(100, 1)
     master.create_nanoparticles_and_ligands(2, 10, 10, 1)
     master.agents[0].position = np.array([1, 1, 1])
     position = np.array([23 - 1e-10, 1, 1])
     self.assertFalse(master._check_space_available_nanoparticle(position))
     x = 22 / np.sqrt(3) + 1 - 1e-10
     position = np.array([x, x, x])
     self.assertFalse(master._check_space_available_nanoparticle(position))
Exemplo n.º 31
0
    def getListMaster(cursor):

        masters = []

        for (id_master, nm_email, nm_password, nr_killed, nr_life,
             dt_record) in cursor:
            master = Master()
            master.idMaster = id_master
            master.email = nm_email
            master.password = nm_password
            master.killed = nr_killed
            master.life = nr_life
            master.dateRecord = dt_record

            masters.append(master)

        return masters
Exemplo n.º 32
0
class Simulation(object):
	def __init__(self):
		self.master = Master()
		self.slave = Slave()

	def start_simulation(self):
		detections = 0
		numOfDetections = 4000
		timeArray = np.arange(numOfDetections)
		

		masters_clock = 1 # 1 - 16384

		# 15 + 1023 + 16 <- Max case
		# min 4 max 1054

		true_clock = 1
		while(detections < numOfDetections):
			self.master.tic(masters_clock)
			self.slave.tic()

			if masters_clock == 1:
				print true_clock
			#if true_clock >= 2048:
				#print '****************'
				#print 'Clock ' + str(true_clock)
				#print 'F1: ' + str(self.master.freqNumOne) + ' F2: ' + str(self.master.freqNumTwo)
				
			#if true_clock == 4096:
				#break;

			if self.master.slotMode == MasterSlotMode.tx:
				if (self.slave.sendFHS==True):
					print 'Assert: TX & slave sending FHS'
				if ((self.slave.inBackOffZone==False) & (self.slave.inOneSlotTo==False)):
					if ((self.slave.freqNum == self.master.freqNumOne) | (self.slave.freqNum == self.master.freqNumTwo)):
						self.slave.listen("Master_MAC")
						print '>> Hit at ' + str(true_clock)
			else: # in Rx mode
				if (self.slave.sendFHS==True):
					if ((self.slave.freqNum == self.master.freqNumOne) | (self.slave.freqNum == self.master.freqNumTwo)):
						time = true_clock
						timeArray[detections] = time

						# Reset Master & Slave
						self.slave.reset()
						self.master.resetTrain()
						masters_clock = 0 # because it will get increment at the end of while loop
						true_clock = 0

						detections = detections +1
					else:
						print 'Assert: RX & FHS sent, freqs didnt match ' + str(true_clock)
					

			#increment clocks
			true_clock = true_clock + 1
			masters_clock = masters_clock + 1
			if masters_clock > 16384:
				masters_clock = 1
				#self.master.resetTrain()
			
		rand_str = ''.join(random.choice(
                    string.ascii_lowercase
                    + string.ascii_uppercase
                    + string.digits)
               for i in range(5)) + '.csv'
		path = 'temp/'+rand_str
		#print timeArray
		np.savetxt(path, timeArray, delimiter=',', header='Time', fmt='%1.0f')
Exemplo n.º 33
0
	def __init__(self):
		self.master = Master()
		self.slave = Slave()
Exemplo n.º 34
0
	def __init__(self, master, name, pool, virt_co):
		
		self.master = master
		
		Master.__init__(self, name, pool, virt_co)
Exemplo n.º 35
0
import sys
import os 
import shutil
sys.path.append('src')

from Master import Master

if os.path.exists('Testing/Master'):
	shutil.rmtree('Testing/Master')

m = Master(name = 'Server01', debug=True, destination_folder='Testing/Master', expected_connections=2)
m.setServer(host='localhost', port=8080)
m.setDelimeter(':::')
m.run()