Exemplo n.º 1
0
    def __init__(self, ip: str, port: int):
        self.client = OSCClient(ip, port)

        self.root = tkinter.Tk()
        self.root.geometry("400x400")
        self.root.protocol("WM_DELETE_WINDOW", self.handleQuit)
        bind_event_data(self.root, Stub.eventPIGPIO, self.handlePIGPIO)

        self.canvas = tkinter.Canvas(self.root, width=400, height=400)
        self.screen = turtle.TurtleScreen(self.canvas)
        self.screen.tracer(0, 0)
        self.machine = Machine(pigpio_provider.pi('GUI', self.screen))
        self.machine.setup()

        frame_top = tkinter.Frame(self.root)
        self.button_ping = tkinter.Button(frame_top,
                                          text='ping',
                                          command=self.call_ping)
        self.button_reset = tkinter.Button(frame_top,
                                           text='reset',
                                           command=self.call_reset)
        self.button_ping.pack(side='left', anchor='n')
        self.button_reset.pack(side='left', anchor='n')

        frame_command = self.__renderFrameCommand()

        frame_top.pack()
        frame_command.pack()

        self.canvas.pack(anchor='s')
Exemplo n.º 2
0
 def __init__(self, vm_limit, azure_config, skip_setup, local):
     self.vm_limit = vm_limit # user input
     self.budget = 0
     self.timestamp = datetime.now()
     self.cost_pred = 0
     self.wf_end = None
     
     self.jobs_terminated = False
     self.last_resched = None
     
     self.workflow = Workflow()
     self.logwatcher = LogWatcher()
     
     self.schedule = Schedule()
     
     manager = Machine()
     manager.status = MachineStatus.manager
     manager.condor_slot = 'manager'
     self.machines = [manager]
     
     boot_entry = ScheduleEntry(Job('boot', None), manager, self.timestamp, self.timestamp)
     boot_entry.real_start = self.timestamp
     boot_entry.real_end = self.timestamp
     boot_entry.status = EntryStatus.completed
     self.schedule.add_entry_host(boot_entry, manager)
     
     self.local = local
     if azure_config and not local:
         hostname = socket.gethostname()
         self.exp = AzureExperiment(azure_config, skip_setup=skip_setup, name=hostname)
         self.master_addr = socket.gethostbyname(hostname)
         self.user = azure_config.admin_username
     else:
         self.exp = self.master_addr = self.user = None
Exemplo n.º 3
0
def main(argv):
	
	if len(argv) < 5:
		print "Usage: mipssim.py -i [input_file_name] -o [output_file_name]"
		quit(-1)
	try:
		inputFilenameIndex = argv.index('-i') + 1
		outputFilenameIndex = argv.index('-o') + 1
	except ValueError:
		print "Usage: mipssim.py -i [input_file_name] -o [output_file_name]"
		quit(-1)
	
	infileName = argv[inputFilenameIndex]
	if '.bin' not in infileName:
		infileName+='.bin'
	outFileName = argv[outputFilenameIndex]
	
	(word, address) = filemanager.loadInstructionsAndAddresses(infileName)
	instruction = []
	for i in range(len(word)):
		instruction.append(Instruction(word[i], address[i]))
	
	disassembler.target_file = open(outFileName+'_dis.txt', 'w')
	disassembler.disassembleSet(instruction)
	mips = Machine(outFileName+'_sim.txt')
	mips.loadInstructions(instruction)
	mips.executeInstructions()
Exemplo n.º 4
0
 def __init__(self, max_players=6):
     self.machine = Machine()
     self.round = 0
     self.max_players = max_players
     print('Max players:', self.max_players)
     self.dealer = None
     self.players = [None] * self.max_players
Exemplo n.º 5
0
def machine():

    if request.form['mantissa'] != '' and request.form['exponent'] != '':
        mantissa = request.form['mantissa']
        exponent = request.form['exponent']
    else:
        mantissa = request.cookies.get('mantissa')
        exponent = request.cookies.get('exponent')

    if int(mantissa) + int(exponent) == 10:

        machine = Machine(int(mantissa), int(exponent))
        maximum = machine.biggest()
        minimum = machine.lowest()
        positive = machine.positive()
        resp = make_response(
            render_template('machine.html',
                            maximum=maximum,
                            minimum=minimum,
                            binary=0,
                            positive=positive))
        resp.set_cookie('exponent', value=exponent, max_age=90)
        resp.set_cookie('mantissa', value=mantissa, max_age=90)

        return resp
    else:
        return mantissa + exponent
Exemplo n.º 6
0
    async def machine_connected(self, reader, writer):
        self.logger.info('machine connected')

        machine = Machine(reader, writer)

        try:
            await machine.obtain_id()
            self.add_machine(machine)

            while True:
                await machine.wait_acquired()
                self.logger.info('machine acquired')
                self.remove_machine(machine)

                await machine.wait_released()
                self.logger.info('machine released')
                self.add_machine(machine)

        except MachineDisconnectedException:
            self.remove_machine(machine)
            self.notify_machine()

        except:
            self.logger.exception('unknown machine error')
            machine.close()
