Esempio n. 1
0
 def test01(self):
     """ Test main function returns no value """
     want = ""
     with patch('sys.stdout', new=StringIO()) as result:
         main()
         got = result.getvalue().strip()
         self.assertEqual(got, want)
def cargar_usuarios():
    Main()  #Me lleva  al menu de usuarios
    print ("Ingrese aqui su DNI")
    dniUsuario = input()
    usuarioJugando = buscarUsuarioEnTXT(int(CantidadUsuarios()),
    int(dniUsuario), RecuperarUsuarios())
    main(usuarioJugando)
Esempio n. 3
0
def sudoku_solve(n_clicks, rows, columns):
    if rows[0]['column-0'] == '' and n_clicks is None:
        raise PreventUpdate
    else:
        print(rows[0]['column-0'])
        # print(type(rows))
        df = pd.DataFrame(rows)
        board = df.values.tolist()
        board = setZero(board)
        main(board)
        for i in range(9):
            for j in range(9):
                board[i][j] = str(board[i][j])
        print(board)
        key_list = [
            'column-0', 'column-1', 'column-2', 'column-3', 'column-4',
            'column-5', 'column-6', 'column-7', 'column-8'
        ]
        n = len(board)
        rows = []
        for idx in range(9):
            rows.append({
                key_list[0]: board[idx][0],
                key_list[1]: board[idx][1],
                key_list[2]: board[idx][2],
                key_list[3]: board[idx][3],
                key_list[4]: board[idx][4],
                key_list[5]: board[idx][5],
                key_list[6]: board[idx][6],
                key_list[7]: board[idx][7],
                key_list[8]: board[idx][8]
            })
        print(rows)
        return rows
def cargar_usuarios():
    Main()  #Me lleva  al menu de usuarios
    print("Ingrese aqui su DNI")
    dniUsuario = input()
    usuarioJugando = buscarUsuarioEnTXT(int(CantidadUsuarios()),
                                        int(dniUsuario), RecuperarUsuarios())
    main(usuarioJugando)
Esempio n. 5
0
def set_DFS():
    global is_running
    if is_running:
        pygame.quit()
        is_running=False
    is_running=True
    main(600,50,"DFS")
Esempio n. 6
0
def upload_file():
    if request.method == 'POST':
        if 'files[]' not in request.files:
            return redirect(request.url)
        files = request.files.getlist(r'files[]')
        print(files[0].filename)
        file_upload = files[0].filename

        # taking filename as a title
        title = " ".join(file_upload.split('.')[:-1])

        try:
            for file in files:
                if file and allowed_file(file.filename):
                    filename = secure_filename(file.filename)
                    file.save(
                        os.path.join(app.config['UPLOAD_FOLDER'], filename))

            # go to that file and read it
            file_upload = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            print(file_upload)
            main(file_upload, title)
            # after completion of processsing delete that file from folder.
            os.remove(file_upload)

            # I know this way of doing it, is very wrong, It's more like a cheating. But I have done this for a particular reason
            # I will change it after sometime.

            return redirect('/')

        except Exception:
            print("Hello")
            return redirect('/')
Esempio n. 7
0
    def __init__(self):
        """
        __init__(self)
            this function will initiate the startwindow
        """
        environ['SDL_VIDEO_CENTERED']='1'
        pygame.init()
        seticon('images/icon.png')
        start_screen = pygame.display.set_mode((498,501),NOFRAME,32)
        init_background = pygame.image.load("images/init_bg.png").convert()
        pygame.display.set_caption("Dominoes!")
        onQuite_clicked_img = pygame.image.load("images/onclicked1.png")
        onenjoy_clicked_img = pygame.image.load("images/onclicked2.png")
        
        bg_sound = path.join('sounds','bg.wav')
        soundtrack = pygame.mixer.Sound(bg_sound)
        soundtrack.set_volume(0.9)
        soundtrack.play(-1)
        
        enjoy_sound = path.join('sounds','enjoy.wav')
        enjoyTick = pygame.mixer.Sound(enjoy_sound)
        enjoyTick.set_volume(0.9)

        quit_sound = path.join('sounds','quit.wav')
        quitTick = pygame.mixer.Sound(quit_sound)
        quitTick.set_volume(0.9)
                
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    exit()
                     
                if event.type == MOUSEBUTTONDOWN:
                    x,y = pygame.mouse.get_pos()
                    if x >= 172 and x <= 320 and y >= 435 and y<=480:
                        start_screen.blit(onenjoy_clicked_img,(190,438))
                        enjoyTick.play(0)
                        pygame.display.update()
                        pygame.time.wait(500)
                        main()
                    
                    if x >= 324 and x <= 423 and y >= 327 and y<=369:
                        start_screen.blit(onQuite_clicked_img,(317,322))
                        quitTick.play(1)
                        pygame.display.update()
                        exit()
                
                if event.type == KEYDOWN:
                    if event.key == K_KP_ENTER or event.key == K_SPACE:
                        enjoyTick.play(0)
                        main()
                        
                    if event.key == K_ESCAPE:
                        quitTick.play(0)
                        exit()
                        
            
            start_screen.blit(init_background,(0,0))
            pygame.display.update()
Esempio n. 8
0
def test_version(argv, capsys: CaptureFixture):
    with raises(SystemExit) as exc_info:
        main(argv)
    assert exc_info.value.code == 0

    out, err = capsys.readouterr()
    assert re.match(r'\d+\.\d+\..*', out)
    assert not err
Esempio n. 9
0
def script(argv):
    # Save PEP 3122!
    if "." in __name__:
        from .script import main
    else:
        from script import main

    main(argv, version)
