示例#1
0
def view_test() -> bool:
    grid_world = grid.GridWorld(constants.GRID, rng)
    my_view = view.View(grid_world)
    my_view.open_window()
    my_view.display_and_wait()

    return True
示例#2
0
文件: control.py 项目: gavicus/stars
 def __init__(self):
   self.model = model.Model()
   self.view = view.View(self.model, self.viewCallback)
   self.view.draw()
   self.mouseButtons = [None,0,0,0,0,0]
   self.mouseLast = [None,0,0,0,0,0]
   self.loop()
示例#3
0
 def __init__(self, dir):
   self.model = model.Model(dir)
   self.model.setCWD()
   self.view = view.View(self)
   self.view.notify()
   self.search = False
   self.key =""
示例#4
0
	def resetGraph(self, event=None):
		
		self.v=view.View()
		#self.updateAxes()
		self.rotate.delete('1.0', tk.END)
		self.zoom.delete('1.0', tk.END)
		self.statslabel.delete('1.0',tk.END)
示例#5
0
    def __init__(self):
        # test a connection with the database
        try:
            print("Trying to connect to the database : '{}".format(
                config.DATABASE))
            self.database = mysql.connector.connect(user=config.USER,
                                                    password=config.PASSWORD,
                                                    host=config.HOST)
            print("\tConnection established")
        # if there is an error :
        except mysql.connector.Error as error:
            if error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("user'sname or password is wrong")
            elif error.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
            else:
                print(
                    "Connection with database failed: \n Detected error : \n%s"
                    % error)

        else:
            print("creating cursor ...")
            self.cursor = self.database.cursor()
            print("cursors created !")

        # this variable access to api
        self.api_access = api.Api(self.cursor)

        # This variable access to database.py
        self.db_access = database.Database(self.cursor)

        # This variable access to view.py
        self.request_access = view.View(self.cursor, self.database)
示例#6
0
 def __init__(self):
     '''We initiate and set variables to call different modules.'''
     self.pygame = pygame
     self.x = view.View()
     self.view = View_pygame.View()
     self.model = Model.Model()
     self.running = True
示例#7
0
 def __init__(self,
              user=None,
              password=None,
              view_=None,
              model_=None,
              debug=False,
              threads=1):
     if view_ == None:
         self.view = view.View()
     else:
         self.view = view_
     if model_ == None:
         self.model = model.Model()
     else:
         self.model = model_
     self.debug = debug
     self.user = user
     self.password = password
     maxthreads = threads
     self.pool_sema = threading.BoundedSemaphore(value=maxthreads)
     self.chomik = Chomik(self.view, self.model)
     if self.user == None:
         self.user = raw_input('Podaj nazwe uzytkownika:\n')
     if self.password == None:
         self.password = getpass.getpass('Podaj haslo:\r\n')
     self.view.print_('Logowanie')
     if not self.chomik.login(self.user, self.password):
         self.view.print_('Bledny login lub haslo')
         sys.exit(1)
示例#8
0
 def __init__(self, parent):
     self.parent = parent
     self.year = date.today().year
     self.index = date.today().timetuple().tm_yday - 1
     self.view = view.View(self)
     self.model = model.Model(self)
     self.view.currentDay()
示例#9
0
 def __init__(self):
     """
     Wczytywanie danych z plikow uploaded.txt i notuploaded.txt
     """
     self.view                  = view.View()
     self.lock                  = threading.Lock()
     ##synchronizacja zmiany katalogow w chomiku
     self.chdirs_lock           = threading.Lock()
     self.notuploaded_file_name = 'notdownloaded.txt'
     self.uploaded_file_name    = 'downloaded.txt'
     self.uploaded              = []
     self.notuploaded           = []
     
     if not os.path.exists(self.uploaded_file_name):
         open(self.uploaded_file_name, 'w').close()
     f = open(self.uploaded_file_name, 'r')
     self.uploaded = f.read().split('\n')
     self.uploaded = set([i.strip() for i in self.uploaded])
     f.close()
     #TODO: tu stanowczo jakis test zrobic
     if not os.path.exists(self.notuploaded_file_name):
     	open(self.notuploaded_file_name,"w").close()
     f     = open(self.notuploaded_file_name,"r")
     files = [ i.strip() for i in f.readlines()]
     f.close()
     self.notuploaded_resume = []
     self.notuploaded_normal = []
     self.pending            = []
     
     for f in files:
         try:
             filepath, filename, folder_id, chomik_id, token, host, port, stamp = re.findall("([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)", f)[0]
             self.notuploaded_resume.append( (filepath, filename, folder_id, chomik_id, token, host, port, stamp) )
         except IndexError, e:
             self.notuploaded_normal.append( f.strip() )
