def __init__(self, initial_position, scale, num_stacks, scenario_boundaries, stack_desp):
        self.DIRECTORIO = "images/gameplay/arm/"
        self.estado = "IDLE"
        self.stack_desp = stack_desp
        self.scenario_boundaries = scenario_boundaries
        self.scale = scale
        self.moving = False
        self.direction = None
        self.scenario = None
        self.function_set = None
        self.velocity = 255
        self.function_id = 0
        self.instruction_id = 0
        self.ticksResuelto = 0
        self.termino_instruction = True
        self.currentPos = initial_position
        self.initial_pos = initial_position
        self.catching = False
        self.catching2 = False
        self.movingUp = False
        self.movingDown = False
        self.resuelto = False
        self.ERROR = False
        self.returnPoints = []

        self.attachedBox = None

        rscale_x = 145/283.0*self.scale
        rscale_y = 125/313.0*self.scale
        x0 = (160 + 110*(initial_position + self.stack_desp - 1) - 15)*self.scale + self.scenario_boundaries[0]
        y0 = self.scenario_boundaries[1] + 1

        self.cable = Application.createSfSprite(self.DIRECTORIO+"cable.png",
                                                x0 + (145*self.scale - rscale_x*44)/2.0, y0 - 4,
                                                44*rscale_x, 65*rscale_y + 4)

        self.base_cable_size = (44*rscale_x, 65*rscale_y + 4)
        self.cable_height = self.base_cable_size[1]

        self.holder = Application.createSfSprite(self.DIRECTORIO+"holder.png",
                                                 x0 + 26*rscale_x, y0 + 65*rscale_y,
                                                 230*rscale_x, 72*rscale_y)
        
        self.base_holder_size = (230*rscale_x, 72*rscale_y) 

        self.left_pin = Application.createSfSprite(self.DIRECTORIO+"left_pin.png",
                                                   x0, y0 + 65*rscale_y + 72*rscale_y,
                                                   53*rscale_x, 176*rscale_y)
        
        self.base_left_pin_pos = (x0, y0 + 65*rscale_y + 72*rscale_y)
        self.base_left_pin_size = (53*rscale_x, 176*rscale_y)

        self.ddx = 26*rscale_x

        self.right_pin = Application.createSfSprite(self.DIRECTORIO+"right_pin.png",
                                                    x0 + 145*self.scale - 53*rscale_x, y0 + 65*rscale_y + 72*rscale_y,
                                                    53*rscale_x, 176*rscale_y)
        
        self.base_right_pin_pos = (x0 + 145*self.scale - 53*rscale_x, y0 + 65*rscale_y + 72*rscale_y)
        self.base_right_pin_size = (53*rscale_x, 176*rscale_y)
Exemplo n.º 2
0
    def __init__(self, prevScreen, puzzle_number):
        self.puzzle_number = puzzle_number
        self.width = 1200
        self.heigth = 700
        self.blanco = sf.Color(250, 250, 250)
        self.negro = sf.Color(0, 0, 0)
        name = Application.username
        self.window = sf.RenderWindow(
            sf.VideoMode(self.width, self.heigth), "DRAG BOX - LETS PLAY " + name, sf.Style.Close
        )
        self.window.SetIcon(16, 16, Icon.window_icon())
        self.Evento = sf.Event()
        self.window.SetFramerateLimit(60)
        self.backScreen = prevScreen
        self.sonidos = None
        self.temp = None
        self.dragging_instruction = False
        self.playing = False
        self.playingStepByStep = False
        self.instruction_name = None
        self.function_set = Drawable_FunctionSet()
        self.slider = Drawable_Slider(249, 98, 505, 143, 50)

        self.toolbox = Drawable_Toolbox()
        self.goal = Drawable_Scenario(77, 461, 511, 700, prevScreen, str(puzzle_number), True)
        self.working_area = Drawable_Scenario(529, 87, 1200, 700, prevScreen, str(puzzle_number), False)
        self.working_area.goal = self.goal
        self.bg_over = Application.createSfSprite(self.DIRECTORIO + "bgs/gameplay/scenario_bg2.png", 0, 0, 2000, 1000)
        self.message = None
        Application.setActiveWindow(self)
    def __init__(self, xi, yi, xf, yf, level_name, puzzle_number, final):
        self.puzzle_number = puzzle_number
        self.level_name = level_name        
        self.DIRECTORIO = "images/gameplay/"
        self.there_is_arm = False
        self.goal = None
        self.final = final

        self.num_stacks = Application.getNumberStacksLevel(level_name, puzzle_number)
        stack_desp = (8 - self.num_stacks)/2
        self.scale_x = (xf - xi)/1200.0
        self.scale_y = (yf - yi)/700.0
        self.stack_desp = stack_desp 
        self.stacks = []
        
        for i in range(self.num_stacks):
            self.stacks.append(Drawable_Stack(i, level_name, puzzle_number,self.scale_x, [xi, yi, xf, yf], final, stack_desp))

        #imagenes
        self.filter = Application.createSfSprite(self.DIRECTORIO+"scenario_filter.png", xi, yi, xf - xi, yf - yi)
        self.bg = Application.createSfSprite(self.DIRECTORIO+"scenario_bg2.png", xi, yi, xf - xi, yf - yi)

        #self.bg_bot = Application.createSfSprite(self.DIRECTORIO+"scenario_bg_bottom.png", xi, 650, xf - xi, yf - 650)

        #self.poleL = Application.createSfSprite(self.DIRECTORIO+"pole.png", xi, yi, 30, yf - yi)

        #self.poleR = Application.createSfSprite(self.DIRECTORIO+"pole.png", xf - 30, yi, 30, yf - yi)
        if not final:
            self.BuildArm([xi, yi, xf, yf])
Exemplo n.º 4
0
def main():
    """ Tests the game over state. """
    app = Application()
    config = app.game_config
    config.home_pile_size = 1
    app.goto_prepare()
    app.main()
    def DefinirTops(self):
        self.tops = []
        self.tops2 = []
        positions = [(292,190), (666,190), (1037,190), (292,438), (666,438), (1037,438)]

        for i in range(6):
            self.tops.append(Application.createSfSprite(self.DIRECTORIO+"buttons/top.png", positions[i][0], positions[i][1], 110, 64))
            self.tops2.append(Application.createSfSprite(self.DIRECTORIO+"buttons/top_2.png", positions[i][0], positions[i][1], 110, 64))
  def __init__(self):
    # Change these to set the window resolution and title as you desire
    myResolution = (1024, 640)
    myTitle = "MyGame"

    # Don't change this
    Application.__init__(self, myResolution, myTitle)
    self.Initialize()
    def deleteStack(self,cual):
        Application.putOnDeleteList(self.stacks[cual])
        del self.stacks[cual]
        self.i-= 1

        x=cual
        while( x< len(self.stacks)):
            self.stacks[x].Reposition(x)
            x+=1
def main():
    '''Turn on the DBus Mainloop and start the program'''
    #turn on the dbus mainloop
    DBusGMainLoop(set_as_default=True)

    #constructor for your class instances
    options = parse_options()

    app = Application(options.gui)
    app.start_app()
    def DefinirSprites(self):
        self.bgwidth = 65
        self.bgheight = 700 - 167
        posX_btns = 11
        self.btnwidth = 44
        width_btns = self.btnwidth
        height_btns = self.btnwidth

        self.bg = Application.createSfSprite(self.DIRECTORIO+"bg_toolbox.png", 0, 167, self.bgwidth, self.bgheight)        

        self.botonDown = Application.createSfSprite(self.DIRECTORIO+"img_INS_DOWN.png", posX_btns, 184, width_btns, height_btns)

        self.botonRight = Application.createSfSprite(self.DIRECTORIO+"img_INS_RIGHT.png", posX_btns, 249, width_btns, height_btns)

        self.botonLeft = Application.createSfSprite(self.DIRECTORIO+"img_INS_LEFT.png", posX_btns, 313, width_btns, height_btns)

        self.botonProg1 = Application.createSfSprite(self.DIRECTORIO+"img_PROG_1.png", posX_btns, 376, width_btns, height_btns)

        self.botonProg2 = Application.createSfSprite(self.DIRECTORIO+"img_PROG_2.png", posX_btns, 442, width_btns, height_btns)

        self.botonProg3 = Application.createSfSprite(self.DIRECTORIO+"img_PROG_3.png", posX_btns, 506, width_btns, height_btns)

        self.botonProg4 = Application.createSfSprite(self.DIRECTORIO+"img_PROG_4.png", posX_btns, 569, width_btns, height_btns)

        self.botonClear = Application.createSfSprite(self.DIRECTORIO+"img_INS_CLEAR_2.png", posX_btns, 634, width_btns, height_btns)