Esempio n. 10
0
 def test_version(self, versionarg, capsys):
     with raises(SystemExit) as exc_info:
         main(['progname', versionarg])
     out, err = capsys.readouterr()
     # Should print out version.
     assert out == '{0} {1}\n'.format(metadata.project, metadata.version)
     # Should exit with zero return code.
     assert exc_info.value.code == 0
Esempio n. 11
0
def test_help(argv, capsys: CaptureFixture):
    with raises(SystemExit) as exc_info:
        main(argv)
    assert exc_info.value.code == 0

    out, err = capsys.readouterr()
    assert 'show this help message and exit' in out
    assert not err
Esempio n. 12
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)
    if (chat_id == 'chat_id'):
        if content_type == 'text':
            text = msg['text']
            if (text == 'help'):
                bot.sendMessage(
                    chat_id,
                    'model#cascadeModel#n_nodes#size_iniziators#iterations\nexample: 2, 2, 500, 1, 0\nmodel: 1 = rich get richer, 2 = erdos renyi\nCascade model: 1 = 1 BF, 2 = all BF\nn_nodes: a number \nsize initiators: 1 = sqrt, 2 = log\nIteration: n iteration only for rich\nprobability:0.2/0.8\n\nint'
                )
            else:
                if (text.count('#') == 5):
                    model, cascadeModel, n_nodes, size_iniziators, iterations, probability = text.split(
                        '#')
                    try:
                        main(int(model), int(cascadeModel), int(n_nodes),
                             int(size_iniziators), int(iterations),
                             float(probability))
                    except:
                        bot.sendMessage(chat_id, 'scusa, ma errore :(')
                elif (text.isdigit()):
                    i = 0
                    for iteration in text:

                        model = random.randint(1, 2)
                        cascadeModel = random.randint(1, 2)
                        n_nodes = random.choice([500, 800, 1000, 5000, 10000])
                        size_iniziators = random.randint(1, 2)
                        iterations_fraction = random.choice(
                            ['1.2', '2.3', '4.5'])
                        a, b = iterations_fraction.split('.')
                        iterations = int(n_nodes / int(b)) * int(a)
                        if (model == 1):
                            probability = random.choice([
                                0.2, 0.2, 0.3, 0.3, 0.4, 0.4, 0.5, 0.6, 0.7,
                                0.8
                            ])
                        elif (model == 2):
                            probability = random.choice([
                                0.2, 0.3, 0.4, 0.5, 0.6, 0.6, 0.7, 0.7, 0.8,
                                0.8
                            ])

                        print(
                            str(model) + ' | ' + str(cascadeModel) + ' | ' +
                            str(n_nodes) + ' | ' + str(size_iniziators) +
                            ' | ' + str(iterations) + ' | ' + str(probability))
                        try:
                            i = i + 1
                            main(int(model), int(cascadeModel), int(n_nodes),
                                 int(size_iniziators), int(iterations),
                                 float(probability))
                        except:
                            i = i - 1
                            bot.sendMessage(chat_id, 'Error')

                    bot.sendMessage(chat_id, str(i) + ' ' + str(text))
Esempio n. 13
0
    def __init__(self):
        """
        __init__(self)
            this function will initiate the startwindow
        """
        environ['SDL_VIDEO_CENTERED'] = '1'
        pygame.init()
        seticon('images/icon.png')
        start_screen = pygame.display.set_mode((498, 501), NOFRAME, 32)
        init_background = pygame.image.load("images/init_bg.png").convert()
        pygame.display.set_caption("Dominoes!")
        onQuite_clicked_img = pygame.image.load("images/onclicked1.png")
        onenjoy_clicked_img = pygame.image.load("images/onclicked2.png")

        bg_sound = path.join('sounds', 'bg.ogg')
        soundtrack = pygame.mixer.Sound(bg_sound)
        soundtrack.set_volume(0.9)
        soundtrack.play(-1)

        enjoy_sound = path.join('sounds', 'enjoy.ogg')
        enjoyTick = pygame.mixer.Sound(enjoy_sound)
        enjoyTick.set_volume(0.9)

        quit_sound = path.join('sounds', 'quit.ogg')
        quitTick = pygame.mixer.Sound(quit_sound)
        quitTick.set_volume(0.9)

        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    exit()

                if event.type == MOUSEBUTTONDOWN:
                    x, y = pygame.mouse.get_pos()
                    if x >= 172 and x <= 320 and y >= 435 and y <= 480:
                        start_screen.blit(onenjoy_clicked_img, (190, 438))
                        enjoyTick.play(0)
                        pygame.display.update()
                        pygame.time.wait(500)
                        main()

                    if x >= 324 and x <= 423 and y >= 327 and y <= 369:
                        start_screen.blit(onQuite_clicked_img, (317, 322))
                        quitTick.play(1)
                        pygame.display.update()
                        exit()

                if event.type == KEYDOWN:
                    if event.key == K_KP_ENTER or event.key == K_SPACE:
                        enjoyTick.play(0)
                        main()

                    if event.key == K_ESCAPE:
                        quitTick.play(0)
                        exit()

            start_screen.blit(init_background, (0, 0))
            pygame.display.update()
Esempio n. 14
0
def brain_extraction(args):
    print 'Starting pre-processing'
    preprocessing(args)
    print 'Starting Decomposition/Registration'
    main(args)
    print 'Starting post-processing'
    postprocessing(args)

    return
Esempio n. 15
0
def test_main_wrong_cwd(mocker):
    cwd = mocker.MagicMock(name="mocked", __str__=mocker.Mock(return_value="invalid/"))
    mocker.patch.object(Path, "cwd", return_value=cwd)
    with pytest.raises(
        ValueError,
        match=r"Given configuration path either does not "
        r"exist or is not a valid directory: invalid.*",
    ):
        main()
 def saveChanges(self):
     """
     call function in other file with write to csv
     """
     print("savechanges")
     if self.completed():
        main(self.get_data())
        self.master.printSchedule()
        self.closeWindow()