示例#10
0
    def run(self):
        # Instantiate the view
        # --------------------
        self.view = view.View(self)
        print("View instantiated")

        # Detect existing HDDs/USBs
        # -------------------------
        os.chdir("/dev/disk/by-id")
        try:
            for path in glob.glob("usb*"):
                # Try to automatically mount it
                device_path = os.path.realpath("/dev/disk/by-id/" +
                                               os.readlink(path))
                mounts = open("/proc/mounts")
                for line in mounts:
                    parts = line.split(' ')
                    if parts[0] == device_path and parts[1].startswith(
                            os.path.join('/media', getpass.getuser())):
                        path = parts[1]
                        self.backup_mediums[path] = model.BackupMedium(path)
                        self.view.drive_inserted(self.backup_mediums[path])
                mounts.close()
        except Exception as exception:
            print('Error while detecting existing HDDs/USBs {0}: {1}'.format(
                path, exception))

        # Start main loop
        # ---------------
        print("Running main loop")
        Gtk.main()
示例#11
0
def run_view(grid_start, agent1=ep2.RandomAgent, agent2=ep2.RandomAgent):
    """ Runs a game in the graphical mode """
    tank = util.TANK_CAPACITY
    problem = util.USPber(grid=grid_start,
                          multi_agent=True,
                          tank_capacity=tank)
    pl1 = agent1(player_number=1,
                 number_of_agents=2,
                 tank_capacity=tank,
                 max_depth=util.MAX_DEPTH)
    pl2 = agent2(player_number=2,
                 number_of_agents=2,
                 tank_capacity=tank,
                 max_depth=util.MAX_DEPTH)

    if util.SHOW_INFO:
        print("********************")
        print("   Starting game    ")
        print("********************")
        print("Initial board")
        for line in grid_start:
            print(line)

    ctrl = GameControlller(problem, pl1, pl2)

    game_view = view.View(controller=ctrl, gridboard=grid_start)
    game_view.root.mainloop()
示例#12
0
 def __init__(self,fuzzySystem, filename="input.in"):
     self.__view = view.View(fuzzySystem)
     self.__system = fuzzySystem
     self.__inputs = []
     self.__currentInput = -1
     self.__filename = filename
     self.__readInputs()
示例#13
0
def debug_fun(tb):
    """
    tb = traceback
    """
    v = view.View()
    st = traceback.format_tb(tb)
    stack = []
    while tb:
        stack.append(tb.tb_frame)
        tb = tb.tb_next
    #traceback.print_exc()
    v.print_("-" * 10)
    v.print_(''.join(st))
    v.print_("Locals by frame, innermost last")
    for frame in stack:
        v.print_()
        v.print_(
            "Frame %s in %s at line %s" %
            (frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno))
        for key, value in frame.f_locals.items():
            try:
                v.print_("\t%20s = " % key, value)
            except:
                v.print_("<ERROR WHILE PRINTING VALUE>")
    v.print_("-" * 10)
示例#14
0
def blog_wsgi_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/html')]  # HTTP Headers
    start_response(status, headers)

    blog_post = view.View()

    path = environ['PATH_INFO']
    #output = getOutput(URL_routing[path])

    if path == '/create':
        output = blog_post.new_post(environ)
    elif path == '/display_post_links':
        #method = URL_routing[path]
        #output = blog_post.method
        output = blog_post.display_post_links()
    elif path.find('/id/') != -1:
        parsed_path = path.split("/")

        try:
            post_id = int(
                parsed_path[2]
            )  #obtain ID for clicked post, should be second item of path. if no error is thrown then it can be converted to an int and is therefore a string.
            output = blog_post.display_post(str(post_id))
        except (ValueError):
            output = '404 Error'
    elif path == '/':
        output = blog_post.render_main(environ)
    else:
        output = '404 Error'

    return output
