Esempio n. 1
0
    def playGame(self) -> None:
        player1 = Human("X","Player 1")
        player2  = None
        players = [player1]

        numPlayers = self.getNumPlayers()
        if numPlayers==1:
            player2 = CPU()
            player2.setOrder(2)
        else:
        	player2 = Human("O", "Player 2")
        players.append(player2)
        self.modifyTurnOrder(players)
        turn = 1
        playedMoves = []
        while not self.board.isGameOver() and turn<=9:
            self.board.display()
            print(players[(turn-1)%2].getName()+"'s Turn")
            move = players[(turn-1)%2].getMove(self.board.getBoard(), turn,copy.copy(playedMoves))
            playedMoves.append(move)
            self.board.update(move,players[(turn-1)%2].getSymbol())
            turn+=1

        self.board.display()
        if not self.board.isGameOver():
            print("It's a Draw :|")
        elif self.board.rowWinner()<0 or self.board.columnWinner()<0 or self.board.diagonalWinner()<0:
            print(players[1].getName(), "wins!")
        else:
            print(players[0].getName(), "wins!")
Esempio n. 2
0
def main():

    if algorithm == 'daxpy':

        RAM_size = 3 * dimension * float_size
        cpu = CPU(RAM_size=RAM_size,
                  cache_size=cache_size,
                  block_size=block_size,
                  associativity=associativity,
                  replacement=replacement)
        Daxpy(cpu)
        results(cpu, RAM_size)

    if algorithm == 'mxm':

        RAM_size = 3 * dimension**2 * float_size
        cpu = CPU(RAM_size=RAM_size,
                  cache_size=cache_size,
                  block_size=block_size,
                  associativity=associativity,
                  replacement=replacement)
        MXM(cpu)
        results(cpu, RAM_size)

    if algorithm == 'mxm_block':

        RAM_size = 3 * dimension * dimension * float_size
        cpu = CPU(RAM_size=RAM_size,
                  cache_size=cache_size,
                  block_size=block_size,
                  associativity=associativity,
                  replacement=replacement)
        MXMblock(cpu)
        results(cpu, RAM_size)
Esempio n. 3
0
def main():
    """main part"""
    temphumi = DHT22_AM2302(19)  # BCM 19 = PIN 35
    temp_cpu = CPU()

    measurements = {DS_TEMP1:   Measurements(3), \
                    DS_TEMPCPU: Measurements(3), \
                    DS_TEMP2:   Measurements(3), \
                    DS_HUMI:    Measurements(3)}

    rrd_template = DS_TEMP1   + ":" + \
                   DS_TEMPCPU + ":" + \
                   DS_TEMP2   + ":" + \
                   DS_HUMI

    while (True):
        _temp, _humi = temphumi.read()
        measurements[DS_TEMP1].append(_temp)
        measurements[DS_HUMI].append(_humi)
        measurements[DS_TEMPCPU].append(temp_cpu.read())
        measurements[DS_TEMP2].append(0)  # empty, for later useage

        rrd_data     = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                        ":{:.2f}".format(measurements[DS_HUMI].last())
        print strftime("%H:%M:%S", localtime()), rrd_data
        rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data)

        sleep(35)
Esempio n. 4
0
    def __init__(self, rom="invaders.rom"):
        self.cpu = CPU()
        self.memory = Memory()
        self.memory.Load(rom)

        self.ports = Puertos()
        self.Screen = Screen()
Esempio n. 5
0
    def placePieceGeneric(self, locI, locJ):
        board = CPU.convertBoard(self.cpu, self.getGameBoard())

        currTurn = self.getCurrTurn()
        if currTurn == "Player":
            player = -1
        else:
            player = 1
        five = self.fiveInARow(board, player)
        self.checkWin()
        if not self.getGameBoard()[locI][locJ].hasStone and not self.gameOver:

            # Check who's turn it is
            if currTurn == "Player":
                self.getGameBoard()[locI][locJ].click(currTurn)
                self.setCurrTurn("CPU")
                board = CPU.convertBoard(self.cpu, self.getGameBoard())
                five = self.fiveInARow(board, -1)
                self.checkWin()

                self.placePieceCPU()
            elif currTurn == "CPU":
                self.getGameBoard()[locI][locJ].click(currTurn)
                self.setCurrTurn("Player")
                board = CPU.convertBoard(self.cpu, self.getGameBoard())
                five = self.fiveInARow(board, 1)
                self.checkWin()
            else:
                return -1 # A problem occurred
        five = self.fiveInARow(board, player)
        board = CPU.convertBoard(self.cpu, self.getGameBoard())

        self.checkWin()
Esempio n. 6
0
def main():
    """main part"""
    sq = SensorQueueClient_write("../../configs/weatherqueue.ini")
    qvalue_temp = SensorValue("ID_06", "TempKinderzimmer",
                              SensorValue_Data.Types.Temp, "°C")
    qvalue_humi = SensorValue("ID_07", "HumiKinderzimmer",
                              SensorValue_Data.Types.Humi, "% rF")
    sq.register(qvalue_temp)
    sq.register(qvalue_humi)

    temphumi = DHT22_AM2302(19, qvalue_temp, qvalue_humi)  # BCM 19 = PIN 35
    temp_cpu = CPU()

    measurements = {DS_TEMP1:   Measurements(3), \
                    DS_TEMPCPU: Measurements(3), \
                    DS_TEMP2:   Measurements(3), \
                    DS_HUMI:    Measurements(3)}
    udp = Sender(CREDENTIALS)

    while (True):
        _temp, _humi = temphumi.read()
        measurements[DS_TEMP1].append(_temp)
        measurements[DS_HUMI].append(_humi)
        measurements[DS_TEMPCPU].append(temp_cpu.read_temperature())
        measurements[DS_TEMP2].append(0)  # empty, for later useage

        rrd_data = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                    ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                    ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                    ":{:.2f}".format(measurements[DS_HUMI].last())
        # Log(rrd_data)
        udp.send(rrd_data)

        sleep(35)