Esempio n. 17
0
def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('wifi', '22224444')
        while not wlan.isconnected():
            main()
    print('network config:', wlan.ifconfig())
Esempio n. 18
0
def test_main(sample_data):
    main("data/input")  # Look in current dir
    expected = pd.read_excel("data/final.xlsx", skiprows=1, index_col="part")
    output = pd.read_excel("price_list_compare.xlsx",
                           skiprows=1,
                           index_col="part")  # file created
    print(output)
    print("")
    print(expected)
    assert_frame_equal(output, expected)
Esempio n. 19
0
 def generate():
     y1Path = y1PathEntry.get()
     y2Path = y2PathEntry.get()
     Title = titleEntry.get()
     XLabel = xLabelEntry.get()
     Y1Label = y1LabelEntry.get()
     Y2Label = y2LabelEntry.get()
     chckVar = checkVar.get()
     root.destroy()
     main(y1Path, y2Path, Title, XLabel, Y1Label, Y2Label, chckVar)
Esempio n. 20
0
 def get(self):
     print('scraping data for website please wait..........')
     main()
     df = pd.read_excel('./scrape_data.xlsx')
     # print(df)
     out = df.to_json(orient='index')
     data = json.loads(out)
     headers = {'Content-Type': 'text/html'}
     return make_response(render_template('index.html', data=data), 200,
                          headers)
 def saveChanges(self):
     """
     send data from get_data to write csv fcn in main py file
     """
     print("savechanges")
     if self.completed():
         print("Ee")
         main(self.get_data())
         self.master.printSchedule()
         self.closeWindow()
Esempio n. 22
0
def run(tag, env, parallel, runner):
    """Run the pipeline."""
    from {{cookiecutter.python_package}}.run import main
    if parallel and runner:
        raise KedroCliError(
            "Both --parallel and --runner options cannot be used together. "
            "Please use either --parallel or --runner."
        )
    if parallel:
        runner = "ParallelRunner"
    main(tags=tag, env=env, runner=runner)
Esempio n. 23
0
 def game_loop(self):
     while self.playing:
         self.check_events()
         if self.START_KEY:
             self.playing = False
         # self.display.fill(self.BLACK)
         # self.draw_text('Thanks for Playing', 20, self.DISPLAY_W / 2, self.DISPLAY_H / 2)
         # self.window.blit(self.display, (0, 0))
         main(WIN, WIDTH)
         # pygame.display.update()
         self.reset_keys()
Esempio n. 24
0
 def test(self):
     self.assertEqual(health, 100)
     self.assertEqual(position, 0)
     self.assertEqual(coins, 0)
     main()
     self.assertEqual(log[0], 'roll_dice')
     self.assertEqual(log[1], 'move')
     self.assertEqual(log[2], 'combat')
     self.assertEqual(log[3], 'get_coins')
     self.assertEqual(log[4], 'buy_health')
     self.assertEqual(log[5], 'print_status')
    def sendToSolve(self):
        SOLVESTATE = 1

        self.buttonSolve["command"] = " "
        self.reset_cube()
        text_file = open("UserData.txt", "w")
        for i in range(0,4):
            text_file.write("%s " % str(COLORS[WHITEFACE[i]]))
        for i in range(5,9):
            text_file.write("%s " % str(COLORS[WHITEFACE[i]]))
        text_file.write("\n")
        for i in range(0,4):
            text_file.write("%s " % str(COLORS[YELLOWFACE[i]]))
        for i in range(5,9):
            text_file.write("%s " % str(COLORS[YELLOWFACE[i]]))
        text_file.write("\n")
        for i in range(0,4):
            text_file.write("%s " % str(COLORS[ORANGEFACE[i]]))
        for i in range(5,9):
            text_file.write("%s " % str(COLORS[ORANGEFACE[i]]))
        text_file.write("\n")
        for i in range(0,4):
            text_file.write("%s " % str(COLORS[REDFACE[i]]))
        for i in range(5,9):
            text_file.write("%s " % str(COLORS[REDFACE[i]]))
        text_file.write("\n")
        for i in range(0,4):
            text_file.write("%s " % str(COLORS[GREENFACE[i]]))
        for i in range(5,9):
            text_file.write("%s " % str(COLORS[GREENFACE[i]]))
        text_file.write("\n")
        for i in range(0,4):
            text_file.write("%s " % str(COLORS[BLUEFACE[i]]))
        for i in range(5,9):
            text_file.write("%s " % str(COLORS[BLUEFACE[i]]))
        text_file.write("\n")
        text_file.close()

        main()

        notfound = True
        self.thingsToDo = []
        while notfound:
            with open("instructions.txt") as file:
                for line in file:
                    self.thingsToDo.append(line.strip())
                notfound = False
        currThing = 0
        for i in range(len(self.thingsToDo)):
            if currThing == 0: self.label1(type = str(self.thingsToDo(i)))
            if currThing == 1: self.label2(type = str(self.thingsToDo(i)))
            if currThing == 2: self.label3(type = str(self.thingsToDo(i)))
            if currThing == 3: currThing = 0
