Exemplo n.º 1
0
def run():
    if args.file is not None:
        print(args.function)
        for f in args.file:
            print(f + " | " + hash_file(filename=f, function=args.function))
        sys.exit(0)
    main(function=args.function)
Exemplo n.º 2
0
 def usr_log_in():
     #输入框获取用户名密码
     usr_name = var_usr_name.get()
     usr_pwd = var_usr_pwd.get()
     #从本地字典获取用户信息,如果没有则新建本地数据库
     try:
         with open('usr_info.pickle', 'rb') as usr_file:
             usrs_info = pickle.load(usr_file)
     except FileNotFoundError:
         with open('usr_info.pickle', 'wb') as usr_file:
             usrs_info = {'admin': 'admin'}
             pickle.dump(usrs_info, usr_file)
     #判断用户名和密码是否匹配
     if usr_name in usrs_info:
         if usr_pwd == usrs_info[usr_name]:
             messagebox.showinfo(title='welcome', message='欢迎您:' + usr_name)
             window.destroy()
             from gui import main
             main()
         else:
             messagebox.showerror(message='密码错误')
     #用户名密码不能为空
     elif usr_name == '' or usr_pwd == '':
         messagebox.showerror(message='用户名或密码为空')
     #不在数据库中弹出是否注册的框
     else:
         messagebox.askyesno('请联系管理员', '新用户或忘记密码,请联系管理员')
Exemplo n.º 3
0
def cli_interface():
    """
    Command Line Interface
    """
    file = input('Enter file name with unsolved puzzle: ')
    try:
        sudoku = read_file(file)
    except FileNotFoundError:
        print('File does not exist')
        cli_interface()
    except ValueError:
        print('There are errors in the file')
        file_instruction.file_instruction()
        cli_interface()
    mode = int(input('Enter mode number: '))
    if mode != 1 and mode != 2 and mode != 3:
        print('Mode does not exist')
        cli_interface()
    else:
        if mode == 1:
            solve(sudoku)
            file_to_write = input(
                'Enter the name of the file to write solved puzzle: ')
            write_file(file_to_write, print_puzzle(sudoku))
        if mode == 2:
            solve_and_print.solve(sudoku)
            solve_and_print.print_puzzle(sudoku)
        if mode == 3:
            gui.main(sudoku)

        print('Enjoy! Your puzzle is solved\n')
Exemplo n.º 4
0
def open_gui():
    flash("Live recorder started")
    # main = tk.Tk()
    # app = gui.App(main)
    gui.main()
    flash("Live recorder closed")
    return redirect('/')
Exemplo n.º 5
0
def main():
    '''
    Main program. Prepares configuration object from different sources (cli,cfg_file,default).
    Creates simulation object structure, from configuration object. Depending on the configuration
    it executes the simulation with or without GUI.
    '''
    logger.info("Visual Cache Launcher Module starting...")
    # Prepare the arguments received from command line
    args_list = []
    for entry in sys.argv[1:]:
        args_list.append(entry)
    logger.debug('Arguments list ready to be sent: {0}'.format(args_list))
    configuration = command_interpreter.main()
    logger.info('Parsed arguments received are: {0}'.format(configuration))

#    trazas_file = initialization_parameters["Memory_Access_Instructions"]
#    trazas_file_path = os.path.join(os.getcwd(),os.path.join("simulation_files",trazas_file))

#    logging.debug("this is the path to the simulation trazas file: {0}".format(trazas_file_path))

#    parsed_instructions = trazas_sanitizer.main(trazas_file_path)
#    logger.debug("Parsed Memory Access Instructions: {0}".format(parsed_instructions))

    # Build simulator objects
    simulation = create_simulation(configuration)

    # Start simulation in gui or in command line mode
    if 'gui' in configuration and configuration['gui'] == '1':
        gui.main(simulation)
    else:
        logger.info("Ejecución continua")
        while not simulation.finished():
            while not simulation.exe():
                1
        logger.debug("Simulation process finished.")
Exemplo n.º 6
0
def main():
    interface = select_interface()
    db = database.Database()
    db.configuration_check(interface)
    os.chdir(db.database_location)
    if interface == "1":
        cli.main(db)
    else:
        gui.main(db)
Exemplo n.º 7
0
def confirm(root,main):
	function.clear(root)
	Label(root,text="Are you sure?").grid(row=0,column=0, columnspan=2)
	if(main==True):
		Button(root,text="Yes",command=gui.exit()).grid(row=1,column=0)
		Button(root,text="No",command=gui.main()).grid(row=1,column=1)
	else:
		Button(root,text="Yes",command=gui.main()).grid(row=1,column=0)
		Button(root,text="No",command=gui.ingame()).grid(row=1,column=1)
Exemplo n.º 8
0
def main():
    """Parse user input and start the simulation or launch GUI accordingly."""
    init()
    save_file = "data/save.txt"

    if "-s" in sys.argv or not os.path.exists(save_file):
        control.main(save_file)

    if "-a" not in sys.argv:
        gui.main(save_file)
Exemplo n.º 9
0
def main(args):
    skip_req_check = False
    for arg in args:
        if arg.strip() == "-y":
            skip_req_check = True
    if not skip_req_check:
        if not check_reqs():
            return False
    import gui
    gui.main()