def get_exercise_three():
    return [
        [CPU(Constants.FIFO, get_exercise_three_processes()), Constants.FIFO],
        [CPU(Constants.SJF, get_exercise_three_processes()), Constants.SJF],
        [CPU(Constants.SRTF, get_exercise_three_processes()), Constants.SRTF],
        [CPU(Constants.RR, get_exercise_three_processes(), 4), Constants.RR]
    ]
Esempio n. 8
0
def main():
    """main part"""
    temphumi = DHT22_AM2302(19)  # BCM 19 = PIN 35
    temp_cpu = CPU()

    measurements = {
        DS_TEMP1: Measurements(3),
        DS_TEMPCPU: Measurements(3),
        DS_TEMP2: Measurements(3),
        DS_HUMI: Measurements(3),
    }

    rrd_template = DS_TEMP1 + ":" + DS_TEMPCPU + ":" + DS_TEMP2 + ":" + DS_HUMI

    while True:
        _temp, _humi = temphumi.read()
        measurements[DS_TEMP1].append(_temp)
        measurements[DS_HUMI].append(_humi)
        measurements[DS_TEMPCPU].append(temp_cpu.read())
        measurements[DS_TEMP2].append(0)  # empty, for later useage

        rrd_data = (
            "N:{:.2f}".format(measurements[DS_TEMP1].last())
            + ":{:.2f}".format(measurements[DS_TEMPCPU].last())
            + ":{:.2f}".format(measurements[DS_TEMP2].last())
            + ":{:.2f}".format(measurements[DS_HUMI].last())
        )
        print strftime("%H:%M:%S", localtime()), rrd_data
        rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data)

        sleep(35)
Esempio n. 9
0
    def __init__(self):
        super().__init__()

        self.code = 0

        self.cpu = CPU(None)  # 初始IM中的元素是none,到时候判断是否为none即可

        self.initUI()
Esempio n. 10
0
class Chip8:
    def __init__(self, rom_file):
        self.mem = Mem()
        self.mem.load_rom(rom_file)
        self.cpu = CPU(START_ADDRESS, self.mem)

    def run(self):
        while True:
            self.cpu.emulate_cycle()
Esempio n. 11
0
def main():
    channel.channel1.ChannelBusy = True
    channel.channel3.ChannelBusy = True
    channel.channel2.ChannelBusy = True

    while (not channel.ChannelIdle()):
        simulate()
        CPU.Process()
        CPU.IOInterrupt()
Esempio n. 12
0
class Machine:

    def __init__(self):
        self.memory = Memory()
        self.cpu = CPU(self.memory)
        self.memory.Init()

    def starting_up(self):
        self.cpu.run()

    def shut_down(self):
        pass
Esempio n. 13
0
def main():
    """main part"""
    temp1        = DS1820("/sys/bus/w1/devices/28-000006d62eb1/w1_slave")
    temp2        = DS1820("/sys/bus/w1/devices/28-000006dd6ac1/w1_slave")
    temp4        = DS1820("/sys/bus/w1/devices/28-000006de535b/w1_slave")
    temphumi     = DHT22_AM2302(21)   # BCM 21 = PIN 40
    tempcpu      = CPU()
    heatcontrol  = Schedules.Control(Schedules.ScheduleHeat(), heatlamp)
    lightcontrol = Schedules.Control(Schedules.ScheduleLight(), lightlamp)

    measurements = {DS_TEMP1:   Measurements(), \
                    DS_TEMP2:   Measurements(), \
                    DS_TEMP3:   Measurements(), \
                    DS_TEMP4:   Measurements(), \
                    DS_TEMPCPU: Measurements(), \
                    DS_HUMI:    Measurements()}
 
    rrd_template = DS_TEMP1   + ":" + \
                   DS_TEMP2   + ":" + \
                   DS_TEMP3   + ":" + \
                   DS_TEMP4   + ":" + \
                   DS_TEMPCPU + ":" + \
                   DS_HUMI    + ":" + \
                   DS_HEATING + ":" + \
                   DS_LIGHTING
                     
    while (True):
        measurements[DS_TEMP1].append(temp1.read())
        measurements[DS_TEMP2].append(temp2.read())
        measurements[DS_TEMP4].append(temp4.read())
        _temp3, _humi = temphumi.read()
        measurements[DS_TEMP3].append(_temp3)
        measurements[DS_HUMI].append(_humi)
        measurements[DS_TEMPCPU].append(tempcpu.read())

        heatcontrol.control(measurements[DS_TEMP3].avg())
        lightcontrol.control(measurements[DS_TEMP3].avg())
        
        rrd_data     = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP3].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP4].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                        ":{:.2f}".format(measurements[DS_HUMI].last()) + \
                        ":{:}".format(heatlamp.status())    + \
                        ":{:}".format(lightlamp.status())
        print strftime("%H:%M:%S", localtime()), rrd_data
        rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data) 

        sleep(35)