Esempio n. 26
0
def menu_inicial():
    qtd_botao = 5
    textos_botao = ["Iniciar", u"Instruções", "Recordes", "Sobre", "Sair"]
    botoes = []
    for i in range(qtd_botao):
        botao = Botao(tela)
        botao.texto = textos_botao[i]
        botao.redimensionar(150, 50)
        botoes.append(botao)

    rodando = True
    pygame.mouse.set_visible(False)
    while rodando:
        pos_mouse = pos_mouse_x, pos_mouse_y = pygame.mouse.get_pos()

        LIMITE_BOTAO_X = pos_mouse_x > 20 and pos_mouse_x < 170
        LIMITE_1 = LIMITE_BOTAO_X and (pos_mouse_y > 300 and pos_mouse_y < 350)
        LIMITE_2 = LIMITE_BOTAO_X and (pos_mouse_y > 355 and pos_mouse_y < 405)
        LIMITE_3 = LIMITE_BOTAO_X and (pos_mouse_y > 410 and pos_mouse_y < 460)
        LIMITE_4 = LIMITE_BOTAO_X and (pos_mouse_y > 465 and pos_mouse_y < 515)
        LIMITE_5 = LIMITE_BOTAO_X and (pos_mouse_y > 520 and pos_mouse_y < 570)
        LIMITES = [LIMITE_1, LIMITE_2, LIMITE_3, LIMITE_4, LIMITE_5]

        tela.fill(branco)
        tela.blit(img_fundo, (0, 0))
        botao_y = 300
        for botao in botoes:
            botao.mostrar_botao(20, botao_y)
            texto = font.render(botao.texto, True, branco)
            tela.blit(texto, (40, botao_y + 15))
            botao_y += 55
        cursor.mostrar(pos_mouse)

        img_selecao = pygame.image.load("img/homem_neve.png")
        for i in range(len(LIMITES)):
            if LIMITES[i]:
                tela.blit(img_selecao, (175, 300 + 55 * i))

        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if LIMITES[0]:
                    tema_inicial.stop()
                    main()
                elif LIMITES[1]:
                    sub_menu("instrucoes")
                elif LIMITES[2]:
                    sub_menu("recordes")
                elif LIMITES[3]:
                    sub_menu("sobre")
                elif LIMITES[4]:
                    rodando = False
                    pygame.display.quit()
Esempio n. 27
0
 def test_help(self, helparg, capsys):
     with raises(SystemExit) as exc_info:
         main(['progname', helparg])
     out, err = capsys.readouterr()
     # Should have printed some sort of usage message. We don't
     # need to explicitly test the content of the message.
     assert 'usage' in out
     # Should have used the program name from the argument
     # vector.
     assert 'progname' in out
     # Should exit with zero return code.
     assert exc_info.value.code == 0
Esempio n. 28
0
def test_populate(argparse: mock.MagicMock, app_env: AppEnvType, db: Session) -> None:
    """Test that db is populated with demo content."""

    argparse.ArgumentParser.return_value.parse_args.return_value.config = "etc/test.ini"
    main()

    assert db.query(User).count() == 3
    # manual test teardown is needed because main() does db.commit()
    with transaction.manager:
        engine = app_env["registry"].settings["sqlalchemy.engine"]
        tables = ", ".join(Base.metadata.tables.keys())
        engine.execute("TRUNCATE {} CASCADE".format(tables))
Esempio n. 29
0
 def add_more():
     print('Desea agregar más?(S/N)')
     while True:
         agregar_mas = str(input('> '))
         if agregar_mas.upper() == 'S':
             add()
             break
         elif agregar_mas.upper() == 'N':
             main()
             break
         else:
             print('INGRESE UNA ENTRADA VÁLIDA')
Esempio n. 30
0
def menu_final(tempo, skiador, obstaculos, homem_neve):
    texto_fim = font.render("FIM DE JOGO", True, branco)
    pontuacao = funcoes.cronometro(tempo)
    texto_pontuacao = font.render(pontuacao, True, branco)
    texto_aviso = font.render("Enter para Jogar", True, branco)
    nome_usuario = ""

    imagem_input = pygame.image.load("img/input-field.png")
    imagem_input = pygame.transform.scale(imagem_input, (234, 46))
    imagem_menu = pygame.image.load("img/menu.png")
    imagem_logo = pygame.image.load("img/logo_pyski.png")
    font_menor = pygame.font.SysFont("arial", 12)

    rodando = True
    while rodando:
        tela.fill(branco)
        skiador.mostrar_skiador()
        for obstaculo in obstaculos:
            obstaculo.mostrar_obstaculo()

        homem_neve.mostrar()

        texto_nome_usuario = font.render(nome_usuario, True, (0, 0, 0))
        texto_digite_nome = font_menor.render("Digite seu nome", True, branco)

        tela.blit(imagem_menu, (250, 80))
        tela.blit(imagem_input, (285, 190))
        tela.blit(texto_pontuacao, (355, 150))
        tela.blit(texto_nome_usuario, (300, 200))
        tela.blit(texto_fim, (340, 380))
        tela.blit(texto_aviso, (330, 480))
        tela.blit(texto_digite_nome, (360, 240))
        tela.blit(imagem_logo, (335, 330))

        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                rodando = False
                pygame.display.quit()

            elif event.type == pygame.KEYDOWN:
                if event.unicode.isalpha():
                    if len(nome_usuario) <= 10:
                        nome_usuario += event.unicode.upper()
                elif event.key == pygame.K_BACKSPACE:
                    nome_usuario = nome_usuario[:-1]

                elif event.key == pygame.K_RETURN:
                    if nome_usuario == "":
                        nome_usuario = "JOGADOR"
                    funcoes.ranking(nome_usuario, tempo)
                    main()
Esempio n. 31
0
def start():
    app_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(app_dir)  # Change working dir to zeronet.py dir
    sys.path.insert(0, os.path.join(app_dir, "src/lib"))  # External liblary directory
    sys.path.insert(0, os.path.join(app_dir, "src"))  # Imports relative to src

    if "--update" in sys.argv:
        sys.argv.remove("--update")
        print("Updating...")
        import update
        update.update()
    else:
        main()