Exemplo n.º 7
0
def do_set_component_setting(component_id, setting_name):
    try:
        Machine.set_component_setting(component_id, setting_name,
                                      request.get_json())
    except BaseException as e:
        return make_response(jsonify(str(e)), 400)
    return render_state()
Exemplo n.º 8
0
    def random_lb(self, nr_req):
        count = nr_req

        for i, worker in enumerate(self.workers_info_list):
            if count != 0:
                if i == len(self.workers_info_list) - 1:
                    machine = Machine(worker["region"], worker["id"], count)
                    self.workers_list.append(machine)
                    break
                r = random.randint(1, count)
                machine = Machine(worker["region"], worker["id"], r)
                count = count - r
                self.workers_list.append(machine)

        self.run_workers()
        self.join_workers()

        avrg_time = 0
        for worker in self.workers_list:
            avrg_time = avrg_time + worker.resp_time

        avrg_time = avrg_time / len(self.workers_list)
        print('Average time:', avrg_time)

        self.workers_list = []
Exemplo n.º 9
0
def compararResultado(machine, status, rodadas):
    best = Machine(machine.generation)
    best.readBest(True)
    continuar = False

    if status == "LOSE":
        roundsToLose = rodadas
    elif status == "WIN":
        machine.winStreak += 1
        continuar = True
    elif status == "DRAW":
        machine.winStreak += 1
        machine.empates += 1
        continuar = True
    elif status == "ERROR":
        machine.erro = True

    newBest = False
    if (status != "ERROR"):
        if (machine.winStreak > best.winStreak):
            newBest = True
        elif (best.winStreak == machine.winStreak) and (machine.empates < best.empates):
            newBest = True
        elif (best.winStreak == machine.winStreak) and (machine.empates == best.empates) and (machine.roundsToLose > best.roundsToLose):
            newBest = True

    if newBest:
        machine.writeBest()

    return continuar
Exemplo n.º 10
0
    def test_can_refill_biscuits(self):
        racks = [Rack("A", "Biscuits", 100)]
        machine = Machine(racks)
        machine.refill("A", 5)

        # machine.racks: A => Rack, B => Rack
        self.assertEqual(machine.racks["A"].quantity, 5)
Exemplo n.º 11
0
def best_hit(target, flavor_list, machine_memory, machine_cpu):
    machine_list = []
    if target == 'CPU':
        flavor_list.sort(key=lambda Flavor: Flavor.cpu, reverse=True)
    else:
        flavor_list.sort(key=lambda Flavor: Flavor.memory, reverse=True)
    for flavor in flavor_list:
        for index in range(flavor.predict_num):
            if not machine_list:
                machine_list.append(Machine(machine_memory, machine_cpu))
            best = -1
            best_memory = machine_memory
            best_cpu = machine_cpu
            index = 0
            if machine_list:
                for machine in machine_list:
                    if machine.can_accommodate(flavor.memory, flavor.cpu):
                        if (target == 'CPU' and machine.residueCPU <= best_cpu) or (
                                        target == 'MEM' and machine.residueMemory <= best_memory):
                            best = index
                            best_cpu = machine.residueCPU
                            best_memory = machine.residueMemory
                    index += 1
            if best == -1:
                machine_list.append(Machine(machine_memory, machine_cpu))
                machine_list[-1].assign_vm(flavor.name, flavor.memory, flavor.cpu, target)
            else:
                machine_list[best].assign_vm(flavor.name, flavor.memory, flavor.cpu, target)
    return machine_list
Exemplo n.º 12
0
    def visitLanguage(self, ctx: RegularParser.LanguageContext):
        # Construct the final NFA by connecting the terms to single start and final states
        # Take note of each concatenated machine
        concatenated_machines = []

        for termComponent in ctx.getChildren():
            if type(termComponent) is RegularParser.TermContext:
                concatenated_machines.append(self.visitTerm(termComponent))

        # Create a new initial state
        new_init_state = Machine.assign_state_name()

        # Create a new final state
        new_final_state = Machine.assign_state_name()

        # Create a new state table, merging all the state tables of the concatenated machines, then connecting the new
        # initial state to all the old initial states of the concatenated machines, then finally connecting the old
        # final states of the machines to the new final state
        new_state_table = {new_init_state: {}, new_final_state: {}}

        for concatenated_machine in concatenated_machines:
            # Merge its state table with the new state table
            new_state_table.update(concatenated_machine.state_table)

            # Create an epsilon transition from the new initial state to the old initial state of the concatenated
            # machine
            new_state_table[new_init_state][Machine.assign_epsilon_transition(
            )] = concatenated_machine.init_state

            # Create an epsilon transition from the old final state of the concatenated machine to the new final state
            new_state_table[concatenated_machine.final_states[0]][
                Machine.assign_epsilon_transition()] = new_final_state

        return Machine(concatenated_machines[0].alphabet, new_state_table,
                       new_init_state, [new_final_state])
Exemplo n.º 13
0
    def test_issue(self):
        machine = Machine()
        instr = Instruction(0x20010003)
        self.assertTrue(machine.issue(instr))
        self.assertTrue(machine.hasInstruction())

        rstations = machine.unitContainers['IntUnit'].dumpRStations()
