ssh_password = getpass("Enter your SSH password: "******"web_runner"
    db_password = getpass("MongoDB web_runner password: "******"mongodb://{quote_plus(user)}:{quote_plus(db_password)}@localhost:{args.mongo_port}/?authSource=gpu_runner"
    )
    del db_password

    gpu_runner_db = mongo_client.gpu_runner

    # make sure we can actually connect now so we don't get errors later
    gpu_runner_db.list_collections()
    print("Connected to gpu_runner database.")

    machines = {}
    for machine in gpu_runner_db.machines.find():
        try:
            machines[machine["_id"]] = Machine(
                app=app, jobs_db=gpu_runner_db.jobs, ssh_password=ssh_password, **machine
            )
            print(f"Established connection to {machine['_id']}")
        except:
            print(f"Error establishing connection to {machine['_id']}")

    for machine in machines.values():
        machine.start()

    app.run(port=args.port)
Exemplo n.º 2
0
#!/usr/bin/env python3
import logging
from machine import Machine, MachineLoopException

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    log = logging.getLogger(__name__)

    log.info("Reading program")
    with open("input.txt", "r") as f:
        program = []

        for line in f:
            instr, arg = line.strip().split()
            program.append((instr, int(arg)))

    log.info("Initializing machine")
    machine = Machine(program)

    log.info("Starting machine")
    try:
        machine.run()
        log.info("The machine halted cleanly")
    except MachineLoopException:
        log.warning("The machine looped")

    print(f"The current accumulator value is {machine.accumulator}")
Exemplo n.º 3
0
        if step % 2 == 0 and middle > 0:
            plane[middle] = Colors.green("\\")
            plane[middle - 1] = Colors.green("/")
        else:
            plane[middle] = Colors.green("/")
            plane[middle - 1] = Colors.green("\\")

    def plot_binding(self, plane, loop, step, *args, **kwargs):
        return
        # if step == 0:
        #     plane[-1] = "\\"
        # elif step == 1:
        #     plane[-3] = "+"
        # elif step == 2:
        #     plane[-4] = "+"
        # elif step == 3:
        #     plane[-5] = "+"

    def __call__(self, plane, loop, step, *args, **kwargs):
        self.plot_pattern_1(plane, loop, step, *args, **kwargs)
        self.plot_pattern_2_left(plane, loop, step, *args, **kwargs)
        self.plot_middle(plane, loop, step, *args, **kwargs)
        self.plot_pattern_2_right(plane, loop, step, *args, **kwargs)
        self.plot_binding(plane, loop, step, *args, **kwargs)


if __name__ == "__main__":
    machine = Machine(MyPlot, delay=0.1)
    machine.run()
Exemplo n.º 4
0
def mffd(target, flavor_list, machine_memory, machine_cpu):
    range_number = 10
    bins = [[] for i in range(range_number)]
    ranges = [[] for i in range(range_number)]
    if target == 'CPU':
        per = float(machine_cpu) / range_number
        for i in range(len(flavor_list)):
            if flavor_list[i].predict_num == 0:
                continue
            else:
                for k in range(flavor_list[i].predict_num):
                    kind = int(math.floor(flavor_list[i].cpu / per))
                    ranges[kind].append(flavor_list[i])
    else:
        per = float(machine_memory) / range_number
        for i in range(len(flavor_list)):
            if flavor_list[i].predict_num == 0:
                continue
            else:
                for k in range(flavor_list[i].predict_num):
                    kind = int(math.floor(flavor_list[i].cpu / per))
                    ranges[kind].append(flavor_list[i])
    for i in range(range_number - 1, -1, -1):
        while len(ranges[i]) != 0:
            item_id = random.randint(0, len(ranges[i]) - 1)
            item = ranges[i][item_id]
            allocate = False
            for j in range(len(bins)):
                if len(bins[j]) == 0:
                    continue
                bin_id = random.randint(0, len(bins[j]) - 1)
                bin = bins[j][bin_id]
                if bin.can_accommodate(item.memory, item.cpu):
                    bin.assign_vm(item.name, item.memory, item.cpu, target)
                    allocate = True
                    bins[j].pop(bin_id)
                    # 更新bins
                    if target == 'CPU':
                        per = float(machine_cpu) / range_number
                        kind = int(math.floor(bin.residueCPU / per))
                        bins[kind].append(bin)
                    else:
                        per = float(machine_memory) / range_number
                        kind = int(math.floor(bin.residueMemory / per))
                        bins[kind].append(bin)
                    break
            if not allocate:
                newbin = Machine(machine_memory, machine_cpu)
                newbin.assign_vm(item.name, item.memory, item.cpu, target)
                # 更新bins
                if target == 'CPU':
                    per = float(machine_cpu) / range_number
                    kind = int(math.floor(newbin.residueCPU / per))
                    bins[kind].append(newbin)
                else:
                    per = float(machine_memory) / range_number
                    kind = int(math.floor(newbin.residueMemory / per))
                    bins[kind].append(newbin)
            # 更新ranges
            ranges[i].pop(item_id)
    machine_list = []
    for i in range(range_number):
        if len(bins[i]) == 0:
            continue
        for j in range(len(bins[i])):
            machine_list.append(bins[i][j])
    return machine_list
Exemplo n.º 5
0
from socket import *
import socket
import threading
import logging

from machine import Machine

pm = Machine()


class ProcessTheClient(threading.Thread):
    def __init__(self, connection, address):
        self.connection = connection
        self.address = address
        threading.Thread.__init__(self)

    def run(self):
        while True:
            data = self.connection.recv(2048)
            if data:
                d = data.decode()
                hasil = pm.proses(d)
                self.connection.sendall(hasil.encode())
            else:
                break
        self.connection.close()


class Server(threading.Thread):
    def __init__(self):
        self.the_clients = []
Exemplo n.º 6
0
import sys

# Machine parameters
k = 100
n = 10
l = 10

# Update rule
update_rules = ['hebbian', 'anti_hebbian', 'random_walk']
update_rule = update_rules[0]

# Create 3 machines : Alice, Bob and Eve. Eve will try to intercept the communication between
# Alice and Bob.
print("Creating machines : k=" + str(k) + ", n=" + str(n) + ", l=" + str(n))
print("Using " + update_rule + " update rule.")
Alice = Machine(k, n, l)
Bob = Machine(k, n, l)
Eve = Machine(k, n, l)


# Random number generator
def random():
    return np.random.randint(-l, l + 1, [k, n])


# Function to evaluate the synchronization score between two machines.
def sync_score(m1, m2):
    return 1.0 - np.average(1.0 * np.abs(m1.W - m2.W) / (2 * l))


# Synchronize weights
Exemplo n.º 7
0
    group.add_argument("-resume", "-r", action="store_true", help="Executa o programa até o fim em modo silencioso e "
                                                                  "depois imprime o conteúdo final da fita.")
    group.add_argument("-verbose", "-v", action="store_true", help="Mostra a execução passo a passo do programa até "
                                                                   "o fim.")
    group.add_argument("-step", "-s", type=int, help="Mostra n computações passo a passo na tela, depois abre prompt e "
                                                     "aguarda nova opção (-r,-v,-s). Caso não seja fornecida nova opção"
                                                     " (entrada em branco), o padrão é repetir a última opção.",
                       default=None)
    parser.add_argument("name", type=str, help="Nome do arquivo fonte")  # adiciona o argumento nome do arquivo

    # faz o parse dos argumentos e faz uma copia deles para usar ela no programa
    args = parser.parse_args()
    options = copy.deepcopy(args)

    # cria uma maquina de turing com o argumento do cabeçote
    machine = Machine(args.head)
    print("")
    print("Simulador de Máquina de Turing ver 1.0")
    print("Desenvolvido como trabalho prático para a disciplina de Teoria da Computação")
    print("Arthur Teodoro e Saulo Ricardo, IFMG, 2018")
    print("")

    try:
        machine.load_code(args.name)

        word_input = input("Forneça a palavra inicial: ")
        print("")
        machine.load_word(word_input)

        if not options.resume:
            print(machine.output)
Exemplo n.º 8
0
 def setUp(self):
     self.m = Machine([1, 5, 20, 30])
Exemplo n.º 9
0
 def setUp(self):
     self.m = Machine([1, 2, 10, 20])
Exemplo n.º 10
0
sys.path.insert(0, os.path.join(os.getcwd(), 'saveLoad/'))
from configurator import Configurator
from jsonParser import Parser

sys.path.insert(0, os.path.join(os.getcwd(), 'logic/'))
from logicUnit import LOGIC

#sys.path.insert(0, os.path.join(os.getcwd(),'productClasses/'))
"""
Create A Machine, called Product for clarity reasons
	Machine will contain all information about:
		Parts
		Directives that apply
"""
Product = Machine()
Logic = LOGIC(Product)
"""
Load several known definitions
definitions can either be printed as txt, or displayed as html

Idea is, that user can look at definitions and decide if they apply
	#TODO: (machine parts should be able to softly activate definitions)
"""
defs = Definitions()

machineDef_txt, machineDef_html = defs.maschine()
ausweAusr_txt, ausweAusr_html = defs.ausweAusr()
sichBaut_txt, sichBaut_html = defs.sichBaut()
lastMit_txt, lastMit_html = defs.lastMit()
ketten_txt, ketten_html = defs.ketten()
Exemplo n.º 11
0
 def setUp(self):
     self.m = Machine([1, 5, 10, 19])
Exemplo n.º 12
0
from getsym import getsym
from block import block,root,table,code,tableList
from treePlotter import createPlot
from machine import Machine
import pickle
filename='test.txt'
#getsym('lv1.txt')#词法分析
print('开始词法分析')
getsym(filename)
print('词法分析完成')
print('开始语法和语义分析')
block()  # 语法分析
print(root)
print('语法和语义分析完成')
#createPlot(root)
for i in tableList:
    print(i)
for i,x in enumerate(code):
    print(str(i)+':\t\t'+str(x))
# with open(filename.split('.')[0]+'.litong', 'wb') as fp:
#     pickle.dump(code,fp)
#     fp.close()
machine=Machine(code)#指令运行
machine.run()
print('目标程序结束')
Exemplo n.º 13
0
def main():
    pygame.init()  # 初始化pygame
    # 根据定义的屏幕长宽,初始化准备显示的窗口
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    # 设置窗口标题
    pygame.display.set_caption("五子棋_Python程序设计作业_林郭城_2019210471")
    pygame.font.init()
    font = pygame.font.SysFont("SimHei", 72)  # 使用系统自带字体,否则显示会出现异常
    fontSmall = pygame.font.SysFont("SimHei", 36)
    fontSmallText = pygame.font.SysFont("SimHei", 18)
    textWidth, textHeight = font.size("某方获胜")  # 确定表示文本的空间
    # 打印初始菜单
    screen.fill(ORANGE_COLOR)  # 填充背景色
    printText(screen, fontSmall, (SCREEN_WIDTH - textWidth) // 2,
              (SCREEN_HEIGHT - textHeight) // 4, "游戏规则", BLACK_COLOR)
    printText(screen, fontSmallText, (SCREEN_WIDTH - textWidth) // 2,
              (SCREEN_HEIGHT - textHeight) // 4 + 100, "该五子棋游戏包括人人对战模式和人机对战模式",
              BLACK_COLOR)
    printText(screen, fontSmallText, (SCREEN_WIDTH - textWidth) // 2,
              (SCREEN_HEIGHT - textHeight) // 4 + 130,
              "若按下Q键切换为人人对战,按下E键切换为人机对战", BLACK_COLOR)
    printText(screen, fontSmallText, (SCREEN_WIDTH - textWidth) // 2,
              (SCREEN_HEIGHT - textHeight) // 4 + 160, "祝您游戏愉快!!!",
              BLACK_COLOR)
    printText(screen, fontSmallText, (SCREEN_WIDTH - textWidth) // 2,
              (SCREEN_HEIGHT - textHeight) // 4 + 190, "注:该屏幕五秒后自动消失",
              BLACK_COLOR)
    pygame.display.flip()  # 更新屏幕
    sleep(5)

    board = Board(POINT_NUMBER)  # 创建棋盘对象
    currentRunner = BLACK_CHESSMAN  # 黑方先执子
    winner = None  # 胜者初始化
    computer = Machine(POINT_NUMBER, WHITE_CHESSMAN)  #AI#

    blackWinCount = 0
    whiteWinCount = 0

    gameType = 1  # 游戏模式,默认为人机对战。0为人人,1为人机
    while True:
        for event in pygame.event.get():  # 监听用户事件
            if event.type == pygame.QUIT:  # 若用户点击'X'键
                pygame.quit()  # 否则点击退出键后程序会变成未响应
                sys.exit()  # 停止程序运行
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:  # 棋局结束后按下回车键重启游戏
                    if winner is not None:  # 当有胜者出现时
                        winner = None  # 重置胜者
                        currentRunner = BLACK_CHESSMAN  # 重置执子方
                        board = Board(POINT_NUMBER)  # 重置对象
                        if gameType == 1:
                            computer = Machine(POINT_NUMBER,
                                               WHITE_CHESSMAN)  #重置电脑
                if event.key == pygame.K_q:  # Q键切换为人人模式
                    gameType = 0
                    winner = None  # 重置胜者
                    currentRunner = BLACK_CHESSMAN  # 重置执子方
                    board = Board(POINT_NUMBER)  # 重置对象
                if event.key == pygame.K_e:  # E键切换为人机模式
                    gameType = 1
                    winner = None  # 重置胜者
                    currentRunner = BLACK_CHESSMAN  # 重置执子方
                    board = Board(POINT_NUMBER)  # 重置对象
                    computer = Machine(POINT_NUMBER, WHITE_CHESSMAN)  #重置电脑
            elif gameType == 1 and event.type == pygame.MOUSEBUTTONDOWN:  # 人机模式下按下鼠标
                if winner is None:
                    pressArray = pygame.mouse.get_pressed(
                    )  # 获取鼠标当前点击操作,返回一个三元组,分别对应左键、中键、右键
                    if pressArray[0] or pressArray[2]:  # 若按下的是鼠标左键或右键
                        clickPlace = pygame.mouse.get_pos(
                        )  # 获取鼠标当前位置,返回值为元组类型(x, y)
                        clickPoint = getClick(
                            clickPlace)  # 将获取的鼠标位置转换为棋盘上的坐标位置
                        if clickPoint is not None:  # 若点击的位置在棋盘上
                            if board.ifDropChess(clickPoint):  # 判断鼠标单击位置是否可以落子
                                winner = board.dropChess(
                                    currentRunner, clickPoint)  # 判断落子后是否获胜
                                if winner is None:  # 若还未出现胜者
                                    currentRunner = getNextRunner(
                                        currentRunner)  # 交换执子方
                                    computer.getRivalDrop(
                                        clickPoint)  # 电脑获取玩家落子
                                    machinePoint = computer.machineDrop(
                                    )  # 电脑落子
                                    winner = board.dropChess(
                                        currentRunner,
                                        machinePoint)  # 判断电脑落子后是否获胜
                                    if winner is not None:  # 若有胜者
                                        whiteWinCount += 1
                                    currentRunner = getNextRunner(
                                        currentRunner)
                                else:
                                    blackWinCount += 1  # 胜利局数
                            else:
                                print("您点击的位置已有棋子")
                        else:
                            print("您点击的位置超出了棋盘区域")
            elif gameType == 0 and event.type == pygame.MOUSEBUTTONDOWN:  # 人人模式下按下鼠标
                if winner is None:
                    pressArray = pygame.mouse.get_pressed(
                    )  # 获取鼠标当前点击操作,返回一个三元组,分别对应左键、中键、右键
                    if pressArray[0] or pressArray[2]:  # 若按下的是鼠标左键或右键
                        clickPlace = pygame.mouse.get_pos(
                        )  # 获取鼠标当前位置,返回值为元组类型(x, y)
                        clickPoint = getClick(
                            clickPlace)  # 将获取的鼠标位置转换为棋盘上的坐标位置
                        if clickPoint is not None:  # 若点击的位置在棋盘上
                            if board.ifDropChess(clickPoint):  # 判断鼠标单击位置是否可以落子
                                winner = board.dropChess(
                                    currentRunner, clickPoint)  # 判断落子后是否获胜
                                # 交换执子方
                                if currentRunner == BLACK_CHESSMAN:
                                    currentRunner = WHITE_CHESSMAN
                                else:
                                    currentRunner = BLACK_CHESSMAN
                                if winner is not None:  # 若有胜者
                                    if winner is WHITE_CHESSMAN:
                                        whiteWinCount += 1
                                    elif winner is BLACK_CHESSMAN:
                                        blackWinCount += 1  # 胜利局数
                            else:
                                print("您点击的位置已有棋子")
                        else:
                            print("您点击的位置超出了棋盘区域")

        drawBoard(screen)  # 绘制棋盘

        for y, row in enumerate(board.board):  # 按行遍历数组化的棋盘
            for x, column in enumerate(row):  # 遍历棋盘中每个点对应数组的元素
                if column == BLACK_CHESSMAN.Value:  # 若x列对应的值为黑子,则画黑子
                    drawChess(screen, Point(x, y), BLACK_CHESSMAN.Color)
                elif column == WHITE_CHESSMAN.Value:  # 若是白子,则画白子
                    drawChess(screen, Point(x, y), WHITE_CHESSMAN.Color)
        if gameType == 1:
            printText(screen, fontSmallText, SCREEN_WIDTH - 220,
                      SCREEN_HEIGHT - 130, "您正在进行的是:人机对战", BLACK_COLOR)
            printText(screen, fontSmallText, SCREEN_WIDTH - 220,
                      SCREEN_HEIGHT - 110, "按下Q键可切换为人人对战", BLACK_COLOR)
        elif gameType == 0:
            printText(screen, fontSmallText, SCREEN_WIDTH - 220,
                      SCREEN_HEIGHT - 130, "您正在进行的是:人人对战", BLACK_COLOR)
            printText(screen, fontSmallText, SCREEN_WIDTH - 220,
                      SCREEN_HEIGHT - 110, "按下E键可切换为人机对战", BLACK_COLOR)
        # 画信息栏中的黑白子
        drawChessInformation(
            screen,
            (SCREEN_WIDTH - PIECE_RADIUS_RIGHT - 160, BOARD_START_PLACE + 20),
            BLACK_COLOR)
        drawChessInformation(screen,
                             (SCREEN_WIDTH - PIECE_RADIUS_RIGHT - 160,
                              BOARD_START_PLACE + 20 + PIECE_RADIUS_RIGHT * 3),
                             WHITE_COLOR)
        # 刻画胜利局数
        printText(screen, fontSmallText, SCREEN_WIDTH - 200,
                  SCREEN_HEIGHT - 80, "黑子获胜局数:" + str(blackWinCount),
                  BLACK_COLOR)
        printText(screen, fontSmallText, SCREEN_WIDTH - 200,
                  SCREEN_HEIGHT - 50, "白子获胜局数:" + str(whiteWinCount),
                  BLACK_COLOR)
        if winner:
            # 在屏幕中央显示获胜和开始新一轮游戏的方法
            printText(screen, font, (SCREEN_WIDTH - textWidth) // 2,
                      (SCREEN_HEIGHT - textHeight) // 2, winner.Name + "获胜",
                      RED_COLOR)
            printText(screen, fontSmall,
                      (SCREEN_WIDTH - textWidth) // 2 - 0.25 * textWidth,
                      (SCREEN_HEIGHT - textHeight) // 2 + textHeight * 1.5,
                      "请按回车开始新一局游戏", RED_COLOR)
            # 在信息栏部分显示获胜
            if winner == WHITE_CHESSMAN:
                printText(screen, fontSmall, INFORMATION_PLACE,
                          BOARD_START_PLACE + PIECE_RADIUS_RIGHT * 3, "获胜",
                          BLUE_COLOR)
            else:
                printText(screen, fontSmall, INFORMATION_PLACE,
                          BOARD_START_PLACE, "获胜", BLUE_COLOR)
        else:  # 在信息栏部分显示当前落子状态
            if gameType == 0:
                if currentRunner == BLACK_CHESSMAN:
                    printText(screen, fontSmall, INFORMATION_PLACE,
                              BOARD_START_PLACE, "落子中", BLUE_COLOR)
                else:
                    printText(screen, fontSmall, INFORMATION_PLACE,
                              BOARD_START_PLACE + PIECE_RADIUS_RIGHT * 3,
                              "落子中", BLUE_COLOR)
            elif gameType == 1:
                printText(screen, fontSmall, INFORMATION_PLACE,
                          BOARD_START_PLACE, "玩家", BLUE_COLOR)
                printText(screen, fontSmall, INFORMATION_PLACE,
                          BOARD_START_PLACE + PIECE_RADIUS_RIGHT * 3, "电脑",
                          BLUE_COLOR)

        pygame.display.flip()  # 更新屏幕
Exemplo n.º 14
0
 def setUp(self):
     """
     setUp class
     """
     # Instantiate
     self.machine = Machine()
Exemplo n.º 15
0
    print "Input file not found."
    sys.exit(1)

try:
    outfile = open(output_filename, "w")
except IOError as ier:
    print "Output file not found."
    sys.exit(1)

try:
    key = sys.argv[4]
except IndexError as ier:
    key = getpass.getpass("Enter key: ")

start = time.time()
data = infile.read()
infile.close()

if mode == "encrypt":
    c = Machine().encrypt(data, key)
    outfile.write(c)
elif mode == "decrypt":
    plain_text = Machine().decrypt(data, key)
    outfile.write(plain_text)
outfile.close()

end = time.time() - start
bps = len(data) / end
sys.stdout.write("Completed in " + str(end) + " seconds\n")
sys.stdout.write(str(bps) + " bytes per second.\n")
Exemplo n.º 16
0
from machine import Machine

machine = Machine()
while True:
    halt = machine.step()
    if halt is not None:
        break

print(machine.registers[0])
Exemplo n.º 17
0
    lines = [x.strip() for x in f.readlines()]

n_tests = int(lines[1].split(": ")[1])
n_machines = int(lines[2].split(": ")[1])
n_resources = int(lines[3].split(": ")[1])
tests, machines, resources = [], [], []
i = 5
for i in range(i, i + n_tests):
    split = lines[i].split("( ")[1][:-2].split(", ")
    test = Test(eval(split[0]), eval(split[1]), eval(split[2]), eval(split[3]))
    tests.append(test)

i += 2
for i in range(i, i + n_machines):
    name = lines[i].split("( ")[1][:-2]
    machine = Machine(eval(name))
    machines.append(machine)
i += 2
for i in range(i, i + n_resources):
    split = lines[i].split("( ")[1][:-2].split(", ")
    resource = Resource(eval(split[0]), eval(split[1]))
    resources.append(resource)

sim = Simulation(machines, resources)

best_candidate = range(len(tests))
best_fitness = sim.run_simulation(deque([tests[x] for x in best_candidate]))
tabu_list = deque()
max_tabu_size = 5
start = time()
neighbourhood_size = 20
def test_plugin_init(settings):
    machine = Machine(settings=settings)
    actions = machine._plugin_actions
    plugin_cls = actions['listen_to'][
        'tests.fake_plugins:FakePlugin2.another_listen_function-doit']['class']
    assert plugin_cls.x == 42
Exemplo n.º 19
0
from machine import Machine

program = []
with open('input') as f:
    f.readline() # ignore first line
    for line in f:
        op, a, b, c = line.strip().split(' ')
        program.append((op, int(a), int(b), int(c)))

#print(program)
# machine = Machine(5, [8, 10551374, 10551374, 10551373, 111331472185129, 16])
machine = Machine(5)
print(machine.run_program(program))
def test_required_settings(settings_with_required, required_settings_class):
    machine = Machine(settings=settings_with_required)
    missing = machine._check_missing_settings(required_settings_class)
    assert 'SETTING_1' not in missing
    assert 'SETTING_2' in missing
Exemplo n.º 21
0
    if message['cmd'] == "use_machine":
        user = users[message['user']]
        machine = machines[message['machine']]
        user.uses = machine.id
        #machine.set_user(user.id)
        curio.run(machine.set_user, user.id)
        print(f'User {user.id} now uses machine {machine.id}')


if __name__ == "__main__":
    ioc_options, run_options = ioc_arg_parser(default_prefix='toy:',
                                              desc='a toy IOC server')

    ioc = SimpleIOC(**ioc_options)
    prefix = ioc_options['prefix']

    for i in range(1, 5):
        u = User(prefix, i, f'user_{i}', ioc=ioc)
        users[u.id] = u
        ioc.pvdb.update(**u.pvs.pvdb)

    for i in range(1, 3):
        m = Machine(prefix, i, f'machine_{i}')
        machines[m.id] = m
        ioc.pvdb.update(**m.pvs.pvdb)

    dispatcher_thread = Thread(target=run_dispatcher)
    dispatcher_thread.start()

    run(ioc.pvdb, **run_options)
Exemplo n.º 22
0
def fight(gen):
    m = Machine(gen)
    m.readBest(True)
    while True:
        newMatch(m, False)
Exemplo n.º 23
0
                                         [1 / machine_number] * machine_number,
                                         size=1)[0]

# user_ownership (a 2D list) - test successful
user_ownership = np.empty([user_number, machine_number])
for i in range(machine_number):
    tmp = np.random.multinomial(core_per_machine[i],
                                [1 / user_number] * user_number,
                                size=1)
    for j in range(user_number):
        user_ownership[j][i] = tmp[0][j]
"""
register the 'Path' of input data (job.json, stage.json, runtime.json)
"""
json_dir = "./"
"""
Run this simulation finally
"""
machines = [Machine(i, core_per_machine[i]) for i in range(0, machine_number)]
users = [
    User(i, user_ownership[i], preference_value[i]) for i in range(user_number)
]
cluster = Cluster(machines, users)
simulator = Simulator(cluster, json_dir, user_number)

cluster.totalJobNumber = 200
simulator.scheduler.scheduler_type = "fair"

simulator.run()
print "finish"
Exemplo n.º 24
0
import sys
import os
from machine import Machine
from cluster import Cluster
from simulator import Simulator
from math import pow

## data preparation
# get_block_size(json_dir+"-default-ssd")
# get_stage_profile(json_dir + "-default-ssd")
# get_task_run_time(json_dir + "-default-ssd")

user_number = 1
machine_number = 800
core_number = 1
json_dir = "./"

machines = [Machine(i, core_number) for i in range(0, machine_number)]
cluster = Cluster(machines)

simulator = Simulator(cluster, json_dir, user_number)
cluster.alpha = 0.90
cluster.totalJobNumber = 200
simulator.scheduler.scheduler_type = "fair"

simulator.run()
print "finish"
Exemplo n.º 25
0
from tkinter import *

from components import IO, Replacer, Sorter
from machine import Machine, Connection, SharedLayer
from custom_machines import Eq2or3

if __name__ == "__main__":
    root = Tk()
    machine = Machine(root)

    cell1 = IO()
    cell2 = IO()
    cell3 = IO()
    cell4 = IO()
    cell5 = IO()
    cell6 = IO()
    cell7 = IO()
    cell8 = IO()
    cell9 = IO()

    r_colors = [
        'red', 'blue', 'purple', 'dark green', 'gold', 'grey', 'orange', 'cyan'
    ]

    r1 = Replacer(['black'], r_colors)
    r2 = Replacer(['black'], r_colors)
    r3 = Replacer(['black'], r_colors)
    r4 = Replacer(['black'], r_colors)
    r5 = Replacer(['black'], r_colors)
    r6 = Replacer(['black'], r_colors)
    r7 = Replacer(['black'], r_colors)
Exemplo n.º 26
0
    with open("input.txt", "r") as f:
        program = []

        for line in f:
            instr, arg = line.strip().split()
            program.append((instr, int(arg)))

    for i in range(len(program)):
        patched_program = program.copy()
        instr, arg = patched_program[i]

        if instr == "jmp":
            patched_program[i] = ("nop", arg)
        elif instr == "nop":
            patched_program[i] = ("jmp", arg)
        else:
            continue

        log.info(f"Initializing machine with instr {i} modified")
        machine = Machine(patched_program)

        log.info("Starting machine")

        try:
            machine.run()
            log.info("The machine halted cleanly")
            print(f"The current accumulator value is {machine.accumulator}")
            break
        except MachineLoopException:
            log.warning("The machine looped")
Exemplo n.º 27
0
    print(
        "Enter new to create a new machine or enter load to load from a .model file: "
    )
    while (command := input("  > ")) not in ("new", "load"):
        print("  Not a valid command. Try again.")

    m = None
    if command == "new":
        states = gather_states()
        alphabet = gather_alphabet()
        trans_func = define_trans_func(states, alphabet)
        start_state = define_start_state(states)
        accept_states = define_accept_states(states)

        m = Machine(states, alphabet, trans_func, start_state, accept_states)

    elif command == "load":
        print("Enter the .model filename: ")
        filename = input("  > ")
        with open("models/" + filename + ".model", "rb") as file:
            m = pickle.load(file)

    print("Enter commands (help for help, quit to exit): ")
    while (command := input("  > ")) != "quit":
        if command == "help":
            print("  help - prints the help menu")
            print("  quit - exits the program")
            print("  run - run a string through the machine")
            print("  print - print the tuple represetation of the machine")
            print("  save - save the model")
Exemplo n.º 28
0
from machine import Machine
from job import Job
from spec import Spec

machines = [Machine(1), Machine(2)]

# setup times dalla tabella 2 dell'articolo
setup_times = {
    "length": 60,
    "width": 15,
    "thickness": 10,
    "hardness": 20,
    "colour": 15,
}

# creazione delle specs per ogni job, dalla tabelle 2 dell'articolo
specs_list = {
    1: [
        Spec("length", 240, setup_times["length"]),
        Spec("width", 12, setup_times["width"]),
        Spec("thickness", 1.5, setup_times["thickness"]),
        Spec("hardness", 7, setup_times["hardness"]),
        Spec("colour", 1, setup_times["colour"])
    ],
    2: [
        Spec("length", 96, setup_times["length"]),
        Spec("width", 36, setup_times["width"]),
        Spec("thickness", 5.0, setup_times["thickness"]),
        Spec("hardness", 8, setup_times["hardness"]),
        Spec("colour", 1, setup_times["colour"])
    ],
Exemplo n.º 29
0
 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)
Exemplo n.º 30
0
from machine import Machine

m = Machine('input')
m.step()

while True:
    m.step()
    if m.terminated:
        break

print(m.mul_called)