示例#15
0
    def __init__(self, playerX_is_ai, playerO_is_ai):
        if not Controller.__instance:
            self.model = model.Model()
            self.view = view.View("Quixo")

            if (playerX_is_ai == 'ai'):
                self.model.playerX.is_ai = True
            else:
                playerX_is_ai = False

            if (playerO_is_ai == 'ai'):
                self.model.playerO.is_ai = True
            else:
                playerO_is_ai = False

            for i in range(0, 5):
                for j in range(0, 5):
                    self.view.matrixOfButton[i][j] = self.createButton(i, j)
                    if (i != 0 and i != 4 and j != 0 and j != 4):
                        view.disableButton(self.view.matrixOfButton[i][j])
                    self.view.matrixOfButton[i][j].grid(row=i, column=j)

            if (self.model.activePlayer.is_ai == True):
                self.model.aiPlay()
                self.setBoardFromSimplified(self.model.board)

            self.view.root.mainloop()
        else:
            self.getInstance()
示例#16
0
    def __init__(self, width, height):

        # create a tk object, which is the root window
        self.root = tk.Tk()

        # width and height of the window
        self.initDx = width
        self.initDy = height

        # set up the geometry for the window
        self.root.geometry("%dx%d+50+30" % (self.initDx, self.initDy))

        # set the title of the window
        self.root.title("Tony's Data Dots")

        # set the maximum size of the window for resizing
        self.root.maxsize(1600, 900)

        # setup the menus
        self.buildMenus()

        # build the controls
        self.buildControls()

        # build the Canvas
        self.buildCanvas()

        # bring the window to the front
        self.root.lift()

        # - do idle events here to get actual canvas size
        self.root.update_idletasks()

        # now we can ask the size of the canvas
        print self.canvas.winfo_geometry()

        # set up the key bindings
        self.setBindings()

        # set up the application state
        self.objects = [
        ]  # list of data objects that will be drawn in the canvas
        self.data = None  # will hold the raw data someday.
        self.baseClick = None  # used to keep track of mouse movement

        #------------------------------------#Project3, Task1
        #task1.a
        self.view = v.View()

        #task1.b
        self.axesEndpoints = np.matrix([
            [0, 0, 0, 1],  #x_origin
            [1, 0, 0, 1],  #x_endpoint
            [0, 0, 0, 1],  #y_origin
            [0, 1, 0, 1],  #y_endpoint
            [0, 0, 0, 1],  #z_origin
            [0, 0, 1, 1]
        ])  #z_endpoint
        #task1.c
        self.axes = []
示例#17
0
 def __init__(self,
              user=None,
              password=None,
              view_=None,
              model_=None,
              debug=False):
     if view_ == None:
         self.view = view.View()
     else:
         self.view = view_
     if model_ == None:
         self.model = model.Model()
     else:
         self.model = model_
     self.debug = debug
     self.user = user
     self.password = password
     self.notuploaded_file = 'notuploaded.txt'
     self.uploaded_file = 'uploaded.txt'
     self.chomik = Chomik(self.view, self.model, debug=self.debug)
     if self.user == None:
         self.user = raw_input('Podaj nazwe uzytkownika:\n')
     if self.password == None:
         self.password = getpass.getpass('Podaj haslo:\r\n')
     self.view.print_('Logowanie')
     if not self.chomik.login(self.user, self.password):
         self.view.print_('Bledny login lub haslo')
         sys.exit(1)