Esempio n. 32
0
 def test_with_initially_incomplete_arguments(self):
     """should prompt user_for files, then proceed"""
     mkr = mock.Mock(side_effect=["vvexport_471745.txt"])
     out = StringIO()
     trans = main(["-s limesurvey_survey_471745.txt"], mkr, out)
     self.assertTrue("survey structure txt is limesurvey_survey_471745.txt"
             in out.getvalue())
     mkr = mock.Mock(side_effect=["limesurvey_survey_471745.txt"])
     out = StringIO()
     trans = main(["-v vvexport_471745.txt"], mkr, out)
     self.assertTrue("response vvexport txt is vvexport_471745.txt"
             in out.getvalue())
     self.assertIn("translated_EDNA_471745.txt", os.listdir("."))
Esempio n. 33
0
def hRun(c, inp):
    if (len(inp) == 2):
        temp = len(cmdHistory) - inp[1]
    else:
        temp = len(cmdHistory) - 2

    main.scw(">> " + cmdHistory[temp])
    i = input("? ")

    if (i.lower() == ""):
        main(cmdHistory[temp])

    elif (i.lower() != "n"):
        error(2, inp[0])
Esempio n. 34
0
def interface_graphique_fixe():
    tapis(-650, -325)
    jetons(580, -260, "yellow", "white", 50)
    jetons(520, -310, "blue", "white", 50)
    jetons(460, -280, "black", "white", 50)

    up()
    left(125)
    down()
    main(583, 322, 80, 160)

    up()
    left(90)
    down()
    main(-580, -315, 80, 160)
Esempio n. 35
0
    def lan():
        a = buttonbox(msg='Keyboard Piano',
                      title='Keyboard Piano',
                      choices=('启动', '操作说明/关于'))
        if a == '启动':
            main()

        if a == '操作说明/关于':
            textbox(
                msg='操作说明/关于',
                title='Reader',
                text=
                'KeyboardPiano 操作说明/关于\n\n按下:1,2,3,4,5,6,7,8 发出声音\n本钢琴声为C调\n按下键时会有一秒延迟\n\n使用到的工具:\n1. python3.7(64-bit)\n2. pygame\n3. easygui'
            )
            lan()
Esempio n. 36
0
 def run(self):
     global text, time_out, current_theme, results, song
     time_out = True
     song = None
     results = main(text)
     results = results.decode("gbk")
     if text == "#":
         results = '<p style="font-family:Microsoft Yahei;font:24px">Stuart:好吧...</p>'.decode("utf-8")
     if results[-5:] == "@sing":
         song = str(random.randint(1, 2))
         lyric_file = open("data/sounds/" + song + ".txt", "r")
         lyric = lyric_file.read()
         lyric_file.close()
         href_file = open(style_path + "href.txt", "r")
         href = href_file.read()
         href_file.close()
         results = (
             '<p style="font-family:Microsoft Yahei;font:24px">'
             + lyric.replace("\n", "<br>")
             + '<br><a style="text-decoration:none;color:#'
             + href
             + '" href="#">别唱了!</a></p>'
         )
         results = results.decode("utf-8")
     time_out = False
     self.trigger.emit()
Esempio n. 37
0
def entry(isPublic, isSelectable, threadNum, appID, target):

    log_utils.info("Curr Python Version::%s", config_utils.get_py_version())

    print(u"**********所有游戏**********")
    print(u"\t appID \t\t 游戏文件夹 \t\t 游戏名称 \n\n")

    games = config_utils.getAllGames()
    if games != None and len(games) > 0:
        for ch in games:
            print(u"\t %s \t\t %s \t\t\t%s" % (ch['appID'], ch['appName'], ch['appDesc']))

    sys.stdout.write(u"请选择一个游戏(输入appID):")
    sys.stdout.flush()

    selectedGameID = str(appID)

    game = getGameByAppID(selectedGameID, games)

    log_utils.info("current selected game is %s(%s)", game['appName'], game['appDesc'])

    if isSelectable:
        return main(game, isPublic, target)
    else:
        return main_thread.main(game, isPublic, threadNum)
Esempio n. 38
0
def launcher():
    outputs = main()

    #update the text
    tex.insert(END, outputs)

    # join
    sb.config(command=tex.yview)
    tex.config(yscrollcommand=sb.set)
Esempio n. 39
0
 def test_with_initially_empty_arguments(self):
     """should prompt user_for files, then proceed"""
     mkr = mock.Mock(side_effect=["limesurvey_survey_471745.txt",
         "vvexport_471745.txt"])
     out = StringIO()
     trans = main([], mkr, out)
     self.assertEqual(trans.survey_structure.sid, "471745",
             "should produce trans")
     self.assertIn("translated_EDNA_471745.txt", os.listdir("."),
             "should write output")
