def run(): try: memory = bytearray(MEMORY_SIZE) # PERIPHERALS: Line -> Device pp = { #0 : loopback interrupt SYSTIMER_LINE : peripheral.SysTimer(memory), SERIAL_LINE : peripheral.Serial(memory) } proc = cpu.CPU(memory, pp) start_pp(pp) load_rom(memory) while(True): proc.exec_next() process_int_queue(pp, proc) except cpu.Halt: lg.info("Execution halted gracefully") return EXIT_HALT except cpu.Assert: lg.info("Execution halted on false assertion") return EXIT_ASSERT_FAIL except KeyboardInterrupt: lg.info("Execution halted by the user") return EXIT_KEYBOARD except Exception as e: lg.info("Execution halted on general error {0}".format(e)) traceback.print_exc() return EXIT_EXEC_ERROR finally: stop_pp(pp)
def main(): initMemory() players = createPlayers() if players == None: return win = GraphWin("Harvest Memory", 1280, 800, autoflush=False) drawTitle(win) drawPlayers(win, players) drawColumns(win) updateColumns() vm = cpu.CPU(memory, fruit, players) timer = 0 while True: for i in range(0, 100): # Speed it up! if vm.ticks < 10000: vm.execute() if timer % 4 == 0: # Only update periodically updatePlayers(players) updateMemoryGraphics(vm.fruit) print("Ticks: " + str(vm.ticks)) timer = timer + 1 update(5) # 5 frames per second
def run(program_fpath: str): rom = memory.ReadOnlyMemory(32 * 1024) rom.load_program(program_fpath) ram = memory.ReadWriteMemory(16 * 1024) cpu_ = cpu.CPU(rom, ram) cpu_.run()
def test_hundred_processes(self): self.simulation_values["number_processes"] = 100 cpuobj = cpu.CPU(self.simulation_values) thread_cpu = threading.Thread(target=cpuobj.page_access_stream) thread_cpu.start() time.sleep(5) self.assertTrue(len(cpuobj.page_num_stream) > 0)
def start(self): c = 0 self.bus = bus.BUS(self.ram, self.rom, self.ppu, self.apu, self.io) self.cpu = cpu.CPU(self.bus) for i in range(1000000): c += self.cpu.run() if c > 28000 * 60: print("NES got 60 fps lol") exit()
def __init__(self): load = loader.Loader("TETRIS") load.read() memory = mmu.MMU(load.data) processor = cpu.CPU(memory) display = video.Video() display.mainloop(processor.step)
def test_normal(self): my_cpu = cpu.CPU() my_cpu.run(seqs) expected = str([{ 'baby': 'xiaying' }, { 'mami': 'yoyo', 'haha': 'xiaoyoyo' }, {}, {}, {}, {}, {}, {}, {}, {}]) self.assertEqual(expected, str(disk.fs))
def test_crash_before_commit(self): my_cpu = cpu.CPU() my_cpu.run(seqs_crash) # Check log is empty self.assertEqual(0, len(my_cpu.processor.log.buffers)) self.assertEqual(self.empty_fs, str(disk.fs)) my_cpu.restart() # FS is not updated. self.assertEqual(self.empty_fs, str(disk.fs))
def main(w1, w2, f): c = cpu.CPU(strategy=WeightedScorer, bl_args=[w1, w2]) ms = [] rs = [] ts = [] ss = [] while c.distribution: rs.append(''.join(c.rack)) t = time.time() ms.append(c.run()) ts.append(round(time.time() - t, 2)) ss.append(c.score) write_state_to_file(c, ms, rs, ts, ss, file=f)
def __init__(self, path=None, mapname=None, width=MIN_WIDTH): if path: self._cpu = cpu.CPU(path=path) self._cpu.init_instruction_table() self._cheats = SpaceInvadersCheatEngine(self._cpu.memory) elif mapname: self._cpu = cpu.CPU(rom=self._create_memory(mapname)) self._cpu.init_instruction_table() self._cheats = SpaceInvadersCheatEngine(self._cpu.memory) else: # From save state self._cpu = None self._cheats = None self._path = path self._width = max(MIN_WIDTH, width) self._height = round(self._width / self.ASPECT_RATIO) self._scaled_width = self._width self._scaled_height = self._height self._window_width = self._height self._window_height = self._width self._px_array = None self._fps = 60
def __init__(self, path=None, width=MIN_WIDTH): if path: self._cpu = cpu.CPU(path) self._cpu.init_instruction_table() self._cheats = SpaceInvadersCheatEngine(self._cpu.memory) else: # From save state self._cpu = None self._cheats = None self._path = path self._width = max(MIN_WIDTH, width) self._height = round(self._width / self.ASPECT_RATIO) self._display_size = self._height, self._width self._px_array = None self._fps = 60
def test_crash_after_commit(self): my_cpu = cpu.CPU() my_cpu.make_crash() my_cpu.run(seqs) # FS is empty due to system crash right before install updates. self.assertEqual(self.empty_fs, str(disk.fs)) # System restarts and FS recovers from log. my_cpu.restart() expected = str([{ 'baby': 'xiaying' }, { 'mami': 'yoyo', 'haha': 'xiaoyoyo' }, {}, {}, {}, {}, {}, {}, {}, {}]) self.assertEqual(expected, str(disk.fs))
def __init__(self, manufacturer, loc, mode="udp"): try: self.ip, self.port = loc.split(':') self.port = int(self.port) self.mode = mode except ValueError: print "give \"ip:port\" string" raise self.__variables = {} self.__session = False self.__state = VMState.working self.__stop_request = False self.__gdb = gdb.GDB(self.ip, self.port, self.mode) self.cpu = cpu.CPU(manufacturer, self.__gdb) self.mem = memory.Memory(self.cpu, self.__gdb) self.__setup_sig(signal.SIGINT, self.int_event)
def __init__(self): """Creates an instance of the main application window, which displays all widgets with information about CPU and memory usage """ super().__init__() self.attributes('-alpha', 1) self.attributes('-topmost', True) self.resizable(False, False) self.title(settings.APPLICATION_TITLE) self.__cpu_load_labels = list() self.__cpu_load_progress_bars = list() self.__ram_load_label = None self.__ram_load_bar = None self.__cpu = cpu.CPU() self.__ram = ram.RAM() self.__create_widgets() self.__configure_cpu_section() self.__configure_ram_section()
def __init__(self, mode: int=0): # NEWIT core ref регистры переносим в АЛУ # self.A = Registry('A') # регистр A # self.B = Registry('B') # регистр B # регистр Z теперь полностью принадлежит АЛУ, в калькуляторе его нет # DEPRECATED 06-06-2020 используем флаг PI (инициализируется в Flags) # self.OP = None # текущее арифметическое действие # DEPRECATED 06-06-2020 флаги создаются в CPU # self.flags = flags.Flags() # флаги калькулятора # DEPRECATED 06-06-2020 нет необходимости сохранять (используется в display) # self.mode = mode # включение/выключения отладочного режима # в АЛУ добавляем ссылку на флаги, но сам АЛУ их не изменеят self.__CPU = cpu.CPU() # инициализация АЛУ # ссылка на флаги self.flags = self.__CPU.flags # Инициализация дисплея self.display = display.Display(self.__CPU, mode) # DEPRECATED 06-06-2020 вывод стартовой надписи из display # print("press 'q' to exit, 0-9 to enter value, 'ESC'-to clear, 'ENTER' to evaluate") self.displayRegisters()
def main(): programa = ["CARGI 10", "ARMM 2", "CARGI 32", "SOMA 2", "ARMM 0", "PARA"] dados = [0] * 4 my_cpu = cpu.CPU() my_cpu.altera_programa(programa) my_cpu.altera_dados(dados) while my_cpu.get_interrupcao() == "normal": my_cpu.executa() inst = my_cpu.instucao() dados = my_cpu.mem_dados d = dados[0] print(f"CPU parou na instrução {inst} (deve ser PARA)") print(f"O valor de m[0] é {dados[0]} (deve ser 42)")
def main(): initMemory() players = createPlayers() #打印出所有玩家的名字 print('当前玩家有: {}'.format([player.displayName for player in players])) if players == None: return vm = cpu.CPU(memory, fruit, players) tty = terminal.Display(vm, players) timer = 0 for i in range(0, 12000): if vm.ticks < 1000000: vm.execute() else: break timer += 1 if timer % 1000 == 0: # 定时更新状态 tty.display() tty.display()
def __init__(self, manufacturer, loc, mode="udp"): self.__state = VMState(VMState.working) try: self.ip, self.port = loc.split(':') self.port = int(self.port) self.mode = mode except ValueError: log.log("error", "give \"ip:port\" string") raise self.__variables = {} self.__session = False self.__detach_filter = None self.__intr_filter = None self.__stop_request = False self.__gdb = gdb.GDB(self.ip, self.port, self.mode) self.cpu = cpu.CPU(manufacturer, self.__gdb) self.mem = memory.Memory(self.cpu, self.__gdb) self.__setup_sig(signal.SIGINT, self.int_event) self.__state.update(VMState.ready)
def debug(self): def printRegister(): print("RegisterA: " + str(self.cpu.registers.A)) print("RegisterX: " + str(self.cpu.registers.X)) print("RegisterY: " + str(self.cpu.registers.Y)) print("RegisterS: " + str(self.cpu.registers.S)) print("RegisterP: " + str(self.cpu.registers.P)) print("RegisterPC: " + str(self.cpu.registers.PC) + "\n") self.bus = bus.BUS(self.ram, self.rom, self.ppu, self.apu, self.io) self.cpu = cpu.CPU(self.bus) msg = '' while (True): argv = input("(debug) cmd: ").split(" ") argc = len(argv) if argv[0] == "run": if argc > 1: import time start = time.time() for i in range(int(argv[1])): msg = self.cpu.debugRun() end = time.time() print(msg) printRegister() print("operation took " + str(end - start) + " secs") else: msg = self.cpu.debugRun() print(msg) printRegister() if argv[0] == "register": printRegister() if argv[0] == "quit": exit()
def create_all_dict(self): data1 = cpu.CPU() cpu_dict = data1.clean_dict( ) # instantiate cpu class, creates cpu dict data2 = gpu.GPU() gpu_dict = data2.clean_dict( ) # instantiate gpu class, creates gpu dict data3 = ram.RAM() ram_dict = data3.clean_dict( ) # instantiate ram class, creates ram dict year1 = 1960 value_list = [] while year1 < 2021: if str(year1) in ram_dict.keys(): if str(year1) in gpu_dict.keys(): if str(year1) in cpu_dict.keys( ): # checks to see if year1 value is a key in all three dictionaries (cpu, gpu, and ram) ram_value = ram_dict[str( year1 )] # sets variable equal to value of dictionary key gpu_value = gpu_dict[str(year1)] cpu_value = cpu_dict[str(year1)] value_list.append(ram_value) # appends value to list value_list.append(gpu_value) value_list.append(cpu_value) for x in value_list: # iterate through list of values x = (map(float, x)) valueSum = (sum(x) / 3) self.all_dict[year1] = round(valueSum, 2) year1 += 1
import cpu import itertools cpu = cpu.CPU("25.state") cpu.run() def exec(inp): for c in inp: cpu.stdin.append(ord(c)) cpu.stdin.append(ord("\n")) cpu.run() def out(): out = "" while cpu.stdout: out += chr(cpu.stdout.pop()) return out while True: line = input() if line == "bf": print("brrr") possible = [ "food ration", "weather machine", "antenna", "space law space brochure", "semiconductor", "planetoid", "monolith" ]
def main(): exitFalse = True while exitFalse: userInput = int( input(''' Please select an option below: 1) CPU Data 2) GPU DATA 3) RAM Data 4) All Data 5) Exit ''')) if userInput == 1: cpuExitTrue = False choice_cpu = cpu.CPU() while cpuExitTrue is False: cpu_selection = int( input(''' Please select an option below: 1) Year by year analysis 2) Moore's Law (two year) analysis 3) Exit ''')) if cpu_selection == 1: choice_cpu.avg_perc_inc() elif cpu_selection == 2: choice_cpu.two_year_inc() elif cpu_selection == 3: cpuExitTrue = True else: print('Invalid Selection') elif userInput == 2: gpuExitTrue = False choice_gpu = gpu.GPU() while gpuExitTrue is False: gpu_selection = int( input(''' Please select an option below: 1) Year by year analysis 2) Moore's Law (two year) analysis 3) Exit ''')) if gpu_selection == 1: choice_gpu.avg_perc_inc() elif gpu_selection == 2: choice_gpu.two_year_inc() elif gpu_selection == 3: gpuExitTrue = True else: print('Invalid Selection') elif userInput == 3: ramExitTrue = False choice_ram = ram.RAM() while ramExitTrue is False: ram_selection = int( input(''' Please select an option below: 1) Year by year analysis 2) Moore's Law (two year) analysis 3) Exit ''')) if ram_selection == 1: choice_ram.avg_perc_inc() elif ram_selection == 2: choice_ram.two_year_inc() elif ram_selection == 3: ramExitTrue = True else: print('Invalid Selection') elif userInput == 4: allExitTrue = False choice_all = all.ALL() while allExitTrue is False: all_selection = int( input(''' Please select an option below: 1) Year by year analysis 2) Moore's Law (two year) analysis 3) Exit ''')) if all_selection == 1: choice_all.avg_perc_inc() elif all_selection == 2: choice_all.two_year_inc() elif all_selection == 3: allExitTrue = True else: print('Invalid Selection') elif userInput == 5: exitFalse = False else: print('Invalid selection')
import pygame import ball import player import cpu game_width, game_height = 800, 600 game_size = {"width": game_width, "height": game_height} font_size = 50 surface = pygame.display.set_mode( (game_size.get("width"), game_size.get("height"))) ball = ball.Ball(game_size) player = player.Player(game_size) cpu = cpu.CPU(game_size) pygame.init() def main(): run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False surface.fill((0, 0, 0)) draw() update() pygame.display.update()
import cpu cpu = cpu.CPU("17.in") cpu.run() x = 0 y = 0 grid = [] row = ["."] sx = sy = 0 while len(cpu.stdout) > 0: char = chr(cpu.stdout.pop()) if char == "\n": row.append(".") grid.append(row) row = ["."] x = 0 y += 1 else: row.append(char) x += 1 if char == "^": sx = x sy = y + 1
for i, m in enumerate(moves, start=1): t.append([ i, cpu.skips_formatted(m), m.score, m.valuation, (m.row, m.col), racks[i - 1], times[i - 1] ]) s += tb.tabulate(t, headers=h, tablefmt="fancy_grid") s += '\n' s += c.displayBoard(c.board) f = open(file, 'w', encoding='utf-8') f.write(s) f.close() c = cpu.CPU() ms = [] rs = [] ts = [] racks = ["ITIATWE", "ITMDEXY", "TYAUAOU", "UAURAEF", "UFOLOIT", "LITUCKE"] i = 0 while c.distribution: c.rack = list(racks[i]) rs.append(''.join(c.rack)) t = time.time() ms.append(c._run()) c.board.updateCrosschecks(ms[-1]) ts.append(round(time.time() - t, 2)) write_state_to_file(c, ms, rs, ts) print(open('run.txt').read()) i += 1
from aocd import get_data import cpu total = 0 for x in range(50): for y in range(50): program = cpu.CPU("19.in") program.stdin.append(x) program.stdin.append(y) program.run() if program.stdout.pop() == 1: total += 1 print(total)
def inBeam(x, y): program = cpu.CPU("19.in") program.stdin.append(x) program.stdin.append(y) program.run() return program.stdout.pop() == 1
def __init__(self): self.cpu = cpu.CPU(self) self.ram = mem.MEM(self)
import cpu cpu = cpu.CPU("21.in") PROGRAM = """NOT C T OR D J AND T J NOT A T OR T J WALK """ for char in PROGRAM: cpu.stdin.append(ord(char)) cpu.run() grid = [] row = [] while len(cpu.stdout) > 0: num = cpu.stdout.pop() if num > 256: print(num) exit() char = chr(num) if char == "\n":
def main(): emulator = cpu.CPU(640, 320) emulator.initialize() emulator.load_rom(ROM) while True: emulator.emulate_cycle()