Exemplo n.º 14
0
Arquivo: vm.py Projeto: k3an3/redbot
def clean_machines() -> None:
    """
    Delete all Docker Machine instances that we are aware of.
    """
    m = Machine()
    for machine in storage.smembers('machines'):
        m.rm(machine=machine)
Exemplo n.º 15
0
class StarTest(object):
    def __init__(self, tmpdir):
        self.tmpdir = str(tmpdir)
        self.root = Compound(None, 'root')
        self.events = {}
        for meth_name in dir(self):
            meth = getattr(self, meth_name)
            ticks = getattr(meth, 'ticks', None)
            if ticks is not None:
                for tick in ticks:
                    events = self.events.get(tick, [])
                    events.append(meth)
                    self.events[tick] = events

    def each_tick(self, tick):
        pass

    def each_clock(self, clock):
        pass

    def get_total_ticks(self):
        return max(self.events.keys() or [0]) + 1

    def run_machine(self, ticks=None):
        self.machine = Machine(self.root,
                               on_tick=self.each_tick,
                               on_clock=self.each_clock)
        self.machine.run(ticks or self.get_total_ticks(), self.events)

    def view(self, prefix, tick=None):
        tick = tick if tick is not None else self.machine.tick
        builder = GraphBuilder()
        graph = builder.visit(self.root)
        graph.render(os.path.join(self.tmpdir, '%s_%i' % (prefix, tick)))
Exemplo n.º 16
0
def main():
    if len(sys.argv) != 3:
        print "usage: %s [input_directory] [output_directory]" % (sys.argv[0])
        sys.exit()

    input_dir = os.path.abspath(sys.argv[1])
    output_dir = os.path.abspath(sys.argv[2])
    os.path.exists(output_dir) or os.mkdir(output_dir)

    framework_dir = os.path.dirname(os.path.abspath(os.path.join(os.getcwd(), __file__)))
    os.chdir(framework_dir)

    m = Machine(input_dir=input_dir, output_dir=output_dir, framework_dir=framework_dir, program=[])
    m.setup(
        "defaults",
        "exception",
        "parse",
        "modules",
        "php_backend",
        "php_view",
        "macro",
        "global_command",
        "guard",
        "handler",
        "view",
        "generate",
    )
    m.boot()
Exemplo n.º 17
0
    def execute(self):
        db = setting.DB['7560']  # select database
        try:
            wb = openpyxl.load_workbook(db)  # load workbook
            sheets = ['PRE', 'SUTC', 'MUTC', 'SCR', 'MICE']
            sheets = ['SUTC', 'MUTC','MICE','PRE']
            while True:  # loop csv_name
                for csv_name in sheets:
                    ws = wb[csv_name]  # get worksheet obj
                    t1 = time.time()
                    if csv_name not in self.setup_info:
                        self.setup_info[csv_name] = []  # record setup obj
                        for row in ws.iter_rows(min_row=2):  # iterate worksheet with row ways
                            machine_obj = Machine(row[0].value.strip())  # instantiate Machine obj
                            machine_obj.operator = row[1].value.strip()
                            self.setup_info[csv_name].append(machine_obj)  # append machine obj into to  setup_info list
                            self.execute_mtbf(machine_obj, csv_name)
                    else:
                        for machine in self.setup_info[csv_name]:
                            self.execute_mtbf(machine, csv_name)
                    for t in self.thread_list:
                        t.join()
                    self.html_dis(csv_name)
                    print('[%s]' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 'total setup:',
                          len(self.setup_info[csv_name]))  # print total setup
                    print('[%s]' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 'time', time.time() - t1)

        except Exception as e:
            print('\033[1;31mException:%s.\033[0m' % e)
Exemplo n.º 18
0
class LFizz(Service):
    def __init__(self, config_file, mock_gpio=False):
        super().__init__()

        if not mock_gpio:
            GPIO.setwarnings(False)
            if GPIO.getmode() != GPIO.BOARD:
                GPIO.setmode(GPIO.BOARD)
            Electrical.setup_gpio()
            Eink.EPD = EPD()

        self.eink = Eink(reactor)
        self.config = self._parse_config(config_file)
        self._setup_logging(self.config)
        self.app_state = AppState(self.config)
        self.leds = Leds()
        self.machine = Machine(reactor, self.app_state, self.eink, self.leds)
        self.network_health = NetworkHealth(reactor, self.machine)
        self.invoicer = Invoicer(reactor, self.app_state, self.machine)
        self.electical = Electrical(reactor, self.machine)

    ###########################################################################

    def _parse_config(self, config_file):
        if not os.path.exists(config_file):
            sys.exit("please add a config file at %s" % config_file)
        config = configparser.ConfigParser()
        config.read(config_file)
        if config['OpenNode']['ApiKey'] == 'sk_your_api_key':
            sys.exit("please set your Node API key in %s" % config_file)
        return config

    def _setup_logging(self, config):
        if not config['Logging']['Enabled']:
            return
        filename = os.path.join(config['Logging']['Dir'], "lfizz.log")
        setup_logging(filename)

    ###########################################################################

    def run_lfizz(self):
        self.network_health.run()
        self.invoicer.run()
        self.machine.run()
        reactor.run()

    def stop_lfizz(self):
        self.invoicer.stop()
        reactor.stop()

    ###########################################################################

    def startService(self):
        super().startService()
        self.run_lfizz()

    def stopService(self):
        super().stopService()
        self.stop_lfizz()
        reactor.stop()
