コード例 #1
0
ファイル: main.py プロジェクト: diN0bot/miller
def run_app(moves):
    """
    @param moves: iterable of Move objects
    """
    try:
        controller = Controller(settings.SERIAL_PORT)
        controller.set_board(moves)
        
        gui = GUI(controller)
        gui.drawer.init_pen('simmove', 400)
        
        controller.set_gui(gui)
    
        # set start position
        controller.virtualmachine.position[0] = 1
        controller.virtualmachine.position[1] = 1
        #For some reason setting this also changes the local computer movetable!!! Why???
        controller.virtualmachine.position[2] = 0.002
        
        # mill board!
        controller.mill_board()
    
        # gui should continue running until user presses escape key
        while True:
            gui.check_events()
            time.sleep(0.2)
    except Exception, error:
        print " ERROR "
        print Exception, error
        self.controller.exit()
        sys.exit(0)
コード例 #2
0
ファイル: Editor.py プロジェクト: stephenmm/pynsource
class Editor:
    def __init__(self):
        self.topHandler = TopHandler()
        self.GUI = GUI(self.topHandler)
        self.topHandler.setGUI(self.GUI)
        self.statechart = Statechart(self.GUI.getStatechartHandler())
        self.statechart.setCanvas(self.GUI.getCanvas())
        self.topHandler.setStatechart(self.statechart)

    def start(self):
        self.GUI.mainloop()
コード例 #3
0
ファイル: Main.py プロジェクト: JacobLuke/minesweeper
class Minesweeper(object):
  def __init__ (self, *args):
    self.settings = Settings()
    self.game = self.getGame()
    
    self.gui = GUI(self.settings, self.game)
  
  def getGame(self):
    mode = self.settings['MODE']
    if mode in game_by_mode:
      return game_by_mode[mode](self.settings)
    elif mode is None:
      gui = SettingsGUI(self.settings)
      if gui.cancelled:
        sys.exit(0)
      return self.getGame()
    elif not isinstance(mode, tuple) or len(mode) != 3:
      raise ValueError("expected 3-tuple for Custom Game, got {0}".format(mode))
    return Game(self.settings,*mode)
  
  def run(self):
    return self.gui.start()
  
  def restart (self):
    self.game = self.getGame()
    self.gui = GUI(self.settings, self.game)
コード例 #4
0
ファイル: Editor.py プロジェクト: stephenmm/pynsource
 def __init__(self):
     self.topHandler = TopHandler()
     self.GUI = GUI(self.topHandler)
     self.topHandler.setGUI(self.GUI)
     self.statechart = Statechart(self.GUI.getStatechartHandler())
     self.statechart.setCanvas(self.GUI.getCanvas())
     self.topHandler.setStatechart(self.statechart)
コード例 #5
0
ファイル: activity.py プロジェクト: Bundloleers/bundle
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self._name = handle
        # Set up logging. We're sending messages to the default log directory,
        # which can be browsed with the Log activity.
        
        self._logger = logging.getLogger('bundle.BundleActivity')
        self._logger.setLevel(logging.DEBUG) # Show ALL messages
        # self._logger.setLevel(logging.WARNING) # Ignore DEBUG/INFO msgs
        self._logger.debug("Initializing BundleActivity.")

        # Set title for our Activity
        self.set_title('Bundle Activity')

        # Attach sugar toolbox (Share, ...)
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        #toolbox.show()
        
        self.activity_toolbar = toolbox.get_activity_toolbar()
        
        #create toolbar
        self.main_toolbar = gtk.Toolbar()
        #self.main_toolbar.show()
        
        toolbox.add_toolbar(_('Bundle'),  self.main_toolbar)
        toolbox.set_current_toolbar(1)
        toolbox.show()
        
        # Create the main container
        self._main_view = gtk.VBox()

        # Import our class Bundle():

        # Step 1: Load class, which creates Bundle.widget
        self.myBundle = Bundle(None)
        self._logger.debug("Bundle instance created.")
        self.myBundle.parent = self
        
        self.myGUI = GUI(self)
        self.myGUI.xid = handle
        self.myGUI.myBundle = self.myBundle
        self.myGUI.set_bundle(self.myBundle)
        #self.myGUI.parent = self
 
        # Step 3: We attach that widget to our window
        self._main_view.pack_start(self.myGUI.widget)

        # Display everything
        self.myGUI.widget.show()
        self._main_view.show()
        self.set_canvas(self._main_view)
        self.show_all()
        
        self.scratchDir = os.path.join(self.get_activity_root(),  'instance')
        self._logger.debug("Scratch dir is %s", self.scratchDir)
        self._logger.debug("__init__() finished")
        
        self.activityRegistry = ActivityRegistry()
コード例 #6
0
ファイル: Main.py プロジェクト: liniii/Real_time_sys_project
def main():
        
        #Create new threads
        comedi = ComediCom()
        mon = Monitor()
        Gui_Thread = GUI(mon, comedi)
        RefThread = ReferenceGenerator(mon)
        ControlThread = Controller(mon, comedi)

        # set daemon = True to connect all threads exit states such that when one exits, all does
        ControlThread.daemon = True
        RefThread.daemon = True

        # Start new Threads
        ControlThread.start()
        Gui_Thread.start()
        RefThread.start()
コード例 #7
0
ファイル: client.py プロジェクト: Henning-Klatt/Robot
def main(DEBUG=True):
    screen_width  = 400
    screen_height = 300
    stream_resolution = (320, 240)

    try:

        listener = inputDevice()
        tkinter_app = GUI(host='192.168.1.1', port=8000, resolution="1440x900", stream_resolution=stream_resolution)
        tkinter_app.run()

    except (KeyboardInterrupt, SystemExit):
        print('Quit')
        tkinter_app.quit()
    except Exception as error:
        print('Error: ' + str(error))
        exit()
コード例 #8
0
ファイル: Scene.py プロジェクト: agakax/arkanoid
 def __init__(self, base, gameEngine, gameState):
     self.__base = base
     self.__gameEngine = gameEngine
     self.setCamera()
     self.__base.taskMgr.add(self.updateTask, "updateTask")
     self.__gameEngine.accept('a', self.switchColliderDisplay)
     self.__gameEngine.accept('r', self.restart)
     self.__gameEngine.accept('escape', self.backToMenu)
     self.__gameState = gameState
     self.__gui = GUI(self.__gameEngine, self.__base, self.__gameState)
     self.__background = ParallaxBackground(self.__gameEngine, self.__base)