Esempio n. 14
0
def main():
    """main part"""
    temp1 = DS1820("/sys/bus/w1/devices/28-000006d62eb1/w1_slave")
    temp2 = DS1820("/sys/bus/w1/devices/28-000006dd6ac1/w1_slave")
    temp4 = DS1820("/sys/bus/w1/devices/28-000006de535b/w1_slave")
    temphumi = DHT22_AM2302(21)  # BCM 21 = PIN 40
    tempcpu = CPU()
    heatcontrol = Schedules.Control(Schedules.ScheduleHeat(), heatlamp)
    lightcontrol = Schedules.Control(Schedules.ScheduleLight(), lightlamp)

    measurements = {DS_TEMP1:   Measurements(), \
                    DS_TEMP2:   Measurements(), \
                    DS_TEMP3:   Measurements(), \
                    DS_TEMP4:   Measurements(), \
                    DS_TEMPCPU: Measurements(), \
                    DS_HUMI:    Measurements()}

    rrd_template = DS_TEMP1   + ":" + \
                   DS_TEMP2   + ":" + \
                   DS_TEMP3   + ":" + \
                   DS_TEMP4   + ":" + \
                   DS_TEMPCPU + ":" + \
                   DS_HUMI    + ":" + \
                   DS_HEATING + ":" + \
                   DS_LIGHTING

    while (True):
        measurements[DS_TEMP1].append(temp1.read())
        measurements[DS_TEMP2].append(temp2.read())
        measurements[DS_TEMP4].append(temp4.read())
        _temp3, _humi = temphumi.read()
        measurements[DS_TEMP3].append(_temp3)
        measurements[DS_HUMI].append(_humi)
        measurements[DS_TEMPCPU].append(tempcpu.read())

        heatcontrol.control(measurements[DS_TEMP3].avg())
        lightcontrol.control(measurements[DS_TEMP3].avg())

        rrd_data     = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP3].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP4].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                        ":{:.2f}".format(measurements[DS_HUMI].last()) + \
                        ":{:}".format(heatlamp.status())    + \
                        ":{:}".format(lightlamp.status())
        print strftime("%H:%M:%S", localtime()), rrd_data
        rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data)

        sleep(35)
Esempio n. 15
0
def main():
    """main part"""
    sq = SensorQueueClient_write("../../configs/weatherqueue.ini")
    qvalue_temp = SensorValue("ID_06", "TempKinderzimmer",
                              SensorValue_Data.Types.Temp, "°C")
    qvalue_humi = SensorValue("ID_07", "HumiKinderzimmer",
                              SensorValue_Data.Types.Humi, "% rF")
    sq.register(qvalue_temp)
    sq.register(qvalue_humi)

    temphumi = DHT22_AM2302(19, qvalue_temp, qvalue_humi)  # BCM 19 = PIN 35
    temp_cpu = CPU()

    measurements = {DS_TEMP1:   Measurements(3), \
                    DS_TEMPCPU: Measurements(3), \
                    DS_TEMP2:   Measurements(3), \
                    DS_HUMI:    Measurements(3)}

    rrd_template = DS_TEMP1   + ":" + \
                   DS_TEMPCPU + ":" + \
                   DS_TEMP2   + ":" + \
                   DS_HUMI

    while (True):
        _temp, _humi = temphumi.read()
        measurements[DS_TEMP1].append(_temp)
        measurements[DS_HUMI].append(_humi)
        measurements[DS_TEMPCPU].append(temp_cpu.read_temperature())
        measurements[DS_TEMP2].append(0)  # empty, for later useage

        rrd_data = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                    ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                    ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                    ":{:.2f}".format(measurements[DS_HUMI].last())
        # print(strftime("%H:%M:%S", localtime()), rrd_data)
        # rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data)

        # python rrdtool seems not to work here; the pi needs a proper reinstall.
        # as a workaround, i just call the os for rrd update
        # rrd = "/usr/bin/rrdtool update {} --template {} {}".format(RRDFILE, rrd_template, rrd_data)
        rrd = [
            "/usr/bin/rrdtool", "update", RRDFILE, "--template", rrd_template,
            rrd_data
        ]
        print(rrd)
        subprocess.call(rrd)

        sleep(35)
Esempio n. 16
0
 def __init__(self):
     self.gameOver = False
     self.computerWins = False
     self.playerWins = False
     self.rows = 15
     self.cols = 15
     self.boxWidth = 50
     self.objectGameBoard = []
     self.stoneRadius = 20
     self.firstPlayer = self.chooseFirstPlayerEasyDifficulty()
     self.currTurn = self.firstPlayer
     self.check = [False]
     self.countfiv = [0, 0, 0, 0]
     self.checkcom = [False]
     self.countfivcom = [0, 0, 0, 0]
     self.cpu = CPU(self.cols, self.rows)
Esempio n. 17
0
File: VM.py Progetto: blixuk/microvm
def main():
	print(sys.argv)

	# if len(sys.argv) > 2:
	# 	if sys.argv[2] == 'true':
	# 		DEBUG().ON()
	# 	if sys.argv[2] == 'false':
	# 		DEBUG().OFF()
	if len(sys.argv) == 2:
		if sys.argv[1].endswith('.bin'):
			CPU().LOAD(sys.argv[1])
		else:
			print('Please select a microVM BIN file!')
	elif len(sys.argv) == 3:
		if sys.argv[1] == '--compile' or sys.argv[1] == '-c':
			if sys.argv[2].endswith('.mvm'): 
				compile(sys.argv[2])
			else:
				print('Please select a microVM source file!')
	else:
		print('microVM: A Micro Virtual Machine!')
		print('')
		print('Options:')
		print('<bin>			| ex: mvm test.bin')
		print('-c <file>		| ex: mvm -c test.mvm | --compile')
		print('')
Esempio n. 18
0
class Computer:
    cpu = None
    process_table = None

    # def startPc(self):
    #     self.process_table = ProcessTable()
    #self.cpu = CPU(self.process_table.getRunningProcessRegisters())

    def  __init__(self):
        self.process_table = ProcessTable()
        self.cpu = CPU(self.process_table.getRunningProcessRegisters())

    def print(self):
        print()
        print()
        self.cpu.printRegisters()
        print()
        self.process_table.printProcess()