Esempio n. 40
0
def de():
  def evaluate(frontier):
    for n, i in enumerate(frontier):
      assign(i)
      scores[n] = main()[-1] # score[i]= [pd,pf,prec, g], the second objecit in returned value
    print scores
    return scores

  def best(scores):
    ordered = sorted(scores.items(), key=lambda x: x[1][-1])  # alist of turple
    bestconf = frontier[ordered[-1][0]] #[(0, [100, 73, 9, 42]), (1, [75, 41, 12, 66])]
    bestscore = ordered[-1][-1][-1]
    return bestconf, bestscore

  scores = {}
  global The  
  The.option.tuning = True
  np = Settings.de.np
  repeats = Settings.de.repeats
  life = Settings.de.life
  changed = False
  evaluation = 0
  frontier = [generate() for _ in xrange(np)]
  scores = evaluate(frontier)
  bestconf, bestscore = best(scores)
  for k in xrange(repeats):
    if life <= 0 or bestscore >=90:
      break
    nextgeneration = []
    for n, f in enumerate(frontier):
      new = update(n, f, frontier)
      assign(new)
      newscore = main()[-1]
      evaluation +=1
      if newscore[-1] > scores[n][-1] : # g value
        nextgeneration.append(new)
        scores[n] = newscore[:]
        changed = True
      else:
        nextgeneration.append(f)
    frontier = nextgeneration[:]
    newbestconf, newbestscore = best(scores)
    if newbestscore > bestscore:
      print "newbestscore %s:" % str(newbestscore)
      print "bestconf %s :" % str(newbestconf)
      bestscore = newbestscore
      bestconf = newbestconf[:]
    if not changed: # the pareto frontier changed or not
      life -= 1
    changed = False
  assign(bestconf)
  writeResults(bestscore, evaluation)
 def setUp(self):
     from {{ cookiecutter.repo_name }} import main
     app = main({})
     from webtest import TestApp
     self.testapp = TestApp(app)
 def test_main(self):
     self.assertEqual(main([]), 0)
"""
Entrypoint module, in case you use `python -m{{cookiecutter.package_name}}`.


Why does this file exist, and why __main__? For more info, read:

- https://www.python.org/dev/peps/pep-0338/
- https://docs.python.org/2/using/cmdline.html#cmdoption-m
- https://docs.python.org/3/using/cmdline.html#cmdoption-m
"""
{%- if cookiecutter.command_line_interface|lower == 'plain' %}
import sys
{% endif %}
from {{cookiecutter.package_name}}.cli import main

if __name__ == "__main__":
{%- if cookiecutter.command_line_interface|lower == 'click' %}
    main()
{%- else %}
    sys.exit(main())
{%- endif %}
Esempio n. 44
0
def comenzar_nuevo_juego():
    main()
Esempio n. 45
0
def addpocket(arg):
    import pocket
    pocket.addpocket(arg)

def pbreload():
    print "Reloading... Please wait."    
    launchArgs = 'tell application "Alfred 3" to run trigger "reload" in workflow "com.jmjeong.alfredv2.pinboard" with argument ""'
    os.system("osascript -e '%s' > /dev/null" % launchArgs)
    
def main(args):
    if args.startswith('goreload'):
        pbreload()
    elif args.startswith('go'):
        go(args[2:])
    elif args.startswith('copy'):
        copy(args[4:])
    elif args.startswith('star'):
        star(args[4:])
    elif args.startswith('deletehistory'):
        delete_history(args[13:])
    elif args.startswith('delete'):
        delete(args[6:])
    elif args.startswith('addpocket'):
        addpocket(args[9:])
    
if __name__ == '__main__':
    start = time.clock()
    main(sys.argv[1])
    end = time.clock()
    logger.info("Elapsed time : %.5gs"%(end-start))
"""
@Authors: mikhail-matrosov and Alexey Boyko
"""
from main import *
from animate import *
import Tkinter, tkFileDialog

print 'Select input image'
root = Tkinter.Tk()
root.withdraw()
inputImagePath = tkFileDialog.askopenfilename()

# layers=1 : trace several layers (MM style)
# layers=0 : trace single lines (A.I.BO style)
fname = main(inputImagePath, layers=0, stat_params=[800,30,10], Canny_param_koefs=[-1,1])

print 'Now printing.'
#animate(fname, comPort='COM7')
Esempio n. 47
0
 def test__main_is_callable(self):
     main()
Esempio n. 48
0
        namespace = importlib.__import__(file_name[:-3])
        if namespace.plugin_main(parent, PWD):
            print("plugin:", file_name, file=sys.stderr)
            parent.plugins[file_name[:-3]] = namespace


def argparser():
    parser = argparse.ArgumentParser(description="anubad")
    parser.add_argument(
        "-q", "--quick",
        action  = "store_true",
        default = False,
        help    = "Disable plugins loading")

    return parser.parse_args()


if __name__ == '__main__':
    args = argparser()

    root = main()
    root.set_title(PKG_NAME)
    root.visible = True
    root.toolbar.b_About.connect("clicked", about_dialog)

    if not args.quick:
        load_plugins(root)

    tray = TrayIcon(root)
    Gtk.main()
Esempio n. 49
0
def continueOp():
	content = request.json['content']
	return (json.dumps(main(query=content.query, prevResult=content.prevResult, type=content.type)), 200, {'content-type', "application/json"})
Esempio n. 50
0
		elif opt_action == "write-eeprom":
			top.writeEEPROM(fileIn(top, opt_action, opt_file, opt_informat))
		elif opt_action == "read-fuse":
			fileOut(opt_file, opt_outformat, top.readFuse())
		elif opt_action == "write-fuse":
			image = fileIn(top, opt_action, opt_file, opt_informat)
			top.writeFuse(image)
		elif opt_action == "read-lock":
			fileOut(opt_file, opt_outformat, top.readLockbits())
		elif opt_action == "write-lock":
			top.writeLockbits(fileIn(top, opt_action, opt_file, opt_informat))
		elif opt_action == "read-ram":
			fileOut(opt_file, opt_outformat, top.readRAM())
		elif opt_action == "write-ram":
			top.writeRAM(fileIn(top, opt_action, opt_file, opt_informat))
		elif opt_action == "read-uil":
			fileOut(opt_file, opt_outformat, top.readUserIdLocation())
		elif opt_action == "write-uil":
			top.writeUserIdLocation(fileIn(top, opt_action, opt_file, opt_informat))
		else:
			if opt_verbose >= 1:
				print "No action specified"
		top.shutdownChip()
	except (TOPException, BitfileException, IOError), e:
		print e
		return 1
	return 0