Exemplo n.º 10
0
 def __init__(self, xi, yi, xf, yf, default_value):
     self.current = default_value
     self.clicked = False
     self.DIRECTORIO = "images/gameplay/slider/"
     r_width = 768
     r_height = 133
     scale_x = 356.0/768.0
     scale_y = 45.0/143.0
      
     self.piece = Application.createSfSprite(self.DIRECTORIO+"piece.png", xi, yi - 10, (xf - xi)*(2.03/13.0), yf - yi + 9)
     self.fixed = Application.createSfSprite(self.DIRECTORIO+"fixed.png", xi, yi + (1.02/2.27)*(yf - yi), xf - xi, (yf - yi)*(1.25/2.27))
Exemplo n.º 11
0
    def _configure(self):
        Application._configure(self)

        import os
        self.home = os.path.abspath(
            os.path.expanduser(self.inventory.home))

        # should the following be in _init?
        import os
        if not os.path.exists(self.home):
            os.makedirs(self.home)
            
        return
    def setInitialState(self, stack_id,scale, scenario_boundaries, final, stack_desp):
        if final:
            boxes = Application.getColorBoxFromStackSolution(level_name, puzzle_number, stack_id+1)
        else:
            boxes = Application.getColorBoxFromStack(level_name, puzzle_number, stack_id+1)
        
        self.stack_boundaries = [(120 + 110*(stack_id+stack_desp) + 15)*scale + scenario_boundaries[0], 650,
                                (120 + 110*(stack_id+stack_desp) + 15)*scale + scenario_boundaries[0] + 90*scale, 650 + 30*scale]

        for box in boxes:
            self.stack.append(Drawable_Box(stack_id, box, stack_boundaries, scale, len(boxes)))

        self.scale = scale
        self.stack_boundaries = stack_boundaries
Exemplo n.º 13
0
    def DefinirBotones(self):
        #boton create
        self.boton1 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_create_1.png", 434, 504, 367, 140)
        self.boton2 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_create_2.png", 434, 504, 367, 140)

        #boton home
        self.botonHome1 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_home_1.png", 1200-157, 0, 157, 80)
        self.botonHome2 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_home_2.png", 1200-157, 0, 157, 80)

        image = sf.Image()
        image.LoadFromFile(self.DIRECTORIO+"buttons/CREATE.png")
        self.create = sf.Sprite(image)
        self.create.Resize(1013-829,661-500)
        self.create.SetCenter(0, 0)
        self.create.SetPosition(688,348)
Exemplo n.º 14
0
    def DefinirFondo(self):
        self.Fondo = Application.createSfSprite(self.DIRECTORIO+"bgs/TBG.png", 0, 0, 1200, 700)
        
        font = sf.Font()
        font = sf.Font.GetDefaultFont()
        #font.LoadFromFile('my_downloaded_font.ttf', 50)
        self.tittle = sf.String("LEVEL: " + self.backScreen + ", PUZZLE " + str(self.puzzle_number) + "(" + Application.username + ")", font)
        color = sf.Color(0, 0, 0)
        rect = self.tittle.GetRect()
        self.tittle.SetColor(color)
        self.tittle.SetCenter(0,0)        
        self.tittle.SetSize(35)
        self.tittle.SetPosition((1200 - rect.GetWidth())/2, 15)

        self.delimiter = Application.createSfSprite(self.DIRECTORIO+"gameplay/delimiter.png", 0, rect.GetHeight() + 47, 1200, 10)
Exemplo n.º 15
0
    def EndPuzzle(self):
        c = self.function_set.GetCount()
        #actualizar archivos
        #primero a ver si entra a los top 5!
        made_it = Application.updateTopFile("levels/" + self.backScreen + "/", str(self.puzzle_number) + "_top", Application.username, c)

        #ahora a ver si mejoro su marca personal.
        pers = Application.saveScore(Application.username, self.backScreen, self.puzzle_number, c)

        #levantar ventana final!
        from Game_Over import Game_Over
        nuevaVentana = Game_Over(c, made_it, pers)
        nuevaVentana.sonidos = self.sonidos
        self.window.Close()
        nuevaVentana.Update()
Exemplo n.º 16
0
    def post(self):
        try:
            app_id, command = self.validate_arguments()
        except tornado.web.MissingArgumentError:
            return

        app = Application(app_id, command, self.agent)
        app.start()

        agent.add_running_application(app_id, app)

        self.write(dict(
            app_id=app_id,
            command=command,
            result="started"
        ))
Exemplo n.º 17
0
 def __init__(self, style=STYLE_DEFAULT, fixed_size=None):
     View.__init__(self)
     self._window = self
     self._first_responder = None
     self._title = None
     self._style = style
     self._resizable = fixed_size is None
     self._application = Application.shared_application()
     self._min_size = None
     self._max_size = None
     self._zoomed = False
     self._key_window = False
     self._main_window = False
     if fixed_size is None:
         # normal window
         self._pyglet = PygletWindow(self, 
                                     style=style, 
                                     resizable=True)
     else:
         # fixed size window
         self._pyglet = PygletWindow(self, 
                                     style=style, 
                                     resizable=False, 
                                     width=fixed_size.width, 
                                     height=fixed_size.height)
     x, y = self._pyglet.get_location()
     width, height = self._pyglet.get_size()
     View.set_frame(self, Rect(x, y, width, height))
     self._application._add_window(self)
Exemplo n.º 18
0
    def BotonPlayStop(self):
        self.playingStepByStep = False
        image = sf.Image()
        if self.playing:
            self.working_area.DetenerEjecucion()
            self.working_area.ResetConfigs()
            self.function_set.ResetConfigs()
            Application.putOnDeleteList(self.message)
            self.message = None

            image.LoadFromFile(self.DIRECTORIO + "gameplay/play_1.png")
            self.botonPlayStop.SetImage(image)
        else:
            self.working_area.Ejecutar(self.function_set)
            image.LoadFromFile(self.DIRECTORIO + "gameplay/stop_1.png")
            self.botonPlayStop.SetImage(image)

        self.playing = not self.playing
Exemplo n.º 19
0
 def __init__(self, tipo, mensaje):
     self.errorCount = 4
     self.DIRECTORIO = "images/errors/"
     self.fade = Application.createSfSprite(self.DIRECTORIO + "fade.png", 0, 0, 0, 0)
     if tipo in ["ERROR_1", "ERROR_2"]:
         self.DefinirMensaje(tipo, 0, 0, 350, 200)
     else:
         self.DefinirMensaje(tipo)
     self.DefinirSprites()
Exemplo n.º 20
0
    def DefinirBotones(self):
        self.boton1 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_choose_1.png", 434, 564, 367, 120)
        self.boton2 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_choose_2.png", 434, 564, 367, 120)
        
        self.botonHome1 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_home_1.png", 1200-157, 0, 157, 80)
        self.botonHome2 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_home_2.png", 1200-157, 0, 157, 80)
        
        self.botonPrev1 = Application.createSfSprite(self.DIRECTORIO+"buttons/scroll_prev_1.png", 0, 0, 130, 700)
        self.botonPrev2 = Application.createSfSprite(self.DIRECTORIO+"buttons/scroll_prev_2.png", 0, 0, 130, 700)

        self.botonNext1 = Application.createSfSprite(self.DIRECTORIO+"buttons/scroll_next_1.png", 1070, 0, 130, 700)
        self.botonNext2 = Application.createSfSprite(self.DIRECTORIO+"buttons/scroll_next_2.png", 1070, 0, 130, 700)