Esempio n. 19
0
def ALUMemHelper(f, opcode: bytes, cpu: CPU.CPU):
    #find the addressing mode of this operation. The addressing mode for the ALU operations are stored in bit 2, 3 and 4.
    code = (opcode & 0b11100) >> 2

    #use the helper function to retrieve the byte from memory
    print("Counter: " + str(cpu.PC))
    print(cpu.instructions[0:100])
    nextbytes = cpu.instructions[cpu.PC + 1:cpu.PC + 1 + 2]
    try:
        print("Next bytes: " + str(nextbytes[0]) + " : " + str(nextbytes[1]))
    except:
        print("Next bytes: " + str(nextbytes[0]))

    print("code: " + str(code))
    val = getMemArray[code](cpu, nextbytes)
    print("Memory address to be accessed: " + str(val[0]))

    cpu.PC += val[1]

    if (code == 2):
        val = cpu.instructions[val[0]:val[0] + 1]
    else:
        val = cpu.ram.read_bytes(val[0], 1)

    print("Val retrieved from memory: " + str(val))

    #perform the ALU operation on the retrieved byte
    result = f(cpu.A, val[0])
    print("Result: " + str(result))

    #TODO: not sure of the exact functionality of the carry bit. Should it be cleared if no carry occurs in bit 7?

    #set cpu flags
    if not (opcode >> 7 == 1):
        fresult = result % 256
        carry = result > fresult
        cpu.P = (cpu.P & 0b01111100) | carry | (
            (fresult == 0) << 1) | (fresult & 0b10000000)
        result = fresult

    #save result to accumulator
    cpu.A = result
Esempio n. 20
0
File: main.py Progetto: ch3rag/NESPY
def main():
    parser = argparse.ArgumentParser(description="Nes Emulator")
    parser.add_argument("rom_path",
                        type=str,
                        metavar="ROM",
                        help="Path to rom")
    args = parser.parse_args()

    # TODO: Verify ROM Path
    rom = ROM(args.rom_path)
    cpu = CPU()
Esempio n. 21
0
    def __init__(self, inputData):
        self.inputData = inputData

        nTasks = self.inputData.nTasks
        nThreads = self.inputData.nThreads
        nCPUs = self.inputData.nCPUs
        nCores = self.inputData.nCores
        rh = self.inputData.rh
        rc = self.inputData.rc
        CK = self.inputData.CK
        TH = self.inputData.TH

        self.tasks = []  # vector with tasks
        for tId in xrange(0, nTasks):  # tId = 0..(nTasks-1)
            task = Task(tId)
            for hId in xrange(0, nThreads):  # hId = 0..(nThreads-1)
                # if thread hId belongs to task tId
                if (TH[tId][hId]):
                    # add thread hId requiring res resources to task tId
                    resources = rh[hId]
                    task.addThreadAndResources(hId, resources)
            self.tasks.append(task)

        self.cpus = []  # vector with cpus
        self.maxCapacityPerCPUId = [
            0
        ] * nCPUs  # vector with max capacity of each CPU. initialized to nCPUs zeros [ 0 ... 0 ]
        self.maxCapacityPerCoreId = [
            0
        ] * nCores  # vector with max capacity of each core. initialized to nCores zeros [ 0 ... 0 ]
        for cId in xrange(0, nCPUs):  # cId = 0..(nCPUs-1)
            cpu = CPU(cId)
            for kId in xrange(0, nCores):  # kId = 0..(nCores-1)
                # if core kId belongs to CPU cId
                if (CK[cId][kId]):
                    # add core kId with capacity to CPU cId
                    capacity = rc[cId]
                    cpu.addCoreAndCapacity(kId, capacity)
                    self.maxCapacityPerCPUId[cId] += capacity
                    self.maxCapacityPerCoreId[kId] = capacity
            self.cpus.append(cpu)
Esempio n. 22
0
def main():
	parser = ArgumentParser(description="Interpreter for the register machine")
	parser.add_argument("infile", type=FileType("rb"), metavar="input", help="input file")
	args = parser.parse_args()

	cpu = CPU()

	cpu.load_file(args.infile)

	instr = 0
	start = time.time()
	while(not cpu.exit):
		cpu.next_instruction()
		instr += 1

	taken = time.time() - start
	ips = instr / taken

	print("time elapsed: {:.6f} instructions executed: {}".format(taken, instr))
	print("ips: {:.0f}".format(ips))
	sys.exit(cpu.err)
Esempio n. 23
0
    def checkWin(self):
        # Check which player wins and output it
        board = CPU.convertBoard(self.cpu, self.getGameBoard())
        cpuWon = self.fiveInARow(board, 1)
        playerWon = self.fiveInARow(board, -1)

        if not self.gameOver:
            if playerWon > 0:
                self.playerWins = True
                self.gameOver = True
            if cpuWon > 0:
                self.computerWins = True
                self.gameOver = True
Esempio n. 24
0
    def LoadCode(self):
        fname = QFileDialog.getOpenFileName(self, 'open file', '.')  # 直接打开本文件夹

        if fname[0]:

            with open(fname[0], 'r', encoding='utf-8') as file:
                if self.cpu.isForwarding is False:
                    self.cpu = CPU(None)
                else:
                    self.cpu = CPU(None)
                    self.cpu.isForwarding = True
                self.code = file.read()

                # 解析代码同时把解析后的代码放入cpu的IM中
                anaylser = LexicalAnalyzer(self.code)
                self.cpu.IM.initIM(anaylser.returnCodeAnalyse())

                self.winSummary.getMessage(self.cpu)
                self.winCode.getMessage(self.code)
                self.winPipeLine.getMessage(None)
                self.winRegFile.getMessage(self.cpu.RegFile.rf)
                self.winDataMem.getMessage(self.cpu.DM.mem)