if __name__ == "__main__":
	sys.exit(main(sys.argv))
Esempio n. 51
0
def mkUncPDF():
	mp = parser()
	opts,fout,samples = main(mp,False,False,True)

	jsons = prepare(opts)
	gROOT.ProcessLine("TH1::SetDefaultSumw2(1);")

########################################
	l1("List of samples:")
	SAMPLES = {}
	l2("| %20s | %20s | %20s | %20s | %20s |"%("sample","entries","cross section","scale factor","ref sample"))
	l2("-"*(23+23+23+23+23+1)) 
	for s in sorted(samples): 
		S = sample(opts,jsons['samp']['files'][s]['tag'],s,jsons['samp']['files'][s]['npassed'],jsons['samp']['files'][s]['xsec'],jsons['samp']['files'][s]['scale'],jsons['samp']['files'][s]['ref'])	
		SAMPLES[S.name] = S
		l2("| %20s | %20.f | %20.3f | %20.6f | %20s |"%(S.name,S.npassed,S.xsec,S.scale,S.ref))

########################################
	l1("List of PDF sets:")
	PSETS = {}
	l2("| %20s | %20s | %5s | %5s | %60s |"%("tag","purpose","id","nmem","name"))
	l2("-"*(23+23+8+8+63+1))
	if opts.PDFS:
		for ps in opts.PDFS: 
			if not any([ps in x for x in jsons['pdfs']]): sys.exit("\n%s!! %s unknown, exiting.%s\n"%(Red,ps,plain))
	reftag,refmem = opts.refPDF[0]
	refmem = int(refmem)
	refname = [x['name'] for x in jsons['pdfs'].itervalues() if x['tag']==reftag][0]
	for pstag,ps in sorted(jsons['pdfs'].iteritems(),key=lambda (x,y):(y['id'],not y['purpose']=='main',y['name'])):
		if opts.PDFS and not any([x in pstag for x in opts.PDFS]): continue
		if (not opts.alphas) and ps['purpose']=='alphas': continue
		PS = pdf(ps['name'],ps['tag'],ps['purpose'],ps['id'],ps['nmax'],refname,reftag,refmem)
		PSETS[PS.name] = PS
		l2("| %20s | %20s | %5d | %5d | %60s |"%(PS.tag,PS.purpose,PS.id,PS.nmem,PS.name))
	l2("-"*(23+23+8+8+63+1))
	l2("refpdf: %s(%s)"%(reftag,refmem))
		
########################################
########################################
########################################
	l1("Working with trees:")

	for kS,S in sorted(SAMPLES.iteritems(),key=lambda (x,y):(x)):
		l2("%s"%S.name)
		l3("Directory %s in %s"%(S.name,fout.GetName()))
		makeDirsRoot(fout,S.name)
		gDirectory.cd("%s:/%s"%(fout.GetName(),S.name))

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

		if opts.mkTree:
			tnew = S.tree.CloneTree()
# container for wghts
			PDFwghts = std.vector(std.vector('double'))()
			PDFwghts.resize(len(PSETS.keys()))
			bnew = tnew.Branch("PDFwghts","vector<vector<double> >",PDFwghts)
# container for wghts alphas
			PDFwghtsalphas = std.vector(std.vector('double'))()
			PDFwghtsalphas.resize(len(PSETS.keys()))
			bnewalphas = tnew.Branch("PDFwghtsalphas","vector<vector<double> >",PDFwghtsalphas)
# container for labels
			PDFlabels = std.vector('TString')()
			PDFlabels.resize(len(PSETS.keys()))
			blabels = tnew.Branch("PDFlabels","vector<TString>",PDFlabels)
# nentries
			nentries = tnew.GetEntries()
	
# event loop
			pdf1, pdf2, newpdf1, newpdf2, alphas, newalphas = 0.,0.,0.,0.,0.,0.
			flagSkip=False
			for iev,ev in enumerate(tnew):
				if not opts.ncut==-1 and iev > opts.ncut: break
				if iev % int(float(nentries)/10.) == 0: l5("%d / %d"%(iev,nentries))
				flagSkip=False
				for iPS,(kPS,PS) in enumerate(sorted(PSETS.iteritems(),key=lambda (x,y):(not y.purpose=='main',y.name))):
# reference pdf
					pdf1 = PS.xfxref(ev.pdfID1,ev.pdfX1,ev.pdfQ)/ev.pdfX1
					pdf2 = PS.xfxref(ev.pdfID2,ev.pdfX2,ev.pdfQ)/ev.pdfX2
					alphas = PS.refpdf.alphasQ(ev.pdfQ)
# other pdfs
					for imem in range(PS.nmem if not ('+' in PS.purpose or '-' in PS.purpose) else 1):
						newpdf1 = PS.xfx(imem,ev.pdfID1,ev.pdfX1,ev.pdfQ)/ev.pdfX1
						newpdf2 = PS.xfx(imem,ev.pdfID2,ev.pdfX2,ev.pdfQ)/ev.pdfX2
						newalphas = PS.pdfmem(imem).alphasQ(ev.pdfQ)
# weights
						PS.wghts[imem] = newpdf1/pdf1*newpdf2/pdf2
						PS.wghtsalphas[imem] = newalphas/alphas

						if 'GF' in S.name:
							if PS.wghts[imem]>1.5 and (ev.pdfX1>0.7 or ev.pdfX2>0.7): 
								flagSkip=True