Exemplo n.º 21
0
    def __init__(self):
        self.width = 1200
        self.heigth = 700
        self.blanco = sf.Color(250, 250, 250)
        self.negro =  sf.Color(0, 0, 0)
        self.window = sf.RenderWindow(sf.VideoMode(self.width, self.heigth), "DRAG BOX - PUZZLES (EASY)", sf.Style.Close)
        self.Evento = sf.Event()
        self.window.SetFramerateLimit(60)

        self.scores = Application.getScores(Application.username, "EASY")
Exemplo n.º 22
0
    def __init__(self):
        self.width = 1200
        self.heigth = 700
        self.blanco = sf.Color(250, 250, 250)
        self.negro =  sf.Color(0, 0, 0)
        self.window = sf.RenderWindow(sf.VideoMode(self.width, self.heigth), "CARGO BOT - PUZZLES (TUTORIAL)", sf.Style.Close)
        self.Evento = sf.Event()
        self.window.SetFramerateLimit(60)
        self.sonidos = None

        self.scores = Application.getScores(Application.username, "TUTORIAL")
Exemplo n.º 23
0
    def __init__(self):
        self.width = 1200
        self.heigth = 700
        self.blanco = sf.Color(250, 250, 250)
        self.negro =  sf.Color(0, 0, 0)
        self.window = sf.RenderWindow(sf.VideoMode(self.width, self.heigth), "DRAG BOX - CHANGE PROFILE", sf.Style.Close)
        self.Evento = sf.Event()
        self.window.SetFramerateLimit(60)
        self.usernames = Application.getFiles("profiles/")

        self.isSelected = False
        self.xSelected = 0
        self.ySelected = 0
        self.name_selected = None
Exemplo n.º 24
0
    def DefinirFondo(self):
        self.Fondo0 = Application.createSfSprite(self.DIRECTORIO+"bgs/TBG3.png", 0, 0, 1200, 700)
        self.Fondo = Application.createSfSprite(self.DIRECTORIO+"bgs/GBG.png", 0, 0, 1200, 700)

        self.credits = Application.createSfSprite(self.DIRECTORIO+"scores/credits.png", 0, 700 - 43, 113, 43)
        self.mmenu = Application.createSfSprite(self.DIRECTORIO+"scores/main_menu.png", 1200 - 197, 700 - 43, 197, 43)

        self.credits_2 = Application.createSfSprite(self.DIRECTORIO+"scores/credits_2.png", 0, 700 - 43, 113, 43)
        self.mmenu_2 = Application.createSfSprite(self.DIRECTORIO+"scores/main_menu_2.png", 1200 - 197, 700 - 43, 197, 43)
Exemplo n.º 25
0
    def __init__(self, stack_id, level_name, puzzle_number, scale, scenario_boundaries, final, stack_desp):
        self.DIRECTORIO = "images/gameplay/"
        self.stack_id = stack_id
        self.level_name = level_name
        self.puzzle_number = puzzle_number
        self.scenario_boundaries = scenario_boundaries
        self.final = final
        self.stack_desp = stack_desp
        self.stack = []

        self.base = Application.createSfSprite(self.DIRECTORIO+"base.png",
                                               (160 + 110*(stack_id+stack_desp) + 15)*scale + scenario_boundaries[0],650,
                                               90*scale, 30*scale)
        
        self.setInitialState(stack_id, level_name, puzzle_number, scale, scenario_boundaries, final, stack_desp)
def main_thread():
    #thread gesture recognition
    t1 = threading.Thread(target=main_predict_on_thread)
    t1.start()
    #thread main run application
    app = QtWidgets.QApplication(sys.argv)
    player = Application()
    player.show()
    player.resize(640, 480)
    sys.exit(app.exec_())
Exemplo n.º 27
0
    def __init__(self, level, puzzle_number):
        self.backScreen = level
        self.width = 1200
        self.heigth = 700
        self.window = sf.RenderWindow(sf.VideoMode(self.width, self.heigth), "CARGO BOT - TOP 5: "+ level + " PUZZLE " + str(puzzle_number), sf.Style.Close)
        self.Evento = sf.Event()
        self.sonidos = None

        self.data = Application.getTopScores(level, puzzle_number)

        self.posiciones = [(909, 190), (702, 289), (494, 386), (290, 485), (79, 582)]
        self.star_posiciones = [(1088, 222),(877, 319),(671, 412),(465, 509),(257, 609)]
        self.userSize = (289 - 79, 638 - 574)
        self.starSize = (324 - 257, 674 - 609)

        self.FillInTops(self.data, self.posiciones, self.userSize)
Exemplo n.º 28
0
    def DefinirBotones(self):
        self.botonHome1 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_home_1.png", 1200-157, 0, 157, 80)
        self.botonHome2 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_home_2.png", 1200-157, 0, 157, 80)

        self.botonBack1 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_back_1.png", 0, 0, 80, 80)
        
        self.botonBack2 = Application.createSfSprite(self.DIRECTORIO+"buttons/button_back_2.png", 0, 0, 80, 80)

        self.botonPlayStop = Application.createSfSprite(self.DIRECTORIO+"gameplay/play_1.png", 10, 91, 100, 70)

        self.botonStep = Application.createSfSprite(self.DIRECTORIO+"gameplay/stepbystep.png", 125, 100, 70, 50)
Exemplo n.º 29
0
 def FillInTops(self, data, posiciones, size):
     self.tops = []
     self.stars = []
     for i in range(len(data)):
         if data[i][0] == "__EMPTY__":
             t = sf.String("----------")                
         else:
             t = sf.String(data[i][0])
             print "valor: " + str(data[i][1])
             self.stars.append(Application.createSfSprite("images/buttons/stars/" + str(data[i][1]) + ".png",
                                                          self.star_posiciones[i][0], self.star_posiciones[i][1],
                                                          self.starSize[0], self.starSize[1]))
                               
         color = sf.Color(0, 0, 0)
         rect = t.GetRect()
         t.SetColor(color)
         t.SetCenter(0,0)        
         t.SetSize(25)
         t.SetPosition(posiciones[i][0] + (size[0] - rect.GetWidth())/2 + 5, posiciones[i][1] + (size[1] - rect.GetHeight())/2)
         self.tops.append(t)
Exemplo n.º 30
0
    def __init__(self, score, made_it, personal_mark):
        self.width = 1200
        self.heigth = 700
        self.window = sf.RenderWindow(sf.VideoMode(self.width, self.heigth), "DRAG BOX - CONGRATULATIONS!", sf.Style.Close)
        self.Evento = sf.Event()
        self.sonidos = None

        if not (personal_mark in ["BETTER", "NOT_BETTER", "FIRST_TIME", "EQUAL"] or made_it):
            self.img_score = Application.createSfSprite(self.DIRECTORIO+"scores/"+str(score)+".png", 181, 350, 1022-181, 336 - 251)
        else:
            self.img_score = Application.createSfSprite(self.DIRECTORIO+"scores/"+str(score)+".png", 181, 251, 1022-181, 336 - 251)
        
        if made_it:        
            self.img_gratz = Application.createSfSprite(self.DIRECTORIO+"scores/gratz.png", 181, 330, 1022 - 181, 250)
        elif personal_mark == "BETTER":
            self.img_gratz = Application.createSfSprite(self.DIRECTORIO+"scores/better.png", 181, 330, 1022 - 181, 250)
        elif personal_mark == "NOT_BETTER":
            self.img_gratz = Application.createSfSprite(self.DIRECTORIO+"scores/worse.png", 181, 330, 1022 - 181, 250)
        elif personal_mark == "FIRST_TIME":
            self.img_gratz = Application.createSfSprite(self.DIRECTORIO+"scores/first.png", 181, 330, 1022 - 181, 250)
        elif personal_mark == "EQUAL":
            self.img_gratz = Application.createSfSprite(self.DIRECTORIO+"scores/equal.png", 181, 330, 1022 - 181, 250)