Esempio n. 25
0
    def boot(self):
        self.os_start = time()
        self.number_of_processes = 0

        self.io = IODevice(self.Wait_Queue, self.Ready_Queue)
        self.io.start()

        self.cpu = CPU(self.time_slice)
        with open(self.file_name, 'r') as csvfile:
            processReader = csv.reader(csvfile)

            for row in processReader:
                ID, arrival, priority, program = row
                ID = int(ID)
                arrival = int(arrival)
                priority = int(priority)
                program = program.strip().strip(';')
                program = [int(i) for i in program]
                program = interpret(program)
                process = ProcessImage(ID, arrival, priority, program)
                self.New_Queue.put(process)
                self.number_of_processes += 1
        self.put_in_ready_queue()
Esempio n. 26
0
def main():

    # Ask the user for the hilillos to use
    hilillos_to_use = -1
    while hilillos_to_use != 0 and hilillos_to_use != 1 and hilillos_to_use != 2:
        result = input(
            "Ingrese un 0 para correr el hilillo facilísimo, "
            "un 1 para los hilillos simples "
            "o un 2 para los hilillos de la prueba final(Para ayuda, digite una h)\n"
        )
        if (str(result)).lower() == 'h':
            print(
                "\n\nAYUDA: Para utilizar hilillos distintos de los que se encuentran en el directorio del proyecto, remplace"
                " el hilillo que se encuentra en Hilillos/Hilillo-FACILISIMO, y luego seleccione 0 al correr el "
                "programa\n\n")
        elif result.isdigit():
            hilillos_to_use = int(result)

        # Initialize CPU
    quantum = input("Ingrese el quantum\n")
    cpu = CPU(hilillos_to_use, int(quantum))

    # Start the simulation
    cpu.start_cores()
Esempio n. 27
0
def bot():
    """
    Loop runs to retrieve and process all new mentions
    """
    lastSeen = get_last_seen()
    batch = get_new_mentions()  # pulls and processes new Tweets
    commandsInBatch = process_tweet_batch(batch)[::-1]
    for command in commandsInBatch:  # for each command in the batch
        log_user(command)
        if command['cmd'] == "start":
            userBoard = Board()  # initializes the Board
            if command['flag'] is None:
                userBoard.gameDifficulty = 'easy'
            elif command['flag'] == 'easy':
                userBoard.gameDifficulty = 'easy'
            elif command['flag'] == 'medium':
                userBoard.gameDifficulty = 'medium'
            elif command['flag'] == 'hard':
                userBoard.gameDifficulty = 'hard'
            playerFirst = bool(
                random.getrandbits(1))  # determines if player is first
            if playerFirst:
                reply_board_message(
                    YOUR_TURN + str(userBoard), command['id'],
                    command['player'])  # replies that it's player's turn
                save_progress(userBoard,
                              command['player'])  # creates player save file
            elif not playerFirst:
                CPU.play_move(userBoard, O)  # plays CPU move on Board
                reply_board_message("I'll start, I'll be " + Board.O + ": " +
                                    str(userBoard), command['id'],
                                    command['player'],
                                    YOUR_TURN)  # replies Board to Tweet
                save_progress(
                    userBoard,
                    command['player'])  # saves the user's game progress
        elif command['cmd'] == "play":
            try:
                userBoard = load_progress(command['player'])
                flagValid = (1 <= command['flag'] <= 9)
                hasBeenPlayed = userBoard.has_been_played(command['flag'])
                if flagValid and not hasBeenPlayed:
                    userBoard.play_move(
                        command['flag'], X
                    )  # if the flag is valid and the move hasn't already been
                    # played
                    if userBoard.is_won(
                    ):  # if the user won the game with their move
                        botReply = reply_board_message(
                            YOU_PLAYED + str(userBoard.lastPlayed) + '\n' +
                            str(userBoard), command['id'], command['player']
                        )  # replies the current board and the WON message
                        retweet_winner(botReply.id)
                        reply_message(random.choice(YOU_WON), botReply.id,
                                      command['player'])
                        os.remove(
                            cache + command["player"] + ".txt"
                        )  # deletes the save file if the game is over
                    elif userBoard.is_draw(
                    ):  # if the user forced a draw on the game with their move
                        botReply = reply_board_message(
                            YOU_PLAYED + str(userBoard.lastPlayed) + '\n' +
                            str(userBoard), command['id'],
                            command['player'])  # replies the current board
                        # and the DRAW message
                        retweet_winner(botReply.id)
                        reply_message(random.choice(DRAW), botReply.id,
                                      command['player'])
                        os.remove(cache + command["player"] +
                                  ".txt")  # deletes the save file if the
                        # game is over
                    else:  # if the user's move doesn't cause the end of the game
                        botReply = reply_board_message(
                            YOU_PLAYED + str(userBoard.lastPlayed) + '\n' +
                            str(userBoard), command['id'], command['player'],
                            MY_TURN)
                        CPU.play_move(userBoard,
                                      O)  # the CPU plays the best move
                        if userBoard.is_won(
                        ):  # if the CPU won the game with their move
                            botReply = reply_board_message(
                                I_PLAYED + str(userBoard.lastPlayed) + '\n' +
                                str(userBoard), botReply.id,
                                command['player'])  # replies the current board
                            # and the WON message
                            retweet_winner(botReply.id)
                            reply_message(random.choice(I_WON), botReply.id,
                                          command['player'])
                            os.remove(
                                cache + command["player"] + ".txt"
                            )  # deletes the save file if the game is over
                        elif userBoard.is_draw(
                        ):  # if the CPU forced a draw on the game with their move

                            botReply = reply_board_message(
                                I_PLAYED + str(userBoard.lastPlayed) + '\n' +
                                str(userBoard), botReply.id,
                                command['player'])  # replies the current board
                            # and the DRAW message
                            retweet_winner(botReply.id)
                            reply_message(random.choice(DRAW), botReply.id,
                                          command['player'])
                            os.remove(cache + command["player"] +
                                      ".txt")  # deletes the save file if
                            # the game is over
                        else:  # if the CPU's move doesn't cause the end of the game
                            reply_board_message(
                                I_PLAYED + str(userBoard.lastPlayed) + '\n' +
                                str(userBoard), botReply.id, command['player'],
                                YOUR_TURN)
                            save_progress(userBoard, command['player']
                                          )  # saves the user's game progress
                else:
                    if not flagValid:  # if the given command flag isn't valid
                        reply_message(INCORRECT_INPUT, command['id'],
                                      command['player'])
                    elif userBoard.has_been_played(
                            command['flag']
                    ):  # if the given command flag has already been
                        # played
                        reply_message(BEEN_PLAYED, command['id'],
                                      command['player'])
            except FileNotFoundError:  # if the user tries to play a move on a game that hasn't started
                reply_message(COMMAND_BEFORE_START, command['id'],
                              command['player'])
        elif command['cmd'] == "quit":
            try:
                os.remove(cache + command["player"] + ".txt")
                reply_message(COME_AGAIN, command['id'], command['player'])
            except OSError:
                reply_message(COMMAND_BEFORE_START, command['id'],
                              command['player'])
        lastSeen = command['id']
    update_last_seen(lastSeen)
    time.sleep(600)