Exemplo n.º 10
0
Arquivo: app.py Projeto: shaief/stopgo
def getOptions():
    '''
    Analizu datumoj
    '''
    args = argv[1:]
    parser = argparse.ArgumentParser(description="Parses command.",
                                     argument_default=argparse.SUPPRESS)
    parser.add_argument("project", nargs="?")
    parser.add_argument("-c",
                        "--config",
                        nargs="?",
                        dest='config',
                        help="Optional path to a non-default config file.")
    parser.add_argument("-s",
                        "--shell",
                        dest='shell',
                        action='store_true',
                        help="Keep it in the shell. Do not launch the GUI.")
    parser.add_argument(
        "-m",
        "--make-project",
        nargs="?",
        dest='make',
        help=
        "Path to a directory of sequential images to load as if it were a StopGo project."
    )

    options = parser.parse_args(args)
    opts = vars(options)
    '''
    if not opts.has_key('project'):
        opts['project'] = 'stopgo_project.db'


    if not opts.has_key('config'):
        if os.path.isfile( os.path.join( HOME + '.config/stopgo.conf' ) ):
            opts['config'] = os.path.isfile( os.path.join( HOME + '/.config/stopgo.conf' ) ):
        elif os.path.isfile('/etc/config/stopgo.conf'):
            opts['config'] = '/etc/config/stopgo.conf'
        else:
            print('Failed: No template file found.')
            exit()
    '''

    if not opts.has_key('shell'):
        import gui
        gui.main(opts)
        #applo = wx.App()
        #instancer = gui.GUI(parent=None, id=-1, title="stopgo")
        #instancer.Show()
        #applo.MainLoop()
    else:
        import shell
        shell.execute(opts)
Exemplo n.º 11
0
def main():
    gui.main()
    game = gui.launch
    game_settings = gui.launch_settings
    if game == 'sp_game':
        pass
        # singleplayer.main()
    elif game == 'mp_game':
        gui.clear_launch()
        print(game_settings)
        multiplayer.main(game_settings, debug_mode=0)
Exemplo n.º 12
0
def test():
    rc = 0
    if not isUserAdmin():
        #print "You're not an admin.", os.getpid(), "params: ", sys.argv
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        #print "You are an admin!", os.getpid(), "params: ", sys.argv
        rc = 0
        import gui
        gui.main()
    #x = raw_input('Press Enter to exit.')
    return rc
Exemplo n.º 13
0
def _gui(args):
  error=0
  try:
    import pimouss
    pimouss.gui.main()
  except:
    try:
      logger.warning('can not find pimouss.gui')
      import gui
      gui.main()
    except:  
      logger.warning('neither gui')
      error=-1
  return error
Exemplo n.º 14
0
def main():
    cli_arguments()
    global cli, cron, debug, settings_files
    if debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)
    logger.info(str(logger.getEffectiveLevel))

    if cli:
        from functions import cli
        cli.main(settings_files, cron)
    else:
        import gui
        gui.main(settings_files)
Exemplo n.º 15
0
def run_gui(input_start_page, end_page, strict):
    """ Batch cleans the pages in text/clean."""
    config = ConfigParser()
    config.read('book.cnf')
    if strict and \
        config.has_option('process', 'last_strict_page'):
        hold_page = config.getint('process', 'last_strict_page')
    elif not strict and \
        config.has_option('process', 'last_checked_page'):
        hold_page = config.getint('process', 'last_checked_page')
    else:
        hold_page = input_start_page
    print hold_page
    if input_start_page == 0:
        start_page = hold_page
    else:
        start_page = input_start_page
    lang = get_lang()
    lm = line_manager.LineManager(
        spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
        start_page,
        end_page
        )
    lm.load('text/clean')
    app = gui.main(lm, strict)
    lm.write_pages('text/clean', False)

    if strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_strict_page', app.last_page)
    elif not strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_checked_page', app.last_page)
    with open('book.cnf', 'wb') as f:
        config.write(f)
Exemplo n.º 16
0
def run_gui(input_start_page, end_page, strict):
    """ Batch cleans the pages in text/clean."""
    config = ConfigParser()
    config.read('book.cnf')
    if strict and \
        config.has_option('process', 'last_strict_page'):
        hold_page = config.getint('process', 'last_strict_page')
    elif not strict and \
        config.has_option('process', 'last_checked_page'):
        hold_page = config.getint('process', 'last_checked_page')
    else:
        hold_page = input_start_page
    print hold_page
    if input_start_page == 0:
        start_page = hold_page
    else:
        start_page = input_start_page
    lang = get_lang()
    lm = line_manager.LineManager(
        spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
        start_page, end_page)
    lm.load('text/clean')
    app = gui.main(lm, strict)
    lm.write_pages('text/clean', False)

    if strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_strict_page', app.last_page)
    elif not strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_checked_page', app.last_page)
    with open('book.cnf', 'wb') as f:
        config.write(f)
Exemplo n.º 17
0
def main():
    ui = Thread(target=gui.main())
    ui.start()
    # fucku = Thread(target=f**k)
    # fucku.start()
    marker = Thread(target=marker_read.read_loop())
    marker.start()
Exemplo n.º 18
0
def options(root,main):
	function.clear(root)
	Label(root, text="Options", font=32).grid(row=0,column=0)
	if(main==True):
		Button(root, text="Back", command=gui.main()).grid(row=6,column=0)
	else:
		Button(root, text="Back", command=gui.ingame()).grid(row=6,column=0)