示例#18
0
    def setup_views(self, requestedViews, results):
        self.requestedViews = requestedViews
        # Check for availability of CALMA data
        hasCalma = False
        try:
            for result in results['results']['bindings']:
                if len(result['calma']['value']) > 0:
                    hasCalma = True
        except Exception as e:
            print(e)
            pass

        # Remove previous views on screen
        toRemove = self.main.searchForm.topLevelSearchLayout.takeAt(1)
        toRemove.widget().deleteLater()

        # Create new view
        self.view = view.View(self.main, self, requestedViews, results,
                              hasCalma)

        # Add new view to layout
        self.main.searchForm.topLevelSearchLayout.addWidget(
            self.view.get_widget())

        # Check span is still correct in top level layout
        self.main.searchForm.topLevelSearchLayout.setStretch(0, 2)
        self.main.searchForm.topLevelSearchLayout.setStretch(1, 8)

        # Set results to viewable if not already
        self.main.searchForm.leftSideWidget.setTabEnabled(1, True)
    def factory(self, applet, iid):
        print applet
        print iid
        # homebrew MVC
        V = view.View()
        M = model.TogglModel()
        V.set_model(M.generate_liststore())
        self.appwin.add(V.treeview)
        self.appwin.resize(400, 300)
        #self.appwin.add(gtk.Label('hi there'))

        im = gtk.Image()
        im.set_from_file("/home/up45/github/toggl-gnome-applet/logo-small.png")
        ebox = gtk.EventBox()

        ebox.add(im)
        ebox.connect('button-press-event', self.button_press)
        #applet.set_background_widget(applet)
        #applet.connect('button-press-event',button_press)
        applet.add(ebox)

        applet.show_all()
        print applet.window

        return gtk.TRUE
 def handleResetButton(self):
     print('handling reset button')
     self.vobj = view.View().clone()
     self.updateAxes()
     self.updatePoints()
     self.updateLabels()
     self.updateFits()
示例#21
0
def main(args):
    # TODO: command line argument to do this properly.
    # HOST = socket.gethostbyname(socket.gethostname())
    HOST = args.server
    PORT = args.port
    username = args.username
    nickname = args.nickname

    # Start a thread to wait for messages coming back from host
    client = IRCClient(HOST, PORT, username, nickname)
    thread = threading.Thread(target=client.run)
    thread.start()
    logger.debug(f'[IRCClient] Client thread started')

    logger.info(f"Client object created")
    with view.View() as v:
        logger.info(f"Entered the context of a View object")
        client.set_view(v)
        logger.debug(f"Passed View object to IRC Client")
        v.add_subscriber(client)
        logger.debug(f"IRC Client is subscribed to the View (to receive user input)")
        async def inner_run():
            await asyncio.gather(
                v.run(),
                return_exceptions=True,
            )
        try:
            asyncio.run( inner_run() )
        except KeyboardInterrupt:
            logger.debug(f"Signifies end of process")
    client.close('IRC Client object terminated')
示例#22
0
def main(args):
    # Pass your arguments where necessary
    client = IRCClient(args[0])

    logger.info(f"Client object created")
    with view.View() as v:
        logger.info(f"Entered the context of a View object")
        client.set_view(v)
        logger.debug(f"Passed View object to IRC Client")
        v.add_subscriber(client)
        logger.debug(
            f"IRC Client is subscribed to the View (to receive user input)")

        async def inner_run():
            await asyncio.gather(
                v.run(),
                client.run(),
                return_exceptions=True,
            )

        try:
            asyncio.run(inner_run())
        except KeyboardInterrupt as e:
            logger.debug(f"Signifies end of process")
    client.close()
示例#23
0
def main(args):
    # Pass your arguments where necessary
    client = IRCClient(args.nickname, args.host, args.port)
    logger.info(f"Client object created")
    with view.View() as v:
        logger.info(f"Entered the context of a View object")
        client.set_view(v)
        client.add_msg_from_other(
            "info",
            "Type /connect <username> <serverhost> <serverport> <realname> to connect to a "
            "server!")
        logger.debug(f"Passed View object to IRC Client")
        v.add_subscriber(client)
        logger.debug(
            f"IRC Client is subscribed to the View (to receive user input)")

        async def inner_run():
            await asyncio.gather(
                v.run(),
                client.run(),
                return_exceptions=True,
            )

        try:
            asyncio.run(inner_run())
        except KeyboardInterrupt as e:
            logger.debug(f"Signifies end of process")
    client.close()