Exemplo n.º 31
0
 def setUp(self):
     self.eventStore = EventStore.get()
     self.appStore = ApplicationStore.get()
     self.fileFactory = FileFactory.get()
     self.userConf = UserConfigLoader.get("user.ini")
     self.engine = PolicyEngine()
     self.ar1 = Application("ristretto.desktop",
                            pid=21,
                            tstart=1,
                            tend=2000)
     self.ar2 = Application("ristretto.desktop",
                            pid=22,
                            tstart=2600,
                            tend=2900)
     self.ag1 = Application("gimp.desktop", pid=23, tstart=1, tend=4000)
     self.ag2 = Application("gimp.desktop", pid=24, tstart=4500, tend=4590)
     self.appStore.insert(self.ar1)
     self.appStore.insert(self.ar2)
     self.appStore.insert(self.ag1)
     self.appStore.insert(self.ag2)
Exemplo n.º 32
0
from kicker.agents.neural_net_agent import NeuralNetAgent
from Application import Application, read_config

config = read_config()

randomness = 0.5

if 'randomness' in config:
    randomness = config['randomness']

agent = NeuralNetAgent(randomness=randomness)
app = Application(agent)

app.run()
Exemplo n.º 33
0
def app(browser):
    all_instances = Application(browser)
    return all_instances
Exemplo n.º 34
0
from Application import Application

if __name__ == '__main__':
    app = Application()
    app.run()
Exemplo n.º 35
0
from Application import Application

if __name__ == '__main__':
    app = Application()
    app.display()
Exemplo n.º 36
0
 def __init__(self, name=None):
     Application.__init__(self, name)
     Stager.__init__(self)
     return
Exemplo n.º 37
0
from Application import Application

if __name__ == '__main__':
    application = Application()
Exemplo n.º 38
0
    def loadDb(self,
               store: ApplicationStore = None,
               checkInitialised: bool = False):
        """Load the PreloadLogger database.

        Go through the directory and create all the relevant app instances and
        events. Can be made to insert all found apps into an ApplicationStore,
        or to exit if some Application instances are not properly initialised.
        """

        count = 0  # Counter of fetched files, for stats
        actors = set()  # Apps that logged anything at all
        empties = 0  # Matching files without content (logger crash)
        invalids = 0  # Files with corrupted content (logger crash)
        nosyscalls = []  # Logs with zero syscalls logged (not a bug)
        nosyscallactors = set()  # Apps that logged zero syscalls
        instanceCount = 0  # Count of distinct app instances in the dataset
        hasErrors = False  # Whether some uninitialised apps were found
        invalidApps = set()  # List of desktop IDs that could not be init'd
        eventCount = 0

        # List all log files that match the PreloadLogger syntax
        for file in os.listdir(self.path):
            # Ignore files that don't match
            if not PreloadLoggerLoader.pattern.match(file):
                continue

            count += 1

            # Process log files that match the PreloadLogger name pattern
            try:
                f = open(self.path + "/" + file, 'rb')
            except (IOError) as e:
                print("Error: could not open file %s: %s" % (file, str(e)),
                      file=sys.stderr)
            else:
                with f:
                    if os.fstat(f.fileno()).st_size == 0:
                        print("Info: file '%s' is empty. Skipping." % file)
                        continue

                    # Parse the first line to get the identity of the app,
                    # but sometimes the header ends up on the second line
                    # in some logs... So, parse until we find a match, and
                    # remember the line index of the header
                    idx = 0
                    headerLocation = 0
                    result = None
                    for binary in f:
                        try:
                            line = binary.decode('utf-8')
                        except (UnicodeDecodeError) as e:
                            print("Error: %s has a non utf-8 line: %s " %
                                  (file, str(e)),
                                  file=sys.stderr)
                            idx += 1
                            continue
                        result = PreloadLoggerLoader.header.match(line)
                        if result:
                            headerLocation = idx
                            break
                        idx += 1

                    # Files with a missing or corrupted header are invalid
                    if result is None:
                        print("%s is missing a header" % file, file=sys.stderr)
                        invalids += 1
                        continue

                    # Parse the header line, make sure it has the right length.
                    g = result.groups()
                    if (len(g) != 3):
                        print("%s has wrong group count: " % file,
                              result.group(),
                              file=sys.stderr)
                        invalids += 1
                        continue

                    # Filter interpreters, and rewrite them to get the identity
                    # of the app they launched instead.
                    items = space.split(g[2])
                    interpreterid = None

                    # Python
                    if (pyre.match(g[0])):
                        interpreterid = g[0]
                        g = self.parsePython(g, items)
                        # print("PYTHON APP: %s" % g[2])

                    # Bash
                    if (bashre.match(g[0])):
                        interpreterid = g[0]
                        g = self.parseBash(g, items)
                        # print("BASH APP: %s" % g[2])

                    # Java
                    if (javare.match(g[0])):
                        interpreterid = g[0]
                        g = self.parseJava(g, items)
                        # print("JAVA APP: %s" % g[2])
                    # Perl
                    if (perlre.match(g[0])):
                        interpreterid = g[0]
                        g = self.parsePerl(g, items)
                        # print("PERL APP: %s" % g[2])

                    # Mono
                    if (monore.match(g[0])):
                        interpreterid = g[0]
                        g = self.parseMono(g, items)
                        # print("MONO APP: %s" % g[2])

                    # PHP
                    if (phpre.match(g[0])):
                        interpreterid = g[0]
                        g = self.parsePHP(g, items)
                        # print("PHP APP: %s" % g[2])

                    # Get first and last event to calculate the timestamps.
                    tstart = float("inf")
                    tend = 0

                    skipCache = None
                    lineIdx = 0
                    f.seek(0, 0)
                    for binary in f:
                        # Ignore the header.
                        if lineIdx == headerLocation:
                            lineIdx += 1
                            skipCache = None
                            continue

                        # Decode line.
                        try:
                            line = binary.decode('utf-8')
                        except (UnicodeDecodeError) as e:
                            print("Error: %s has a non utf-8 line: %s " %
                                  (file, str(e)),
                                  file=sys.stderr)
                            lineIdx += 1
                            skipCache = None
                            continue

                        # Previous line did not end and was skipped, merge it.
                        if skipCache:
                            line = skipCache + line
                            skipCache = None

                        # Line continues...
                        if line.endswith('\\\n'):
                            skipCache = line
                            lineIdx += 1
                            continue

                        line = line.rstrip("\n").lstrip(" ")

                        # Line is a parameter to the last system call logged
                        if line.startswith(' '):
                            lineIdx += 1
                            continue

                        # Check that line is a syntactically valid system call
                        result = PreloadLoggerLoader.syscall.match(line)
                        if result is None:
                            if debugEnabled():
                                print("%s has a corrupted line (match): %s" %
                                      (file, line),
                                      file=sys.stderr)
                            lineIdx += 1
                            continue

                        # Update the timestamp (convert to ZG millisec format)
                        h = result.groups()
                        tstart = int(h[0]) * 1000
                        break

                    # TODO, first non-header line + tail code.
                    lastLine = tail(f)
                    result = None
                    if lastLine:
                        result = PreloadLoggerLoader.syscall.match(lastLine)

                    if result is None:
                        if debugEnabled():
                            print("%s's last line is corrupted: %s" %
                                  (file, lastLine),
                                  file=sys.stderr)
                    else:
                        # Update the timestamp (convert to ZG millisec format)
                        h = result.groups()
                        tend = int(h[0]) * 1000

                    # Check if the timestamps have been set
                    if tend == 0:
                        nosyscalls.append(g)
                        nosyscallactors.add(g[0])
                        continue

                    # Sometimes, short logs have event ordering problems... We
                    # can try to ignore these problems as all events are indi-
                    # vidually timestamped anyway.
                    if tstart > tend:
                        tend, start = tstart, tend

                    # TODO: process deletions and remove corresponding files

                    # Make the application
                    try:
                        app = Application(desktopid=g[0],
                                          pid=int(g[1]),
                                          tstart=tstart,
                                          tend=tend,
                                          interpreterid=interpreterid)
                        app.setCommandLine(g[2])
                    except (ValueError) as e:
                        print("MISSING: %s" % g[0], file=sys.stderr)
                        hasErrors = True
                        invalidApps.add(g[0])
                        continue

                    # Ignore study artefacts!
                    if app.isStudyApp():
                        continue

                    # Add command-line event
                    event = Event(actor=app, time=tstart, cmdlineStr=g[2])
                    app.addEvent(event)

                    # Add system call events
                    skipCache = None
                    lineIdx = 0
                    currentCall = None
                    prevTimestamp = 0
                    timeDelta = 0
                    f.seek(0, 0)
                    for binary in f:
                        # Ignore the header.
                        if lineIdx == headerLocation:
                            lineIdx += 1
                            skipCache = None
                            continue

                        # Decode line.
                        try:
                            line = binary.decode('utf-8')
                        except (UnicodeDecodeError) as e:
                            print("Error: %s has a non utf-8 line: %s " %
                                  (file, str(e)),
                                  file=sys.stderr)
                            lineIdx += 1
                            skipCache = None
                            continue

                        # Previous line did not end and was skipped, merge it.
                        if skipCache:
                            line = skipCache + line
                            skipCache = None

                        # Line continues...
                        if line.endswith('\\\n'):
                            skipCache = line
                            lineIdx += 1
                            continue

                        line = line[:-1]  # Remove ending "\n"

                        # Line is a parameter to the last system call logged
                        if line.startswith(' '):
                            if currentCall:
                                currentCall = (currentCall[0],
                                               currentCall[1] + '\n' + line)
                            elif debugEnabled():
                                print("%s has a corrupted line (no call): %s" %
                                      (file, line),
                                      file=sys.stderr)
                            lineIdx += 1
                            continue

                        # Check that line is a syntactically valid system call
                        result = PreloadLoggerLoader.syscall.match(line)
                        if result is None:
                            if debugEnabled():
                                print("%s has a corrupted line (match): %s" %
                                      (file, line),
                                      file=sys.stderr)
                            lineIdx += 1
                            continue

                        # Update the timestamp (convert to ZG millisec format)
                        h = result.groups()
                        timestamp = int(h[0]) * 1000

                        # Append the system call to our syscall list. Note that
                        # we do something odd with the timestamp: because PL
                        # only logs at second precision, a lot of system calls
                        # have the same timestamp, which causes the EventStore
                        # to sort them in the wrong order. So, every time we
                        # have a timestamp identical to the previous one, we
                        # increase a counter that sorts them. This works under
                        # the assumption that there are at most 1000 events per
                        # second.
                        if timestamp == prevTimestamp:
                            timeDelta += 1
                        else:
                            timeDelta = 0

                        # Process the last system call into an Event, and clear
                        # up the syscalls list to keep RAM free!
                        if currentCall:
                            event = Event(actor=app,
                                          time=currentCall[0],
                                          syscallStr=currentCall[1])
                            app.addEvent(event)
                            eventCount += 1

                        # Create the new syscalls list.
                        currentCall = (timestamp + timeDelta, h[1])
                        prevTimestamp = timestamp

                        lineIdx += 1

                    # Add the found process id to our list of actors, using the
                    # app identity that was resolved by the Application ctor
                    actors.add(app.desktopid)

                    if checkInitialised and not app.isInitialised():
                        print("MISSING: %s" % g[0], file=sys.stderr)
                        hasErrors = True

                    # Insert into the ApplicationStore if one is available
                    if store is not None:
                        store.insert(app)
                        instanceCount += 1

        if checkInitialised and hasErrors:
            if invalidApps:
                print("Invalid apps:", file=sys.stderr)
                for a in sorted(invalidApps):
                    print("\t%s" % a, file=sys.stderr)
            sys.exit(-1)

        # print("Apps that logged valid files:")
        # for act in sorted(actors):
        #     print(act)

        # print("\nApps that logged files without a single system call:")
        # for act in sorted(nosyscallactors):
        #     print(act)

        self.appCount = len(actors)
        self.instCount = count - empties - invalids - len(nosyscalls)
        self.eventCount = eventCount
        self.validEventRatio = 100 - 100 * (invalids + empties +
                                            len(nosyscalls)) / (count)

        print("Finished loading DB.\n%d files seen, %d valid from %d apps, "
              "%d empty files, "
              "%d logs with 0 syscalls from %d apps, "
              "%d invalid.\nIn "
              "total, %.02f%% files processed." %
              (count, self.instCount, self.appCount, empties, len(nosyscalls),
               len(nosyscallactors), invalids, self.validEventRatio))
        print("Instance count: %d" % instanceCount)