Esempio n. 28
0
def main():
    """main part"""
    temp_fridge = DS1820("/sys/bus/w1/devices/28-000006dc8d42/w1_slave")
    temp_cpu = CPU()
    temphumi = DHT22_AM2302(21)  # BCM 21 = PIN 40

    measurements = {DS_TEMP1:   Measurements(3), \
                    DS_TEMPCPU: Measurements(3), \
                    DS_TEMP2:   Measurements(3), \
                    DS_HUMI:    Measurements(3)}

    rrd_template = DS_TEMP1   + ":" + \
                   DS_TEMPCPU + ":" + \
                   DS_TEMP2   + ":" + \
                   DS_HUMI    + ":" + \
                   DS_ON      + ":" + \
                   DS_OPEN

    while (True):
        measurements[DS_TEMP1].append(temp_fridge.read_temperature())
        measurements[DS_TEMPCPU].append(temp_cpu.read())

        _temp, _humi = temphumi.read()
        measurements[DS_TEMP2].append(_temp)
        measurements[DS_HUMI].append(_humi)

        if (measurements[DS_TEMP2].avg() > 5.2):
            fridge.on()
        if (measurements[DS_TEMP2].avg() < 5.0):
            fridge.off()

# if (temp > 6): fridge.on()
# else if (temp > 5):
#   fridge_on_time(60,90) # für 60 sekunden einschalten; 90 Sekunden mindestens aus
# else if (temp < 5.0):
#   fridge.off()

# class fridge_... derived from class Heating

# threading: https://docs.python.org/2/library/threading.html
# multi inheritance:  https://docs.python.org/2/tutorial/classes.html#multiple-inheritance
#    class DerivedClassName(Base1, Base2, Base3):

# fridge_on_time:
#  thread:
#    with lock:
#        timing = active
#    __on()
#    sleep(60)
#    __off()
#    sleep(90)
#    with lock:
#         timing = non_active

# in  on(), off()
#  ...
#  if (active): pass





        rrd_data     = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                        ":{:.2f}".format(measurements[DS_HUMI].last()) + \
                        ":{:}".format(fridge.status())    + \
                        ":{:}".format(reedcontact.status_stretched())
        print strftime("%H:%M:%S", localtime()), rrd_data
        rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data)

        writeMonitoringData(rrd_data)

        sleep(35)
Esempio n. 29
0
def main():
    """main part"""
    temp_fridge = DS1820("/sys/bus/w1/devices/28-000006dc8d42/w1_slave")
    temp_cpu    = CPU()
    temphumi    = DHT22_AM2302(21)   # BCM 21 = PIN 40

    measurements = {DS_TEMP1:   Measurements(3), \
                    DS_TEMPCPU: Measurements(3), \
                    DS_TEMP2:   Measurements(3), \
                    DS_HUMI:    Measurements(3)}

    rrd_template = DS_TEMP1   + ":" + \
                   DS_TEMPCPU + ":" + \
                   DS_TEMP2   + ":" + \
                   DS_HUMI    + ":" + \
                   DS_ON      + ":" + \
                   DS_OPEN

    while (True):
        measurements[DS_TEMP1].append(temp_fridge.read())
        measurements[DS_TEMPCPU].append(temp_cpu.read())

        _temp, _humi = temphumi.read()
        measurements[DS_TEMP2].append(_temp)
        measurements[DS_HUMI].append(_humi)

        if (measurements[DS_TEMP2].avg() > 5.2):
            fridge.on()
        if (measurements[DS_TEMP2].avg() < 5.0):
            fridge.off()



# if (temp > 6): fridge.on()
# else if (temp > 5): 
#   fridge_on_time(60,90) # für 60 sekunden einschalten; 90 Sekunden mindestens aus
# else if (temp < 5.0): 
#   fridge.off()


# class fridge_... derived from class Heating

# threading: https://docs.python.org/2/library/threading.html
# multi inheritance:  https://docs.python.org/2/tutorial/classes.html#multiple-inheritance
#    class DerivedClassName(Base1, Base2, Base3):

# fridge_on_time:
#  thread:
#    with lock:
#        timing = active
#    __on()
#    sleep(60)
#    __off()
#    sleep(90)
#    with lock:
#         timing = non_active