Exemplo n.º 19
0
def Graph(w, h, xmax, ymax, xinterval, function):

    w = int(w)
    h = int(h)
    stop = False
    x = -xmax
    testx = x - xinterval
    pygame.init()
    fps = 120
    clock = pygame.time.Clock()
    display = pygame.display.set_mode((w,h))
    xaxis = pygame.Surface((w,1))
    yaxis = pygame.Surface((1,h))
    xaxis.fill((255,255,255))
    yaxis.fill((255,255,255))
    display.blit(xaxis, (0,h//2))
    display.blit(yaxis, (w//2,0))

    if "sine" in function:
        function = function.replace("sine", "math.sin")

    while True:

        tempfunction = list(function)

        if stop == False:
            for i in tempfunction:
                if i == "x":
                    tempfunction[tempfunction.index(i)] = ("("+str(x)+")")
            convfunction = str(''.join([str(j) for j in tempfunction]))

        if stop == False:
            y = eval(str(convfunction))
        if stop == False:
            pygame.draw.circle(display,(255,255,255),[int(x*(w//2/xmax)+w//2),int(y*-(h//2/ymax)+h//2)],1)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                gui.main()
        if stop == False: x += xinterval
        testx = x - xinterval
        if x >= xmax:
            stop = True
        if stop == True:
            fps = 10
        pygame.display.flip()
        clock.tick(fps)
Exemplo n.º 20
0
	def createmenus(self):
		'''Creates menus.'''
		self.menu_main = gui.main(self)
		self.menu_story = gui.storymode(self)
		self.menu_freeplay = gui.freeplay(self)
		self.menu_options = gui.options(self)
		self.menu_newworld = gui.makenewworld(self)
		self.hide_menus()
Exemplo n.º 21
0
def main():
    """Main runtime function."""
    file_data = None
    args = assign_args()

    if type(args.file) is str:  # Fetches rle file if specified.
        try:
            with open(args.file, 'r') as f:
                file_data = f.read()
        except:
            print("ERROR: File Does Not Exist")
            sys.exit(0)

    if file_data == None:  # If file not specified, parses rle.string
        data = rle.parse_rle(rle.string, frame, frame)
    else:  # Parses file specified for rle pattern data.
        try:
            data = rle.parse_rle(file_data, frame, frame)
        except:
            print("ERROR: Corrupt File Data")
            sys.exit(0)

    if type(args.rand) is int:
        if rule is None:
            default = "b3/s23"
        else:
            default = rule
        life = random_life(args.rand, wrapping, rule=default)
    else:
        if rule is None:
            life = Life(data['matrix'], data['rulestring'], wrapping)
        else:
            life = Life(data['matrix'], rule, wrapping)

    a = time.time()
    if args.nogui:
        no_gui(life, generations)
    else:
        gui.main(life, pixel_size=pixel_size, wait=wait, gen=generations)
    b = time.time()

    print("runtime: " + str(b - a) + " seconds")
Exemplo n.º 22
0
def Save(root,main):
	function.clear(root)
	labels=saveload.labels(False)
	Button(root, text=labels[1], command=saveload.save(1)).grid(row=1,column=0)
	Button(root, text=labels[2], command=saveload.save(2)).grid(row=2,column=0)
	Button(root, text=labels[3], command=saveload.save(3)).grid(row=3,column=0)
	Button(root, text=labels[4], command=saveload.save(4)).grid(row=4,column=0)
	if(main==True):
		Button(root, text="Back", command=gui.main()).grid(row=5,column=0)
	else:
		Button(root, text="Back", command=gui.ingame()).grid(row=5,column=0)
Exemplo n.º 23
0
def sudokuSolver(array):
    try:
        for x in range(9):
            for y in range(9):
                if array[x][y] == 0:
                    for value in range(1, 10):
                        if checkValues(array, x, y, value):
                            array[x][y] = value
                            if sudokuSolver(array):
                                return True
                            array[x][y] = 0
                    return False
        print(array)
        print("\n")
        flatten = array.flatten()
        mainConstraint(flatten)
        gui.main(flatten)
        return True
    except:
        print("An Error has occured, please check the array")
Exemplo n.º 24
0
def main():

    """ 
    Entry point of the program. Takes in the arguments, parses them, 
    and calls the assembler/emulator/gui as appropriate.

    Args:
        None
    Returns:
        None
    """

    parser = argparse.ArgumentParser(description = "Automate the assembling and emulation of the given file.")
    parser.add_argument("filepath", help="The path to the .dasm file to run.")
    parser.add_argument("-g", action="store_true", help="Enable the GUI") 
    parser.add_argument("-a", action="store_true", help="Mark that the code is already assembled")

    args = parser.parse_args()
    
    filepath = args.filepath
    guiFlag = args.g
    assembledFlag = args.a

    fi = open(filepath, "r")
    text = fi.read()
    fi.close()

    if(assembledFlag):
        cpu = emulator.CPU(text)
    else:
        p = assembler.Parser(text).assemble()
        cpu = emulator.CPU(p)


    if not guiFlag:
        cpu.run()
    else:
        if(assembledFlag):
            gui.main(text)
        else:
            gui.main(p)
Exemplo n.º 25
0
    def Calculate(self, master):
            self.args = []
            self.args.append(int(self.T.get()))
            self.args.append(int(self.l.get()))
            self.args.append(float(self.a.get()))
            self.args.append(float(self.h.get()))
            self.args.append(float(self.tau.get()))

            self.args.append(float(self.coefFi[0].get()))
            self.args.append(float(self.coefFi[1].get()))
            self.args.append(float(self.coefFi[2].get()))


            self.args.append(float(self.coefB[0].get()))
            self.args.append(float(self.coefB[1].get()))
            self.args.append(float(self.coefB[2].get()))
            self.args.append(float(self.coefB[3].get()))
            self.args.append(float(self.coefB[4].get()))

            #main(self.args)
            gui.main(self.args)
Exemplo n.º 26
0
def getOptions():
    '''
    Analizu datumoj
    '''
    args = argv[1:]
    parser = argparse.ArgumentParser(description="Parses command.",argument_default=argparse.SUPPRESS)
    parser.add_argument("project",nargs="?")
    parser.add_argument("-c", "--config",nargs="?",dest='config',
                        help="Optional path to a non-default config file.")
    parser.add_argument("-s", "--shell",dest='shell',action='store_true',help="Keep it in the shell. Do not launch the GUI.")
    parser.add_argument("-m", "--make-project",nargs="?",dest='make',
                        help="Path to a directory of sequential images to load as if it were a StopGo project.")

    options = parser.parse_args(args)
    opts = vars(options)
    '''
    if not opts.has_key('project'):
        opts['project'] = 'stopgo_project.db'


    if not opts.has_key('config'):
        if os.path.isfile( os.path.join( HOME + '.config/stopgo.conf' ) ):
            opts['config'] = os.path.isfile( os.path.join( HOME + '/.config/stopgo.conf' ) ):
        elif os.path.isfile('/etc/config/stopgo.conf'):
            opts['config'] = '/etc/config/stopgo.conf'
        else:
            print('Failed: No template file found.')
            exit()
    '''

    if not opts.has_key('shell'):
        import gui
        gui.main(opts)
        #applo = wx.App()
        #instancer = gui.GUI(parent=None, id=-1, title="stopgo")
        #instancer.Show()
        #applo.MainLoop()
    else:
        import shell
        shell.execute(opts)
Exemplo n.º 27
0
def main():
    # Initialize Variables (Imports)
    m = money.Money()
    port = portfolio.Portfolio(m)
    wl = watch_list.Watch_List()

    # Main Text Display
    m.print_funds()
    option = input(display)

    while True:
        if option == '1':
            port.main()
        elif option == '2':
            m.money_main()
        elif option == '3':
            wl.main()
        elif option == '4':
            ipt = input("Would you like to see your current portfolio? (Y/N)  ").upper()
            if ipt == 'Y':
                port.print_portfolio()
            ipt = input("Would you like to see your current watch list? (Y/N)  ").upper()
            if ipt == 'Y':
                wl.print_wl()
            stock_ipt = input("Please type the ticker symbol of a stock.  ").upper()
            try:
                print('\nCurrent Ticker Symbol: ' + str(stock_ipt).upper())
                stock.Stock(stock_ipt).stock_main()
            except (AttributeError, IndexError, KeyError) as e:
                print("\n" + str(stock_ipt) + ' is not a valid ticker symbol in Yahoo Finance '
                                              'or the given ticker symbol is not supported by the yfinance API.')
        elif option == '5':
            google_search_keyword()
        elif option == 'gui':
            gui.main(m, port, wl)
        elif option == 'quit':
            return
        m.print_funds()
        option = input(display)
Exemplo n.º 28
0
def Load(root,main):
	function.clear()
	labels=saveload.labels(True)
	Label(root, text=labels[0], font=32).grid(row=0,column=0)
	Button(root, text=labels[1], command=saveload.load(0)).grid(row=1,column=0)
	Button(root, text=labels[2], command=saveload.load(1)).grid(row=2,column=0)
	Button(root, text=labels[3], command=saveload.load(2)).grid(row=3,column=0)
	Button(root, text=labels[4], command=saveload.load(3)).grid(row=4,column=0)
	Button(root, text=labels[5], command=saveload.load(4)).grid(row=5,column=0)
	if(main=True):
		Button(root, text="Back", command=gui.main()).grid(row=6,column=0)
	else:
		Button(root, text="Back", command=gui.ingame()).grid(row=6,column=0)
Exemplo n.º 29
0
def main():
    if len(sys.argv) == 1:
        print('Usage: calculation [option] or calculation -n [count]\n' +
              '调用交互界面(默认图形用户界面)或者生成指定数量(默认1000道)的四则运算题目' +
              '到默认文件(../res/questions.txt)中\n-t, --terminal    调用命令行交互界面\n' +
              '-g, --gui         调用图形交互界面\n-n, --num         指定生成的题目数量')
        gui.main()
    elif sys.argv[1] == '-t' or sys.argv[1] == '--terminal':
        terminal.main()
    elif sys.argv[1] == '-g' or sys.argv[1] == '--gui':
        gui.main()
    elif sys.argv[1] == '-n' or sys.argv[1] == '--num':
        if len(sys.argv) == 2:
            utl.gen_questions(1000)
        else:
            try:
                num = int(sys.argv[2])
                utl.gen_questions(num)
            except Exception:
                print('error: invalid param')
    else:
        print('error: invalid param')
Exemplo n.º 30
0
def credits(root, main):
	function.clear(root)
	Label(root, text="Credits", font=32).grid(row=0,column=0)
	Label(root, text="Programmer: Roadkillsanta (EN)", font=16).grid(row=1,column=0)
	Label(root, text="Programmer: BOOMCHICKEN (JZ)", font=16).grid(row=4,column=0)
	Label(root, text="Writer: GoobysTheName (WJ)", font=16).grid(row=3,column=0)
	Label(root, text="Writer: BOOMCHICKEN (JZ)", font=16).grid(row=4,column=0)
	Button(root, text="@RGTN (github.com/RGTN)", font=16, command=webbrowser.open("http:github.com/RGTN", new=2, autoraise=True)).grid(row=5,column=0)
	Label(root, text="Special Thanks: GitHub (github.com)", font=16).grid(row=6,column=0)
	Label(root, text=" ", font=16).grid(row=7,column=0)
	if(main==True):
		Button(root, text="Back", font=16, command=gui.main()).grid(row=8,column=0)
	else:
		Button(root, text="Back", font=16, command=gui.ingame()).grid(row=8,column=0)
Exemplo n.º 31
0
def main():
    args = sys.argv
    #print(sys.argv)
    path = os.path.dirname(sys.argv[0])
    #print(path)
    if len(args) == 1:
        main = gui.main()
        main.mainloop()
    elif len(args) == 2:
        if args[1].lower() == "receive":
            receive(path)
        else:
            transfer(args[1], path)
    else:
        if args[1].lower() == "raw":
            transfer(" ".join(args[2:]), path, raw=True)
        else:
            print("Received too many or too few arguments...")
Exemplo n.º 32
0
def switchToPlayer():
    run = False
    pygame.display.quit()
    time.sleep(0.3)
    gui.main(AiYN=False)
Exemplo n.º 33
0
from gui import main
#from easysub import main


if __name__ == '__main__':
	main()

Exemplo n.º 34
0
#!/usr/bin/env python
#
# (c) 2014 Productize <*****@*****.**>

import sys


def cli_main():
    if sys.argv[1] == 'collect':
        import collect
        collect.run()


if __name__ == '__main__':
    if len(sys.argv) == 1:
        import gui
        sys.exit(gui.main())
    else:
        cli_main()
Exemplo n.º 35
0
def switchToAi():
    run = False
    pygame.display.quit()
    time.sleep(0.3)
    gui.main(AiYN=True)
Exemplo n.º 36
0
def main ():
    client = rpyc.connect("elegantgazelle.com", 55889, service.ClientService, config = {"allow_public_attrs" : True})

    background = pygame.image.load("data/freedom_galaxy.jpg")
    #background = pygame.transform.scale(background, (389, 489))

    start = my_button('Start Game')
    join = my_button('Join Game')
    allegiance = my_button('Rebel', 'Empire')
    single_player = my_button('Play AI', '2 Player')
    scenario = my_button('Flight', 'Powder')
    exit = my_button('Exit Game')
    gametextbox = my_textbox('Game Name')
    playertextbox = my_textbox('Your Name')
    screen = pygame.display.set_mode((536,720))
    listingbox = gamelistingbox()
    
    playerside = ''
    playerscenario = ''

    pygame.mixer.music.load('data/starwars-maintheme.mp3') 
    pygame.mixer.music.play(-1)

    clock = pygame.time.Clock()

    redrawscreen = False
    screen.blit(background, background.get_rect())
    pygame.display.flip()
    
    gamelistasync = rpyc.async(client.root.list_games)
    
    selectedtextbox = gametextbox
    gametextbox.switchchar()
    
    run = True
    while run:
        mouse = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.KEYDOWN:
                if selectedtextbox is not None:
                    if event.key == 9:
                        if selectedtextbox == gametextbox:
                            selectedtextbox.switchchar()
                            selectedtextbox = playertextbox
                            selectedtextbox.switchchar()
                        elif selectedtextbox == playertextbox:
                            selectedtextbox.switchchar()
                            selectedtextbox = gametextbox
                            selectedtextbox.switchchar()
                    elif event.key == pygame.K_RETURN:
                        run = False
                        #pygame.mixer.music.stop()
                        playerscenario = setscenario(scenario.is_alt)
                        playerside = setplayer( allegiance.is_alt)
                        gamesetup = client.root.start_game(id=gametextbox.input, player=playertextbox.input) #, scenario=playerscenario, ai=single_player.is_alt)
                        #print("Getting state of planets")
                        #planet = client.root.get_state(object_id=1, object_type="Planet")
                        #print planet
                        #print gamesetup
                        gui.main(client, gamesetup)
                    else:
                        selectedtextbox.addkey(event.key)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if start.obj.collidepoint(mouse):
                    run = False
                    #pygame.mixer.music.stop()
                    playerscenario = setscenario(scenario.is_alt)
                    playerside = setplayer( allegiance.is_alt)
                    #gamesetup = client.root.start_game(id='test1', player=playertextbox.input) #id=gametextbox.input, scenario=playerscenario, ai=single_player.is_alt)
                    #print("Getting state of planets")
                    #planet = client.root.get_state(object_id=1, object_type="Planet")
                    #print planet
                    #print gamesetup
                    gui.main(client)#, gamesetup)
                    #fire request to server
                    print('my_button start game clicked')
                elif join.obj.collidepoint(mouse):
                    listingbox.visible = True
                    gamelisting = gamelistasync()
                    print('my_button join game clicked')
                elif allegiance.obj.collidepoint(mouse):
                    allegiance.switch_text()
                    if single_player.is_alt is False:
                        allegiance.is_alt = False
                    print('my_button rebel clicked')
                elif single_player.obj.collidepoint(mouse):
                    single_player.switch_text()
                    if single_player.is_alt is False:
                        allegiance.is_alt = False
                    print('my button player vs AI clicked')
                elif scenario.obj.collidepoint(mouse):
                    scenario.switch_text()
                    print('my button scenario clicked')
                elif exit.obj.collidepoint(mouse):
                    run = False
                    print('my button exit clicked')
                elif gametextbox.obj.collidepoint(mouse):
                    if selectedtextbox is not None:
                        selectedtextbox.switchchar()
                    selectedtextbox = gametextbox
                    selectedtextbox.switchchar()
                elif playertextbox.obj.collidepoint(mouse):
                    if selectedtextbox is not None:
                        selectedtextbox.switchchar()
                    selectedtextbox = playertextbox
                    selectedtextbox.switchchar()
                elif listingbox.visible is True:
                    if listingbox.obj.collidepoint(mouse):
                        if listingbox.cancelbutton.obj.collidepoint(mouse):
                            redrawscreen = True
                            listingbox.visible = False
                        elif listingbox.joinbutton.obj.collidepoint(mouse):
                            run = False
                            #pygame.mixer.music.stop()
                            playerscenario = setscenario(scenario.is_alt)
                            playerside = setplayer( allegiance.is_alt)
                            gamesetup = client.root.join_game(id=gametextbox.input, player=playertextbox.input) #scenario=playerscenario
                            print gamesetup
                            gui.main(gamesetup, client)
                        elif listingbox.refreshbutton.obj.collidepoint(mouse):
                            gamelisting = gamelistasync()
                        elif listingbox.gamebox.collidepoint(mouse):
                            listingbox.checkclick(mouse)
                            
                        
        if redrawscreen is True:
            screen.blit(background, background.get_rect())
            pygame.display.flip()
            redrawscreen = False
        
        if listingbox.visible is True:
            listingbox.draw(screen, mouse)
            if gamelisting is not None:
                if gamelisting.ready:
                    listingbox.setgamelist(gamelisting.value)
                    gamelisting = None
                else:
                    listingbox.drawloading(screen)
            single_player.is_alt = True
            if listingbox.selectedgame is not None:
                gametextbox.input = str(listingbox.selectedgame["id"])
                gametextbox.text = list(gametextbox.input)
                scenario.is_alt = listingbox.scenarioflag
                
        
        start.draw(screen, mouse, (13,650,170,40), (18,658))
        join.draw(screen, mouse, (196,650,155,40), (201,658))
        exit.draw(screen, mouse, (364,650,155,40), (369,658))
        
        single_player.draw(screen, mouse, (13,607,170,40), (18,611))
        allegiance.draw(screen, mouse, (196,607,155,40), (201,611))
        scenario.draw(screen, mouse, (364,607,155,40), (369,611))
        
        gametextbox.draw(screen, (13,560,250,42))
        playertextbox.draw(screen, (270,560,250,42))
        
        

        pygame.display.update()
        clock.tick(60)
Exemplo n.º 37
0
try:
    from lastscrape.lastscrape import *
except ImportError:
    from lastscrape import *


if __name__ == '__main__':
    import gui
    import sys
    gui.main(*sys.argv)
Exemplo n.º 38
0
def main(argv):
	try:
		import getopt
		import sys

		

		#set default
		dumpfile='/tmp/inforevealer'
		tmp_configfile="/tmp/inforevealer_tmp.conf" #tmp configuration file (substitute)
		verbosity=False
		category=""
		runfile=None #option only for internal use, see above
		gui=False #run the GUI

		defaultPB = "http://pastebin.com" #Default pastebin
		website = defaultPB
		pastebin_choice=False


		#####################
		# GETOPT
		#####################
		try:	
			options, remainder = getopt.gnu_getopt(sys.argv[1:], 'hlc:vf:pw:', ['help',
									   'list',
									   'category=',
									   'verbose',
									   'file=',
									   'pastebin',
									   'website',
									   'runfile=',
									   'gui'
									 ])
									 
		except getopt.GetoptError:
			sys.stderr.write(_("Invalid arguments."))
			io.usage()
			sys.exit(1)

		for opt, arg in options:
			if opt in ('-h', '--help'):
				io.usage()
				sys.exit()
			elif opt in ('-l', '--list'):
				#find categories.conf
				filename=readconf.find_categories_conf()
				#find validator.conf
				spec_filename=readconf.find_validator_conf()
				#open categories.conf with validator.conf
				configfile=readconf.open_config_file(filename,spec_filename)
				# load the list of categories
				list_category=readconf.LoadCategoryList(configfile)
				io.list(list_category)
				sys.exit()
			elif opt in ('-c', '--category'):	
				category=arg
			elif opt in ('-v','--verbose'):
				verbosity=True
			elif opt in ('-f','--file'):
				dumpfile=arg
			elif opt in ('-p','--pastebin'):
				pastebin_choice=True
			elif opt in ('-w','--website'):
				website=arg
				if not website.endswith("/"):
					website += "/"
			elif opt in ('--runfile'):
				runfile=arg
			elif opt in ('--gui'):
				gui=True

		#First to do: runfile (internal use)
		if runfile != None:
			readconf.ReadAndMakeInternalDesire(tmp_configfile)
			sys.exit()
		else:
			#find categories.conf
			filename=readconf.find_categories_conf()
			#find validator.conf
			spec_filename=readconf.find_validator_conf()
			#open categories.conf with validator.conf
			configfile=readconf.open_config_file(filename,spec_filename)
			# load the list of categories
			list_category=readconf.LoadCategoryList(configfile)
			
			if gui==True:
				import gui
				gui.main(configfile,list_category)
			#check if category is ok
			elif category in list_category:
				action.action(category,dumpfile,configfile,tmp_configfile,verbosity)
				sendFileContent(dumpfile,title=category,website=website,version=None)
			else:
				sys.stderr.write(_('Error: Wrong category'))
				io.usage()
				sys.exit(1)
	
	except KeyboardInterrupt:
		sys.exit("KeyboardInterrupt caught.")
Exemplo n.º 39
0
    p["parameters"]["streamServerID"] = streamServer
    p["parameters"]["songID"] = songID
    p["parameters"]["streamKey"] = streamKey
    p["header"] = h
    p["header"]["client"] = jsqueue[0]
    p["header"]["clientRevision"] = jsqueue[1]
    p["header"]["token"] = prepToken("markSongDownloadedEx", jsqueue[2])
    p["method"] = "markSongDownloadedEx"
    conn = httplib.HTTPConnection(URL)
    conn.request("POST", "/more.php?" + p["method"], json.JSONEncoder().encode(p), jsqueue[3])
    return json.JSONDecoder().decode(gzip.GzipFile(fileobj=(StringIO.StringIO(conn.getresponse().read()))).read())["result"]

if __name__ == "__main__":
    if len(sys.argv) < 2: #Check if we were passed any parameters
        import gui
        gui.main() #Open the gui
        exit() #Close the command line
    print entrystring #Print the welcome message
    print "Initializing..."
    getToken() #Get a static token
    i = ' '.join(sys.argv[1:]) #Get the search parameter
    #i = raw_input("Search: ") #Same as above, if you uncomment this, and comment the first 4 lines this can be run entirely from the command line.
    print "Searching for '%s'..." % i
    m = 0
    s = getResultsFromSearch(i) #Get the result from the search
    l = [('%s: "%s" by "%s" (%s)' % (str(m+1), l["SongName"], l["ArtistName"], l["AlbumName"])) for m,l in enumerate(s[:10])] #Iterate over the 10 first returned items, and produce descriptive strings.
    if l == []: #If the result was empty print a message and exit
        print "No results found"
        exit()
    else:
        print '\n'.join(l) #Print the results
Exemplo n.º 40
0
                  export_type=args.write_playlist_type)

    print [str(s) for s in songs.songs] ; exit()

    if not args.target and not args.rename:
        target = os.path.splitext(os.path.basename(args.playlist[0]))[0]
        args.target = target

    if not args.format.endswith(".{ext}"):
        args.format += ".{ext}"

    if args.copy:
        songs.copy_em(args.target, args.format)
    elif args.rename:
        songs.rename_em(args.target, args.format)
    else:
        songs.zip_em(args.target, args.inner_folder_name, args.format)

if __name__ == "__main__":
    try:
        args = parse_args()
        if len(sys.argv) > 1 and not args.graphical:
            main(args)
        else:
            import gui
            gui.main(args)
    except (KeyboardInterrupt, EOFError):
        print "\rCaught keyboard interrupt. Giving up without Cleaning up."
    except RuntimeError, e:
        print "Error! Error!: %s" % e
 def main(self):
     self.run_thread(self.schedule)
     gui.main(self)
     for thread in self.threads:
         thread.join()
Exemplo n.º 42
0
def main():
	import sys, os
	from pprint import pprint

	# Early check for forked process.
	if appinfo.args.forkExecProc:
		# Only import utils now for this case.
		# Otherwise, I want "--pyshell" to be without utils loaded.
		import utils
		utils.ExecingProcess.checkExec()

	# Early check for "--pyshell".
	# This is a simple debug shell where we don't load anything.
	if appinfo.args.pyshell:
		better_exchook.simple_debug_shell({}, {})
		raise SystemExit

	# Early check for "--pyexec".
	# This is a simple Python execution where we don't load anything.
	if appinfo.args.pyexec:
		sourcecode = appinfo.args.pyexec[0]
		exec(compile(sourcecode, "<pyexec>", "exec"))
		raise SystemExit

	import utils
	import time

	print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "git-ref", appinfo.gitRef[:10], "on", appinfo.platform, "(%s)" % sys.platform
	print "startup on", utils.formatDate(time.time())

	utils.setCurThreadName("Python main")

	try:
		# Hack: Make the `__main__` module also accessible as `main`.
		mainmod = sys.modules["__main__"]
		sys.modules.setdefault("main", mainmod)
		del mainmod
	except Exception:
		sys.excepthook(*sys.exc_info())
		# doesn't matter, continue

	# Import PyObjC here. This is because the first import of PyObjC *must* be
	# in the main thread. Otherwise, the NSAutoreleasePool created automatically
	# by PyObjC on the first import would be released at exit by the main thread
	# which would crash (because it was created in a different thread).
	# http://pyobjc.sourceforge.net/documentation/pyobjc-core/intro.html
	objc, AppKit = None, None
	try:
		import objc
	except Exception:
		if sys.platform == "darwin":
			print "Error while importing objc"
			sys.excepthook(*sys.exc_info())
		# Otherwise it doesn't matter.
	try:
		# Seems that the `objc` module is not enough. Without `AppKit`,
		# I still get a lot of
		#   __NSAutoreleaseNoPool(): ... autoreleased with no pool in place - just leaking
		# errors.
		if objc:
			import AppKit
	except Exception:
		# Print error in any case, also ImportError, because we would expect that this works.
		print "Error while importing AppKit"
		sys.excepthook(*sys.exc_info())

	# Import core module here. This is mostly as an early error check.
	try:
		import musicplayer
	except Exception:
		print "Error while importing core module! This is fatal."
		sys.excepthook(*sys.exc_info())
		print "Environment:"
		pprint(os.environ)
		raise

	# Import gui module here. Again, mostly as an early error check.
	# If there is no gui, the module should still load and provide
	# dummy functions where appropriate.
	import gui

	# Default quit handling.
	# Note that this is executed after `threading._shutdown`, i.e. after
	# all non-daemon threads have finished.
	import atexit
	atexit.register(gui.handleApplicationQuit)

	# Import some core modules. They propagate themselves to other
	# subsystems, like GUI.
	# XXX: Maybe move all this to `State` module?
	import State
	import Preferences
	import Search
	import SongEdit

	# This will overtake the main loop and raise SystemExit at its end,
	# or never return.
	# It also just might do nothing.
	gui.main()
	# If we continue here, we can setup our own main loop.

	# We have no GUI. Continue with some simple console control handling.
	import stdinconsole

	handleApplicationInit()

	# Note on quit behavior: Simply iterating state.updates
	# and waiting for its end does not work because we would
	# not interrupt on signals, e.g. KeyboardInterrupt.
	# It is also not possible (in general) to catch
	# signals from other threads, thus we have to do it here.
	# time.sleep() is a good way to wait for signals.
	# However, we use stdinconsole.readNextInput() because
	# there is simply no way to have os.read() in another thread
	# and to be able to interrupt that from here (the main thread).
	# In other threads: thread.interrupt_main() does not work
	# for time.sleep() (or at least it will not interrupt the sleep).
	# os.kill(0, signal.SIGINT) works, though.
	# To interrupt/stop all threads:
	# signal.set_wakeup_fd(sys.stdin.fileno()) also does not really
	# work to interrupt the stdin thread, probably because stdin is
	# not non-blocking.
	# Every thread must only wait on a OnRequestQueue which registers
	# itself in its thread. We cancelAll() here already the main queue
	# (state.updates) and in Module.stop(), we also cancel any custom
	# queue.

	while True:
		try: stdinconsole.readNextInput() # wait for KeyboardInterrupt
		except BaseException, e:
			State.state.updates.put((e, (), {}))
			State.state.updates.cancelAll()
			break
Exemplo n.º 43
0
def main():

	import utils
	utils.ExecingProcess.checkExec()


	import sys, time
	print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "git-ref", appinfo.gitRef[:10], "on", appinfo.platform, "(%s)" % sys.platform
	print "startup on", utils.formatDate(time.time())

	utils.setCurThreadName("Python main")

	try:
		# Hack: Make the `__main__` module also accessible as `main`.
		mainmod = sys.modules["__main__"]
		sys.modules.setdefault("main", mainmod)
		del mainmod
	except Exception:
		sys.excepthook(*sys.exc_info())
		# doesn't matter, continue

	# Import PyObjC here. This is because the first import of PyObjC *must* be
	# in the main thread. Otherwise, the NSAutoreleasePool created automatically
	# by PyObjC on the first import would be released at exit by the main thread
	# which would crash (because it was created in a different thread).
	# http://pyobjc.sourceforge.net/documentation/pyobjc-core/intro.html
	objc, AppKit = None, None
	try:
		import objc
	except Exception:
		if sys.platform == "darwin":
			print "Error while importing objc"
			sys.excepthook(*sys.exc_info())
		# Otherwise it doesn't matter.
	try:
		# Seems that the `objc` module is not enough. Without `AppKit`,
		# I still get a lot of
		#   __NSAutoreleaseNoPool(): ... autoreleased with no pool in place - just leaking
		# errors.
		if objc:
			import AppKit
	except Exception:
		# Print error in any case, also ImportError, because we would expect that this works.
		print "Error while importing AppKit"
		sys.excepthook(*sys.exc_info())


	from State import state, modules
	import stdinconsole
	import gui

	try:
		# This will overtake the main loop and raise SystemExit at its end.
		gui.main()
	except SystemExit:
		raise
	
	for m in modules: m.start()

	successStartup = True

	# Note on quit behavior: Simply iterating state.updates
	# and waiting for its end does not work because we would
	# not interrupt on signals, e.g. KeyboardInterrupt.
	# It is also not possible (in general) to catch
	# signals from other threads, thus we have to do it here.
	# time.sleep() is a good way to wait for signals.
	# However, we use stdinconsole.readNextInput() because
	# there is simply no way to have os.read() in another thread
	# and to be able to interrupt that from here (the main thread).
	# In other threads: thread.interrupt_main() does not work
	# for time.sleep() (or at least it will not interrupt the sleep).
	# os.kill(0, signal.SIGINT) works, though.
	# To interrupt/stop all threads:
	# signal.set_wakeup_fd(sys.stdin.fileno()) also does not really
	# work to interrupt the stdin thread, probably because stdin is
	# not non-blocking.
	# Every thread must only wait on a OnRequestQueue which registers
	# itself in its thread. We cancelAll() here already the main queue
	# (state.updates) and in Module.stop(), we also cancel any custom
	# queue.

	while True:
		try: stdinconsole.readNextInput() # wait for KeyboardInterrupt
		except BaseException, e:
			state.updates.put((e, (), {}))
			state.updates.cancelAll()
			break
Exemplo n.º 44
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import coach
import gui
import sys

if __name__ == '__main__':
	
	file_name = sys.argv[1]
	c = coach.load(file_name)
	gui.main(c)
	coach.save(file_name, c)
Exemplo n.º 45
0
from gui import main

speed = 6
dist = 9
alt = 69
sensorData = [speed, dist, alt]
main()
Exemplo n.º 46
0
#!/usr/bin/env python
#
# (c) 2014 Productize <*****@*****.**>

import sys

def cli_main():
  if sys.argv[1] == 'collect':
    import collect
    collect.run()
    

if __name__ == '__main__':
  if len(sys.argv) == 1:
    import gui
    sys.exit(gui.main())
  else:
    cli_main()
Exemplo n.º 47
0
Arquivo: run.py Projeto: antroy/Home
import gui
import sys

gui.main(sys.argv)
Exemplo n.º 48
0
def main():
	gui.main("test.csv")
Exemplo n.º 49
0
import gui

if __name__ == '__main__':
    gui.main()
Exemplo n.º 50
0
      log.info("Error loading %s, %s", filename, e)

def main():
  options, args = parseOptions()
  log.info(options)

  ais = loadAI(args)
  loadMap(options.map)
  settings.IGNORE_EXCEPTIONS = not options.whiny
  if options.save_images:
    settings.SAVE_IMAGES = True
  if options.cli:
    try:
      cli.main(ais)
    except KeyboardInterrupt, e:
      pass
    finally:
      cli.end_game()
  else:
    try:
      gui.main(ais)
    except KeyboardInterrupt, e:
      gui.end_threads()
    finally:
      gui.end_game()

if __name__ == "__main__":
  import cProfile
  cProfile.run("main()", "mainprof")
#  main()
Exemplo n.º 51
0
utils.ExecingProcess.checkExec()

import sys, time
print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "on", appinfo.platform, "(%s)" % sys.platform
print "startup on", utils.formatDate(time.time())

from State import state, modules

if __name__ == '__main__':	

	import stdinconsole
	import gui

	try:
		# This will overtake the main loop and raise SystemExit at its end.
		gui.main()
	except SystemExit:
		raise
	
	for m in modules: m.start()

	# Note on quit behavior: Simply iterating state.updates
	# and waiting for its end does not work because we would
	# not interrupt on signals, e.g. KeyboardInterrupt.
	# It is also not possible (in general) to catch
	# signals from other threads, thus we have to do it here.
	# time.sleep() is a good way to wait for signals.
	# However, we use stdinconsole.readNextInput() because
	# there is simply no way to have os.read() in another thread
	# and to be able to interrupt that from here (the main thread).
	# In other threads: thread.interrupt_main() does not work
Exemplo n.º 52
0
#plt.rc('ylabel', labelsize=20)
#from scipy.optimize import curve_fit


import math
#import scipy
#import os
import methods
#import DataCursor
#import lgs
import Fittingtools
import gui
import Queue
if __name__=="__main__":
    Thread_queue = Queue.Queue()
    gui.main(Thread_queue)

quit()
def linfunk(x, m, b):
    y = m*x+b
    return y



path_to_data  =  "..\\Daten-bearbeitet\\Stahl ST37\\"
odf_name = "ST37_MTODF.txt"  # "AL_textur_complet.txt"

Data_Iron = methods.Data_old(path_to_data + odf_name, 6)
Data_Iron.read_scattering_SPODI_data(path_of_unstraind_data="Euler-Scans ohne Last\\",
                                     path_of_straind_data="Euler-Scans unter 5kN\\")
modi = ["reus", "voigt", "hill", "eshelby"]