###						if PS.wghts[imem]>2.0 and (ev.pdfX1>0.8 or ev.pdfX2>0.8):  #VBF
###							print "wght new1 pdf1 new2 pdf2 imem iev Q x1 xfx1 x2 xfx2"
###							print "%12.2f | %12.9f %12.9f | %12.9f %12.9f | %8d %8d | %12.8f | %12.8f %12.8f | %12.8f %12.8f" % (PS.wghts[imem],newpdf1, pdf1, newpdf2, pdf2, imem, iev, ev.pdfQ, ev.pdfX1, PS.xfx(imem,ev.pdfID1,ev.pdfX1,ev.pdfQ), ev.pdfX2,PS.xfx(imem,ev.pdfID2,ev.pdfX2,ev.pdfQ))
	
					PDFwghts[iPS] = PS.wghts
					PDFwghtsalphas[iPS] = PS.wghtsalphas
					PDFlabels[iPS] = TString(PS.tag)

				# veto ridiculous weight factors
					if any([x>2000 for x in PS.wghts]): 
						flagSkip=True
						break
				if flagSkip==True: 
					l5('Skipped ev %d with bad weight.'%(iev))
					continue
# storing
				bnew.Fill()
				bnewalphas.Fill()
				blabels.Fill()
# writing and closing
			tnew.Write(tnew.GetName(),TH1.kOverwrite)

		gDirectory.cd("%s:/"%(fout.GetName()))
Esempio n. 52
0
 def run(self):
     main()
Esempio n. 53
0
        return 1

    libcalamares.globalstorage = libcalamares.GlobalStorage()

    # if a file for simulating globalStorage contents is provided, load it
    if args.globalstorage_yaml:
        with open(args.globalstorage_yaml) as f:
            gs_doc = yaml.load(f)
        for key, value in gs_doc.items():
            libcalamares.globalstorage.insert(key, value)

    cfg_doc = dict()
    if args.configuration_yaml:
        with open(args.configuration_yaml) as f:
            cfg_doc = yaml.load(f)

    libcalamares.job = Job(args.moduledir, doc, cfg_doc)

    scriptpath = os.path.abspath(args.moduledir)
    sys.path.append(scriptpath)
    import main

    print("Output from module:")
    print(main.run())

    return 0


if __name__ == "__main__":
    sys.exit(main())
Esempio n. 54
0
            window.current_frame[-2] = window.player.previous_reward
            window.current_frame[-1] = window.game_over

            
            # Send the bytes of the current frame
            self.request.sendall(window.current_frame)
            
            action_count += 1
            if action_count % COUNTER_DISPLAY_FREQUENCY == 0:
                print("TOTAL ACTION COUNT: %d" % action_count)


if __name__ == '__main__':
    global window

    # Verify the necessary directories exist and conform to the configurations in this file
    verify_directories()
    # Verify the necessary files conform to the configurations in this file
    verify_files()
    
    window = main()

    HOST, PORT = TCP_HOST, TCP_PORT

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
Esempio n. 55
0
            traceback.print_exc()
        from Config import config
        traceback.print_exc(file=open(config.log_dir + "/error.log", "a"))

    if main and main.update_after_shutdown:  # Updater
        # Restart
        gc.collect()  # Garbage collect
        print "Restarting..."
        import time
        time.sleep(1)  # Wait files to close
        args = sys.argv[:]

        sys.executable = sys.executable.replace(".pkg", "")  # Frozen mac fix

        if not getattr(sys, 'frozen', False):
            args.insert(0, sys.executable)

        if sys.platform == 'win32':
            args = ['"%s"' % arg for arg in args]

        try:
            print "Executing %s %s" % (sys.executable, args)
            os.execv(sys.executable, args)
        except Exception, err:
            print "Execv error: %s" % err
        print "Bye."


if __name__ == '__main__':
    main()
Esempio n. 56
0
    _LOG.info(
        'Target is url %s from application_id %s on server %s',
        parsed_args.course_url_prefix, parsed_args.application_id,
        parsed_args.server)

    if not parsed_args.disable_remote:
        environment_class(
            parsed_args.application_id, parsed_args.server).establish()

    _force_config_reload()

    if parsed_args.mode == _MODE_DELETE:
        _delete(
            parsed_args.course_url_prefix, parsed_args.type,
            parsed_args.batch_size)
    elif parsed_args.mode == _MODE_DOWNLOAD:
        _download(
            parsed_args.type, parsed_args.archive_path,
            parsed_args.course_url_prefix, parsed_args.datastore_types,
            parsed_args.batch_size, privacy_transform_fn)
    elif parsed_args.mode == _MODE_RUN:
        _run_custom(parsed_args)
    elif parsed_args.mode == _MODE_UPLOAD:
        _upload(
            parsed_args.type, parsed_args.archive_path,
            parsed_args.course_url_prefix, parsed_args.force_overwrite)


if __name__ == '__main__':
    main(PARSER.parse_args())
Esempio n. 57
0
 
	# numpy array scaling method based on:
	# http://osdir.com/ml/python.pygame/2001-12/msg00000.html
	n = scaleBy
	if (title_array.shape[0] >= title_array.shape[1]):
		scaled = numpy.repeat(numpy.repeat(title_array,n,1), n,0)
	else:
		scaled = numpy.repeat(numpy.repeat(title_array, n,0), n,1)

	print scaled.shape
	print screen.get_size()
	print title_screen.get_size()
	pygame.surfarray.blit_array(screen, scaled)

	while title:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit(0)
			elif event.type == pygame.KEYDOWN:
				if (event.key == pygame.K_r):
					title = False
					game = Game()
					game.run(width, height, scaleBy)
		pygame.display.flip()


if __name__ == "__main__":
	print "title"
	main(240*2, 160*2, 2)
def test_main():
    assert main([]) == 0