Exemplo n.º 19
0
class StarTest(object):
    def __init__(self, tmpdir):
        self.tmpdir = str(tmpdir)
        self.root = Compound(None, 'root')
        self.events = {}
        for meth_name in dir(self):
            meth = getattr(self, meth_name)
            ticks = getattr(meth, 'ticks', None)
            if ticks is not None:
                for tick in ticks:
                    events = self.events.get(tick, [])
                    events.append(meth)
                    self.events[tick] = events

    def each_tick(self, tick):
        pass

    def each_clock(self, clock):
        pass

    def get_total_ticks(self):
        return max(self.events.keys() or [0]) + 1

    def run_machine(self, ticks=None):
        self.machine = Machine(self.root, on_tick=self.each_tick,
                               on_clock=self.each_clock)
        self.machine.run(ticks or self.get_total_ticks(), self.events)

    def view(self, prefix, tick=None):
        tick = tick if tick is not None else self.machine.tick
        builder = GraphBuilder()
        graph = builder.visit(self.root)
        graph.render(os.path.join(self.tmpdir, '%s_%i' % (prefix, tick)))
Exemplo n.º 20
0
    def test_can_refill_coins(self):
        slots = [Slot("A", "Chocolate Biscuits", 100)]
        machine = Machine(slots)
        coins = {'NICKEL': 10, 'DIME': 10, 'QUARTER': 10, 'DOLLAR': 5}
        machine.refill_coins(coins)

        self.assertEqual(machine.coins['QUARTER'], 10)
Exemplo n.º 21
0
  def test_state_entity(self):
    machine = Machine(self.hass, States, entity='sensor.state')
    machine.add_transition(A, Timeout(10), B)

    self.assertEqual(self.hass.get_state('sensor.state'), 'A')
    self.hass.advance_time(10)
    self.assertEqual(self.hass.get_state('sensor.state'), 'B')
Exemplo n.º 22
0
    def second_random_lb(self, nr_req):
        req_per_machine = int(nr_req / len(self.workers_info_list))
        rest = nr_req % len(self.workers_info_list)
        count = req_per_machine
        remain = 0
        r = 0
        rest_req = nr_req

        for i, worker in enumerate(self.workers_info_list):
            if rest_req != 0:
                if i == len(self.workers_info_list) - 1:
                    machine = Machine(worker["region"], worker["id"], rest_req)
                    self.workers_list.append(machine)
                    break
                r = random.randint(1, count)
                remain = count - r
                count = req_per_machine + remain
                if rest > 0:
                    r = r + 1
                    rest = rest - 1
                machine = Machine(worker["region"], worker["id"], r)
                rest_req = rest_req - r
                self.workers_list.append(machine)

        self.run_workers()
        self.join_workers()

        avrg_time = 0
        for worker in self.workers_list:
            avrg_time = avrg_time + worker.resp_time

        avrg_time = avrg_time / len(self.workers_list)
        print('Average time:', avrg_time)

        self.workers_list = []
def add_machine():
    if request.method == "POST":
        json = request.get_json()
        action = json.pop("action")

        if action == "add":
            gpu_runner_db.machines.insert_one(json)

            # add to current machines / connections
            machine = Machine(
                app=app, jobs_db=gpu_runner_db.jobs_db, ssh_password=ssh_password, **json
            )
            machine.start()
            machines.update({json["_id"]: machine})
        else:
            assert action == "delete"
            delete_ids = [machine["_id"] for machine in json["machines"]]
            gpu_runner_db.machines.remove({"_id": {"$in": delete_ids}})

            # also remove these machines from the current list of machines / connections
            for machine in json["machines"]:
                machines.pop(machine["_id"])
        return ""
    else:
        return render_template("add_machine.html")
Exemplo n.º 24
0
Arquivo: main.py Projeto: kmtr/machine
def start(ip, addr):
    pi = pigpio_provider.pi()
    machine = Machine(pi)
    machine.setup()

    md = MachineDriver(machine)
    server = OSCServer(md, ip=args.ip, port=args.port)
    server.serve_forever()
Exemplo n.º 25
0
    def test_math_is_right_on_restock(self):
        bev1 = Beverage('Coke', 150, 1.00)
        bev = ['Coke', 150, 1.00]

        my_machine = Machine()
        my_machine.beverages.append((bev1))

        self.assertEqual('9 Cokes have been added to the machine', my_machine.restock(bev, 9))
Exemplo n.º 26
0
def run():
    print 'machine echo side a'
    ma = Machine('proxy_runner')
    ma.add_peer(peer)
    n = ProxyNode('node.example.TestNode')
    ma.add(n)

    return ma
Exemplo n.º 27
0
 def test_brUnit1(self):
     sys.stdout = output = io.StringIO()
     machine = Machine()
     machine.loadProgram('Tomasulo/brUnit1.hex')
     machine.run()
     with open('Tomasulo/brUnit1.out', 'r') as answerFile:
         answer = answerFile.read()
     self.assertEquals(output.getvalue(), answer)