コード例 #9
0
ファイル: ReaderProgram.py プロジェクト: Tiacs/gb-reader
class ReaderProgram:
    def __init__(self):
        self.gui = GUI(self.readHeader, self.readGame, self.startGame,
                       self.refreshCOMList, self.changeCOMDevice,
                       self.saveFile)

        self._reader = None
        self._cartridge = None

    def run(self):
        self._reader = None
        #self.initReader("COM1")
        self.gui.mainloop()

    def initReader(self, com):
        self.gui.setError("")
        self.gui.setInfoButtonEnabled(False)
        self.gui.setReadButtonEnabled(False)
        self.gui.setStartButtonEnabled(False)
        try:
            if self._reader is not None:
                self._reader.close()
            self._reader = GBReader(com)

            self.gui.setInfoButtonEnabled(True)
        except NoGBReaderException as e:
            self.gui.setError("No GBC Reader connected at " + com + "!")
            sys.stdout.write("\033[31mNo GBC Reader connected at" + com +
                             "!\n")
            sys.stdout.write("\033[31mFurther information:\n")
            print(e)

    def readHeader(self):
        self.gui.setError("")
        self.gui.setInfoButtonEnabled(True)
        self.gui.setReadButtonEnabled(False)
        self.gui.setStartButtonEnabled(False)

        try:
            self._cartridge = self._reader.readCartridgeHeader()
            self.gui.setTitle(self._cartridge.gameTitle)
            self.gui.setFlag(self._cartridge.cgbFlag)
            self.gui.setSize(str(self._cartridge.romSizeKB) + " KB")
            self.gui.setType(self._cartridge.cartridgeType)
            self.gui.setBanks(self._cartridge.romBankCount)

            logo = NintendoLogo(
                self._cartridge.nintendoLogo)  # create nintendo logo from data
            self.gui.setImage(logo.getImage())

            self.gui.setReadButtonEnabled(True)
        except serial.serialutil.SerialException:
            self.gui.setError("No GBC Reader connected!")
            sys.stdout.write("\033[31mNo GBC Reader connected!\n")
        except UnknownGBDataException as e:
            self.gui.setError(
                "Undefined data read from the cartridge! Are you sure a cartridge is connected?"
            )
            sys.stdout.write(
                "\033[31mError loading CartridgeHeader! Unknown Data!\n")
            sys.stdout.write("\033[31mFurther information:\n")
            print(e)

    def readGame(self):
        self.gui.setError("")
        self.gui.setInfoButtonEnabled(False)
        self.gui.setReadButtonEnabled(False)
        self.gui.setStartButtonEnabled(False)

        thread = Thread(target=self._readGame)
        thread.start()

    def _readGame(self):
        try:
            self._reader.readGameData(self._cartridge, self.gui.setProgress)
            self.gui.setInfoButtonEnabled(True)
            self.gui.setReadButtonEnabled(True)
            self.gui.setStartButtonEnabled(True)

            if self._reader.checkGlobalChecksum(self._cartridge):
                print('Checksum correct!')
            else:
                self.gui.setError(
                    "Checksum incorrect! A real Game Boy would not care.")
                print('Checksum incorrect!')
        except GBCartridgeChangedException as e:
            self.gui.setError(
                "Error loading Cartridge! Cartridge has changed since reading header information! Please try again!"
            )
            sys.stdout.write(
                "\033[31mError loading Cartridge! Cartridge has changed since reading header information!\n"
            )
            sys.stdout.write("\033[31mPlease try again!\n")

    def startGame(self):
        self.gui.setError("")
        self.gui.setInfoButtonEnabled(False)
        self.gui.setReadButtonEnabled(False)
        self.gui.setStartButtonEnabled(False)

        thread = Thread(target=self._startGame)
        thread.start()

    def _startGame(self):
        filename = "temp.gb"
        file = open(filename, 'wb')
        self._reader.saveROMFile(self._cartridge, file)
        file.close()

        p = subprocess.Popen("./emulator/bgb.exe run " + filename)
        p.wait()

        os.remove(filename)

        self.gui.setInfoButtonEnabled(True)
        self.gui.setReadButtonEnabled(True)
        self.gui.setStartButtonEnabled(True)

    def saveFile(self):
        if self._cartridge is None or self._cartridge.gameData is None:
            showerror("GameBoy Reader - Error",
                      "You have to read a cartridge first!")
            return

        file = asksaveasfile(mode='wb',
                             initialfile=self._cartridge.gameTitle + '.gbc',
                             filetypes=[('gbc roms', '.gbc')])
        self._reader.saveROMFile(self._cartridge, file)
        showinfo("GameBoy Reader - Done", "Game Boy ROM saved!")

    def refreshCOMList(self):
        ports = list(list_ports.comports())
        self.gui.setCOMList(ports)

    def changeCOMDevice(self, comDevice):
        self.initReader(comDevice)
コード例 #10
0
 def create_origin_face(self):
     self.open_camera('create_origin_face', 'origin')
     cv2.waitKey(1000)
     self.catch_face('origin.jpg', 'origin')
     GUI.popupmsg("新增人臉完成")
コード例 #11
0
ファイル: Scene.py プロジェクト: agakax/arkanoid
class Scene(object):
    __gameEngine = None
    __cameraPosition = LPoint3f(38, -80, 65)
    __cameraDirection = LPoint3f(0, -25, 0)
    __objects = []
    __gui = None
    __background = None
    __gameState = None

    def __init__(self, base, gameEngine, gameState):
        self.__base = base
        self.__gameEngine = gameEngine
        self.setCamera()
        self.__base.taskMgr.add(self.updateTask, "updateTask")
        self.__gameEngine.accept('a', self.switchColliderDisplay)
        self.__gameEngine.accept('r', self.restart)
        self.__gameEngine.accept('escape', self.backToMenu)
        self.__gameState = gameState
        self.__gui = GUI(self.__gameEngine, self.__base, self.__gameState)
        self.__background = ParallaxBackground(self.__gameEngine, self.__base)

    def setCamera(self):
        self.__base.disableMouse()
        self.__base.camera.setPos(self.__cameraPosition)
        self.__base.camera.setHpr(self.__cameraDirection)

    def showMenu(self):
        self.__gui.showMenu()
        pass

    def loadGame(self, isPreviousStatePause):
        if not isPreviousStatePause:
            self.destroyObjects()
            self.__objects.append(Board(self.__gameEngine, self.__base))
            self.__objects.append(Paddle(self.__gameEngine, self.__base, self.__background))
            self.__objects.append(Ball(self.__gameEngine, self.__base, self))
            self.__objects.append(LevelBlocks(self.__gameEngine, self.__base))
            self.__objects[3].loadLevelBlocks()
            self.drawObjects()

    def pauseGame(self):
        pass

    def destroyObjects(self):
        for obj in self.__objects:
            obj.destroy()
        del self.__objects[:]

    def drawObjects(self):
        for obj in self.__objects:
            obj.draw()

    def updateTask(self, task):
        elapsedTime = self.__gameEngine.getTime()
        self.__gui.update(elapsedTime)
        for obj in self.__objects:
            obj.update(elapsedTime)
        return task.cont

    def switchColliderDisplay(self):
        global collshow
        collshow=not collshow
        if collshow:
            self.__base.cTrav.showCollisions(self.__base.render)
            l=self.__base.render.findAllMatches("**/+CollisionNode")
            for cn in l: cn.show()
        else:
            self.__base.cTrav.hideCollisions()
            l=self.__base.render.findAllMatches("**/+CollisionNode")
            for cn in l: cn.hide()

    def restart(self):
        self.destroyObjects()
        self.__gui.hideGameOver()
        self.loadGame(False)

    def ballLost(self):
        self.__gui.showGameOver()

    def backToMenu(self):
        self.destroyObjects()
        self.__gui.backToMenu()
コード例 #12
0
    return game, possible_actions