Exemplo n.º 39
0
from Application import Application

application = Application([])
application.start()
Exemplo n.º 40
0
import tkinter as tk

from Application import Application
from lib import *

if __name__ == '__main__':
    root = tk.Tk()
    root.title('paint')
    center_window(root)
    Application(master=root)
    root.mainloop()
    print('terminated')
Exemplo n.º 41
0
 def createApplication(self):
     return Application(server=self, useSessionSweeper=False)
Exemplo n.º 42
0
import os
import ctypes
import pygame
from Application import Application

screen_size = ctypes.windll.user32.GetSystemMetrics(
    0), ctypes.windll.user32.GetSystemMetrics(1)
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (screen_size[0] / 2 - 569,
                                                screen_size[1] / 2 - 320)
pygame.init()

if __name__ == "__main__":
    app = Application()
    app.Run()
Exemplo n.º 43
0
class TestBoard(TestCase):
    def setUp(self):
        self.app = Application()
        self.app.load_deck()

    def test_algerian_create(self):
        fields = algerian(self.app._double_deck)
        # check numbers of fields
        self.assertTrue(17, len(fields))
        # check types of fields
        for field in fields[:8]:
            self.assertTrue(isinstance(field, Stack))
        for field in fields[8:16]:
            self.assertTrue(isinstance(field, Pile))
        self.assertTrue(isinstance(fields[16], LongDeck))

    def test_algerian_shuffle(self):
        fields = algerian(self.app._double_deck)
        fields = algerian_shuffle(fields, self.app._double_deck)
        for field in fields[:8]:
            self.assertFalse(field.show_cards())
        for field in fields[8:12]:
            self.assertTrue(len(field.show_cards()) == 2)
        for field in fields[12:16]:
            self.assertTrue(len(field.show_cards()) == 1)
        self.assertTrue(len(fields[16].show_cards()) == 68)
        for field in fields[16].show_subfields():
            self.assertTrue(len(field.show_cards()) == 4)

    def test_canfield_create(self):
        fields = canfield(self.app._deck)
        # check number of fields
        self.assertEqual(10, len(fields))
        # check types of fields
        for field in fields[:4]:
            self.assertTrue(isinstance(field, Stack))
        self.assertTrue(isinstance(fields[4], Deck))
        for field in fields[5:9]:
            self.assertTrue(isinstance(field, Pile))
        self.assertTrue(isinstance(fields[9], UnputtablePile))

    def test_canfield_shuffle(self):
        fields = canfield(self.app._deck)
        fields = canfield_shuffle(fields, self.app._deck)
        for field in fields[:4]:
            self.assertFalse(field.show_cards())
        self.assertEqual(34, len(fields[4].show_cards()))
        for field in fields[5:9]:
            self.assertEqual(1, len(field.show_cards()))
        self.assertEqual(14, len(fields[9].show_cards()))

    def test_fifteen_puzzle_create(self):
        fields = fifteen_puzzle(self.app._deck)
        # check number of fields
        self.assertEqual(15, len(fields))
        # chcek type of fields
        for field in fields:
            self.assertTrue(isinstance(field, Fours))

    def test_fifteen_puzzle_shuffle(self):
        fields = fifteen_puzzle(self.app._deck)
        fields = fifteen_puzzle_shuffle(fields, self.app._deck)
        for field in fields[:13]:
            self.assertEqual(4, len(field.show_cards()))
        self.assertEqual(0, len(fields[13].show_cards()))
        self.assertEqual(0, len(fields[14].show_cards()))

    def test_klondike_create(self):
        fields = klondike(self.app._deck)
        self.assertEqual(12, len(fields))
        self.assertTrue(isinstance(fields[0], Deck))
        for field in fields[1:8]:
            self.assertTrue(isinstance(field, Pile))
        for field in fields[8:]:
            self.assertTrue(isinstance(field, Stack))

    def test_klondike_shuffle(self):
        fields = klondike(self.app._deck)
        fields = klondike_shuffle(fields, self.app._deck)
        self.assertEqual(24, len(fields[0].show_cards()))
        for i, field in enumerate(fields[1:8]):
            self.assertEqual(i + 1, len(field.show_cards()))

    def test_natali_create(self):
        fields = natali(self.app._double_deck)
        self.assertEqual(17, len(fields))
        for field in fields[:8]:
            self.assertTrue(isinstance(field, Stack))
        for field in fields[8:16]:
            self.assertTrue(isinstance(field, Pile))
        self.assertTrue(isinstance(fields[16], Deck))

    def test_natali_shuffle(self):
        fields = natali(self.app._double_deck)
        fields = natali_shuffle(fields, self.app._double_deck)
        for field in fields[:8]:
            self.assertFalse(field.show_cards())
        for i, field in enumerate(fields[8:16:-1]):
            self.assertEqual(i + 1, len(field.show_cards()))
        self.assertEqual(68, len(fields[16].show_cards()))

    def test_osmosis_create(self):
        fields = osmosis(self.app._deck)
        self.assertEqual(9, len(fields))
        for field in fields[:4]:
            self.assertTrue(isinstance(field, Fours))
        for field in fields[4:8]:
            self.assertTrue(isinstance(field, Cascade))
        self.assertTrue(isinstance(fields[8], Deck))

    def test_osmosis_shuffle(self):
        fields = osmosis(self.app._deck)
        fields = osmosis_shuffle(fields, self.app._deck)
        for field in fields[:4]:
            self.assertEqual(4, len(field.show_cards()))
        self.assertEqual(1, len(fields[4].show_cards()))
        for field in fields[5:8]:
            self.assertEqual(0, len(field.show_cards()))
        self.assertEqual(35, len(fields[8].show_cards()))
Exemplo n.º 44
0
def main():
	# Data centre sizes
	MY_RESOURCE_TYPES = {
		"L":{ 
				"CPU":		{'CAPACITY':100.0, 'EXECOST': LinearCostFunc(1.0,0.0),'OVERLOADCOST': NoCostFunc(),'MU':1},
				"NET_UP":	{'CAPACITY':100.0, 'EXECOST': NoCostFunc(),'OVERLOADCOST': NoCostFunc(),'MU':1},
				"NET_DOWN":	{'CAPACITY':100.0, 'EXECOST': NoCostFunc(),'OVERLOADCOST': NoCostFunc(),'MU':1}
			},
		"M":{ 
				"CPU":		{'CAPACITY':50.0, 'EXECOST': LinearCostFunc(1.0,0.0),'OVERLOADCOST': NoCostFunc(),'MU':1},
				"NET_UP":	{'CAPACITY':50.0, 'EXECOST': NoCostFunc(),'OVERLOADCOST':NoCostFunc(),'MU':1},
				"NET_DOWN":	{'CAPACITY':50.0, 'EXECOST': NoCostFunc(),'OVERLOADCOST': NoCostFunc(),'MU':1}
			},
		"S":{ 
				"CPU":		{'CAPACITY':10.0, 'EXECOST': LinearCostFunc(1.0,0.0),'OVERLOADCOST': NoCostFunc(),'MU':1},
				"NET_UP":	{'CAPACITY':10.0, 'EXECOST': NoCostFunc(),'OVERLOADCOST': NoCostFunc(),'MU':1},
				"NET_DOWN":	{'CAPACITY':10.0, 'EXECOST': NoCostFunc(),'OVERLOADCOST': NoCostFunc(),'MU':1}
			}
		}
	
	#workloadName = "workload_v1_6_a5mini_1may"
	workloadName = "workfile_tripple_production"
	nbrApps = 5
	depth = 4
	mode = "_continuous"
	testCase  = "_cost_ver"

	logging.basicConfig(filename='activities.log', level=logging.DEBUG, filemode='w')
	logging.info("---- %s ----" % time.strftime("%d/%m/%Y - %H:%M:%S"))
	
	applications = {}
	applicationTypes = Application.TYPES.keys()
	for i in range(0, nbrApps):
		#applications.update({'A%i'%i : Application('A%i'%i, Application.TYPES[random.choice(applicationTypes)])})
		applications.update({'A%i'%i : Application('A%i'%i, Application.TYPES['SYMMETRIC'])})

	env = simpy.Environment()

	topologyMaker = TopologyMaker(env, None, applications)

	datacentres, links, leafnodes = topologyMaker.GenerateTreeFromParameters(	childStruct 	= [2, 2, 1], 
																				sizeStruct 		= [	MY_RESOURCE_TYPES['L'],
																									MY_RESOURCE_TYPES['M'],
																									MY_RESOURCE_TYPES['S'] ], 
																				uplinkStruct 	= [10000,1000,1000], 
																				downlinkStruct 	= [10000,1000,1000], 
																				latencyStruct 	= [1,1,1] )
																				
	logging.info('Topology generated, with %i datacentres' % len(datacentres))
	
	topology = Topology(env, datacentres, links, leafnodes)
	
	scheduler = optScheduler(env, topology, applications)
	logging.info('%s scheduler created' % type(scheduler).__name__)
	
	coordinator = Coordinator(env, topology, scheduler, depth)
	
	workload = Workload(env,'workloads/'+workloadName+'.json', coordinator)
	monitor = SystemMonitor(env, 1, 0.2, workloadName+mode+testCase, topology, coordinator, applications, scheduler, 	
															[	("TOTAL_OVERLOAD", SystemMonitor.measureSystemOverloaFactor),
																("COMPONENT_OVERLOAD", SystemMonitor.measureComponentOverloadFactor),
																("RESOURCE_UTILISATION", SystemMonitor.measureComponentResourceUtilisation),
																("APP_RESOURCE_UTILISATION", SystemMonitor.measureUtilisationPerApp),
																("APP_RTT", SystemMonitor.measureAppLatency),
															], 
															[	("TOTAL_OVERLOAD", SystemMonitor.fileCSVOutput, None),
																("COMPONENT_OVERLOAD", SystemMonitor.fileCSVOutput, SystemMonitor.composeDCLinkHeader),
																("RESOURCE_UTILISATION", SystemMonitor.fileCSVOutput, SystemMonitor.composeDCLinkHeader),
																("APP_RESOURCE_UTILISATION", SystemMonitor.fileCSVOutput, None),
																("APP_RTT", SystemMonitor.fileCSVOutput, SystemMonitor.composeLatencyHeader)
															],
															[])
	
	#workload.produceWorkload()
	env.process(workload.produceWorkload())
	env.process(monitor.measure())
	
	logging.info("Controller started")
	controller = PeriodicController(env, coordinator, 1, 0.1)
	
	logging.info("Simulation started")
	env.run(until=workload.getWorkloadTimeSpan())
	logging.info("Simulation Done")
	
	monitor.compose()
	logging.info("Composing results")
	
	monitor.produceOutput()
	scheduler.output(workloadName+mode+testCase)
	
	print "DONE"
Exemplo n.º 45
0
 def __init__(self):
     Application.__init__(self, (800, 600))
     self.player = Player()
Exemplo n.º 46
0
 def __init__(self, name):
     Application.__init__(self, name)
     self._pid = None
     return
Exemplo n.º 47
0
 def createApplication(self):
     """Create and return an application object. Invoked by __init__."""
     return Application(server=self)
Exemplo n.º 48
0
from Application import Application

if __name__ == '__main__':
    gameApp = Application()
    gameApp.run()
Exemplo n.º 49
0
from Application import Application
from unittest.mock import MagicMock
from ratelimit import RateLimitException
from time import sleep

instance = Application()

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

def testThrottlePollFail():
  mock = MagicMock()

  # test the function
  try:
    while True:
      instance.throttledPoll(mock)

  except RateLimitException:
    assert(mock.call_count == 1)

def testThrottlePoll():
  mock = MagicMock()

  # test the function
  try:
    instance.throttledPoll(mock)
    sleep(5)
    instance.throttledPoll(mock)

  except RateLimitException:
Exemplo n.º 50
0
 def setUp(self):
     self.console_input = PromptFake()
     self.console_output = ConsoleSpy()
     self.app = Application(self.console_input, self.console_output)
Exemplo n.º 51
0
from Application import Application
"""
Main: Run this file to start Application
"""

if __name__ == '__main__':

    application = Application()

    application.setup_environment()
Exemplo n.º 52
0
 def setUp(self):
     self.app = Application()
     self.app.load_deck()
Exemplo n.º 53
0
#!/usr/bin/python3

import sys
from Application import Application, Window

app = Application(sys.argv)
win = Window()
sys.exit(app.exec_())
Exemplo n.º 54
0
from Application import Application

application = Application()

application.run()
Exemplo n.º 55
0
def main(started_at=None):
    """
    main entry point for the program

    :param started_at: optional point in time where the application has been started
    :return:
    """

    # ### SETUP APPLICATION
    locale.setlocale(locale.LC_ALL, '')
    app_started_at = started_at or datetime.utcnow().replace(tzinfo=tz.tzutc())

    application = Application(appname=six.u(os.path.basename(__file__).split('.')[0]), appauthor=__author__)
    _ = application.ugettext

    # ### SETUP CONFIGURATION
    default_configuration = OrderedDict()

    default_configuration['Privacy'] = OrderedDict()
    default_configuration['Privacy']['Participate in anonymous system analytics'] = 'Yes'

    default_configuration['Logging'] = OrderedDict()
    default_configuration['Logging']['Logging to'] = 'Stream, File'
    default_configuration['Logging']['Disable syslog on'] = 'uberspace.de'

    configuration = application.configuration(
        filename=os.path.join(application.user_config_dir, application.appname.lower() + '.conf'),
        default=default_configuration)

    # get list of hosts on which syslog will be disabled (e.g. on servers like uberspace.de)
    disable_syslog_on_hosts = configuration.get('Logging', 'Disable syslog on').split(',')
    disable_syslog_on_hosts = [hostname.strip() for hostname in disable_syslog_on_hosts]

    # ### SETUP COMMAND LINE OPTIONS
    # command line options in CSV format in a formatted string for easier translation
    cli_options_csvdata = """\
        Argument Flags\tAction\tGroup\tHelp\tOther Options
        --reset\tstore_true\t{reset_opts}\t{reset}\tdefault=False
        --delete\tstore\t{reset_opts}\t{deletes}\tdefault=0
        -h, --help\tstore_true\t{other_opts}\t{help}\tdefault=False
        -v\tcount\t{other_opts}\t{verbose}\tdefault=0
        -V, --version\tversion\t{other_opts}\t{version}\t
        -q, --quiet\tstore_true\t{other_opts}\t{quiet}\tdefault=False
        --logging\tstore\t{other_opts}\t{logging}\tdefault=stream,file
        --nosyslog\tstore_true\t{other_opts}\t{nosyslog}\tdefault={enable_syslog}"""

    cli_options = textwrap.dedent(cli_options_csvdata.format(
        # Translate: Command line option group
        verbose_opts=_('Options for verbosity'),
        # Translate: Command line option group
        other_opts=_('Other Options'),
        # Translate: Command line option group
        reset_opts=_('Application Resetting'),
        # Translate: Command line option to show help
        help=_('Show help and exit'),
        # Translate: Command line option to show version
        version=_('Show version and exit'),
        # Translate: Command line option to show verbose messages
        verbose=_('Show additional information; stackable with -vv or -vvv'),
        # Translate: Command line option to supress all output, overwriting the command line open '-v'
        quiet=_('Suppress all output; overwrites -v, -vv and -vvv'),
        # Translate: Command line option to reset the application
        reset=_('Deletes all reclaimable configuration files'),
        # Translate: Command line option to delete specific configuration files
        deletes=_('Delete specific configuration files and tries to regenerate them at the next start'),
        # Translate: Command line option to configure logging messages (choices: stream, file, stream+file, off)
        logging=textwrap.dedent(_('''\
                Toggles logging; possible values: stream, file, syslog, nteventlog, off or any comma separated list \
                (e.g. stream,file; stream,sys; file,nt ...)''')),
        # Translate: Command line option to disable logging to syslog
        nosyslog=_('disable automatically logging to syslog'),
        # enable syslog by default on all machines except the ones with platform.node() occurring in server_hostnames
        enable_syslog=any(name in platform.node().lower() for name in disable_syslog_on_hosts)))

    # create a temporary argument parser to get initial options to setup logging
    # this parser will be overwritten later to enable localisation of parser messages (like the command line help)
    parser = application.parser(cli_options,
                                copyright=_(__copyright__),
                                contact=_(__contact__),
                                license=_(__license__),
                                author=_(__author__)
                                doc=_(__doc__))
    args = parser.parse_args()

    # ### SETUP LOGGER
    logger = logging.getLogger(application.appname.lower())
    logger.setLevel(logging.DEBUG)
    syslog = logging.getLogger(application.appname.lower() + "_syslog")
    syslog.setLevel(100)

    logging_handlers = args.logging.split(',') if args.nosyslog else '{},system'.format(args.logging).split(',')
    try:
        logging_handlers.extend([handler.strip() for handler in configuration.get('Logging', 'Handlers').split(',')])
    except (configparser.NoSectionError, configparser.NoOptionError):
        pass
    logger, syslog = application.setup_logging_handlers(logging_handlers, verbose=args.v, logger=logger, syslog=syslog)

    # ### SETUP FINAL PARSER
    # this second initialisation enables localisation of the command line interface if preferred
    parser = application.parser(cli_options, copyright=_(__copyright__), contact=_(__contact__), license=_(__license__))
    parser.epilog = '\n{copy}\n{license}\n\n{contact}\n'.format(copy=_(__copyright__),
                                                                license=_(__license__),
                                                                contact=__contact__)
    args = parser.parse_args()

    # ### HANDLE COMMAND LINE ARGUMENTS
    if args.help:
        # handle command line help manually to enable localisation
        parser.print_help()
        sys.exit(0)

    if args.reset:
        application.reset(['language', 'configuration', 'cache', 'log', 'data'])
        for handler in logger.handlers and not args.quiet:
            handler.setLevel(logging.INFO)
        logger.info('Application has been reset. Please restart.')
        sys.exit(0)

    if args.delete:
        to_delete = []
        to_delete.extend([x.lower().strip() for x in args.delete.split(',')])
        application.reset(to_delete)

    # ### SETUP FINISHED

    # ### START APPLICATION
    # Translate: Everything between curled brackets are placeholder;
    # Please replace the %X to set proper date formatting for your language.
    # See http://strftime.org for details.
    logger.info('{application} started at {time}'.format(application=application.appname.lower(), time=app_started_at))

    record = Sniffer.record(detailed=True, format='json', cache=application.user_cache_dir)
    if record.startswith('"'):
        record = record[1:]
    if record.endswith('"'):
        record = record[:-1]
    # record = json.loads(record, encoding='utf8')

    url = 'http://localhost:5000'
    endpoint = '/alpha/log/systeminformation'

    # todo: use Module "request" for Http POST requests for Python 3 Support
    request = urllib2.Request(url + endpoint, record)
    project_url = 'https://github.com/piaballerstadt/Sniffer'
    request.add_header('User-Agent', 'Sniffer/{version} by {author} ({url})'.format(version='0.1',
                                                                                    author='Pia Ballerstadt',
                                                                                    url=project_url))

    try:
        f = urllib2.urlopen(request)
        print(f.read())
    except urllib2.HTTPError as e:
        print('HTTP Error {code}: {message}'.format(code=e.code, message=e.read()))
Exemplo n.º 56
0
parser = argparse.ArgumentParser()
parser.add_argument("-v",
                    "--verbose",
                    help="increase output verbosity",
                    action="store_true")
parser.add_argument("-c",
                    "--charachter",
                    type=str,
                    help="charachter name to fetch details")
parser.add_argument("-l",
                    "--list_of_characters",
                    help="get list of characters",
                    action="store_true")

args = parser.parse_args()
app = Application()

# app begins
chars = CharachterPage()

if args.list_of_characters:
    list_of_characters = [str(x['*']) for x in chars.getCharachtersList()]
    pprint(list_of_characters)
    sys.exit(0)

if args.charachter:
    char_name = urllib.quote(args.charachter)
    file_name_text = '/'.join(
        [app.settings['storage_folder']['Charachters_text'], char_name])
    file_name_info = '/'.join(
        [app.settings['storage_folder']['Charachters_info'], char_name])
Exemplo n.º 57
0
import os
import argparse
import urllib
from pprint import pprint
from Houses import HousesPage
from Application import Application


# Command line options
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
parser.add_argument("-s", "--house", type=str, help="house name to fetch details")
parser.add_argument("-l", "--list_of_houses", help="get list of houses", action="store_true")

args = parser.parse_args()
app = Application()
list_of_houses = []

# app begins
houses = HousesPage(dict())
if args.list_of_houses:
  list_of_houses = houses.getListOfHouses()
  pprint (list_of_houses)

if args.house:
    house_name = urllib.quote(args.house)

    # setup persistent storage locations
    file_name_text = '/'.join([app.settings['storage_folder']['Houses_text'],house_name])
    file_name_info = '/'.join([app.settings['storage_folder']['Houses_info'],house_name])
    file_name_nlp = '/'.join([app.settings['storage_folder']['Houses_nlp'],house_name])
Exemplo n.º 58
0
    def test_app_types(self):
        ff = Application("firefox.desktop", pid=1, tstart=0, tend=2)
        cf = Application("catfish.desktop", pid=2, tstart=21, tend=32)
        th = Application("thunar.desktop", pid=3, tstart=5, tend=8)
        gd = Application("gnome-disks.desktop", pid=4, tstart=2, tend=4)

        self.assertTrue(ff.isUserlandApp())
        self.assertTrue(cf.isDesktopApp())
        self.assertTrue(th.isDesktopApp())
        self.assertTrue(gd.isDesktopApp())
Exemplo n.º 59
0
import Tkinter as tk
from Application import Application
from Style import Style

transferedArtStyles = [
    Style("Starry night",
          "chainer_fast_neuralstyle/models/thumbnails/starry-night.jpg",
          "chainer_fast_neuralstyle/models/starry.model"),
    Style("Kanagawa",
          "chainer_fast_neuralstyle/models/thumbnails/kanagawa-style.jpg",
          "chainer_fast_neuralstyle/models/kanagawa.model"),
    Style("Kandinsky",
          "chainer_fast_neuralstyle/models/thumbnails/kandinsky.jpg",
          "chainer_fast_neuralstyle/models/kandinsky_e2_full512.model"),
    Style("Candy",
          "chainer_fast_neuralstyle/models/thumbnails/candy-style.jpg",
          "chainer_fast_neuralstyle/models/candy_512_2_49000.model"),
    Style("Cubist",
          "chainer_fast_neuralstyle/models/thumbnails/cubist-style.jpg",
          "chainer_fast_neuralstyle/models/cubist.model")
]

root = tk.Tk()
root.attributes("-fullscreen", True)

app = Application(root, transferedArtStyles)
root.mainloop()
Exemplo n.º 60
0
    def setUp(self):
        self.userConf = UserConfigLoader.get("user.ini")
        self.appStore = ApplicationStore.get()
        self.eventStore = EventStore.get()
        self.fileStore = FileStore.get()
        self.fileFactory = FileFactory.get()
        self.sim = AttackSimulator()
        self.a1 = Application("ristretto.desktop", pid=1, tstart=1, tend=2000)
        self.a2 = Application("firefox.desktop", pid=2, tstart=1, tend=2000)
        self.a3 = Application("ristretto.desktop", pid=3, tstart=3000,
                              tend=6000)
        self.ac = Application("catfish.desktop", pid=100, tstart=1, tend=2900)
        self.appStore.insert(self.a1)
        self.appStore.insert(self.a2)
        self.appStore.insert(self.a3)
        self.appStore.insert(self.ac)

        self.p001 = "/home/user/.cache/firefox/file"
        s001 = "open64|%s|fd 10: with flag 524288, e0|" % self.p001
        e001 = Event(actor=self.a1, time=10, syscallStr=s001)
        e001.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e001)
        e001b = Event(actor=self.a2, time=11, syscallStr=s001)
        e001b.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e001b)

        self.p002 = "/home/user/Images/picture.jpg"
        s002 = "open64|%s|fd 10: with flag 524288, e0|" % self.p002
        e002 = Event(actor=self.a1, time=12, syscallStr=s002)
        e002.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e002)
        e002b = Event(actor=self.ac, time=30, syscallStr=s002)
        e002b.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e002b)

        self.p003 = "/home/user/Downloads/logo.jpg"
        s003 = "open64|%s|fd 10: with flag 524288, e0|" % self.p003
        e003 = Event(actor=self.a1, time=13, syscallStr=s003)
        e003.evflags |= EventFileFlags.designation  # this event by designation
        self.eventStore.append(e003)
        e003b = Event(actor=self.a3, time=3003, syscallStr=s003)
        e003b.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e003b)

        self.p004 = "/home/user/Downloads/logo.png"
        s004 = "open64|%s|fd 10: with flag 64, e0|" % self.p004
        e004 = Event(actor=self.a1, time=14, syscallStr=s004)
        e004.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e004)

        self.p005 = "/home/user/Dropbox/Photos/holidays.jpg"
        s005 = "open64|%s|fd 10: with flag 524288, e0|" % self.p005
        e005 = Event(actor=self.a1, time=15, syscallStr=s005)
        e005.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e005)
        e005b = Event(actor=self.a1, time=1005, syscallStr=s005)
        e005b.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e005b)

        self.p006 = "/home/user/Images/random.txt"
        s006 = "open64|%s|fd 10: with flag 524288, e0|" % self.p006
        e006 = Event(actor=self.a1, time=16, syscallStr=s006)
        e006.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e006)

        self.p007 = "/home/user/Images/file.jpg"
        s007 = "open64|%s|fd 10: with flag 524288, e0|" % self.p007
        e007 = Event(actor=self.a1, time=17, syscallStr=s007)
        e007.evflags |= EventFileFlags.designation  # this event by designation
        self.eventStore.append(e007)

        self.p008 = "/home/user/Images/other.foo"
        s008 = "open64|%s|fd 10: with flag 64, e0|" % self.p008
        e008 = Event(actor=self.a1, time=18, syscallStr=s008)
        e008.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e008)

        self.p009 = "/home/user/Downloads/unknown.data"
        s009 = "open64|%s|fd 10: with flag 64, e0|" % self.p009
        # e009 = Event(actor=self.a1, time=18, syscallStr=s009)
        # e009.evflags |= EventFileFlags.designation  # this event by designation
        # self.eventStore.append(e009)
        e009b = Event(actor=self.a3, time=3009, syscallStr=s009)
        e009b.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e009b)

        self.p010 = "/home/user/Dropbox/Photos/holidays.metadata"
        s010 = "open64|%s|fd 10: with flag 524288, e0|" % self.p010
        e010 = Event(actor=self.a1, time=20, syscallStr=s010)
        e010.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e010)

        self.p011 = "/home/user/Dropbox/Photos/holidays.evenmoremetadata"
        s011 = "open64|%s|fd 11: with flag 524288, e0|" % self.p011
        e011 = Event(actor=self.a3, time=3020, syscallStr=s011)
        e011.evflags &= ~EventFileFlags.designation  # not by designation
        self.eventStore.append(e011)

        self.eventStore.simulateAllEvents()

        self.acCache = AccessListCache.get()
        self.lookUps = dict()
        self.allowedCache = dict()