def __init__(self): super().__init__() nes = Nes() nes.load('roms/mario.nes') # configure ppu self._ppu_bus = Bus() self._ppu_pattern = PatternTable() self._ppu_pattern.load(nes.chr) self._ppu_name = NameTable() self._ppu_palette = PaletteTable() self._ppu_bus.connect(self._ppu_pattern) self._ppu_bus.connect(self._ppu_name) self._ppu_bus.connect(self._ppu_palette) self._ppu = Ppu(self._ppu_bus) # configure cpu self._cpu_ram = Ram() self._pgr = PGRRom() self._pgr.load(nes.pgr) self._papu_ram = PAuExp() self._cpu_bus = Bus() self._cpu_bus.connect(self._pgr) self._cpu_bus.connect(self._cpu_ram) self._cpu_bus.connect(self._papu_ram) self._cpu_bus.connect(self._ppu.get_register()) self._cpu = Cpu6502(self._cpu_bus) self._cpu.reset() self._ppu.set_request_nmi(self._cpu.request_nmi) self._addr_map, self._code = self._cpu.decode(0x8000, 0xFF00) self._font = pygame.font.SysFont('inconsolatan', 24) self._cpu_running = False self._cpu_time_last = 0
def test_operations(intA, intB): from util import bits2int, int2bits from register import Register from bus import Bus A = Bus("A", 32) B = Bus("B", 32) C = Bus("C", 32) mir = Register("MIR", 36, None, None, None) alu = ALU(A, B, C, mir) wordSize = max(intA.bit_length(), intB.bit_length()) A.val = int2bits(intA, wordSize) B.val = int2bits(intB, wordSize) print("A = binary({0}) -> {1}".format(intA, list(reversed(A.val)))) print("B = binary({0}) -> {1}".format(intB, list(reversed(B.val)))) print() for _, op in operations.items(): mir.val = [0 for _ in range(16) ] + op.bit_string + [0 for _ in range(16 + 6, 36)] alu.tick() sol = C.val print("f(A,B) = {0}".format(op.name)) print("binary({0}) -> {1}".format(bits2int(sol), list(reversed(sol)))) print()
def main(): list = [ Vehicle(100, 200000, 4), Bus(90, 350000, 45), Vehicle(200, 300000, 8), Bus(100, 300000, 40), Vehicle(150, 250000, 2), Bus(95, 400000, 35), ] for x in list: if not isinstance(x, Bus): continue print(f"{ x }\nFare: { fare(x) } $", end="\n\n")
def __init__(self): super(TestWindow, self).__init__() self.__bus = Bus() print self.__bus.get_name() self.__bus.connect("disconnected", gtk.main_quit) context_path = self.__bus.create_input_context("Test") print context_path self.__context = InputContext(self.__bus, context_path) self.__context.set_capabilities(9) self.__context.connect("commit-text", self.__commit_text_cb) self.__context.connect("update-preedit-text", self.__update_preedit_text_cb) self.__context.connect("show-preedit-text", self.__show_preedit_text_cb) self.__context.connect("update-auxiliary-text", self.__update_auxiliary_text_cb) self.__context.connect("update-lookup-table", self.__update_lookup_table_cb) self.set_events(gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK | gtk.gdk.FOCUS_CHANGE_MASK) self.connect("key-press-event", self.__key_press_event_cb) self.connect("key-release-event", self.__key_release_event_cb) self.connect("delete-event", gtk.main_quit) self.connect("focus-in-event", lambda *args: self.__context.focus_in()) self.connect("focus-out-event", lambda *args: self.__context.focus_out()) self.show_all()
def query_stop(router_name, stop_id): stoptype = request.args.get('stoptype', '0') bus = Bus() res = bus.query_stop(router_name, stoptype, stop_id) return jsonify(res)
def query_router(router_name): direction = request.args.get('direction', '0') router_name = router_name.encode('utf-8') bus = Bus() routers = bus.query_router(router_name, direction) return jsonify(routers)
def get_stops(stop_type, number): if stop_type not in ['up', 'down']: return jsonify(Response(error=1, msg='stop type error').dumps()) bus = Bus(number=number, stop_type={'up': 0, 'down': 1}[stop_type]) bus.get_stations() stops = bus.get_stops() return jsonify(Response(error=0, msg='', data=stops).dumps())
def update_buses(self): """ Polls the API and creates and adds Bus objects to the current bus list. Puts the buses in the current list to the previous bus list. Then sorts the current list by Bus ID. """ self.__prev = self.__buses self.__buses = [] raw_bus_list = api.get_buses() # raw_bus_list = api.get_buses_on_route(633) for raw_bus in raw_bus_list: id = raw_bus['id'] name = raw_bus['name'] route = raw_bus['route'] location = (raw_bus['lat'], raw_bus['lon']) heading = raw_bus['heading'] speed = -1 last_stop = raw_bus['lastStop'] last_update = raw_bus['lastUpdate'] b = Bus(id, name=name, route=route, location=location, heading=heading, speed=speed, last_stop=last_stop, last_update=last_update) self.__buses.append(b) self.__buses.sort(key=lambda x: x.get_id()) self.calculate_speeds()
def main(args): readConfig(vars(args)) if args.debug: level = logging.DEBUG else: level = logging.INFO logstream = sys.stderr try: if args.logMain: logstream = open(args.logMain, 'w') except: pass logging.basicConfig(level=level, stream=logstream) logging.debug(args) ser = rs485.RS485(args.port, args.baudrate, timeout=0.2, writeTimeout=0.2) bus = Bus(ser) script = None try: if args.script: script = open(args.script) except Exception as e: logging.warning("Unable to open script file (%s)" % str(e)) master = Master(bus, script) master.loop() return 0
def poll(): os.system('setterm -cursor off') interface = Bus() device = interface.identify() time.sleep(0.02) while device['system'] == WB_DOWN: device = interface.identify() time.sleep(1) if device['system'] == WB_AUTH: interface.wavebird_init(device['id']) try: while 1: device = interface.identify() time.sleep(0.02) status = interface.status(device['system']) for field, values in BUTTON[device['system']].items(): for value in values: if value.mask != 0xFF: print("{}{}{} ".format(value.color if getattr(status, field) & value.mask else DGRAY, value.name, END), end='') else: print("{}{}:{:+03X}{} ".format(value.color, value.name, getattr(status, field), END), end='') if 'slot' in device: print("slot:{}".format(device['slot']), end='') print("\r", end='') time.sleep(0.02) except KeyboardInterrupt: pass os.system('setterm -cursor on') print("")
def __init__(self, debug): """ Initialize the data members of the component. """ self.debug_info = debug if self.debug_info is True: print("[CPU] initializing...") self.bus = Bus(debug) self.register_table = { # General purpose registers "rax": 0, "rbx": 0, "rcx": 0, "rdx": 0, "r8": 0, "r9": 0, # Special purposee registers "pc": 0, "rsp": 0, "rbp": 0, "rip": 0, "rflags": 0, } # Performance/timing variables self.current_instr_size = 0 self.current_instr_cycles = 0 self.cpi = 0 ########################### if self.debug_info is True: print("[CPU] finished initializing...")
def test_bus_apply(): bus = Bus(4) bus.line = [0, 1, 0, 1] bus.apply([1, None, None, 0]) assert bus.line == [1, 1, 0, 0]
def query_router_details(router_name): direction = request.args.get('direction', '0') bus = Bus() router_details = bus.query_router_details(router_name, direction) return jsonify(router_details)
def query_router_details(router_name): stoptype = request.args.get('stoptype', '0') bus = Bus() router_details = bus.query_router_details(router_name, stoptype) return jsonify(router_details)
def query_stop(router_name, stop_id): direction = request.args.get('direction', '0') bus = Bus() res = bus.query_stop(router_name, direction, stop_id) return jsonify(res)
def __init__(self, cache_size, block_size, debug): """ Initialize the cache component. """ self.debug_info = debug if self.debug_info is True: print("[Cache] initializing...") ### Initialization code ### self.cache_size = cache_size self.block_size = block_size self.num_of_blocks_used = 0 self.max_number_of_blocks = int(self.cache_size / self.block_size) self.cache = [Block()] * int(self.cache_size / self.block_size) self.bus = Bus(self.debug_info) ########################### #### Performance Stats #### self.hits = 0 self.misses = 0 self.replacements = 0 ########################### if self.debug_info is True: print("[Cache] finished initializing...") print("[Cache] Max number of blocks '", self.max_number_of_blocks, "'...")
def _startBuses(self): for _ in range(2): self._queuesOut.append(queue.Queue()) self._buses.append( Bus("P" + str(0), self._chipNumber, self._queuesIn, self._queuesOut[0], self._lock, self._mainwin, self._guiQueues[1:3], self._gameMode)) self._buses.append( Bus("P" + str(1), self._chipNumber, self._queuesIn, self._queuesOut[1], self._lock, self._mainwin, self._guiQueues[3:5], self._gameMode)) self._buses[0].start() self._buses[1].start()
def main(): """ Main Routine """ print("\n[.] Initializing parameters/settings for simulator...") print("[.] Values in brackets represent reccommended/tested values.") print("[.] Using untested values may result in unstable behavior.\n") # Ask for parameters user_debug = input("[?] Enable debugging information [No]: ") debug = (user_debug == "Yes") memory_size = input("[?] Size of main memory (bytes) [100]: ") virtual_memory_size = input("[?] Size of virtual memory (bytes) [8000]: ") cache_size = input("[?] Size of cache (bytes)[40]: ") block_size = input("[?] Size of cache blocks (bytes)[4]: ") page_size = input("[?] Size of disk pages (bytes)[32]: ") table_size = input("[?] Number of TLB table entries (bytes)[10]: ") # Initialize components with bus and debug flag bus = Bus(debug) cpu = CPU(debug) cache = Cache(int(cache_size), int(block_size), debug) tlb = TLB(int(table_size), debug) memory = Memory(int(memory_size), int(virtual_memory_size), debug) disk = Disk(int(page_size), debug) # Initialize GUI menu = GUI(bus, cpu, cache, tlb, memory, disk, debug) menu.menu_loop()
def __init__(self, memory_size, virtual_memory_size, debug): self.debug_info = debug if self.debug_info is True: print("[Memory] initializing...") ### Initialization code ### self.virtual_memory = [None] * virtual_memory_size self.memory = [None] * memory_size self.page_table_register = None self.bus = Bus(debug) self.memory_size = memory_size self.number_of_pages_loaded = 0 self.memory_used = 0 ### Virtual Memory ### # Assuming size of memory is self.stack_address_used = 0x8000 # decrease as memory is used, stack # grows up self.const_stack_start = 0x8000 self.heap_address_used = 0 # increase as memory is used self.const_heap_start = 0x4000 self.bss_address_used = 0 # increase as memory is used self.const_bss_start = 0x2000 self.text_address_used = 0 # increase as memory is used self.const_text_start = 0x1000 ########################### if self.debug_info is True: print("[Memory] finished initializing...")
def main(): _ppu_bus = Bus() _ppu_pattern = PatternTable() # _ppu_pattern.load(nes.chr) _ppu_name = NameTable() _ppu_palette = PaletteTable() _ppu_bus.connect(_ppu_pattern) _ppu_bus.connect(_ppu_name) _ppu_bus.connect(_ppu_palette) _ppu = Ppu(_ppu_bus) ram = Ram() pgr = PGRRom() ppu_reg = PPURegister(_ppu_bus) pau_exp = PAuExp() nes = Nes() nes.load('roms/nestest.nes') pgr.load(nes.pgr) bus = Bus() bus.connect(pgr) bus.connect(ram) bus.connect(pau_exp) bus.connect(ppu_reg) cpu = Cpu6502(bus) cpu.test_mode() real_log = Log() n = 0 while True: n += 1 log = cpu.log() if not real_log.check(log): # print('F: {}'.format(OrderedDict(log))) # print('T: {}'.format(OrderedDict(real_log.log()))) # print('{} Addr: {}, Data: {}'.format(n, cpu._addr, cpu._data)) break else: pass # print('T: {}'.format(OrderedDict(log))) cpu.run() end = real_log.next() if end: break print('{} ins passed'.format(n))
def test_bus_arrived_and_everybody_got_on_the_bus(self): lane = Lane() stop = BusStop(lane, 30, 10) line = BusLine([stop], 0, 500) bus = Bus(line, 10, 10) control.bus_stop(bus, stop) self.assertEquals(bus.people_carried, 20) self.assertEquals(stop.people, 0)
def test_bus_arrived_and_people_were_left_at_stop(self): lane = Lane() stop = BusStop(lane, 30, 10) line = BusLine([stop], 0, 500) bus = Bus(line, 10, 93) control.bus_stop(bus, stop) self.assertEquals(bus.people_carried, 100) self.assertEquals(stop.people, 3)
def test_bus_arrived_at_stop_at_full_capacity(self): lane = Lane() stop = BusStop(lane, 30, 10) line = BusLine([stop], 0, 500) bus = Bus(line, 10, 100) control.bus_stop(bus, stop) self.assertEquals(bus.people_carried, 100) self.assertEquals(stop.people, 10)
def dispatch(self): if self._dspt_times: if self._curr_time >= self._dspt_times[0]: bus = Bus(self._total_bus, self._stop_num) self._total_bus += 1 self._link_list[0].enter_bus(bus, 0) self._dspt_times.remove(self._dspt_times[0]) self._total_bus_list.append(bus)
def read_back_up(): '''this function allows backup file to input string attributes to each person and bus, then it changes those string attributes into town objects''' personList.clear() busList.clear() townList.clear() # create objects whose attributes reflect the current state of the system infile = open("backup.txt", "r") for aline in infile.readlines(): values = aline.split() if values[0] == "Person": personList.append( Person(values[3], values[7], values[5], values[9])) if values[0] == "Bus": busList.append( Bus(values[4:7], int(values[8]), int(values[10]), values[12:])) if values[0] == "Town": townList.append(Town(values[1], values[2:])) # change person.origin and person.destination into town objects for person in personList: for town in townList: if person.locate() == town.getName(): person.setLocation(town) if person.getBus() == "None": town.addPeople( person ) # add ppl who are not on bus to town.peoplelist if person.getDestination() == town.getName(): person.setDestination(town) # change each person's bus information from string into bus object if person.getBus() == "None": person.setBus(None) else: personOnBus = int(person.getBus()) # cannot use int(person.getBus()) in "for" loop because person.getBus() # ceases to be a string at one point and there will be an error in loop for bus in busList: if bus.getID() - 12 == personOnBus: # subtract 12 because 12 bus objects have been created before person.setBus(bus) # change items in bus.route list into town objects for n in range(len(busList[0].getRoute())): for bus in busList: for town in townList: if bus.getRoute()[n] == town.getName(): bus.setRoute(n, town) # change items in bus.peopleList list into person objects for bus in busList: if bus.getPeople() is not None: for n in range(len(bus.getPeople())): for person in personList: if bus.getPeople()[n] == person.getName(): bus.getPeople()[n] = person # add buses to respective towns for town in townList: town.locateBus(busList)
def distribute_initial_buses(self): m = 2 n = self._stop_num // m for bs in range(n - 1): enter_link_no = (bs + 1) * m bus = Bus(self._total_bus, self._stop_num) bus.is_counted = False self._total_bus += 1 self._link_list[enter_link_no].enter_bus(bus, 0) self._total_bus_list.append(bus)
def put_accommodation(): post_data = request.get_json() id = post_data['id'] number_of_passengers = post_data['number_of_passengers'] gearbox = post_data['gearbox'] number_of_flights = post_data['number_of_flights'] new_bus = Bus(number_of_passengers, gearbox, number_of_flights) bus[id] = new_bus return 'Put'
def load_cache(cls): """Load cache objects before get_vehicle() method""" car = Car() cls._vehicle_dict["car"] = car bus = Bus() cls._vehicle_dict["bus"] = bus three_wheel = ThreeWheel() cls._vehicle_dict["three wheel"] = three_wheel
def post_bus(): post_data = request.get_json() id = post_data['id'] number_of_passengers = post_data['number_of_passengers'] gearbox = post_data['gearbox'] number_of_flights = post_data['number_of_flights'] new_bus = Bus(number_of_passengers, gearbox, number_of_flights) bus[id] = new_bus return 'Posted ' + str(bus.get(id).number_of_flights)
class EventBus: bus = Bus() observers = {} @staticmethod def post(addr, message): if addr == BLUETOOTH_ADDR: bt_task_handler.post_outgoing(message) else: EventBus.bus.send(message.as_packet_data(), addr) @staticmethod def pop(unit_addr): if unit_addr == BLUETOOTH_ADDR: return bt_task_handler.pop_incoming() else: return EventBus.bus.try_receive(unit_addr) @staticmethod def receive(): EventBus.receive_from_addr(BLUETOOTH_ADDR) EventBus.receive_from_addr(SENSOR_ADDR) EventBus.receive_from_addr(STYR_ADDR) @staticmethod def receive_from_addr(unit_addr): for i in range(MAX_READ_COUNT): data = EventBus.pop(unit_addr) if data is None: break if unit_addr == BLUETOOTH_ADDR: EventBus.notify(data.cmd_id, *data.data) else: command = Event.parse(data) command.process() EventBus.notify(command.message_id, *command.arguments) @staticmethod def subscribe(command_id, handler): observer = EventBus._get_observer_for_command(command_id) observer.subscribe(handler) @staticmethod def notify(command_id, *args): observer = EventBus._get_observer_for_command(command_id) observer.notify(*args) @staticmethod def _get_observer_for_command(command_id): if command_id not in EventBus.observers: EventBus.observers[command_id] = Observer() return EventBus.observers[command_id]