with tf.Session() as sess:

    PGNetwork = PGNetwork(state_shape=state_size,
                          action_shape=action_size,
                          learning_rate=learning_rate,
                          name="PGNetwork")
    game, possible_actions = create_environment()
    totalScore = 0
    saver = tf.train.Saver()

    saver.restore(sess, "./PGModels_v1/model.ckpt")
    window = GUI(50)

    step = 0

    for i in range(10):

        game.newInstance()
        while not game.gameEnd():
            step += 1
            if (step == 30):
                print("TOTAL_SCORE", totalScore)
                step = 0
            frame = game.getState()
            print(frame)
            action_probability_distribution = sess.run(
                PGNetwork.action_distribution,
コード例 #13
0
ファイル: Main.py プロジェクト: JacobLuke/minesweeper
 def __init__ (self, *args):
   self.settings = Settings()
   self.game = self.getGame()
   
   self.gui = GUI(self.settings, self.game)
コード例 #14
0
ファイル: main.py プロジェクト: Avabin/ai-arms
from math import sin, cos, radians
from random import randint

import sys
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QApplication, QWidget
from Drone import Position, Drone
from GUI import GUI
from move import Move, generate_moves


if __name__ == '__main__':

    app = QApplication(sys.argv)

    w = GUI()

    w.init_gui()

    sys.exit(app.exec_())
コード例 #15
0
def game():
    altura = 600
    largura = 1230
    mainClock = pygame.time.Clock()
    screen = pygame.display.set_mode((largura, altura), 0, 32)

    vel = 10
    anim = 0
    home = pygame.image.load("images\home.png")
    IdleDonw = pygame.image.load("images\spritesTestes\imagem_1.png")
    IdleLeft = pygame.image.load("images\spritesTestes\imagem_4.png")
    IdleUp = pygame.image.load("images\spritesTestes\imagem_7.png")
    IdleRigth = pygame.image.load("images\spritesTestes\imagem_10.png")
    animImgDonw = ["images\spritesTestes\imagem_1.png", "images\spritesTestes\imagem_2.png",
                   "images\spritesTestes\imagem_1.png", "images\spritesTestes\imagem_3.png"]
    animImgLeft = ["images\spritesTestes\imagem_4.png", "images\spritesTestes\imagem_5.png",
                   "images\spritesTestes\imagem_4.png", "images\spritesTestes\imagem_6.png"]
    animImgUP = ["images\spritesTestes\imagem_7.png", "images\spritesTestes\imagem_8.png",
                 "images\spritesTestes\imagem_7.png", "images\spritesTestes\imagem_9.png"]
    animImgRight = ["images\spritesTestes\imagem_10.png", "images\spritesTestes\imagem_11.png",
                    "images\spritesTestes\imagem_10.png", "images\spritesTestes\imagem_12.png"]
    pos_x = 340
    pos_y = 130
    vida = 30
    vidaS = "Vida: "
    dire = [animImgDonw, animImgLeft, animImgRight, animImgUP]
    çao = 0
    character = pygame.image.load("images\spritesTestes\imagem_1.png")
    screen.blit(home, (0, 0))
    screen.blit(character, (pos_x, pos_y))
    running = True
    while running:
        screen.fill((0, 0, 0))
        keys = pygame.key.get_pressed()
        character = pygame.image.load(dire[çao][0])
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                if event.key == pygame.K_m:
                    GUI()
        if keys[pygame.K_LEFT]:
            pos_x -= vel
            anim += 1
            çao = 1
            if anim == 4:
                anim = 0
            character = pygame.image.load(animImgLeft[anim])
        if keys[pygame.K_RIGHT]:
            pos_x += vel
            anim += 1
            çao = 2
            if anim == 4:
                anim = 0
            character = pygame.image.load(animImgRight[anim])
        if keys[pygame.K_UP]:
            pos_y -= vel
            anim += 1
            çao = 3
            if anim == 4:
                anim = 0
            character = pygame.image.load(animImgUP[anim])
        if keys[pygame.K_DOWN]:
            pos_y += vel
            anim += 1
            çao = 0
            if anim == 4:
                anim = 0
            character = pygame.image.load(animImgDonw[anim])
        if pos_x >= 640:
            pos_x -= 10
        if pos_y >= 420:
            pos_y -= 10
        if pos_x <= 30:
            pos_x += 10
        if pos_y <= 70:
            pos_y += 10
        pos_y = collisaCimaHorizontal(40, 310, 330, pos_x, pos_y)
        pos_x = collisaEsquerdaParedeVertical(340, 360, 250, pos_x, pos_y)
        pos_y = collisaCimaHorizontal(200, 250, 360, pos_x, pos_y)
        pos_x = collisaEsquerdaParedeVertical(340, 380, 210, pos_x, pos_y)
        pos_y = collisaCimaHorizontal(160, 210, 380, pos_x, pos_y)
        pos_x = collisaDireitaVertical(340, 390, 150, pos_x, pos_y)
        pos_y = collisaCimaHorizontal(40, 80, 380, pos_x, pos_y)
        pos_x = collisaEsquerdaParedeVertical(240, 330, 310, pos_x, pos_y)
        pos_x = collisaEsquerdaParedeVertical(340, 360, 110, pos_x, pos_y)
        screen.blit(home, (0, 0))
        EscrV = textt(vidaS+"{}".format(vida), (225, 225, 225), screen, 30, 30)
        EscrV.draw_text1()
        screen.blit(character, (pos_x, pos_y))
        pygame.display.update()
        mainClock.tick(10)
        print(pos_y, pos_x)
        pygame.display.update()
コード例 #16
0
 def OnClick_button_Test(self):
     GUI.DisplayDialog("SettingDialog")
コード例 #17
0
WORLD_X = 500
WORLD_Y = 300

actualX = 100
actualY = 100
particles = list()
fvel = 2
rvel = 0

for N in range(0,1000):
    x = random.randint(0,WORLD_X) # initial x position
    y = random.randint(0,WORLD_Y) # initial y position
    orientation = random.randint(0,360) # initial orientation

    par = Robot([x,y,orientation],fvel,rvel,WORLD_X,WORLD_Y)
    particles.append(par)

for robots in particles:
    robots.setNoise(5.0,50.0)
    robots.destDistance = 200

actaulRobot = Robot([actualX,actualY,45],fvel,rvel,WORLD_X,WORLD_Y,color='green')
actaulRobot.setNoise(5.0,15.0)
actaulRobot.destDistance = 200

particles.append(actaulRobot)

world = GUI([WORLD_X,WORLD_Y],particles)
world.createWorld()

コード例 #18
0
ファイル: Main.py プロジェクト: luigisayson/Othello
import Menu
from GUI import GUI

if __name__ == "__main__":
    dimensions = Menu.Menu().get_dimensions()
    GUI(dimensions[0], dimensions[1]).start()
コード例 #19
0
class Main():
    # Main function takes in parameters about GUI and kicks off GUI window setup according to with GUI or without GUI
    # Mode = 1 for interactive GUI
    # Mode = 2 for Command line control with GUI
    # Mode = 3 for Command line control with no GUI in 1 player mode
    # Mode = 4 for Command line control with no GUI in 2 player mode
    def __init__(self, mode = 1):
        self.game = ""
        self.game_mode = mode
        # GUI enabled game
        if self.game_mode == 1:
            # Create GUI object
            self.gui = GUI(self)

            # Loop gui
            self.loop()


        # GUI enabled main without loop
        elif self.game_mode == 2:
            self.gui = GUI(self)

        # Comand line control with no GUI
        elif self.game_mode == 3:
            self.game = Game()

        elif self.game_mode == 4:
            self.game = Game()

        else:
            print("Not a selection!")

    # returns True or False based on whether the game is in the pawn promo state
    def is_pawn_promo_state(self):
        if len(self.game.moves) != 0:
            # TODO: make corresponding passing function in game
            return self.game.moves[-1].pawn_promo
        return -1

    # Chooses pawn promotion piece when in pawn promo state
    def choose_pawn_promo(self, piece):
        # If the game is in pawn promo stage
        if self.is_pawn_promo_state() == 'ready':
            # Make pawn promotion
            self.game.make_pawn_promo(piece)
            self.gui.destroy_popup()
        else:
            print('Not in pawn promo state')

        # Rebuild the game board buttons if gui is used
        if self.game_mode <= 2:
            self.gui.sync_board()

    # Function to undo a move on the board
    def undo(self):
        self.game.undo_move()

        # Rebuild the game board buttons if gui is used
        if self.game_mode <= 2:
            self.gui.sync_board()

    # GUI functions ** Only to be used in GUI mode **

    # Loops GUIs to activate
    def loop(self):
        # loop gui update
        self.gui.loop()

    # Function for Starting in 1 Player
    def goto_1p(self):
        # console message
        print("switching to 1 player....")

        # Destroy previous frame
        self.gui.destroy_frame()

        # Create Game object and pass in the GUI and set to self.game
        self.game = Game()
        setattr(self.gui, 'game', self.game)

        # Set GUI state to 1P
        setattr(self.gui, 'state', '1P')

        # Generate 1p game board
        self.gui.create_board(1)

        # sync GUI
        self.gui.sync_board()

        self.gui.update()

        # TODO: Initiate AI

    # Function for Starting in 2 Player
    def goto_2p(self):
        # console message
        print("switching to 2 player....")

        # Destroy previous frame
        self.gui.destroy_frame()

        # Create Game object and pass in the GUI and set to self.game
        self.game = Game()
        setattr(self.gui, 'game', self.game)

        # Set GUI state to 1P
        setattr(self.gui, 'state', '1P')

        # Generate 1p game board
        self.gui.create_board(1)

        # sync GUI
        self.gui.sync_board()

        self.gui.update()

    # Registers a touch on the board and records it to the game
    def pressed(self, x, y):

        # make move based on move handler
        self.game.handle_move(x, y)

        # sync board
        self.gui.sync_board()

        self.gui.update()

    # Returns to main menu
    def back_to_menu(self):
        # console message
        print("Going back to menu...")

        # Destroy frame game frame
        self.gui.destroy_frame()

        # Reset and save the game board

        # Set GUi state
        setattr(self.gui, 'state', 'Menu')

        # Switch to main page
        self.gui.create_menu()

        self.gui.update()

    def quit_win(self):
        # console message
        print("Quitting game")

        # Save game state

        # Quit
        self.gui.window.quit()

        self.gui.update()
コード例 #20
0
ファイル: main.py プロジェクト: reveza/DiscreteStructureLabs
from Automats import Automates
from GUI import GUI
from tkinter import *
#Note: il faut s'assurer d'avoir la librairie (doit être installé sur linux)

auto = Automates("lexique6.txt")
root = Tk()
root.geometry('300x300')
gui = GUI(root, auto)
gui.mainloop()
コード例 #21
0
ファイル: tutorial-0-GUI.py プロジェクト: Qcrew/LabTools
import rpyc
from GUI import GUI

# ========== connect to the Instruments Server ==========
Instruments = rpyc.classic.connect("localhost").modules["Instruments"]

brick = Instruments.LabBrick(serialNumber=24352, name='brick')
sa124B_IQ = Instruments.SA124B(serialNumber=19184645,
                               mode='IQ',
                               name='sa124B_IQ')
sc5511A = Instruments.SC5511A(serialNumber=10002657, name='sc5511A')
sc5503B = Instruments.SC5503B(serialNumber=10002656, name='SC5503B')

gui = GUI()
gui.add([brick, sa124B_IQ, sc5511A, sc5503B])
gui.run()
コード例 #22
0
def background():

    print("Hi I'm Thursday")
    eng.say('Hi I am Thursday')
    eng.runAndWait()

    while True:

        r = sr.Recognizer()

        with sr.Microphone() as source:
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source, timeout=None)

            try:

                order = r.recognize_google(audio).lower()

                print(order)

                if order.startswith("thursday"):
                    # print("Up")

                    # eng.say('I am Up')
                    # eng.runAndWait()

                    UP(order.replace('thursday ', ''))

                    eng.say("Going to Stand by mode")
                    eng.runAndWait()
                    print("Stand by mode...")

                elif order in TERMINATE:
                    terminate()

                elif ("terminal" in order) or ("criminal" in order) or (
                        "permanent" in order) or ("birmingham" in order):
                    GUI()
                    print('Back to Thursday')
                    eng.say("Back to Thursday")
                    eng.runAndWait()

                elif ("your name" in order) and (order.startswith("what") or
                                                 order.startswith("what's")):
                    eng.say("My Name is Thursday.")
                    eng.runAndWait()
                    print("My Name is Thursday.")

                elif ("your name" in order) and (order.startswith("why")):
                    eng.say(
                        "Because Tony Stark has already used 'Friday'. and The Weeknd's music rocks."
                    )
                    eng.runAndWait()
                    print(
                        "Beacuse Tony Stark already has used 'Friday' and The Weeknd's music rocks."
                    )

            except sr.UnknownValueError:
                print(
                    "Listening to the magic words: 'Wake up ' or 'Shut down'")

            except sr.RequestError:
                eng.say("I'm sorry, I couldn't reach google")
                eng.runAndWait()
                print("I'm sorry, I couldn't reach google")