示例#24
0
    def __init__(self, width, height):

        # create a tk object, which is the root window
        self.root = tk.Tk()

        # width and height of the window
        self.initDx = width
        self.initDy = height

        # set up the geometry for the window
        self.root.geometry("%dx%d+50+30" % (self.initDx, self.initDy))

        # set the title of the window
        self.root.title("Random Datapoints")

        # set the maximum size of the window for resizing
        self.root.maxsize(1600, 900)

        # setup the menus
        self.buildMenus()

        # build the controls
        self.buildControls()

        # build the Canvas
        self.buildCanvas()

        # bring the window to the front
        self.root.lift()

        # - do idle events here to get actual canvas size
        self.root.update_idletasks()

        # now we can ask the size of the canvas
        print self.canvas.winfo_geometry()

        # set up the key bindings
        self.setBindings()

        # set up the application state
        self.objects = [
        ]  # list of data objects that will be drawn in the canvas
        self.data = None  # will hold the raw data someday.
        self.baseClick = None  # used to keep track of mouse movement

        #create new view object
        self.v = view.View()

        #created matrix of endpoints of x,y, and z axes
        self.axes = np.matrix([[0, 0, 0, 1], [1, 0, 0, 1], [0, 0, 0, 1],
                               [0, 1, 0, 1], [0, 0, 0, 1], [0, 0, 1, 1]])

        #list to store the lines for the x, y, and z axes
        self.lines = [0, 0, 0]

        #calls buildAxes function
        self.buildAxes()

        #calls updateAxes function
        self.updateAxes()
示例#25
0
def main():

    
    #ed_user = User(Name='Bogdan', Email='LLLLLLLLS', N_sub=2225)
    #session.add(ed_user)
    #session.commit()
    c = cont.Controller(mod.Model(), view.View())
    c.menu()
示例#26
0
 def __init__(self):
     self.fp = fp.FilePicker()
     self.v = view.View(self)
     self.v.init()
     self.bindEvents()
     self.v.displayProgram()
     self.v.afficherMenu()
     self.v.root.mainloop()
示例#27
0
def setup_gui():
    if GUI_ENABLED:
        root = tkinter.Tk()
        main_view = view.View(root, BOARDWIDTH, BOARDHEIGHT)
    else:
        root = None
        main_view = None
    return root, main_view
示例#28
0
def main():
    g = grid.grid(40,120)
    ml = Model(g)
    vw=view.View(ml,g)

    main_loop = urwid.MainLoop(vw.fill, vw.palette,unhandled_input=vw.unhandled_input)
    main_loop.set_alarm_in(1, vw.callback,user_data={"mod":ml,"vw":vw})
    main_loop.run()
示例#29
0
 def __init__(self):
     self.root = tkinter.Tk()
     self.grid = grid.Grid(self.root, 10, 20)
     self.view = view.View(self.root, self.grid)
     self.view.bind('<Key>', self.handleKey)
     self.root.protocol("WM_DELETE_WINDOW", self.handleClose)
     self.closed = False
     self.timer = Timer()
     self.scoreName = ''
示例#30
0
文件: nvpy.py 项目: LeHack/nvpy
    def __init__(self, config):
        # should probably also look in $HOME
        self.config = config
        self.config.app_version = VERSION

        # configure logging module
        #############################

        # first create db directory if it doesn't exist yet.
        if not os.path.exists(self.config.db_path):
            os.mkdir(self.config.db_path)

        log_filename = os.path.join(self.config.db_path, 'nvpy.log')
        # file will get nuked when it reaches 100kB
        lhandler = RotatingFileHandler(log_filename,
                                       maxBytes=100000,
                                       backupCount=1)
        lhandler.setLevel(logging.DEBUG)
        lhandler.setFormatter(
            logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s'))
        # we get the root logger and configure it
        logger = logging.getLogger()
        if self.config.debug == 1:
            logger.setLevel(logging.DEBUG)
        logger.addHandler(lhandler)
        # this will go to the root logger
        logging.debug('nvpy logging initialized')

        logging.debug('config read from %s' % (str(self.config.files_read), ))

        if self.config.sn_username == '':
            self.config.simplenote_sync = 0

        css = self.config.rest_css_path
        if css:
            if css.startswith("~/"):
                # On Mac, paths that start with '~/' aren't found by path.exists
                css = css.replace("~",
                                  os.path.abspath(os.path.expanduser('~')), 1)
                self.config.rest_css_path = css
            if not os.path.exists(css):
                # Couldn't find the user-defined css file. Use docutils css instead.
                self.config.rest_css_path = None

        self.notes_list_model = NotesListModel()
        # create the interface
        self.view = view.View(self.config, self.notes_list_model)

        # read our database of notes into memory
        # and sync with simplenote.
        try:
            self.notes_db = NotesDB(self.config)

        except ReadError, e:
            emsg = "Please check nvpy.log.\n" + str(e)
            self.view.show_error('Sync error', emsg)
            exit(1)