Exemplo n.º 28
0
def run():
	m = Machine('Chain')
	a = A()
	nodes = [a, B(), C(), D(), E(), F(), G(), H(), I(), J(), K(), L(), M()]
	m.nodes.add(*nodes)
	a=m.get_nodes('A')[0]
	import pdb; pdb.set_trace()
	a.set('on', True)
	return m
Exemplo n.º 29
0
    def test_math_is_right_on_restock(self):
        bev1 = Beverage('Coke', 150, 1.00)
        bev = ['Coke', 150, 1.00]

        my_machine = Machine()
        my_machine.beverages.append((bev1))

        self.assertEqual('9 Cokes have been added to the machine',
                         my_machine.restock(bev, 9))
Exemplo n.º 30
0
 def test_allInts(self):
     for i in range(1, 9):
         sys.stdout = output = io.StringIO()
         machine = Machine()
         machine.loadProgram('Tomasulo/intUnit{0}.hex'.format(i))
         machine.run()
         with open('Tomasulo/intUnit{0}.out'.format(i), 'r') as answerFile:
             answer = answerFile.read()
         self.assertEquals(output.getvalue(), answer)
Exemplo n.º 31
0
Arquivo: vm.py Projeto: k3an3/redbot
def get_docker_client(machine_name: str) -> DockerClient:
    """
    Given the name of a Docker Machine instance, return an instance of DockerClient that is configured to communicate
    with the machine.

    :param machine_name: Docker Machine instance name to interact with.
    :return: DockerClient instance configured for the machine.
    """
    m = Machine()
    return DockerClient(**m.config(machine=machine_name))
Exemplo n.º 32
0
def main():
    # When running this function as console entry point, the current working dir is not in the
    # Python path, so we have to add it
    sys.path.insert(0, os.getcwd())
    bot = Machine()
    try:
        bot.run()
    except (KeyboardInterrupt, SystemExit):
        announce("Thanks for playing!")
        sys.exit(0)
Exemplo n.º 33
0
 def test_buy_item_A(self):
     machine = Machine()
     self.assertIsInstance(machine.press_button("A"), tuple)
     self.assertEqual(machine.press_button("A"), (None, None))
     machine.insert_money({100: 1})
     self.assertEqual(machine.press_button("A"), ("A", 0))
     self.assertEqual(machine.products["A"]["stock"], 9)
     machine.insert_money({100: 2})
     self.assertEqual(machine.press_button("A"), ("A", 100))
     self.assertEqual(machine.products["A"]["stock"], 8)
Exemplo n.º 34
0
Arquivo: main.py Projeto: mions1/RIG
def descruction(desc_type, machines):

    if desc_type == 1:
        # seleziono a random un job dalla macchina con max Cmax
        max_c_machine = Machine.get_machine_with_max_c(machines)
        return max_c_machine.get_random_job()

    elif desc_type == 2:
        # seleziono a random un job da tutte le macchine
        return Machine.get_random_job_among_all(machines)
Exemplo n.º 35
0
 def parseMachine(self, line):
     data = line[21:].split(" ")
     ip_addr = ""
     host_desc = ""
     if len(data) == 1:
         ip_addr = data[0]
     else:
         host_desc = data[0]
         ip_addr = (data[1])[1:-2]
     self.machine = Machine(ip_addr, host_desc)
Exemplo n.º 36
0
def run():
    print 'running simple machine'
    m = Machine()
    m.add_peer('PYRO:obj_d49b952840174542be460c635eec8436@localhost:55090')
    a = A()
    m.add(a)

    print 'perform a.one += 4'
    a.one += 4
    return m
Exemplo n.º 37
0
 def test_all(self):
     sys.stdout = output = io.StringIO()
     for inputFile in os.listdir('Tomasulo'):
         if inputFile.endswith('.dlx'): continue
         if inputFile.endswith('.out'): continue
         machine = Machine()
         machine.loadProgram('Tomasulo/' + inputFile)
         machine.run()
         with open('Tomasulo/' + inputFile.strip('.hex') + '.out', 'r') as answerFile:
             answer = answerFile.read()
         self.assertEquals(output.getvalue(), answer)
Exemplo n.º 38
0
 def __init__(self, app, **kwargs):
     self.app = app or self.app
     super(Guard, self).init(**kwargs)
     self.rpc_server = PyroServer(GUARD_PORT)
     self.rpc_client = PyroClient(self.app.conf['HUB_IP'], HUB_PORT)
     self.pool = Pool(self.app)
     self.machine = Machine(healthy_mock=app.conf['HEALTHY_MOCK'],
                            labels=self.labels)
     self.__shutdown_guard = threading.Event()
     self.LOOP_INTERVAL = 10  # second
     self.alive = False
Exemplo n.º 39
0
class TestAddiInsn(unittest.TestCase):
    def setUp(self):
        self.m = Machine([1, 5, 10, 19])

    def test_addi_1(self):
        self.m.execute(['addi', 0, 10, 0])
        self.assertEqual(self.m.registers, [11, 5, 10, 19])

    def test_addi_2(self):
        self.m.execute(['addi', 0, 10, 1])
        self.assertEqual(self.m.registers, [1, 11, 10, 19])
Exemplo n.º 40
0
    def game(self):
        board = [
            [" ", " ", " "],  # this is the grid
            [" ", " ", " "],
            [" ", " ", " "]
        ]
        finished = False  # determines whether the board is full or not
        win = False  # turns to True when there's a tree match

        u = User()
        user_tile = u.choose_tile()  # the user decides between X and O

        if user_tile == "X":
            machine_tile = "O"  # assigning tile-player
            user_turn = True

        else:
            machine_tile = "X"
            user_turn = False

        m = Machine(machine_tile, user_tile)

        # the game is finished when someone wins or when the board is full
        while finished is False and win is False:

            if user_turn:  # meanwhile, players take turns
                board = u.user_move(board, user_tile)  # user move
                name = "User"
                user_turn = False

            else:
                board = m.machine_move(board)  # machine move
                name = "Machine"
                user_turn = True

            print(name, "turn: ")

            for row in board:  # print the board
                print(row)

            # this method returns a tile when someone wins, otherwise it returns "-" (tie)
            winner_tile = m.board_state(board, False, None)

            if winner_tile == "X" or winner_tile == "O":  # checking if there's a winner
                win = True
                print(name, "has won! Congrats :)")

            else:  # checking if the board is full
                finished = m.finished(board)

            if finished is True and win is False:
                print("It's a tie")

        print("End of game")  # checking end of loop
Exemplo n.º 41
0
def process_start_trans_tape(start_status, transition, tape):
    print("Transition:")
    print(transition)
    print("Tape:")
    print(tape)
    if not start_status:
        machine = Machine(transition,tape)
    else:
        machine = Machine(transition,tape,start_status)
    print("Execution:")
    machine.execute()
Exemplo n.º 42
0
    def test_user_cant_buy_item_b_if_not_enough_money_inserted(self):
        slots = [Slot("B", "Coca", 120)]
        machine = Machine(slots)

        machine.refill("B", 5)
        machine.insert_coin(100)
        machine.insert_coin(10)
        machine.press("B")

        self.assertEqual(machine.slots["B"].quantity, 5)
        self.assertEqual(machine.amount, 110)
Exemplo n.º 43
0
    def test_count_bevs_of_one_name(self):
        my_machine = Machine()
        bevs = []
        new_bev = Beverage('Coke', 150, 1.00)
        new_bev2 = Beverage('Coke', 150, 1.00)
        new_bev3 = Beverage('Pepsi', 150, 1.50)
        bevs.append(new_bev)
        bevs.append(new_bev2)
        bevs.append(new_bev3)
        my_machine.beverages = bevs

        self.assertEqual(2, my_machine.get_number_of_bev('Coke'))
Exemplo n.º 44
0
 def sync_machines(self):
     slots = condor_slots()
     for s in slots:
         if s not in [m.condor_slot for m in self.machines]:
             machine = Machine()
             machine.status = MachineStatus.running
             machine.condor_slot = s
             boot_job = Job('boot', None)
             boot_entry = ScheduleEntry(boot_job, machine, None, None)
             boot_entry.log[LogKey.real_start] = self.creation_timestamp
             boot_entry.log[LogKey.real_end] = self.timestamp
             boot_entry.status = EntryStatus.completed
             self.entries.append(boot_entry)
             self.machines.append(machine)
             print "++Machine", s
def run():
    ma = Machine('example')
    m1 = Machine('foo')
    m2 = Machine('bar')
    n = TestNode()
    n2 = OtherNode()
    pr = Prox()

    a = Address('example.TestNode')
    pr.address = a

    print '---add machines---'
    ma.add(n, n2, pr)
    ma.add_peer('PYRO:obj_47120b94fb6347e89c1ed65024e2061b@localhost:56894')
    ma.add_peer('PYRO:obj_fd447709e96f4ce4a20cfc6c6b3b5dc9@localhost:41106')
    return ma
Exemplo n.º 46
0
 def __init__(self):
     self.workflow = Workflow()
     self.creation_timestamp = self.timestamp = datetime.now()
     self.logwatcher = LogWatcher()
     
     manager = Machine()
     manager.status = MachineStatus.manager
     manager.condor_slot = 'local'
     self.machines = [manager]
     
     boot_entry = ScheduleEntry(Job('boot', None), manager, None, None)
     boot_entry.real_start = self.timestamp
     boot_entry.real_end = self.timestamp
     boot_entry.status = EntryStatus.completed
     self.entries = [boot_entry]
     self.entries_cid = {}
Exemplo n.º 47
0
def run():
    print 'running direction direction'
    m = Machine()
    a= A()
    nodes = [a, B()]
    m.add(*nodes)
    a.one += 1
    print '>  Step up one'
    a.one += 1
    print '>  Step up three'
    a.one += 3
    print '>  Step down two'
    a.one -= 2
    print '>  Step is 4'
    a.one = 100

    return a
Exemplo n.º 48
0
 def test_execute(self):
     machine = Machine()
     machine.loadProgram('Tomasulo/intUnit1.hex')
     count = 0
     while True:
         instruc = machine.nextInstruction()
         machine.execute()
         machine.issue(instruc)
         count += 1
         machine.PC += 4
         if instruc.isHalt():
             break
     self.assertEquals(count, 15)
     rstations = machine.dumpRStations()
Exemplo n.º 49
0
 def test_execute_trap(self):
     machine = Machine()
     machine.loadProgram('Tomasulo/intUnit1.hex')
     instruction = Instruction(0x44800003)
     machine.issue(instruction)
     machine.execute()
     machine.execute()
Exemplo n.º 50
0
 def __init__(self, app, **kwargs):
     self.app = app or self.app
     super(Guard, self).init(**kwargs)
     self.rpc_server = PyroServer(GUARD_PORT)
     self.rpc_client = PyroClient(self.app.conf['HUB_IP'], HUB_PORT)
     self.pool = Pool(self.app)
     self.machine = Machine(healthy_mock=app.conf['HEALTHY_MOCK'], labels=self.labels)
     self.__shutdown_guard = threading.Event()
     self.LOOP_INTERVAL = 10  # second
     self.alive = False
Exemplo n.º 51
0
 def build(self, name, parent):
     from machine import Machine
     from machine import Point
     machinenode = Machine()
     machinenode.configure({'name':name, 'parent':parent})
     for point in self.points:
         if not point.include:
             continue
         metadata = []
         metadata.append({'name': 'property', 
                          'definition': point.property})
         metadata.append({'name': 'point_type', 
                          'definition': point.point_type})
         metadata.append({'name': 'value', 
                          'definition': point.value})
         pointnode = Point()
         pointnode.configure({'name':point.name, 
                              'parent':machinenode, 
                              'metadata': metadata})
     machinenode.start_simulation()
     return machinenode
Exemplo n.º 52
0
    def test_machine_next(self):
        r1 = Rule("A", 0, 1, True, "B")
        r2 = Rule("A", 1, 1, True, "A")
        r3 = Rule("B", 0, 0, False, "B")
        m = Machine(rules=[r1, r2, r3])
        write_symbol, shift_right = m.next(1)
        self.assertEqual(m.state, "A")
        self.assertEqual(write_symbol, 1)
        self.assertEqual(shift_right, True)

        write_symbol, shift_right = m.next(0)
        self.assertEqual(m.state, "B")
        self.assertEqual(write_symbol, 1)
        self.assertEqual(shift_right, True)

        write_symbol, shift_right = m.next(0)
        self.assertEqual(m.state, "B")
        self.assertEqual(write_symbol, 0)
        self.assertEqual(shift_right, False)

        with self.assertRaises(Halt):
            write_symbol, shift_right = m.next(1)
Exemplo n.º 53
0
class TestMachine(unittest.TestCase):

	def setUp(self):
		Machine.available = []
		self.machine = Machine(1, 'Janome', ['overlock', 'zig-zag', 'costura reta'])

	def test_startup_machine(self):
		self.machine.code |should| equal_to(1)
		self.machine.producer |should| equal_to('Janome')
		self.machine.sewing_types |should| equal_to(['overlock', 'zig-zag', 'costura reta'])
		self.machine.repairing |should| equal_to(False)
		self.machine.repairs |should| equal_to([])
		Machine.available |should| equal_to([self.machine])

	def test_repair_machine(self):
		self.machine.repair('supervisor', '16-10-2012')
		self.machine.repairing |should| equal_to(True)
		self.machine.repairs |should| equal_to([{'supervisor': 'supervisor', 'initiate': '16-10-2012'}])
		Machine.available |should_not| contain(self.machine)
	 	(self.machine.repair, 'supervisor2', '17-10-2012') |should| throw(MachineInRepair)

	def test_finish_repair_machine(self):
	 	self.machine.repair('supervisor', '16-10-2012')
	 	self.machine.finish_repair('17-10-2012')
	 	self.machine.repairs |should| equal_to([{'supervisor': 'supervisor', 'initiate': '16-10-2012', 'end': '17-10-2012'}])
	 	self.machine.repairing |should| equal_to(False)
	 	Machine.available |should| contain(self.machine)
		(self.machine.finish_repair, '17-10-2012') |should| throw(MachineNotInRepair)

	def test_problematic_machine(self):
		for i in range(11):
			self.machine.repair('supervisor', '16-10-2012')
			self.machine.finish_repair('17-10-2012')
		len(self.machine.repairs) |should| equal_to(11)
		Machine.problematic_machines |should| contain(self.machine)

	def test_machines_avaiable(self):
		Machine.available_machines() |should| equal_to('producer: Janome sewing types: overlock, zig-zag, costura reta')