コード例 #23
0
from GUI import GUI

if __name__ == "__main__":
    GUI().run()
コード例 #24
0
ファイル: World.py プロジェクト: micmarty/WildWorld-the-Game
        self.infoText.set("ROUND : " + str(self.runoff) + "\n" + self.infoText.get())
        sorted_organisms = []
        self.sort(sorted_organisms)

        for i in sorted_organisms:
            if self.organism[i.x][i.y] is i:
                i.action(self)
                i.age += 1
        self.draw_runoff()
        self.runoff += 1


    def draw_runoff(self):
        """display appropriate icons in labels, if there's no organism->show empty png file"""
        for y in range(20):
            for x in range(20):
                if self.organism[x][y] is None:
                    gui.label[x][y].configure(image=PhotoImage(file='icons/pusty.png'))
                else:
                    gui.label[x][y].configure(image=self.organism[x][y].icon)


if __name__ == '__main__':
    root = Tk()
    world = World()         # create just one World representation
    gui = GUI(root, world)  # sending also reference to our world
    gui.load_game(None, world, load_example_map=True)
    world.draw_runoff()
    root.mainloop()

コード例 #25
0
def main(configFileName):

    ConfigurationFile.read(configFileName)

    gui = GUI()

    hideInput = True
    githubPassword = gui.getUserInput("Enter Github Password", hideInput)

    gui.drawMessage("Updating internal gubbins, please wait")
    Github.GithubWrapper.init(githubPassword)
    _updateRepository()

    branches = []

    releaseArchipelagoName = ConfigurationFile.releaseArchipelago
    branches = Git.getArchipelagoNamesRecentlyActiveInBranch(
        releaseArchipelagoName, ConfigurationFile.
        amountOfTimeInDaysBeforeBranchIsTooOldToBeConsideredRecent)

    # The archipelago(s) which are never merged into anything and we :. can't rely on when they have been merged into the release archipelago.
    #  Usually only the release archipelagos are merged into it except that there might be bug fixes so really any branch could go in from
    #  anywhere. It could be called anything and there could be multiple instances of it (though usually not).
    blackList = ConfigurationFile.blackList
    branches = _removeBlacklistedArchipelagosFromList(branches, blackList)

    archipelagoDataList = _setUpArchipelagoDataList(branches,
                                                    releaseArchipelagoName,
                                                    gui)

    gui.clearScreen()
    gui.drawMessage("Press F5 to refresh")

    # Git.RunAndStoreAllRepeatedCommands()

    keepRunning = True
    justStartedAndThereforeJustUpdatedRepository = True
    haveDrawnCirclesOnceAlready = False
    while keepRunning:
        gui.go()

        events = gui.getEvents()
        for event in events:
            if (event == GUI.WindowClosedEvent) or (event
                                                    == GUI.EscapeKeyEvent):
                keepRunning = False
                return

            if (event == gui.F5KeyEvent):
                gui.drawMessage("Updating internal gubbins, please wait")
                if not justStartedAndThereforeJustUpdatedRepository:
                    _updateRepository()
                justStartedAndThereforeJustUpdatedRepository = False
                needToDrawCirclesEveryTime = ConfigurationFile.automaticallyUpdateRepository
                if needToDrawCirclesEveryTime:
                    _drawIslands(releaseArchipelagoName, gui,
                                 archipelagoDataList)
                elif haveDrawnCirclesOnceAlready:
                    _redrawIslands(releaseArchipelagoName, gui,
                                   archipelagoDataList)
                else:
                    _drawIslands(releaseArchipelagoName, gui,
                                 archipelagoDataList)
                haveDrawnCirclesOnceAlready = True

            if (event == gui.F6KeyEvent):
                if haveDrawnCirclesOnceAlready:
                    _redrawIslands(releaseArchipelagoName, gui,
                                   archipelagoDataList)

            if (event == gui.MouseClickReleaseEvent):
                gui.displayNameOfIslandAtMouseLocation()

            if (event == gui.DeleteKeyEvent):
                gui.doNotRenderSelectedIsland()
コード例 #26
0
ファイル: __main__.py プロジェクト: likeblood/SmartMed
from GUI import GUI

if __name__ == '__main__':
    GUI().start_gui()
コード例 #27
0
ファイル: lora.py プロジェクト: Moahe/PlantsPi
    print(data[0]['dd'])
    str = 'Våning %s sensor %s:' % (plane, sensor)
    strinfo = 'Tid: %s\n timestamp: %s\n Temperature: %s\nHumidity: %s\nLight: %s\n' % (
        data[0]['time'], data[0]['ts'], data[0]['dd']['temperature'],
        data[0]['dd']['humidity'], data[0]['dd']['light'])
    strinfo = strinfo + 'Movement: %s\n Battery: %s\n' % (data[0]['dd']['pir'],
                                                          data[0]['dd']['vdd'])
    return data[0]