# in  on(), off()
#  ...
#  if (active): pass





        rrd_data     = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                        ":{:.2f}".format(measurements[DS_HUMI].last()) + \
                        ":{:}".format(fridge.status())    + \
                        ":{:}".format(reedcontact.status_stretched())
        print strftime("%H:%M:%S", localtime()), rrd_data
        rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data)

        writeMonitoringData(rrd_data)

        sleep(35)
Esempio n. 30
0
 def  __init__(self):
     self.process_table = ProcessTable()
     self.cpu = CPU(self.process_table.getRunningProcessRegisters())
Esempio n. 31
0
	def do_init(self,args):
		"""Initialize the CPU"""
		verbose=bool(args)
		self.cpu=CPU(verbose)
		self.initialized=True
Esempio n. 32
0
class Shell(cmd.Cmd):
	prompt='8008>'
	initialized=False
	def do_help(self,args):
		rargs='do_'+args
		if args and rargs in dir(self) and hasattr(self.__getattribute__(rargs),'__doc__'):
			if self.__getattribute__(rargs).__doc__:
				for line in self.__getattribute__(rargs).__doc__.splitlines():
					print(line.strip())
		elif args and not rargs in dir(self):
			print('Command "{}" does not exists'.format(args))
		else:
			for cmd in dir(self):
				if cmd.startswith('do_') and hasattr(self.__getattribute__(cmd),'__doc__'):
					if self.__getattribute__(cmd).__doc__:
						print(cmd[3:]+':',self.__getattribute__(cmd).__doc__)
			
	def do_asm(self,args):
		"""Enter Assembling mode"""
		self.lastcmd=''
		try:
			if self.initialized:
				self.cpu.load(code=asmsh())
			else:
				print('CPU not Initialized')
		except Exception as e:
			print(e)

	def do_asm_img(self,args):
		"""Enter Assembling mode (RAM Image Output)"""
		self.lastcmd=''
		try:
			if self.initialized:
				self.cpu.load(code=asmsh(fill=True))
			else:
				print('CPU not Initialized')
		except Exception as e:
			print(e)
	
	def do_asm_file(self,args):
		"""Load Assembler File"""
		file=args
		fill=True
		if len(args)>1:
			fill=args[1]	
		if self.initialized:
			self.cpu.load(code=asm_file(file,fill))
		else:
			print('CPU not Initialized')
		
	def do_init(self,args):
		"""Initialize the CPU"""
		verbose=bool(args)
		self.cpu=CPU(verbose)
		self.initialized=True
	
	def do_load(self,args):
		"""Load Assembled Program into RAM"""
		if len(args):
			file=args.split()[0]
			if self.initialized:
				print("Loading file {}".format(file))
				self.cpu.load(file)
			else:
				print('CPU not Initialized')
	
	def do_exit(self,args):
		"""Exit"""
		exit(0)
		
	def do_EOF(self,args):
		exit(0)
	
	def do_rr(self,args):
		"""print values of Registers"""
		if self.initialized:
			if args in self.cpu.registers:
				print(self.cpu.registers[args])
			else:
				for r,v in self.cpu.registers.items():
					print(r,v)
		else:
			print('CPU not Initialized')
	
	def do_wr(self,args):
		"""write value to Registers"""
		value,reg='',''
		if len(args.split())==2:
			reg,value=args.split()
		if value.isnumeric and reg in self.cpu.registers:
			if self.initialized:
				try:
					self.cpu.registers[reg][0]=int(value)
				except Exception as e:
					print(e)
			else:
				print('CPU not Initialized')
	
	def do_dumpmem(self,args):
		"""Dump Memory"""
		m_base=0
		m_len=0
		if len(args.split())>=2:
			m_base=int(args.split()[0])
			m_len=int(args.split()[1])
		elif args:
			m_len=int(args.split()[0])
		else:
			print('missing Argument "length"')
		if self.initialized:
			self.cpu.memory.dump(m_base,m_len)
		else:
			print('CPU not Initialized')
	
	def do_go(self,args):
		"""Execute Assembled Code"""
		if self.initialized:
			while 1:
				if self.cpu.verbose:
					self.cpu.dumpregs()
					print("Flags:",self.cpu.flags)
					print("Memory:")
					self.cpu.memory.dump(length=8,width=32)
					print('-'*10)
				if not self.cpu():
					break
		else:
			print('CPU not Initialized')
	
	def do_bp(self,arg):
		if self.initialized:
			self.cpu.breakpoints.append(int(arg.split()[0]))
		else:
			print('CPU not Initialized')
Esempio n. 33
0
from myhdl import *
from CPU import CPU
from helpers.Clock_Generator import clock_generator
from helpers.Random_Signal import random_signal

if (__name__ == "__main__"):

    rst = Signal(bool(0))

    regOut = []
    for i in range(0, 32):
        regOut.append(Signal(intbv(0, 0, 2**32)))
    CPU_driver = traceSignals(CPU(rst, regOut))

    sim = Simulation(CPU_driver)
    sim.run(100000)
Esempio n. 34
0
def main():
    """main part"""
    qvalue_tempbox     = SensorValueLock("ID_08", "TempDonutBox", SensorValue.Types.Temp, u'°C', Lock())
    qvalue_humi        = SensorValueLock("ID_09", "HumiDonut", SensorValue.Types.Humi, u'% rF', Lock())
    qvalue_tempoutdoor = SensorValueLock("ID_12", "TempDonutOutDoor", SensorValue.Types.Temp, u'°C', Lock())
    qvalue_heatlamp    = SensorValueLock("ID_10", "SwitchHeatlamp", SensorValue.Types.Switch, u'Heizung:', Lock())
    qvalue_lightlamp   = SensorValueLock("ID_11", "SwitchLightlamp", SensorValue.Types.Switch, u'Beleuchtung:', Lock())
    sq.register(qvalue_tempbox)
    sq.register(qvalue_humi)
    sq.register(qvalue_tempoutdoor)
    sq.register(qvalue_heatlamp)
    sq.register(qvalue_lightlamp)
    sq.start()

    temp1        = DS1820("/sys/bus/w1/devices/28-000006d62eb1/w1_slave", qvalue_tempoutdoor)
    temp2        = DS1820("/sys/bus/w1/devices/28-000006dd6ac1/w1_slave")
    temp4        = DS1820("/sys/bus/w1/devices/28-000006de535b/w1_slave")
    temphumi     = DHT22_AM2302(21, qvalue_tempbox, qvalue_humi) # BCM 21 = PIN 40
    tempcpu      = CPU()
    heatcontrol  = Schedules.Control(Schedules.ScheduleHeat(), heatlamp, qvalue_heatlamp)
    lightcontrol = Schedules.Control(Schedules.ScheduleLight(), lightlamp, qvalue_lightlamp)

    measurements = {DS_TEMP1:   Measurements(), \
                    DS_TEMP2:   Measurements(), \
                    DS_TEMP3:   Measurements(), \
                    DS_TEMP4:   Measurements(), \
                    DS_TEMPCPU: Measurements(), \
                    DS_HUMI:    Measurements()}
 
    rrd_template = DS_TEMP1   + ":" + \
                   DS_TEMP2   + ":" + \
                   DS_TEMP3   + ":" + \
                   DS_TEMP4   + ":" + \
                   DS_TEMPCPU + ":" + \
                   DS_HUMI    + ":" + \
                   DS_HEATING + ":" + \
                   DS_LIGHTING
                     
    while (True):
        measurements[DS_TEMP1].append(temp1.read_temperature())
        measurements[DS_TEMP2].append(temp2.read_temperature())
        measurements[DS_TEMP4].append(temp4.read_temperature())
        _temp3, _humi = temphumi.read()
        measurements[DS_TEMP3].append(_temp3)
        measurements[DS_HUMI].append(_humi)
        measurements[DS_TEMPCPU].append(tempcpu.read())

        heatcontrol.control(measurements[DS_TEMP3].avg())
        lightcontrol.control(measurements[DS_TEMP3].avg())
        
        rrd_data     = "N:{:.2f}".format(measurements[DS_TEMP1].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP2].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP3].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMP4].last()) + \
                        ":{:.2f}".format(measurements[DS_TEMPCPU].last()) + \
                        ":{:.2f}".format(measurements[DS_HUMI].last()) + \
                        ":{:}".format(heatlamp.status())    + \
                        ":{:}".format(lightlamp.status())
        print strftime("%H:%M:%S", localtime()), rrd_data
        rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data) 

        sleep(35)
Esempio n. 35
0
import time

from CPU import CPU
from GPU import GPU
from Memory import Memory

RUNNING = True
STEP = False

# Memory Init
Memory = Memory("TETRIS.gb")

# CPU Init
CPU = CPU(Memory)
CPU.DEBUG = False

# GPU Init, pass in the memory that has been initialized in the CPU
GPU = GPU(Memory)

time_display = time.clock()

while RUNNING:

    cycles_before = CPU.cycles
    CPU.fetch()
    if CPU.PC >= 0x100:
        print("0x" + hex(CPU.PC)[2:].zfill(4).upper() + " : ", end="")
        CPU.decode()
        print(CPU.debug_string + "	", end="")
        for i in range(0, CPU.instruction_length - 1):
            print(hex(CPU.args[i])[2:].zfill(2).upper() + " ", end="")
Esempio n. 36
0
 def __init__(self, rom_file):
     self.mem = Mem()
     self.mem.load_rom(rom_file)
     self.cpu = CPU(START_ADDRESS, self.mem)
Esempio n. 37
0
    queueTypeList = ['SRT', 'RR']
    memTypeList = ['nextfit', 'bestfit', 'firstfit']
  
    burst_num = 0
    urg_burst_sum = 0 
    for ptuple in processList:
        burst_num += ptuple[3]
        urg_burst_sum += ptuple[2] * ptuple[3] 

    outfile = open("simout.txt", "w")
    for qtype in queueTypeList: 
        for mtype in memTypeList:
            print "time 0ms: Simulator started for RR (t_slice 80) and ",
            sys.stdout.write(mtype[:-3].capitalize()+"-"+mtype[-3:].capitalize())
            print ""
            cpu = CPU(queuetype=qtype, memtype = mtype)
            for ptuple in processList:
                cpu.addProcess(ProcessInfo(*ptuple)) 
            cpu.run()
	    print ""
	    print ""
            outfile.write("Algorithm %s with %s\n" %(qtype, mtype))
            #outfile.write("-- average CPU burst time: %.2f ms\n" % (1.0 * cpu.burstTimeSum/burst_num))
            outfile.write("-- average CPU burst time: %.2f ms\n" % (1.0 * urg_burst_sum/burst_num))
            outfile.write("-- average wait time: %.2f ms\n" %(1.0 * cpu.waitTimeSum/ cpu.waitTimeNum)) 
            outfile.write("-- average turnaround time: %.2f ms\n" %(1.0 * cpu.waitTimeSum/ cpu.waitTimeNum + urg_burst_sum/burst_num))
            outfile.write("-- time spent on defragmentation : %.2f  ms %.2f/100\n" %(cpu.defragtime, (100.0 * cpu.defragtime / urg_burst_sum) )) 
            outfile.write("-- total number of context switches: %d\n" % cpu.contentSwitchSum)
    outfile.close()