Exemplo n.º 54
0
    def __init__(self, serial_port, reset_pin, print_queue_min_length=50, print_queue_max_length=100):
        Thread.__init__(self)
        self.ready = False
        self.printing = False
        self.config = None
        self.homed_axis = []

        self.heated_bed = None
        self.extruder_heater = None
        self.axis = {}

        self.axis_position = {}
        for axis_name in _axis_config:
            self.axis_position[axis_name] = 0

        self.printer_thread = None
        self._print_queue = None
        self.print_queue_min_length = print_queue_min_length
        self.print_queue_max_length = print_queue_max_length
        self._default_homing_retraction = None
        self._x_step_conversion = None
        self._y_step_conversion = None

        self._homing_timeout = 10
        self._print_queue_wait_time = 0.1
        self.homed = False

        self.led_manager = LedManager()

        # todo why didn't this work as global constant?? - should be confugired anyway
        self._FAN_OUTPUT = beagle_bone_pins.pwm_config[2]['out']

        # finally create the machine
        self.machine = Machine(serial_port=serial_port, reset_pin=reset_pin)
        self.running = True
        self.start()
def run():
    ma = Machine('example')
    n = TestNode()
    ma.add(n)
    return ma
Exemplo n.º 56
0
    def test_restock_bevs_in_machine(self):
        bev = ['Coke', 150, 1.00]
        my_machine = Machine()

        self.assertEqual('10 Cokes have been added to the machine', my_machine.restock(bev, 10))
Exemplo n.º 57
0
 def test_accept_valid_payment(self):
     my_machine = Machine()
     self.assertEqual(True, my_machine.check_payment(1.00))
Exemplo n.º 58
0
class Guard(BaseApp):

    def __init__(self, app, **kwargs):
        self.app = app or self.app
        super(Guard, self).init(**kwargs)
        self.rpc_server = PyroServer(GUARD_PORT)
        self.rpc_client = PyroClient(self.app.conf['HUB_IP'], HUB_PORT)
        self.pool = Pool(self.app)
        self.machine = Machine(healthy_mock=app.conf['HEALTHY_MOCK'], labels=self.labels)
        self.__shutdown_guard = threading.Event()
        self.LOOP_INTERVAL = 10  # second
        self.alive = False

    def setup_defaults(self, **_kw):
        super(Guard, self).setup_defaults(**_kw)
        self.labels = _kw.get('labels', '').split(',') if _kw.get('labels', '') else []

    def start(self, condition=lambda: True):
        """
        Start the guard.
        Setp 1. Start RPC Server
        Step 2. Register to hub
        Step 3. Start loop
        """
        self.__shutdown_guard.clear()
        self._start_rpc_server()
        self._register_to_hub()
        self._start_loop(condition)

    def stop(self):
        '''
        Step 1. Unregister to hub (todo)
        Step 2. Stop rpc server
        Step 3. Stop the loop
        '''
        if self.rpc_server.alive:
            self.rpc_server.stop()
        self.__shutdown_guard.set()
        if wait_condition_till_timeout(self.is_alive, 10):
            raise CouldNotStopException('guard')

    def is_alive(self):
        return self.alive

    def _start_rpc_server(self):
        self.rpc_server.start()

    def _register_to_hub(self):
        self.rpc_client.call('popcorn.apps.hub.commands.register_machine', machine=self.machine)

    def _start_loop(self, condition):
        """
        Things to do:
        1. Heartbeat to hub
        2. Check the orders and follow order
        """
        self.alive = True
        while not self.__shutdown_guard.isSet() and condition():
            try:
                self.heartbeat(self.rpc_client)
                while ORDERS:
                    order = ORDERS.pop(0)
                    debug('[Guard] - [Get Order]: %s' % ','.join([i.cmd for i in order.instructions]))
                    self.follow_order(order)
            except Exception as e:
                import traceback; traceback.print_exc()
                error('[Guard] - [Exception] - [Loop] : %s. PID: %s' % (e.message, get_pid()))
            finally:
                time.sleep(self.LOOP_INTERVAL)
        self.alive = False

    def heartbeat(self, rpc_client):
        self.machine.snapshot(self.pool.pinfo)
        debug('[Guard] - [Send] - [HeartBeat]')
        rpc_client.call('popcorn.apps.hub.commands.update_machine', machine=self.machine)

    def follow_order(self, order):
        for instruction in order.instructions:
            if instruction.operator == Operator.INC:
                self.pool.grow(instruction.queue, instruction.worker_cnt)
            elif instruction.operator == Operator.DEC:
                self.pool.shrink(instruction.queue, instruction.worker_cnt)
Exemplo n.º 59
0
#!/usr/bin/env python3
import sys
from machine import read_instructions_from_file
from machine import Machine

usage_message = (
    "./run.py part infile\n"
    "e.g. ...\n"
    "./run.py part-1 input.txt\n"
    "./run.py part-2 input.txt\n"
    "./run.py both input.txt\n"
)

if (len(sys.argv) != 3):
    print(usage_message)

instructions = read_instructions_from_file(sys.argv[2])

if sys.argv[1] == "part-1" or sys.argv[1] == "both":
    machine = Machine()
    machine.execute_program(instructions)
    print("PART 1 ANSWER -- Register A: %d --- Register B: %d"
            % (machine.registers["a"], machine.registers["b"]))

if sys.argv[1] == "part-2" or sys.argv[1] == "both":
    machine = Machine(1)
    machine.execute_program(instructions)
    print("PART 2 ANSWER -- Register A: %d --- Register B: %d"
            % (machine.registers["a"], machine.registers["b"]))