def getsensorAPI():
    url = "http://webplant.azurewebsites.net/api/soilsensordatas"
    headers = {'content-type': 'application/json'}
    response = requests.get(url, headers).json()

    return response


#Post to Sensor
def postToSensorAPI():
    url = "http://webplant.azurewebsites.net/api/soilsensordatas"
    dir = {'MoistInt': 1, 'timestamp': 1337}
    headers = {'content-type': 'application/json'}
    post = requests.post(url, data=json.dumps(dir), headers=headers).json()

    return post


#print(getsensorAPI())
GUI(loraAPIconnection())
コード例 #28
0
import random
import time

import pygame

from algorithm import algo
from colors import colors
from GUI import COLS, FPS, GUI, ROWS
from matrix import matrix
from nodeClasses.goalNode import goalNode
from nodeClasses.spareNode import spareNode
from nodeClasses.startNode import startNode
from nodeClasses.wallNode import wallNode

matr = matrix(ROWS, COLS)
gui = GUI(matr.arr)

gui.update()

path = algo(matr.arr, matr.start, matr.goal, gui)

# waits one second so we can see the initial state before
# starting the interaction
time.sleep(15)
"""
while True:
    # INPUT PROCESSING
    event = pygame.event.poll()

    if event.type == pygame.QUIT:
        # quits the program if clicked to close the window
コード例 #29
0
class Main:
    def __init__(self):
        #start the gui! - We have to update everything manually here :S
        self.GUI = GUI(self)
        self.GUI.drawLoader()

        self.TextOut = TextOut(self.GUI)
        self.TextOut.addText("[J.A.R.V.I.S.]: Loading Dataset! This could need a second!")
        self.mnist_loader = MNIST_LOADER()
        self.mnist_loader.loadMNIST()
        self.TextOut.addText("[J.A.R.V.I.S.]: Dataset loadeded!")
        self.RandomPicker = RandomPicker(self.mnist_loader)
        self.TextOut.addText("[J.A.R.V.I.S.]: Loading AI!")
        self.ai = AI_LITE()
        self.ai_keras = AI_KERAS()
        self.TextOut.addText("[J.A.R.V.I.S.]: Loading ImageEditor!")
        self.PicEditor = PicEditor()
        self.TextOut.addText("[J.A.R.V.I.S.]: Loading Camera!")

        self.GUI.drawMain()
        self.GUI.display.update()

        self.ai.initialize()
        self.TextOut.addText("[J.A.R.V.I.S.]: Everything's done, Sir.") 
        self.GUI.handler()
        

    def sendThroughAI(self, x):
        values = self.ai.feedforward(x)
        digit = numpy.argmax(values)
        return [digit, values]
        
    def sendThroughAI_Keras(self, x):
        x = (numpy.expand_dims(x, 0))
        values = self.ai_keras.sendThrough(x)
        digit = numpy.argmax(values)
        return [digit,values]

    def runImage(self):
        img = Image.open("data/image_RAW.png").convert("L") #Black-White!
        if min(img.getdata()) == 255:
            self.TextOut.addText("[J.A.R.V.I.S.]: I can't handle this picture.")
            return (False, None, None)
        images = self.PicEditor.getAll(img)[1]
        return (True, images, img)

    #Get a png and translate it... - Returns an array containing arrays (1 pxl = 1 array...)
    def translateToMNIST(self, path=None,img=None):
        if img == None:
            #just in case it's not in greyscale yet.
            img = Image.open(path).convert('L')
            data = list(img.getdata())
            newData = []
            for x in data:
                newData.append([(255 - x) / 255])
            return newData
        #Not working via path; via the img directly:
        data = list(img.getdata())
        newData = []
        for x in data:
            newData.append([(255-x) / 255])
        return newData
コード例 #30
0
ファイル: Corelet.py プロジェクト: Light-Lens/Corelet
        elif Data["realtime_protection"] == True:
            LOG.CORELET_LOG("Realtime Protection is enabled.\n")
            RealTime_Protection(Count)

# Virus names
Virus_names = "virus.exe", "exploit.application", "internet_explorer.exe", "fake_virus.bat"


# This function will check whether it should allow any program or not.
def IsVirus(files):
    if files in Virus_names: return True
    else: return False


# Main Antivirus Loop
Title = GUI.Label(Display, (25, 25, 25), 0, 0, 475, 70)
Title_Text = GUI.Text(Display, "Corelet", (90, 90, 90), (160, 10), 50)

SystemScan = GUI.Button(Display, (50, 50, 50), (70, 70, 70), (40, 40, 40), 30,
                        100, 120, 30)
SystemScan_Info = GUI.Text(Display,
                           f"Scan {WinDir} drive (Cannot scan other drives)",
                           (0, 0, 0), (38, 140), 13)
SystemScan_Text = GUI.Text(Display, "System scan", (255, 255, 255), (38, 104),
                           21)
SystemScan_Border = GUI.Label(Display, (18, 18, 18), 30, 130, 120, 2)
SystemScan_Left_Border = GUI.Label(Display, (18, 18, 18), 30, 100, 2, 30)

CustomScan = GUI.Button(Display, (50, 50, 50), (70, 70, 70), (40, 40, 40), 30,
                        200, 120, 30)
CustomScan_Info = GUI.Text(Display,
コード例 #31
0
import DataSource
from GUI import GUI

if __name__ == "__main__":
    data_source = DataSource.DataSource()
    GUI(data_source)
コード例 #32
0
    def OnGUI(self):
        GUI.BeginGUI(self)
        GUI.BeginGroup("Server Information")
        GUI.BeginHorizontalLayout()
        GUI.Label("服务器IP地址")
        GUI.IPAddress("edit_serverIP")
        GUI.Spacer(50)
        GUI.Label("服务器端口号")
        GUI.LineEdit("edit_port")
        GUI.EndLayout()
        GUI.EndGroup()

        GUI.BeginGroup("Propery Setting")
        GUI.BeginHorizontalLayout()
        GUI.Label("JitterBug阈值w:")
        GUI.LineEdit("edit_w")
        GUI.EndLayout()
        GUI.EndGroup()

        GUI.BeginGroup("Display")
        GUI.BeginHorizontalLayout()
        GUI.Label("发送进度")
        GUI.ProgressBar("progressBar_send")
        GUI.EndLayout()
        GUI.EndGroup()

        GUI.BeginHorizontalLayout()
        GUI.Spacer(400)
        GUI.Button("button_Connect", "连接服务器")
        GUI.Button("button_Send", "开始发送")
        GUI.EndLayout()

        GUI.EndGroup()

        GUI.EndGUI()
コード例 #33
0
ファイル: Main.py プロジェクト: JacobLuke/minesweeper
 def restart (self):
   self.game = self.getGame()
   self.gui = GUI(self.settings, self.game)
コード例 #34
0
ファイル: tp-robot.py プロジェクト: thomas-che/tp_l2_info
            break


#correction fonc
def ParcoursRobotC(G, depart, gui):
    atteint = set()
    P = [(depart, [depart])
         ]  #pile avec initilament le sommet de dep et le chemin dep

    prev_chemin = [depart]
    while P:
        (u, chemin) = P.pop()
        if (u not in atteint):
            atteint.add(u)
            x, y = u

            gui.deplacer_oscar(prev_chemin, chemin)
            prev_chemin = chemin

            if (G[x][y] == "cookie"):
                print("trouver cookie")
                break

            for v in voisins(G, u):
                P.append((v, chemin + [v]))


if __name__ == '__main__':
    grille, pos_robot = creer_grille(12, 20)
    GUI(grille, pos_robot, ParcoursRobot)
コード例 #35
0
ファイル: main.py プロジェクト: salasgar/Ecosystems
def main():
    setup_logger()
    logger.debug('DEBUG')
    print " *"*30, "\nWe start NOW!"  # ***
    # all_gene_names = extract_all_gene_names(my_example_of_ecosystem_settings)
    # all_strings = extract_all_strings(
    #    my_example_of_ecosystem_settings,
    #    exceptions = No_effect_directives + All_action_names)
    # print 'ALL GENES:', all_gene_names
    # print 'ALL STRINGS:', all_strings
    # print 'DIFFERENCE:', [
    #    item
    #    for item in all_strings
    #    if not item in all_gene_names and \
    #        not item in All_allowed_directives_in_expression]
    enable_graphics = True
    make_sleeps = False
    time_lapse = 4
    Total_time = 5000

    ecosystem = Ecosystem(my_example_of_ecosystem_settings)

    ecosystem.minimum_population_allowed = 200

    """ ***********************  TRIAL ZONE ****************************

    ecosystem.evolve()

    org = ecosystem.get_random_organisms(1)[0]

    print_dictionary(
        evaluate_functions_of_a_dictionary(
            org['offers to sell'], org
            )
        )

    f_set = {'-': ('nutrient A reserve', 'minimum nutrient A reserve for procreating')}
    f = ecosystem.function_maker.read_function_settings(
        '#organism',
        f_set)


    print_organism(org, 'nutrient A reserve', 'minimum nutrient A reserve for procreating')
    print_organism(org, 'nutrient A surplus')

    print f(org)

    print org['value in next cycle']['nutrient A surplus'](org)

    exit()

    f_set = {'curve from 0 to 1': 'photosynthesis capacity'}

    f = ecosystem.function_maker.read_function_settings(
        'output function #organism #input',
        f_set)

    for org in ecosystem.organisms_list:
        print f(org, 5)

    exit()

    f_set = {'extract #biotope sunlight (percentage)': (
                            'normalized location x',
                            'normalized location y',
                            0.8
                        )}

    f_2_set = {
        '#biotope sunlight': (
            'normalized location x',
            'normalized location y'
            )
        }

    org = choice(ecosystem.organisms_list)
    print_dictionary(org)

    f = ecosystem.function_maker.read_function_settings('#organism', f_set)
    f_2 = ecosystem.function_maker.read_function_settings('#organism', f_2_set)

    print f(org), f_2(org)

    for i in range(10):
        org.act()

    print_dictionary(org)

    # f_set = ecosystem.settings['constraints']['can procreate']
    # f_set = {'cost': 'procreate'}
    f_set = 'time'
    f = ecosystem.function_maker.read_function_settings('#organism', f_set)

    # print f(ecosystem)

    for org in ecosystem.organisms_list:
        print f(org)

    exit()

    *********************** (TRIAL ZONE) ************************** """

    if enable_graphics:
        gui = GUI(ecosystem)
    # Loop
    print "LOOPING:"
    while ((len(ecosystem.organisms_list) > 0) and
           (ecosystem.time < Total_time)):
        # Print ecosystem status:
        if ecosystem.time % time_lapse == 0:
            print_ecosystem_status(ecosystem)
            # organism1, organism2 = ecosystem.get_random_organisms(
            #    number_of_random_organisms = 2)
        if Store_data:
            ecosystem.data_storer.store_data()
        # Evolve:
        ecosystem.evolve()
        if enable_graphics:
            gui.handle_events()
            gui.draw_ecosystem()
        if make_sleeps:
            sleep(1.0)  # To remove
        if ecosystem.population() < ecosystem.minimum_population_allowed:
            n = ecosystem.minimum_population_allowed - ecosystem.population()
            ecosystem.create_new_organisms(n)
            print n, "organisms created",

    print "Time:", ecosystem.time, "Number of organisms:", \
        len(ecosystem.organisms_list)  # ***

    if enable_graphics:
        gui.delete()
コード例 #36
0
ファイル: xslit.py プロジェクト: oriyanh/xslit-panorama
def main():
    gui = GUI()
    gui.loop()
コード例 #37
0
ファイル: main.py プロジェクト: arturblch/Conway

if __name__ == '__main__':
    world = get_world()

    trains = world.my_trains()
    trains[1].target = 5
    trains[2].target = 15

    trains[1].point = 1
    trains[2].point = 1



    solver = get_solver()
    gui = GUI(*(world.get_parts()))

    limit = 99
    start_time = time()

    while not solved(world):
        gui.turn()
        if((not gui.paused) or gui.onestep):
            world.next_tick()
            solver.step(world)      # apply consist move

            if (limit > 0 and world.tick() > limit):
                break

    stop_time = time()
コード例 #38
0
ファイル: util.py プロジェクト: neobonde/Util
    print("    Hash: " + str(
        check_output(["git", "rev-parse", "--short", "HEAD"]).decode('utf-8')
        [:-1] + postHash))

    # Print the lastest commit message
    print("    Commit Message: " + str(
        check_output(["git", "log", "-1", "--pretty=%B"]).decode('utf-8')[:-2])
          )  # Commit messages are apperently have an extra newline?
    print("")


if __name__ == "__main__":
    if len(sys.argv) > 1:
        # Handle GUI
        if sys.argv[1] in ["-g", "--gui"]:
            GUIRunner(GUI("Utilities"))

        # Handle help
        elif sys.argv[1] in ["-h", "--help"]:
            print("")
            printHelpOutput()

        # Handle version
        elif sys.argv[1] in ["-v", "--version"]:
            printVersionOutput()

        # Handle unknown command
        else:
            print("")

            # Print unkown command passed to util
コード例 #39
0
class Controller():
    def __init__(self):
        self.frames = {}
        self.GUI = GUI()
        self.init_frames()

    def init_frames(self):
        self.init_main_frame()
        self.init_add_process_frame()
        self.show_frame(self.main_frame)

    def init_add_process_frame(self):
        self.add_process_frame = AddProcessFrame(self.get_gui_container(),
                                                 self)
        self.add_process_frame.grid(row=0, column=0, sticky="nsew")
        self.add_process_frame.back.configure(command=self.go_to_main_frame)
        self.add_process_frame.add.configure(command=self.add_process_to_list)

    def init_main_frame(self):
        self.main_frame = MainFrame(self.get_gui_container(), self)
        self.main_frame.add_button.configure(command=self.add_process)
        self.main_frame.del_button.configure(command=self.del_process)
        self.main_frame.ini_button.configure(command=self.ini_process)
        self.main_frame.grid(row=0, column=0, sticky="nsew")

    def add_process(self):
        self.show_frame(self.add_process_frame)

    def add_process_to_list(self):
        self.main_frame.process_list.insert(tk.END,
                                            " " + self.format_process())

    def format_process(self):
        process = ""
        process += self.add_process_frame.pid.get() + " | "
        process += self.add_process_frame.arrival_entry.get() + " | "
        process += self.add_process_frame.duration_entry.get() + " | "
        process += self.add_process_frame.priority.get() + " | "
        process += self.add_process_frame.io_exits_entry.get() + " | "
        process += self.add_process_frame.io_duration_entry.get()
        return process

    def del_process(self):
        self.main_frame.process_list.delete(
            self.main_frame.process_list.curselection())

    def ini_process(self):
        print("INI")

    def get_processes_from_list(self):
        processes = []
        for i in range(self.main_frame.process_list.size()):
            processes.append()

    def get_process_from_listbox_index(self):
        pass

    def go_to_main_frame(self):
        self.show_frame(self.main_frame)

    def get_gui_container(self):
        return self.GUI.container

    def show_frame(self, frame_to_show):
        frame_to_show.tkraise()

    def start_gui(self):
        self.GUI.mainloop()
コード例 #40
0
    def OnGUI(self):
        GUI.BeginGUI(self)
        GUI.BeginGroup("Server Infomation")
        GUI.BeginHorizontalLayout()
        GUI.Label("服务器IP地址")
        GUI.IPAddress("edit_serverIP")
        GUI.Label("服务器端口号")
        GUI.LineEdit("edit_port")
        GUI.Button("button_StartServer", "开启服务器")
        GUI.EndLayout()
        GUI.EndGroup()

        GUI.BeginGroup("Client Information")
        GUI.BeginHorizontalLayout()
        GUI.Table("table_client",
                  ["IP地址", "端口号", "消息总数", "连接时间", "连接状态", "最后消息"])
        GUI.BeginVerticalLayout()
        GUI.Button("button_export", "导出数据")
        GUI.Button("button_deleteClient", "删除Client")
        GUI.Button("button_closeServer", "关闭服务器")
        GUI.EndLayout()
        GUI.EndLayout()
        GUI.EndGroup()
        GUI.EndGUI()
コード例 #41
0
ファイル: activity.py プロジェクト: Bundloleers/bundle
class BundleActivity(activity.Activity):
    
    zip_mime = ["application/x-zip",  "application/zip",  "application/x-zip-compressed"]
    _logger = None
    
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        self._name = handle
        # Set up logging. We're sending messages to the default log directory,
        # which can be browsed with the Log activity.
        
        self._logger = logging.getLogger('bundle.BundleActivity')
        self._logger.setLevel(logging.DEBUG) # Show ALL messages
        # self._logger.setLevel(logging.WARNING) # Ignore DEBUG/INFO msgs
        self._logger.debug("Initializing BundleActivity.")

        # Set title for our Activity
        self.set_title('Bundle Activity')

        # Attach sugar toolbox (Share, ...)
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        #toolbox.show()
        
        self.activity_toolbar = toolbox.get_activity_toolbar()
        
        #create toolbar
        self.main_toolbar = gtk.Toolbar()
        #self.main_toolbar.show()
        
        toolbox.add_toolbar(_('Bundle'),  self.main_toolbar)
        toolbox.set_current_toolbar(1)
        toolbox.show()
        
        # Create the main container
        self._main_view = gtk.VBox()

        # Import our class Bundle():

        # Step 1: Load class, which creates Bundle.widget
        self.myBundle = Bundle(None)
        self._logger.debug("Bundle instance created.")
        self.myBundle.parent = self
        
        self.myGUI = GUI(self)
        self.myGUI.xid = handle
        self.myGUI.myBundle = self.myBundle
        self.myGUI.set_bundle(self.myBundle)
        #self.myGUI.parent = self
 
        # Step 3: We attach that widget to our window
        self._main_view.pack_start(self.myGUI.widget)

        # Display everything
        self.myGUI.widget.show()
        self._main_view.show()
        self.set_canvas(self._main_view)
        self.show_all()
        
        self.scratchDir = os.path.join(self.get_activity_root(),  'instance')
        self._logger.debug("Scratch dir is %s", self.scratchDir)
        self._logger.debug("__init__() finished")
        
        self.activityRegistry = ActivityRegistry()
        #self.myGUI.statusBar.set_text(self._logger.get_logs_dir())
        

    def write_file(self,  file_path):
        self._logger.debug("write_file() called with path = %s", file_path)
        if self.myBundle.status == self.myBundle.unpacked:
            # this means we have a list of items to save, so the mime-type
            # will be set to "application/x-zebra
            self.metadata['mime_type'] = "application/x-zebra"
            
            f = open(file_path,  'w')
            for (item) in self.myBundle.objList:
                f.write(item.object_id + "\n")
            f.close()
            
        elif self.myBundle.status == self.myBundle.packed:
            x = 1
            
    def get_temp_files(self):
        self._logger.debug("get_temp_files called")
        for (item) in self.myBundle.objList:
            if item.status == self.myBundle.notInZip:
                self._logger.debug("Getting file for object = %s", item.object_id)

                jobject = datastore.get(item.object_id)
                filename = jobject.file_path
                self._logger.debug("Copying file %s", filename)

                ext = os.path.splitext(filename)[1]
                self._logger.debug("File extension = %s", ext)
                f,  temp_file = tempfile.mkstemp(ext, prefix= jobject.metadata['title']+"_HASH",   dir = self.scratchDir) 
                # the changes to the line above should preserve and uniquify our filenames  ~J
                #Might be more sensible to use the file name, but I think this'll work...............                
                self._logger.debug("Copying %s", jobject.metadata['title'])
                if (os.path.exists(filename)):
                    shutil.copy(filename,  temp_file)
                    self._logger.debug("Copying DONE");
                    self.myBundle.tempFileList.append((temp_file, jobject.metadata['title'])) 
                else:
                    self._logger.debug("Item %s does not have a file associated",  jobject.metadata['title'])
                    
                jobject.destroy()
        # this segment right here handles modified archives
        # basically modification is also handled when we click "Pack" (after adding new items)
        # just that here we unpack the existing files in the archive to put them in a new archive 
        # file. Files flagged with the "to_delete" flag are not extracted
        if (self.myBundle.status == self.myBundle.packed):
            self._logger.debug("Attempting to re-pack the archive")
            # extract all the files that are not flagged as "TO DELETE"
            for (item) in self.myBundle.objList:
                self._logger.debug("Found item with title %s and to_delete %s",  item.title,  item.to_delete)
                if ((item.status == self.myBundle.inZip) and (item.to_delete == False)):
                   try:
                        f,  temp_file = tempfile.mkstemp(item.ext, prefix= item.title+"_HASH",   dir = self.scratchDir) 
                        del f;
                        f = open(temp_file,  'wb')
                        f.write(self.myBundle.extractOne(item))
                        f.close()
                        self.myBundle.tempFileList.append((temp_file, " "))
                   except Exception,  e:
                       self._logger.error("EXCEPTION: %s",  str(e))
コード例 #42
0
from csv import DictReader
from sys import argv, exit
from negotiator import Negotiator
from mynegotiator import MyNegotiator
from dumbnegotiator import DumbNegotiator
from standardnegotiator import StandardNegotiator
from safenegotiator import SafeNegotiator
from random import randint

##GUI Related Imports
import matplotlib
matplotlib.use('TkAgg')
import pylab
import matplotlib.pylab as plt
from GUI import GUI
g = GUI()

#set_diff(a: list, b: list)
    #Performs the set difference of sets A and B and returns it
def set_diff(a,b):
    B = set(b)
    return [aa for aa in a if aa not in B]

# read_scenario(parameterfile_name : String) --> (int, list(dict))
    # Utility function to read in a single scenario from a csv file
    # Expects a single int on the first line, specifying the iteration limit,
    # and then an arbitrary number of rows of three comma-separated columns,
    # specifying the name of each item, its rank (where 1 is best) for negotiator A,
    # and the same for negotiator B
def read_scenario(parameterfile_name):
    # Open the file for reading
コード例 #43
0
ファイル: main.py プロジェクト: tflave/AI-Project
from GUI import GUI

g = GUI()
g.run()
コード例 #44
0
ファイル: DST.py プロジェクト: asakryukin/SpaceVT
class DST:
    def __init__(self):

        # Load GUI class
        self.G = GUI()
        # Load Prediction Model
        self.PM = PredictionModel()

        # Prepare the Figure
        plt.ion()
        self.fig = mpl.figure.Figure(
            figsize=(10, 5),
            dpi=80,
            facecolor='w',
        )
        self.ax = self.fig.add_subplot(111)

        # Urls for Real-Time DST and IMF data
        self.url_dst = 'http://wdc.kugi.kyoto-u.ac.jp/dst_realtime/presentmonth/index.html'
        self.url_imf = 'https://cdaweb.gsfc.nasa.gov/pub/data/omni/low_res_omni/omni2_2018.dat'

        # Load data
        self.fill_data()
        # Plot data
        self.plot_data()

        # Intilialize a scheduler
        self.scheduler = sched.scheduler(time.time, time.sleep)

        # Load new values
        self.update()
        # Show GUI
        self.G.start_gui()

    def fill_data(self):
        # Initializer of data arrays, creates empty data arrays for DST and IMF

        # Get current date and month length
        month = datetime.datetime.utcnow().month
        year = datetime.datetime.utcnow().year
        self.length = monthrange(year, month)[1]

        # Create arrays for dst and imf with required length
        self.data_dst = np.zeros((self.length, 24), )
        self.data_imf = np.zeros((self.length, 24), )

        # current time
        today = datetime.datetime.utcnow().day
        hour = datetime.datetime.utcnow().hour

        if (hour == 0):
            hour = 24
            today = today - 1
            if (today == 0):
                return True

        # Latest time of update
        self.today = today
        self.hour = hour

        # Load available data
        self.update_data(1, 0, today, hour - 1)

    def update_data(self, from_day, from_time, to_day, to_time):
        self.update_dst(from_day, from_time, to_day, to_time)
        self.update_imf(from_day, from_time, to_day, to_time)

    def update_dst(self, from_day, from_time, to_day, to_time):

        # Load the page from Real-time DST data
        response = urllib2.urlopen(self.url_dst)
        content = response.read()
        parsed_html = BeautifulSoup(content)
        # Get pre tag containing the data
        data = str(parsed_html.body.find('pre', attrs={
            'class': 'data'
        }).text).splitlines()

        # get data day be day
        for i in xrange(from_day, to_day + 1):

            line = data[5 + i + (i - 1) / 5]
            for j in xrange(0, 24):
                # for each day get valid hours
                if (i == from_day and j < from_time):
                    continue
                if (i == to_day and j > to_time):
                    break

                # Parse dst
                value = float(line[(j + 1) * 4 + (j / 8) - 1:(j + 2) * 4 +
                                   (j / 8) - 1])

                self.data_dst[i - 1, j] = value

        return True

    def update_imf(self, from_day, from_time, to_day, to_time):
        # Same as DST function
        response = urllib2.urlopen(self.url_imf)
        content = response.read()
        data = str(content).splitlines()

        for i in xrange(from_day, to_day + 1):
            line = data[(i - 1) * 24:i * 24]
            for j in xrange(0, 24):
                if (i == from_day and j < from_time):
                    continue
                if (i == to_day and j > to_time):
                    break
                splitted = line[j].split()
                value = float(splitted[14])

                self.data_imf[i - 1, j] = value

        return True

    def plot_data(self):
        # Redraw the figure
        self.ax.clear()
        # Flatten the data
        data_dst = (np.ndarray.flatten(
            self.data_dst))[0:(self.today - 1) * 24 + self.hour]
        data_imf = (np.ndarray.flatten(
            self.data_imf))[0:(self.today - 1) * 24 + self.hour]

        # Plot real-time DST and IMF (Bz,GSE)
        self.ax.plot(np.arange(1, (len(data_dst) - 2) / 23.0, 1.0 / 24.0),
                     data_dst,
                     'b',
                     label='DST')
        self.ax.plot(np.arange(1, (len(data_imf) - 2) / 23.0, 1.0 / 24.0),
                     data_imf,
                     'g',
                     label='IMF (Bz, GSE)')

        # If have enough data predict next DST for future 5 hours
        if (len(data_dst) > 4):
            # Prepare input data for the model
            p_input = np.append(data_dst[-5:], data_imf[-5:])
            # Make predictions
            p_dst = self.PM.predict(p_input)
            # Plot predictions
            self.ax.plot(np.arange((len(data_imf) - 2) / 23.0,
                                   ((len(data_imf) - 2) / 23.0) + 5.0 / 24,
                                   1.0 / 24.0),
                         p_dst,
                         'r',
                         label='Predicted DST')

        self.ax.set_title("DST and IMF data (updated: " +
                          str(datetime.datetime.utcnow()) + ")")
        self.ax.set_ylabel('Value (nT)')
        self.ax.set_xlabel('Day of the month')
        self.ax.legend()
        self.ax.set_xlim(1, self.length)

        try:
            self.G.draw(self.fig)
        except RuntimeError:
            pass

    def check_running(self):
        # Check whether the user closed the program
        if (not self.G.is_active()):
            # If yes, kill the background thread
            sys.exit(0)
        else:
            # If no check if it's time to update the data (once in an hour at 15 minutes)
            if ((15 - datetime.datetime.utcnow().minute) == 0):
                self.fill_data()
                self.plot_data()

    def update(self):
        # Background thread for data updates
        if (self.G.active):
            # Check every minute if program running and update data once in an hour
            self.scheduler.enter(60, 2, self.update, {})
            self.scheduler.enter(60, 1, self.check_running, {})
            th = threading.Thread(target=self.scheduler.run, args={})
            th.start()
        else:
            sys.exit(0)
コード例 #45
0
ファイル: main.py プロジェクト: taoyouh/StarPanel
from StarPanel import StarPanel
from StarPanel import makeASolarSystem
from GUI import GUI

starPanel = StarPanel()
gui = GUI(starPanel)
raw_input()

コード例 #46
0
ファイル: runme.py プロジェクト: jrunzer26/SPMS
            
            for i in range(0, 5):
                lst.append(ser.readline().rstrip())
            
            if resetVar == False:
                updateUser(lst)
            else:
                if(checkVip(User(lst))):
                    reset()
                else:

                    gui.updateRFID('INVALID VIP')
                    print("INVALID VIP")
                resetVar = False



        if len(userList) > 0 and not pygame.mixer.music.get_busy() and skipBool == False:
		skip()        
		print 'in skip loop'
	        skipBool = False
               	
		   


#create the GUI
gui = GUI(resetCallback,pausePlay,skip, quit_callback)
thread.start_new(main,('main thread',))
gui.getRoot().wm_protocol('WM_DELETE_WINDOW', quit)
gui.getRoot().mainloop()
コード例 #47
0
        directions_map = np.roll(directions_map, 1, axis=0)


    loc = directions_map.mean(axis=0).argmax()
    if loc == 0:
        text = 'Back'
        HAL.motors.sendV(-1)
    elif loc == 1:
        text = 'Turn right'
        HAL.motors.sendW(-0.05)
    elif loc == 2:
        text = 'Advance'
        HAL.motors.sendV(1)
    elif loc == 3:
        text = 'Turn left'
        HAL.motors.sendW(0.05)
    else:
        text = 'WAITING'

    hsv[:, :, 0] = ang_180
    hsv[:, :, 2] = cv.normalize(mag, None, 0, 255, cv.NORM_MINMAX)
    rgb = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)

    frame = cv.flip(frame, 1)
    cv.putText(frame, text, (30, 90), cv.FONT_HERSHEY_COMPLEX, frame.shape[1] / 500, (0, 0, 255), 2)

    # Show Image
    GUI.showImage(frame)

cap.release()
cv.destroyAllWindows()
コード例 #48
0
    def OnGUI(self):
        GUI.BeginGUI(self)
        GUI.BeginGroup("Server Information")
        GUI.BeginHorizontalLayout()
        GUI.Label("服务器IP地址")
        GUI.IPAddress("edit_serverIP")
        GUI.Spacer(50)
        GUI.Label("服务器端口号")
        GUI.LineEdit("edit_port")
        GUI.Label("发包数量")
        GUI.LineEdit("edit_count")
        GUI.EndLayout()
        GUI.EndGroup()

        GUI.BeginGroup("Propery Setting")
        GUI.BeginHorizontalLayout()
        GUI.Label("间隔时间")
        GUI.LineEdit("edit_interval")
        GUI.Spacer(50)
        GUI.Label("轮换模式")
        GUI.CheckBox("check_turn", "")
        GUI.Label("轮换周期")
        GUI.LineEdit("edit_period")
        GUI.EndLayout()
        GUI.EndGroup()

        GUI.BeginGroup("Display")
        GUI.BeginHorizontalLayout()
        GUI.Label("发送进度")
        GUI.ProgressBar("progressBar_send")
        GUI.EndLayout()
        GUI.EndGroup()

        GUI.BeginHorizontalLayout()
        GUI.Spacer(400)
        GUI.Button("button_Connect", "连接服务器")
        GUI.Button("button_Send", "开始发送")
        GUI.Button("button_Test", "测试")
        GUI.EndLayout()

        GUI.EndGroup()

        GUI.EndGUI()
コード例 #49
0
ファイル: main.py プロジェクト: semone/simon-says
#Set up the window
backgroundColor = (232, 232, 232)
screen = py.display.set_mode((1000, 650))
py.display.set_caption("Train Your Brain")
backgroundSurface = py.Surface([1000,650])
backgroundSurface.fill(backgroundColor)
clock = py.time.Clock()

#Set up local variables
fps = 20 
count = 0
index = 0

#Init the board and GUI
board = Board(screen)
gui = GUI(screen,backgroundColor)

#Load images
wait = py.image.load("images/wait.png")
go = py.image.load("images/go.png")

#Build the initial screen
gui.initScreenBuild()
initScreen = True

buttonList = [gui.easyButton, gui.mediumButton, gui.hardButton]
py.init()
        
while running:
        for event in py.event.get():
                if event.type == py.QUIT: