Esempio n. 1
0
    def __init__(self, stabilisation_time=None, queue=None, parameters=None, filename='test'):
        if parameters == None:
            self.parameters = {'ax1_start': 0, 'ax1_stop': 10, 'ax1_step': 1,
                                'ax2_start': 0, 'ax2_stop': 10, 'ax2_step': 1,
                                'lockin_delay': None}
        else:
            self.parameters = parameters

        self.ax1 = Stage(axis=2)
        self.ax2 = Stage(axis=1)
        self.lockin = Lockin(address="GPIB0::2::INSTR")
        self.pulser = Pulser(address="GPIB0::6::INSTR")
        ax1_steps = int(abs(self.parameters['ax1_start']-self.parameters['ax1_stop'])/self.parameters['ax1_step']+1)
        ax2_steps = int(abs(self.parameters['ax2_start']-self.parameters['ax2_stop'])/self.parameters['ax2_step']+1)
        self.results = np.zeros((ax1_steps, ax2_steps, 3))
        self.elapsed_time = 0
        self.queue = queue

        self.filename = filename
        self.file_written = False
        self.stop_measurement = False

        self.recomm_delay = self.lockin.get_timeconstant()*3*1000
        if self.parameters['lockin_delay'] == None:
            self.parameters['lockin_delay'] = self.recomm_delay
Esempio n. 2
0
    def init_stages(self, cassandra_conf, stage_log):
        assert isinstance(cassandra_conf, CassandraConf)
        stg_name_list = Cassandra.get_all_stage_name_list()
        for stg_name in stg_name_list:
            cur_num_workers = cassandra_conf.get_stg_num_workers(stg_name)
            cur_scheduler_generator = cassandra_conf.get_stg_scheduler_generator(stg_name)
            cur_scheduler = cur_scheduler_generator(self.env)
            cur_schedule_resource = cassandra_conf.get_stg_schedule_resource(stg_name)
            cur_req_cost_func = self.get_req_cost_func(cur_schedule_resource)
            [is_cur_stage_special, cur_stage_type_name, cur_stage_type_data_dict] = \
                cassandra_conf.get_special_stage_constructor_additional_param_dict(stg_name)
            cur_stage_name = self.pn_name + '_' + stg_name
            if not is_cur_stage_special:
                cur_stage = Stage(self.env, cur_stage_name, cur_num_workers, cur_scheduler,
                                  cur_req_cost_func, log_file=stage_log)
            else:
                print 'stage:' + stg_name + ' is a ' + str(cur_stage_type_name) + 'scheduler:' + str(cur_scheduler)
                cur_stage_kwargs_dict = self._get_basic_stage_init_dict(cur_stage_name, cur_num_workers, cur_scheduler,
                                                                        cur_req_cost_func, stage_log)
                cur_stage_kwargs_dict.update(cur_stage_type_data_dict)
                self._transform_resource_str_to_real_obj(cur_stage_kwargs_dict)
                cur_stage = Stage.create_special_stage(cur_stage_type_name, cur_stage_kwargs_dict)

            cur_stage.set_monitor_interval(cassandra_conf.get_stg_monitor_interval())
            self.__dict__.update({stg_name: cur_stage})
Esempio n. 3
0
 def __init__(self, menu: Menu, lan):
     self.figure = Figure([])  # type: Figure
     self.stage = Stage()  # type: Stage
     self.stage.block_drawer = WiredBlockDrawer()
     self.figure.block_drawer = GhostBlockDrawer()
     self.menu = menu
     self.lan = lan
Esempio n. 4
0
 def stage1(self):
   self.initPlayers(self.numPlayers)
   self.deck.shuffle()
   stage1 = Stage(self.deck, self.players, self.printDetail, self.hazardsRemoved)
   self.hazardsRemoved = stage1.runStage(self.deck, self.strategyMap)
   # print(list(map(formatCard,self.hazardsRemoved)))
   return self.deck
Esempio n. 5
0
    def get_datanode(env, name, phy_node, datanode_conf, stage_log=sys.stdout):
        if datanode_conf.datanode_xceive_stage_scheduler_generator is None:
            xceive_stage = OnDemandStage(env, name + "_xceive", log_file=stage_log)
        else:
            xceive_scheduler = datanode_conf.datanode_xceive_stage_scheduler_generator(env)
            xceive_cost_func = ScheduleUtil.get_cost_func(datanode_conf.datanode_xceive_stage_schedule_resource,
                                                          phy_node)
            xceive_stage = Stage(env, name + "_xceive",
                                 datanode_conf.datanode_xceive_stage_handlers,
                                 xceive_scheduler, xceive_cost_func, log_file=stage_log)

        if datanode_conf.datanode_packet_ack_stage_scheduler_generator is None:
            packet_ack_stage = OnDemandStage(env, name + "_packet_ack", log_file=stage_log)
        else:
            packet_ack_scheduler = datanode_conf.datanode_packet_ack_stage_scheduler_generator(env)
            packet_ack_cost_func = ScheduleUtil.get_cost_func(datanode_conf.datanode_packet_ack_stage_schedule_resource,
                                                              phy_node)
            packet_ack_stage = Stage(env, name + "_packet_ack", datanode_conf.datanode_packet_responders,
                                     packet_ack_scheduler, packet_ack_cost_func, log_file=stage_log)

        xceive_stage.monitor_interval = datanode_conf.stage_monitor_interval
        packet_ack_stage.monitor_interval = datanode_conf.stage_monitor_interval
        datanode = SimpleDataNode(env, phy_node, xceive_stage, packet_ack_stage)

        return datanode
Esempio n. 6
0
    def __init__(self):
        """
        """
        Stage.__init__(self, moduleDescription)

        # Info: NTFS partitions, current partition, total drive size
        self.info = self.addWidget(PartitionWidget())

        # NTFS resizing
        self.ntfs = self.addWidget(NtfsWidget(self.size_changed_cb))

        # Info: space after last NTFS partition
        self.rest = self.addWidget(ShowInfoWidget(
                _("(Potential) free space at end of drive:  ")))

        # Get a list of NTFS partitions (all disks) and then the
        # corresponding info about the disks and partitions
        self.partlist = self.getNTFSparts()
        # Each disk (with NTFS partitions) gets an entry in self.diskinfo.
        # Each entry is a list-pair: [disk info, list of partitions' info]
        # The second item, the partition-info list can be changed if a
        # partition is shrunk or removed.
        self.diskinfo = {}
        for p in self.partlist:
            d = p.rstrip("0123456789")
            if not self.diskinfo.has_key(d):
                self.diskinfo[d] = [install.getDeviceInfo(d), None]
                self.diskChanged(d)

        # List of already 'handled' partitions
        self.donelist = []

        self.reinit()
Esempio n. 7
0
    def __init__(self):
        Stage.__init__(self, moduleDescription)

        self.addLabel(_("Please check that the formatting of the"
                " following partitions and their use within the new"
                " installation (mount-points) corresponds with what you"
                " had in mind. Accidents could well result in serious"
                " data loss."))

        # List of partitions configured for use.
        #    Each entry has the form [mount-point, device, format,
        #                         format-flags, mount-flags]
        parts = install.get_config("partitions", False)
        plist = []
        if parts:
            for p in parts.splitlines():
                pl = p.split(':')
                plist.append(pl + [self.getsize(pl[1])])

        # In case of mounts within mounts
        plist.sort()

        # Swaps ([device, format, include])
        swaps = install.get_config("swaps", False)
        if swaps:
            for s in swaps.splitlines():
                p, f, i = s.split(':')
                if i:
                    plist.append(["swap", p, f, "", "", self.getsize(p)])

        self.addWidget(PartTable(plist))
Esempio n. 8
0
 def __init__(self):
     self.masterClock = 0
     self.arrivalTime = self.getNewArrivalTime()
     self.stage = Stage()
     self.cashierStage = CashierStage(0, 0, 3, 1, 25)
     self.createFutureEventList()
     self.createResultsTable()
    def __init__(self, parent, score_to_add = None):
        Stage.__init__(self, parent)

        self.score_to_add = score_to_add
        self.high_scores = load_high_scores()

        self.new_idx = None
        if self.score_to_add != None:
            s = Score("???", self.score_to_add)
            self.new_idx = self.high_scores.potential_position(s)
        if self.new_idx != None:
            self.high_scores.add(s)

        score_frame = Frame(self)
        score_frame.pack()
        for i in range(self.high_scores.max_size):
            score = self.high_scores.get(i)
            if score != None:
                score = self.high_scores.scores[i]
                name = score.name
                points = str(score.points)
            else:
                name = "---"
                points = "---"                
            if i == self.new_idx:
                self.new_entry = Entry(score_frame)
                self.new_entry.grid(row=i, column=0)
            else:
                Label(score_frame, text=name).grid(row=i,column=0)
            Label(score_frame, text=points).grid(row=i,column=1)

        b = Button(self, text="return to main", command=self.button_clicked)
        b.pack()
Esempio n. 10
0
    def __init__(self):
        Stage.__init__(self, moduleDescription)

        # Set up grub's device map and a list of existing menu.lst files.
        assert install.set_devicemap(), "Couldn't get device map for GRUB"

        self.addOption('mbr', _("Install GRUB to MBR - make it the main"
                " bootloader"), True, callback=self.mbrtoggled)
        self.mbrinstall = Mbrinstall(self)
        self.addWidget(self.mbrinstall, False)
        # What if there is >1 drive?

        if install.menulst:
            self.addOption('old', _("Add new installation to existing GRUB"
                    " menu."), callback=self.oldtoggled)
            self.oldgrub = Oldgrub(self)
            self.addWidget(self.oldgrub, False)

        self.addOption('part', _("Install GRUB to installation partition."))

        self.ntfsboot = None
        # Seek likely candidate for Windows boot partition
        dinfo = install.fdiskall()
        nlist = install.listNTFSpartitions()
        for np in nlist:
            # First look for (first) partition marked with boot flag
            if re.search(r"^%s +\*" % np, dinfo, re.M):
                self.ntfsboot = np
                break
        if (not self.ntfsboot) and nlist:
            # Else just guess first NTFS partition
            self.ntfsboot = nlist[0]

        self.request_soon(self.init)
Esempio n. 11
0
 def __init__(self):
     pygame.init()
     self.settings = Settings()
     self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
     self.settings.screen_width = self.screen.get_rect().width
     self.settings.screen_height = self.screen.get_rect().height
     self.settings.grid_width = (self.settings.screen_width -
                                 200) // self.settings.num_column
     self.settings.grid_height = (self.settings.screen_height -
                                  200) // self.settings.num_row
     pygame.display.set_caption("Kohki Hatori")
     self.stage = Stage(self)
     self.barriers = Barriers(self)
     self.mirrors = Mirrors(self)
     self.players = []
     self.start_button = Button(self, "START")
     self._create_environment()
     self.constructing = True
     self.cheating = False
     self.real_game = False
     self.end = False
     self.bullets = []
     self.turn_ended = True
     self.no_bullet = True
     self.player_moved = False
     self.shooter = 0
     self.text = Text(self)
     self.game_active = False
     self.end_button = Button(self, "END")
Esempio n. 12
0
 def __init__(self, paths, parent_module_name, interrupt_if_fail,
              is_logging, log_file_path, stage_name,
              only_fail_notification):
     """
     Parameters
     ----------
     paths : list
         paths to directories with CSV systems
     parent_module_name: str
         a parent module name
     interrupt_if_fail : bool
         interrupt the execution of the all stages if an error has occurred
     is_logging : bool
         write messages to the log file or not
     log_file_path : str
         a path to directory for the log file
     stage_name : str
         stage name
     only_fail_notification : bool
         notification condition
     """
     Stage.__init__(self, parent_module_name, interrupt_if_fail,
                    log_file_path, stage_name, is_logging, "", "", "",
                    only_fail_notification)
     self._vcs_paths = paths.copy()
     for path in self._vcs_paths:
         if not os.path.exists(path):
             raise FileNotFoundError("VCS: Directory " + path +
                                     " doesn't exists!")
     self._commit_msg = 'new '
Esempio n. 13
0
 def stage4(self):
   for player in self.players:
     player.respawn()
   self.deck.shuffle()
   self.deck.cards += [100]
   stage4 = Stage(self.deck, self.players, self.printDetail, self.hazardsRemoved)
   self.hazardsRemoved = stage4.runStage(self.deck, self.strategyMap)
   return self.deck
Esempio n. 14
0
    def __init__(self):
        Stage.__init__(self, moduleDescription)

        self.output = self.addWidget(Report())

        self.progress = self.addWidget(Progress(), False)

        self.request_soon(self.run)
Esempio n. 15
0
class Game:
    
    def __init__(self, world, datadir, configdir):
        self.world = world
        self.datadir = datadir
        self.configdir = configdir
        self.enemies = []

        self.stage = Stage(self)
        self.sprites = Group(self.stage)
        self.screen = world.screen

        # Visor de energia para el enemigo
        self._create_player()
        self.energy = Energy(10, 10, 100, 10)
        self.energy.set_model(self.player.id)

        self.stage.player = self.player
        self.stage.load_level(1)

        if VISIBLE_DEBUG:
            # Visor de rendimiento
            self.text = Text(world.font, world.fps, "FPS: %d")

    def _create_player(self):
        control = Control(0, self.configdir)
        self.player = Player(self, control, self.sprites, self.datadir)
        shadow_player = Shadow(self.player, self.datadir)
        self.sprites.add([self.player, shadow_player])
        
    def update(self):

        self.stage.update()
        self.sprites.update()
        self.energy.update()

        if VISIBLE_DEBUG:
            self.text.update()

        if DEBUG:
            b1, b2, b3 = pygame.mouse.get_pressed()

            if b1:
                self.stage.do_camera_effect()
            elif b2:
                self.stage.do_camera_effect(10)
            elif b3:
                self.world.fps.slow()

    def draw(self):
        self.stage.draw(self.screen)
        self.sprites.draw(self.screen)
        self.screen.blit(self.energy.image, self.energy.rect)

        if VISIBLE_DEBUG:
            self.screen.blit(self.text.image, self.text.rect)

        pygame.display.flip()
Esempio n. 16
0
 def __init__(self):
     Stage.__init__(self, moduleDescription)
     self.addLabel(_('Disk(-like) devices will be detected and offered'
             ' for automatic partitioning.\n\n'
             'If a device has mounted partitions it will not be offered'
             ' for automatic partitioning. If you want to partition'
             ' such a device, you must select the "Manual Partitioning"'
             ' stage.'))
     self.getDevices()
Esempio n. 17
0
def new_stage(protocol, stage, valuation, mem):
    new_valuation = new_stage_valuation(protocol, valuation, stage.disabled)

    if is_stable_or_dead(protocol, new_valuation, stage.disabled):
        return Stage(Formula(new_valuation),
                     new_valuation,
                     stage.disabled,
                     speed=Speed.ZERO,
                     parent=stage)

    F, J = eventually_disabled(protocol, new_valuation, stage.disabled, mem)

    # Compute new_formula (Φ) and new_disabled (T)
    if len(F) > 0:
        if len(J) > 0:
            new_disabled = set(stage.disabled) | set(J)
            new_formula = Formula(new_valuation, new_disabled)

            if v_disabled(J, valuation):
                new_formula.assert_valuation(valuation)
            elif v_enabled(J, valuation):
                K = posts_from_pres(protocol, new_valuation, J)
                new_formula.assert_some_pair_present(K)

            # Compute speed
            if is_very_fast(protocol, new_valuation, stage.disabled):
                new_speed = Speed.QUADRATIC
            elif is_fast(protocol, new_valuation, stage.disabled):
                new_speed = Speed.QUADRATIC_LOG
            else:
                new_speed = Speed.CUBIC
        else:
            new_disabled = set(stage.disabled) | set(F)
            new_formula = Formula(new_valuation, new_disabled)
            new_speed = Speed.POLYNOMIAL
    else:
        new_disabled = set(stage.disabled)
        new_formula = Formula(new_valuation, new_disabled)
        new_speed = Speed.EXPONENTIAL

        I = compute_I(protocol, new_valuation, stage.disabled)

        if any(valuation[Var(q)] is True for q in I):
            L = compute_L(protocol, new_valuation, stage.disabled, I)

            new_formula.assert_all_states_absent(I)
            new_formula.assert_some_pair_present(L)
        elif all(valuation[Var(q)] is False for q in I):
            new_formula.assert_valuation(valuation)
        else:
            new_formula.assert_all_states_absent(I)

    return Stage(new_formula,
                 new_valuation,
                 new_disabled,
                 speed=new_speed,
                 parent=stage)
Esempio n. 18
0
    def __init__(self, parent, *args, **kargs):
        Stage.__init__(self, parent, *args, **kargs)

        Label(self, text="FALLING BLOCK GAME", font=("Helvetica", 30)).pack()

        self.selections = SelectionGroup(self, "Start", "High Scores", "Exit")
        self.selections.pack()
        self.bind_parent("<Up>"  , lambda event: self.selections.previous_selection())
        self.bind_parent("<Down>", lambda event: self.selections.next_selection())
        self.bind_parent("<Return>", self.selection_chosen)
Esempio n. 19
0
 def __init__(self):
     Stage.__init__(self, moduleDescription)
     self.addLabel(_('This will install Arch Linux'
             ' from this "live" system on your computer.'
             ' This program was written'
             ' for the <i>larch</i> project:\n'
             '       http://larch.berlios.de\n'
             '\nIt is free software,'
             ' released under the GNU General Public License.\n\n') +
             'Copyright (c) 2008   Michael Towers')
Esempio n. 20
0
 def stage5(self):
   for player in self.players:
     player.respawn()
   self.deck.shuffle()
   self.deck.cards += [120]
   stage5 = Stage(self.deck, self.players, self.printDetail, self.hazardsRemoved)
   self.hazardsRemoved = stage5.runStage(self.deck, self.strategyMap)
   if (self.printDetail):
     print("Removed Hazards: ", list(map(formatCard,self.hazardsRemoved)))
   return self.deck
Esempio n. 21
0
 def __init__(self, loggers):
     """
     Parameters
     ----------
     loggers: list
         list of loggers to send
     """
     Stage.__init__(self, "", False, "", "Notification", False, "", "", "",
                    False)
     self._loggers = loggers
Esempio n. 22
0
 def __init__(self, parent):
     self.parent = parent
     globalvars.asdf = 0
     self.lagcount = 0
     self.leftkeydown = 0
     self.rightkeydown = 0
     self.enemylist = []
     self.list_enemys = EnemyManager()
     self.stage = Stage(self.list_enemys, globalvars.player_list)
     self.list_allie_shots = pygame.sprite.RenderUpdates()
     self.enemy_shots = pygame.sprite.RenderUpdates()
Esempio n. 23
0
    def generate_tasks(self, user_id, job_profile):
        this_job = Job(user_id)
        stage_list = list()
        sorted_stage_id = np.sort(job_profile.keys())  # todo check
        for stage_id in sorted_stage_id:
            this_stage = Stage(user_id, stage_id)
            task_num = job_profile[stage_id]['Task_Num']
            this_rdd = self.search_rdd_by_name('user%s_rdd%s' %
                                               (user_id, stage_id))
            parent_rdd_ids = job_profile[stage_id]['Parents']
            start_time = float(job_profile[stage_id]['Start_Time'])
            end_time = float(job_profile[stage_id]['End_Time'])

            task_list = list()
            peer_group = list()  # for sticky policies
            for task_id in range(0, task_num):
                this_task = Task(user_id, stage_id, task_id)

                # set start and end time
                this_task.set_start_time(start_time)
                this_task.set_end_time(end_time)

                # set dependent blocks and update their ref counts.
                dependent_blocks = list()
                for parent_rdd_id in parent_rdd_ids:
                    parent_rdd = self.search_rdd_by_name(
                        'user%s_rdd%s' % (user_id, parent_rdd_id))
                    dependent_block_index = task_id % parent_rdd.partitions  # Map the dependent block
                    dependent_block = parent_rdd.blocks[dependent_block_index]
                    dependent_block.add_ref_count()
                    dependent_blocks.append(dependent_block)
                this_task.set_dependent_blocks(dependent_blocks)

                # set peer-groups for LRC conservative policy
                for dependent_block in dependent_blocks:
                    peer_group.append(dependent_block)
                if (isinstance(self.cluster.block_manager.policy,
                               LRCConservativePolicy)):
                    self.cluster.block_manager.policy.add_peer_group(
                        peer_group)
                    peer_group = list()

                # set produced_block
                produced_block = this_rdd.blocks[task_id]
                this_task.set_produced_block(produced_block)
                task_list.append(this_task)
            if (isinstance(self.cluster.block_manager.policy,
                           LRCAggressivePolicy)):
                self.cluster.block_manager.policy.add_peer_group(peer_group)
            this_stage.set_tasks(task_list)
            stage_list.append(this_stage)

        this_job.set_stages(stage_list)
        self.job_list.append(this_job)
Esempio n. 24
0
 def Stage_draw(self, stage_id, stageTxt):
     stage_file = stageTxt
     stage = Stage(self.screen, stage_file, self.data)
     pygame.mixer.music.load('sound/space.mp3')  # 音楽ファイルの読み込み
     pygame.mixer.music.play(-1)  # 音楽の再生回数(ループ再生)
     result = stage.loop()
     if result[0] == EXIT:
         self.exit()
     elif result[0] == RETIRE:
         return
     self.StageResult_draw(stage_id, result)
Esempio n. 25
0
    def __init__(self):
        Stage.__init__(self, moduleDescription)

        # Info on drive
        self.device = install.get_config('autodevice', trap=False)
        if not self.device:
            self.device = install.listDevices()[0][0]
        self.dinfo = install.getDeviceInfo(self.device)

        # Info: total drive size
        totalsize = self.addWidget(ShowInfoWidget(
                _("Total capacity of drive %s:  ") % self.device))
        totalsize.set(self.dinfo[0])

        # Get partition info (consider only space after NTFS partitions)
        parts = install.getParts(self.device)
        self.startpart = 1
        self.startsector = 0
        for p in parts:
            if (p[1] == 'ntfs'):
                self.startpart = p[0] + 1
                self.startsector = p[4] + 1

        avsec = (self.dinfo[1] * self.dinfo[2] - self.startsector)
        self.avG = avsec * self.dinfo[3] / 1.0e9
        if (self.startpart > 1):
            popupMessage(_("One or more NTFS (Windows) partitions were"
                    " found. These will be retained. The available space"
                    " is thus reduced to %3.1f GB.\n"
                    "Allocation will begin at partition %d.") %
                        (self.avG, self.startpart))

        self.homesizeG = 0.0
        self.swapsizeG = 0.0
        self.root = None    # To suppress writing before widget is created

        self.swapfc = None  # To suppress errors due to widget not yet ready
        # swap size
        self.swapWidget()

        self.swapfc = self.addCheckButton(_("Check for bad blocks "
                "when formatting swap partition.\nClear this when running "
                "in VirtualBox (it takes forever)."))
        self.setCheck(self.swapfc, True)

        # home size
        self.homeWidget()

        # root size
        self.root = self.addWidget(ShowInfoWidget(
                _("Space for Linux system:  ")))
        self.adjustroot()
Esempio n. 26
0
 def spawn_stage(self,
                 away_message,
                 effect_time=c.STAGE_SPAWN_TRANSITION,
                 callback=None):
     try:
         self.stage = Stage(self.screen, self, away_message)
         self.stage.transition_in(effect_time, callback)
     except Exception:
         print("Could not spawn screensaver stage:\n")
         traceback.print_exc()
         self.grab_helper.release()
         status.Active = False
         self.cancel_timers()
Esempio n. 27
0
 def spawn_stage(self, away_message, callback=None):
     """
     Create the Stage and begin fading it in.  This may run quickly, in the case of
     user-initiated activation, or slowly, when the session has gone idle.
     """
     try:
         self.stage = Stage(self, away_message)
         self.stage.activate(callback)
     except Exception:
         print("Could not spawn screensaver stage:\n")
         traceback.print_exc()
         self.grab_helper.release()
         status.Active = False
         self.cancel_timers()
Esempio n. 28
0
 def __init__(self, lan):
     pygame.init()
     self.gravity = 0
     self.rotated = 0
     self.next_figure = self.get_random_figure()
     self.figure = self.get_random_figure()
     self.stage = Stage()
     self.menu = Menu(self.stage, self.next_figure)
     self.collision = Collision(self.stage)
     self.move_x = 0
     self.move_y = 0
     if lan is None:
         self.second_player = NoPlayer()
     else:
         self.second_player = LanSecondPlayer(self.menu, lan)
Esempio n. 29
0
    def get_cluster(env, phy_cluster, hdfs_conf, resource_log=sys.stdout, stage_log=sys.stdout):
        """

        :param env:
        :param phy_cluster: the PhysicalCluster HDFS run on; the first node will run NameNode; other nodes will run
                            DataNode
        :param hdfs_conf: HDFSConf object
        :param resource_log: opened file handle
        :param stage_log: opened file handle
        :return: newly constructed HDFS object
        """
        assert len(phy_cluster.node_list) >= 2

        namespace_lock_res = Resource(env, "namespace_lock", 1, 1, FIFOScheduler(env, float('inf')),
                                      log_file=resource_log)
        if hdfs_conf.namenode_scheduler_generator is None:
            namenode_rpc_stage = OnDemandStage(env, "namenode_rpc", log_file=stage_log)
        else:
            namenode_scheduler = hdfs_conf.namenode_scheduler_generator(env)
            namenode_rpc_stage = Stage(env, "namenode_rpc", hdfs_conf.namenode_handlers,
                                       namenode_scheduler, log_file=stage_log)

        namenode = NameNode(env, phy_cluster.node_list[0], namenode_rpc_stage, namespace_lock_res)

        datanode_list = []
        for phy_node in phy_cluster.node_list[1:]:
            datanode = DataNode.get_datanode(env, "datanode_" + str(len(datanode_list)), phy_node,
                                             hdfs_conf.datanode_conf, stage_log)
            datanode_list.append(datanode)

        hdfs = HDFS(env, namenode, datanode_list, hdfs_conf.replica)

        return hdfs
Esempio n. 30
0
def stage_detail_parse(stage_number,url):
    data={}
    urlfetch.set_default_fetch_deadline(45)
    images_json=[]
    data_order=["day","month","avg-speed","cat","start-finish"]
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page, "html.parser")
    tabulka = soup.find("h3", {"class" : "section"})
    div = tabulka.parent
    images = soup.findAll('img')
    for image in images:
        if "Stage" in image["src"]:
            images_json.append(image["src"])
        if "Final_GC" in image["src"]:
            images_json.append(image["src"])
        if "site-icons" in image["src"]:
            data['stage-icon']=image["src"]
        cont=0

        data['stage-images']=images_json

        for element in tabulka.parent:
            if(cont<len(data_order)):
                if element.name is None and "\n" not in element.string and element.string !=" " and  "Tag for network 919" not in element.string:
                    #The interesting information doesn't have a tag
                    data[data_order[cont]]=element.string
                    cont+=1
    print stage_number
    stage=Stage.get_by_id(int(stage_number))
    stage_data=json.loads(stage.data)
    stage_data.update(data)
    stage.data=json.dumps(stage_data)
    stage.put()
Esempio n. 31
0
 def get(self):
     q = Stage.query()
     stages=[]
     for stage in q:
         stages.append(json.loads(stage.data))
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(json.dumps(stages))
Esempio n. 32
0
def enter():
    global ground, character, stage, hp
    global scoreLabel, Label
    global jelly_sound, collide_sound, item_eat

    character = Cookie()
    stage = Stage()
    ground = Ground()
    hp = HP()

    game_world.add_object(character, 1)
    game_world.add_object(stage, 0)
    game_world.add_object(ground, 0)
    game_world.add_object(hp, 0)

    label = score.Label("Score: ", 50, get_canvas_height() - 50, 45, 0)
    label.color = (255, 255, 255)
    score.labels.append(label)
    scoreLabel = label

    jelly_sound = load_wav('jelly.wav')
    jelly_sound.set_volume(32)
    item_eat = load_wav('item.wav')
    item_eat.set_volume(32)
    collide_sound = load_wav('collide.wav')
    collide_sound.set_volume(50)
Esempio n. 33
0
def enter():

    global stage, ground, hp, cookie, jelly, potion, jtrap, djtrap, strap
    global scoreLabel, Label
    global jelly_sound, item_sound, collide_sound

    stage = Stage()  # 스테이지
    ground = Ground()  # 바닥
    hp = HP()  # 체력
    cookie = Cookie()  # 캐릭터

    game_world.add_object(stage, game_world.layer_bg)
    game_world.add_object(ground, game_world.layer_bg)
    game_world.add_object(hp, game_world.layer_bg)
    game_world.add_object(cookie, game_world.layer_player)

    # 점수
    label = score.Label("Score: ", 50, get_canvas_height() - 50, 45, 0)
    label.color = (255, 255, 255)
    score.labels.append(label)
    scoreLabel = label

    # 사운드
    jelly_sound = load_wav('jelly.wav')
    jelly_sound.set_volume(32)
    item_sound = load_wav('item.wav')
    item_sound.set_volume(32)
    collide_sound = load_wav('collide.wav')
    collide_sound.set_volume(50)
Esempio n. 34
0
    def game_condition(self):
        """
        The other main loop of the game. When the fight_loop is complete, this loop checks to see if one the players
        have achieved 2 points.
        :return:
        """
        random.seed()
        selection = random.randint(0, 2)

        if selection == 0:
            stage = 'Sprites/Stages/TrainingRoom.png'
            music = 'Sprites/sfx/bgm/bgmme37.ogg'
        else:
            stage = 'Sprites/Stages/sidewalks.png'
            music = 'Sprites/sfx/bgm/bgmme42.ogg'

        self.stage = Stage(stage, music)

        while self.player_one_wins < 2 and self.player_two_wins < 2:
            player_won = self.fight_loop()

            if player_won == 1:
                self.player_one_wins += 1
            else:
                self.player_two_wins += 1
            self.round += 1
            #print('player_one: ', self.player_one_wins, 'player_two: ', self.player_two_wins)

            self.reset_booleans()

        pygame.mixer.music.fadeout(2000)
        pygame.time.wait(2000)
Esempio n. 35
0
 def test_clear(self):
     stage = Stage()
     stage.add(dot)
     stage.add(kriss)
     stage.clear()
     self.assertTrue(dot not in stage.array)
     self.assertTrue(kriss not in stage.array)
Esempio n. 36
0
def main():
    atexit.register(killall)
    args = parse_args()
    setup_logging(args)
    # read tool config
    config = DFSConfig()

    # setup show
    show = Show(config, args.show_name)
    if not show:
        print('no such show %s', args.show_name)
        sys.exit(1)

    # setup stage
    stage = Stage(show, args.stage_name)
    if not stage:
        print('could not load or create stage %s', args.stage_name)
        sys.exit(1)

    # setup joystick
    joy = xbox.Joystick(debug=args.debug, config=config.joystick)

    if args.check_mode:
        sys.exit(0)

    handler = DmxHandler(config, show, stage, joy)

    # setup data handler, this is our callback loop
    # as DMX data comes in constantly
    wrapper = ClientWrapper()
    rx = wrapper.Client()
    rx.RegisterUniverse(config.input.universe, rx.REGISTER, handler.handle)
    wrapper.Run()
Esempio n. 37
0
 def __init__(self, name, recipe, path):
     self.name = name
     # recipe defining the sequence of jobs to be performed
     self.recipe = recipe
     self.num_stages = self.recipe.num_stages
     self.num_stageworkers = config.STAGE_SIZE
     # Create buffers before and after each stage (hand-off points)
     self.buffers = [Queue.Queue() for i in range(self.num_stages + 1)]
     # The input buffer of the pipeline.
     self.input = self.buffers[0]
     # The output buffer of the pipeline
     self.output = self.buffers[-1]
     # Stage environment variables
     self.stage_environ = dict(pipeline=self, path=path)
     # Create stages and connect them to the buffers
     self.stages = [Stage(name=self.recipe.stage_names[i],
                          WorkerClass=self.recipe.stage_types[i],
                          num_workers=self.num_stageworkers,
                          in_buffer=self.buffers[i],
                          out_buffer=self.buffers[i + 1],
                          seq_number=i,
                          **self.stage_environ) for i in range(self.num_stages)]
     # jobnr is a simple counter of jobs that have been or still are processed
     self.jobnr = 0
     # Set state to inactive
     # FIXME: isactive should be a descriptor and depend on stage's status
     self.isactive = False
Esempio n. 38
0
    def __init__(self):
        Stage.__init__(self, moduleDescription)

        ld = install.listDevices()

        # Offer gparted - if available
        if (install.gparted_available() == ""):
            gparted = self.addOption('gparted',
                    _("Use gparted (recommended)"), True)
        else:
            gparted = None

        # Offer cfdisk on each available disk device
        mounts = install.getmounts().splitlines()
        mounteds = 0
        i = 0
        if ld:
            for d, s, n in ld:
                i += 1
                # Determine devices which have mounted partitions
                dstring = "%16s  (%10s : %s)" % (d, s, n)
                style = None
                for m in mounts:
                    if m.startswith(d):
                        style = 'red'
                        mounteds += 1
                        break
                self.addOption('cfdisk-%s' % d,
                        _("Use cfdisk on %s (%s)") % (d, s),
                        (i == 1) and not gparted,
                        style=style)

        else:
            popupError(_("No disk(-like) devices were found,"
                    " so Arch Linux can not be installed on this machine"))
            mainWindow.exit()

        if mounteds:
            self.addLabel(_('WARNING: Editing partitions on a device with'
                    ' mounted partitions (those marked in red) is likely'
                    ' to cause a lot of trouble!\n'
                    'If possible, unmount them and then restart this'
                    ' program.'), style='red')

        # Offer 'use existing partitions/finished'
        self.done = self.addOption('done',
                _("Use existing partitions / finished editing partitions"))
Esempio n. 39
0
 def build_tor_stage(self, platform_engine, sub_ratio):
     tors = []
     north_links = []
     for rack in self.racks:
         for idx in range(0, rack.rack_count):
             sku = platform_engine.get_matching_tors_for_reqs(rack)
             tor = Tor(rack, idx, sku)
             tors.append(tor)
             self.devices.append(tor)
             tor_links = self.generate_tor_links(tor, rack)
             for link in tor_links:
                 north_links.append(link)
     tor_stage = Stage(0, tors, platform_engine, self.edge_facing_capacity,
                       sub_ratio)
     tor_stage.devices = copy.deepcopy(tors)
     tor_stage.north_links_list = copy.deepcopy(north_links)
     print "A total of " + str(len(tors)) + " TORs has been created"
     return tor_stage
Esempio n. 40
0
 def test_playlist(self):
     stage = Stage()
     stage.add(dot)
     stage.add(kriss)
     stage.createplaylist("test")
     stage.clear()
     self.assertEqual(len(stage.array), 0)
     stage.add("test.m3u")
     self.assertMusicIn(stage)
Esempio n. 41
0
 def spawn_stage(self, away_message, effect_time=c.STAGE_SPAWN_TRANSITION, callback=None):
     try:
         self.stage = Stage(self.screen, self, away_message)
         self.stage.transition_in(effect_time, callback)
     except Exception:
         print("Could not spawn screensaver stage:\n")
         traceback.print_exc()
         self.grab_helper.release()
         status.Active = False
         self.cancel_timers()
Esempio n. 42
0
class LanSecondPlayer(SecondPlayer):
    def __init__(self, menu: Menu, lan):
        self.figure = Figure([])  # type: Figure
        self.stage = Stage()  # type: Stage
        self.stage.block_drawer = WiredBlockDrawer()
        self.figure.block_drawer = GhostBlockDrawer()
        self.menu = menu
        self.lan = lan

    def receive_data(self):
        attack = 0
        data = self.lan.get_data()

        if data:
            data_array = eval(data)
            if len(data_array) == 7:
                self.figure.blocks = data_array[0]
                self.figure.x = data_array[1]
                self.figure.y = data_array[2]
                self.stage.blocks = data_array[3]
                self.stage.score = data_array[4]
                self.stage.completed_lines = data_array[5]
                attack = data_array[6]

        return attack

    def send_data(self, figure: Figure, stage: Stage, attack_power):
        data_array = list()
        data_array.append(figure.blocks)
        data_array.append(figure.x)
        data_array.append(figure.y)
        data_array.append(stage.blocks)
        data_array.append(stage.score)
        data_array.append(stage.completed_lines)
        data_array.append(attack_power)
        self.lan.send_data(data_array)

    def draw(self, stage_surface, menu_surface):
        self.stage.draw(stage_surface)
        self.figure.draw(stage_surface)
        self.menu.draw_second_player(menu_surface, self.stage.score,
                                     self.stage.completed_lines)
Esempio n. 43
0
 def __init__(self, title, width, height):
     """
     ゲームの各パラメータの状態を初期化し、ゲームを開始させる準備をします
     title: ゲームタイトル
     width: 画面幅
     height: 画面高さ
     """
     self.title = title
     self.width = width + Game.UI_WIDTH
     self.height = height
     self.root = tkinter.Tk()
     self.root.bind("<KeyPress>", self.__input)
     self.canvas = tkinter.Canvas(self.root, width=self.width, height=self.height)
     self.stage = Stage(self)
     self.stage.game = self
     self.prev_timer = time.time()
     self.gameover_rendered = False
     self.font_gameover = font.Font(root=self.root, size=50)
     self.images = Images()
     self.reset()
Esempio n. 44
0
	def __init__(self,parent):  
		self.parent=parent        
		globalvars.asdf = 0
		self.lagcount=0		
		self.leftkeydown=0
		self.rightkeydown=0
		self.enemylist=[]
		self.list_enemys=EnemyManager()
		self.stage=Stage(self.list_enemys,globalvars.player_list)
		self.list_allie_shots=pygame.sprite.RenderUpdates()
		self.enemy_shots=pygame.sprite.RenderUpdates()
Esempio n. 45
0
 def get(self):
     self.response.out.write("Getting stages info </br>")
     generate_tour_data()
     q = Stage.query()
     for stage in q:
         d = json.loads(stage.data)
         # Add the task to the default queue.
         taskqueue.add(url='/details', params={'stage_key': stage.key.id(),'stage_link':d["stage-link"]})
         taskqueue.add(url='/clasification', params={'stage_key': stage.key.id()})
         taskqueue.add(url='/image', params={})
         self.response.out.write("Created Task for stage number: <b>"+str(stage.key.id())+"</b></br>")
Esempio n. 46
0
 def test_shuffle(self):
     stage = Stage()
     for i in range(5):
         stage.add(dot)
         stage.add(kriss)
     prev = copy.copy(stage.array)
     stage.shuffle()
     self.assertFalse(prev == stage.array)
     prev.sort()
     stage.array.sort()
     self.assertTrue(prev == stage.array)
Esempio n. 47
0
    def __init__(self):
        """
        """
        Stage.__init__(self, moduleDescription)

        self.swaps = {}
        inuse = install.getActiveSwaps()
        self.done = []
        if inuse:
            self.addLabel(_("The following swap partitions are currently"
                    " in use and will not be formatted (they shouldn't"
                    " need it!)."))
        for p, s in inuse:
            b = self.addCheckButton("%12s - %s %4.1f GB" % (p, _("size"), s))
            self.setCheck(b, True)
            self.done.append(p)
            self.swaps[p] = b

        all = install.getAllSwaps()
        fmt = []
        for p, s in all:
            if not (p in self.done):
                fmt.append((p, s))
        if fmt:
            self.addLabel(_("The following swap partitions will be formatted"
                    " if you select them for inclusion."))
        for p, s in fmt:
            b = self.addCheckButton("%12s - %s %4.1f GB" % (p, _("size"), s))
            self.setCheck(b, True)
            self.swaps[p] = b

        if all:
            self.cformat = self.addCheckButton(_("Check for bad blocks "
                    "when formatting.\nClear this when running in VirtualBox "
                    "(it takes forever)."))
            self.setCheck(self.cformat, True)
        else:
            self.addLabel(_("There are no swap partitions available. If the"
                    " installation computer does not have a large amount of"
                    " memory, you are strongly advised to create one before"
                    " continuing."))
Esempio n. 48
0
    def __init__(self):
        Stage.__init__(self, moduleDescription)

        self.device = None
        self.mounts = install.getmounts()
        # List of partitions already configured for use.
        #    Each entry has the form [mount-point, device, format,
        #                         format-flags, mount-flags]
        global used_partitions
        used_partitions = []
        parts = install.get_config("partitions", False)
        if parts:
            for p in parts.splitlines():
                used_partitions.append(p.split(':'))

        self.table = SelTable()
        self.devselect = SelDevice([d[0] for d in install.listDevices()],
                self.setDevice)
        self.addWidget(self.devselect, False)

        self.addWidget(self.table)
Esempio n. 49
0
    def initialise(self):
        """this function is called when the program starts.
           it initializes everything it needs, then runs in
           a loop until the function returns."""
        #Initialize Everything
        pygame.init()
        self.screen = pygame.display.set_mode((640, 480))
        pygame.display.set_caption('VacuumFire')
        pygame.mouse.set_visible(0)
        #icon
        icon, foo = utils.load_image('icon.png')
        pygame.display.set_icon(icon)

        self.game_paused = False
        #sounds
        self.sounds = {};
        self.sounds['music'] = utils.load_sound('archivo.ogg')
        self.sounds['warning'] = utils.load_sound('warning.wav')
        self.sounds['powerup'] = utils.load_sound('powerup.wav')
        self.sounds['music'].play()
        #Create The Backgound
        self.background = Background(self.screen.get_size())
        #game variables
        self.score = 0
        #Display The Background
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()


        #The player's ship
        self.ship = Ship()
        #The player's ship
        self.lifemeter = LifeMeter()
        self.player    = pygame.sprite.RenderPlain((self.ship))
        #group that stores all enemies
        self.enemies    = pygame.sprite.Group()
        #group that stores all powerups
        self.powerups    = pygame.sprite.Group()
        #group that stores all the lasers the player shoots
        self.fire        = pygame.sprite.Group()
        #group for information sprites in the screen, should be rendered the last one
        self.hud         = pygame.sprite.Group()
        self.explosions  = pygame.sprite.Group()
        self.hud.add(self.lifemeter)
        #The level
        self.level = Stage('level_1')
        self.font = utils.load_font('4114blasterc.ttf', 36)


        self.clock = pygame.time.Clock()

        self.game_started = False
        self.game_finished = False
Esempio n. 50
0
    def __init__(self, parent, state):
        Stage.__init__(self, parent)
        self.state = state
        
        self.state = state
        
        self.fps_counter = FpsCounter()

        self.init_widgets()
        self.init_bindings()

        self.ghost_piece = None

        #True when the user pauses the game
        self.paused = False

        #True when a coroutine is playing that should halt game logic, ex. when lines flash before disappearing
        self.blocking = False

        self.state.register_listener(self.model_alert)
        self.state.start()
        self.update_labels()
Esempio n. 51
0
 def spawn_stage(self, away_message, effect_time=c.STAGE_SPAWN_TRANSITION, callback=None):
     """
     Create the Stage and begin fading it in.  This may run quickly, in the case of
     user-initiated activation, or slowly, when the session has gone idle.
     """
     try:
         self.stage = Stage(self.screen, self, away_message)
         self.stage.transition_in(effect_time, callback)
     except Exception:
         print("Could not spawn screensaver stage:\n")
         traceback.print_exc()
         self.grab_helper.release()
         status.Active = False
         self.cancel_timers()
Esempio n. 52
0
    def __init__(self, world):
        self.world = world
        self.enemies = []

        self.sprites = group.Group()
        self.stage = Stage(self, self.sprites)
        self.sprites.camera = self.stage

        self.sprites_in_front = pygame.sprite.RenderPlain()
        self._create_player()
        self.stage.object_to_follow = self.player
        self.stage.load_level(1)

        if VISIBLE_DEBUG:
            # Visor de rendimiento
            self.text = Text(world.font, world.fps, "FPS: %d")
            self.sprites_in_front.add(self.text)
Esempio n. 53
0
	def __init__(self,parent):  
		self.parent=parent
		globalvars.asdf = 0
		##some key vars, the works
		self.lagcount=0		
		#a little hack so that the background works nicer
		self.background=globalvars.screen
		#make the rectlist to handle dirty updating
		self.updaterects=[]
		#background object
		self.bgstars=BackgroundManager()
		##make the lists to handle various sprites
		self.list_enemys=EnemyManager()
		self.player_list=pygame.sprite.RenderUpdates()
		self.list_allie_shots=pygame.sprite.OrderedUpdates()
		self.enemy_shots=pygame.sprite.RenderUpdates()
		self.token_list=pygame.sprite.RenderUpdates()
		##make a new stage object
		self.stage=Stage(self,self.list_enemys,self.player_list,self.enemy_shots,self.list_allie_shots)
		#self.setup_events()
		self.new_display()
Esempio n. 54
0
    def __init__(self, world, datadir, configdir):
        self.world = world
        self.datadir = datadir
        self.configdir = configdir
        self.enemies = []

        self.stage = Stage(self)
        self.sprites = Group(self.stage)
        self.screen = world.screen

        # Visor de energia para el enemigo
        self._create_player()
        self.energy = Energy(10, 10, 100, 10)
        self.energy.set_model(self.player.id)

        self.stage.player = self.player
        self.stage.load_level(1)

        if VISIBLE_DEBUG:
            # Visor de rendimiento
            self.text = Text(world.font, world.fps, "FPS: %d")
Esempio n. 55
0
def main():
    global stage_width, stage_height, sidebar_width, wall_gap, gap_size, padding, colors, screen, stage, stage2, barrel_cannon1, child_bonus, grandchild_bonus
    stage_width, stage_height = 550, 720
    sidebar_width = 150  # sidebar displays statistics
    wall_gap = 20.0  # space between the walls and the edge of the window
    gap_size = 350.0  # how big the gap in the middle is
    padding = 5.0  # segment padding
    gravity = (0.0, -100.0)
    bound_color = "lightgray"  # boundary walls color
    bg_color = "black"  # window background color
    ball_spacing = 10  # used to space initially fixed balls
    ball_radius = 20
    bullet_color = "green"
    child_bonus = 1.5
    grandchild_bonus = 2.0

    # used in collisions to change ball color
    colors = ["red", "orange", "yellow", "green", "blue", "purple"]

    pygame.init()
    screen = pygame.display.set_mode((stage_width + sidebar_width, stage_height))
    clock = pygame.time.Clock()
    running = True

    pm.init_pymunk()
    matt = Player("Matt", 1)

    stage = Stage(
        matt,
        screen,
        K_LEFT,
        K_RIGHT,
        K_UP,
        stage_width,
        stage_height,
        wall_gap,
        gap_size,
        padding,
        bound_color,
        gravity,
        0,
        100,
        bullet_color,
    )

    stage.space.add_collisionpair_func(1, 3, barrelcannon_load)

    spinner1 = Spinner(stage, 150, 100, 25, 25, 1, 1, math.pi / 120, 1, 0.2 * stage_width, 0.5 * stage_width)
    spinner2 = Spinner(stage, 275, 200, 25, 25, 1, 1, -math.pi / 60, 2, 0.5 * stage_width, 0.8 * stage_width)
    poly_swing1 = Polyswing(stage, 100, 600, 1, 10, 10, 500, 1, 10, 20, 1, 3, None, 3, 1, "orange")
    poly_swing2 = Polyswing(stage, 275, 650, 1, 10, 10, 500, 1, 10, 20, 1, 3, None, 3, 1, "red")
    poly_swing3 = Polyswing(stage, 450, 600, 1, 10, 10, 500, 1, 10, 20, 1, 3, None, 3, 1, "orange")
    stage.swing_limit = len(stage.swings) * 10

    barrel_cannon1 = Barrelcannon(stage, 275, 300, 20, 30, 1, 1, -math.pi / 60, 1, 0.2 * stage_width, 0.8 * stage_width)

    ticks_to_next_reload = 0
    ticks_to_next_respawn = 120

    swing_index = 0
    last_swing_spawn = 0

    start_time = time.time()
    while running:  # main game loop
        pg_time = pygame.time.get_ticks() / 1000.0

        # ===============================================================================
        #        ball_spawn_interval should decrease with time
        # ===============================================================================
        if pg_time < 30:
            ball_spawn_interval = 3
        elif pg_time < 60:
            ball_spawn_interval = 2.75
        elif pg_time < 90:
            ball_spawn_interval = 2.5
        elif pg_time < 120:
            ball_spawn_interval = 2.25
        elif pg_time < 150:
            ball_spawn_interval = 2
        elif pg_time < 180:
            ball_spawn_interval = 1.75
        elif pg_time < 210:
            ball_spawn_interval = 1.5
        elif pg_time < 240:
            ball_spawn_interval = 1.25
        elif pg_time < 270:
            ball_spawn_interval = 1
        elif pg_time < 300:
            ball_spawn_interval = 0.75
        elif pg_time < 330:
            ball_spawn_interval = 0.5

        if pg_time - last_swing_spawn >= ball_spawn_interval:
            last_swing_spawn = pg_time
            stage.spawn_swing()

        for event in pygame.event.get():
            try:
                if event.type == QUIT:
                    running = False
                elif event.type == KEYDOWN and event.key == K_ESCAPE:
                    running = False
                elif event.type == KEYDOWN and event.key == K_UP and stage.running == True:
                    stage.gun.shoot(1000)
                # upgrades

                elif event.type == KEYDOWN and event.key == K_e and stage.running == True:
                    selected_swing.destroy_joint(child_bonus, grandchild_bonus)
                elif event.type == KEYDOWN and event.key == K_s and stage.running == True:
                    # SECRET WEAPONNNNN!!!!
                    for swing in stage.swings:
                        swing.destroy_joint(child_bonus, grandchild_bonus)
                elif event.type == KEYDOWN and event.key == K_r and stage.running == True:
                    # If there is no ball, respawn the ball
                    if selected_swing.ball == None:
                        selected_swing.respawn_ball(selected_swing.circle_mass, selected_swing.radius, 1, "red")
                    else:
                        # If there is a ball create a new child

                        # the masses of the segments and balls are determined by which tier the swing is
                        # Tier1 swing is the original swing and can have 3 children. Has 3 segments
                        # Tier2 swings are children of tier1 swings and can have 2 children. Masses are 1/3 of the tier1. Has 2 segments
                        # Tier3 swings are children of tier2 swings and can't have children. Masses are 1/2 of tier2. Has 1 segment

                        new_tier = selected_swing.tier + 1

                        if new_tier == 2:
                            new_swing = Polyswing(
                                stage,
                                200,
                                550,
                                1,
                                10,
                                0.33 * selected_swing.section_mass,
                                500,
                                1,
                                0.33 * selected_swing.circle_mass,
                                15,
                                1,
                                2,
                                selected_swing,
                                2,
                                new_tier,
                                "red",
                            )
                        else:  # its tier 3
                            new_swing = Polyswing(
                                stage,
                                200,
                                550,
                                1,
                                10,
                                0.5 * selected_swing.section_mass,
                                500,
                                1,
                                0.5 * selected_swing.circle_mass,
                                10,
                                1,
                                1,
                                selected_swing,
                                0,
                                new_tier,
                                "red",
                            )
                elif event.type == KEYDOWN and event.key == K_t:
                    # toggle through the swings
                    try:
                        selected_swing.selected = False
                    except UnboundLocalError:
                        print "no selected swing yet"
                    try:
                        selected_swing = stage.swings[swing_index]
                    except IndexError:
                        print "the swing that was selected isn't there anymore"
                    selected_swing.selected = True
                    if swing_index + 1 > len(stage.swings) - 1:
                        swing_index = 0
                    else:
                        swing_index = swing_index + 1
                elif event.type == KEYDOWN and event.key == K_SPACE:
                    barrel_cannon1.shoot(1200, bullet_color)
                    # new_ball = Bullet(stage, f275, 36 ,2.0,10,0.5,bullet_color)
            except UnboundLocalError:
                print "im too lazy to fix this problem right now"  # cant release or make the ball for poly_swing2 unless it exists

        if stage.running == True:
            barrel_cannon1.move()
            spinner1.move()
            spinner2.move()

        screen.fill(THECOLORS[bg_color])
        stage.process_input()

        stage.draw_stats()

        # create new threads for these calls?
        if stage.running == True:  # two of these need to be done because step must be infront of draw
            stage.bullet_reload(pg_time)
            stage.space.step(1 / 60.0)
        else:
            stage.set_end_time()

        stage.draw_self()

        pygame.display.flip()
        clock.tick(60)
        pygame.display.set_caption("FPS: " + str(clock.get_fps()))
Esempio n. 56
0
def simpletest(_price):
	st = Stage("test")
	st.price(_price)
	return str(st.get_result())
Esempio n. 57
0
 def test_add_random_empty(self):
     stg = Stage()
     dirmanager.add_directory(test_dir)
     stg.addshuffle()
     self.assertMusicIn(stg)
Esempio n. 58
0
class ScreensaverManager(GObject.Object):
    """
    The ScreensaverManager is the central point where most major decision are made, 
    and where ScreensaverService requests are acted upon.
    """
    __gsignals__ = {
        'active-changed': (GObject.SignalFlags.RUN_LAST, None, (bool, )),
    }

    def __init__(self):
        super(ScreensaverManager, self).__init__()

        self.screen = Gdk.Screen.get_default()

        self.activated_timestamp = 0

        self.stage = None

        # Ensure our state
        status.Active = False
        status.Locked = False
        status.Awake = False

        self.grab_helper = GrabHelper(self)
        self.focus_nav = FocusNavigator()

        self.session_client = singletons.SessionClient
        trackers.con_tracker_get().connect(self.session_client,
                                           "idle-changed", 
                                           self.on_session_idle_changed)

        self.cinnamon_client = singletons.CinnamonClient

        singletons.LoginClientResolver(self)

    def is_locked(self):
        """
        Return if we're Locked - we could be Active without being locked.
        """
        return status.Locked

    def lock(self, msg=""):
        """
        Initiate locking (activating first if necessary.)
        """
        if not status.Active:
            if self.set_active(True, msg):
                self.stop_lock_delay()
                if utils.user_can_lock():
                    status.Locked = True
        else:
            if utils.user_can_lock():
                status.Locked = True
            self.stage.set_message(msg)

    def unlock(self):
        """
        Initiate unlocking and deactivating
        """
        self.set_active(False)
        status.Locked = False
        status.Awake = False

    def set_active(self, active, msg=None):
        """
        Activates or deactivates the screensaver.  Activation involves:
            - sending a request to Cinnamon to exit Overview or Expo - 
              this could prevent a successful screen grab and keep the
              screensaver from activating.
            - grabbing the keyboard and mouse.
            - creating the screensaver Stage.
        Deactivation involves:
            - destroying the screensaver stage.
            - releasing our keyboard and mouse grabs.
        """
        if active:
            if not status.Active:
                self.cinnamon_client.exit_expo_and_overview()
                if self.grab_helper.grab_root(False):
                    if not self.stage:
                        self.spawn_stage(msg, c.STAGE_SPAWN_TRANSITION, self.on_spawn_stage_complete)
                    return True
                else:
                    status.Active = False
                    return False
            else:
                self.stage.set_message(msg)
                return True
        else:
            if self.stage:
                self.despawn_stage(c.STAGE_DESPAWN_TRANSITION, self.on_despawn_stage_complete)
                status.focusWidgets = []
            self.grab_helper.release()
            return True
        return False

    def get_active(self):
        """
        Return whether we're Active or not (showing) - this is not
        necessarily Locked.
        """
        return status.Active

    def get_active_time(self):
        """
        Return how long we've been activated, or 0 if we're not
        """
        if self.activated_timestamp != 0:
            return int(time.time() - self.activated_timestamp)
        else:
            return 0

    def simulate_user_activity(self):
        """
        Called upon any key, motion or button event, does different things
        depending on our current state.

        If we're idle:
            - do nothing

        If we're locked:
            - show the unlock widget (if it's already visible, this also has
              the effect of resetting the unlock timeout - see Stage.py)
            - show the mouse pointer, so the user can navigate the unlock screen.

        If we're Active but not Locked, simply deactivate (destroying the Stage
        and returning the screensaver back to idle mode.)
        """
        if not status.Active:
            return

        if status.Locked and self.stage.initialize_pam():
            self.stage.raise_unlock_widget()
            self.grab_helper.release_mouse()
            self.stage.maybe_update_layout()
        else:
            GObject.idle_add(self.idle_deactivate)

    def idle_deactivate(self):
        self.set_active(False)
        return False

    def spawn_stage(self, away_message, effect_time=c.STAGE_SPAWN_TRANSITION, callback=None):
        """
        Create the Stage and begin fading it in.  This may run quickly, in the case of
        user-initiated activation, or slowly, when the session has gone idle.
        """
        try:
            self.stage = Stage(self.screen, self, away_message)
            self.stage.transition_in(effect_time, callback)
        except Exception:
            print("Could not spawn screensaver stage:\n")
            traceback.print_exc()
            self.grab_helper.release()
            status.Active = False
            self.cancel_timers()

    def despawn_stage(self, effect_time=c.STAGE_DESPAWN_TRANSITION, callback=None):
        """
        Begin destruction of the stage.
        """
        self.stage.cancel_unlocking()
        self.stage.transition_out(effect_time, callback)

    def on_spawn_stage_complete(self):
        """
        Called after the stage has faded in.  All user events are now
        redirected to GrabHelper, our status is updated, our active timer
        is started, and emit an active-changed signal (Which is listened to
        by our ConsoleKit client if we're using it, and our own ScreensaverService.)
        """
        self.grab_stage()

        status.Active = True

        self.emit("active-changed", True)

        self.start_timers()

    def on_despawn_stage_complete(self):
        """
        Called after the stage has faded out - the stage is destroyed, our status
        is updated, timer is canceled and active-changed is fired.
        """
        was_active = status.Active == True
        status.Active = False

        if was_active:
            self.emit("active-changed", False)

        self.cancel_timers()

        self.stage.destroy_stage()
        self.stage = None

        # Ideal time to check for leaking connections that might prevent GC by python and gobject
        if trackers.DEBUG_SIGNALS:
            trackers.con_tracker_get().dump_connections_list()

        if trackers.DEBUG_TIMERS:
            trackers.timer_tracker_get().dump_timer_list()

    def grab_stage(self):
        """
        Makes a hard grab on the Stage window, all keyboard and mouse events are dispatched or eaten
        by us now.
        """
        self.grab_helper.move_to_window(self.stage.get_window(), True)

    def start_timers(self):
        """
        Stamps our current time starts our lock delay timer (the elapsed time to allow after
        activation, to lock the computer.)
        """
        self.activated_timestamp = time.time()
        self.start_lock_delay()

    def cancel_timers(self):
        """
        Zeros out our activated timestamp and cancels our lock delay timer.
        """
        self.activated_timestamp = 0
        self.stop_lock_delay()

    def cancel_unlock_widget(self):
        """
        Return to sleep (not Awake) - hides the pointer and the unlock widget,
        which also restarts plugins if necessary.
        """
        self.grab_stage()
        self.stage.cancel_unlocking();

    def on_lock_delay_timeout(self):
        """
        Updates the lock status when our timer has hit its limit
        """
        status.Locked = True

        return False

    def start_lock_delay(self):
        """
        Setup the lock delay timer based on user prefs - if there is
        no delay, or if idle locking isn't enabled, we run the callback
        immediately, or simply return, respectively.
        """
        if not settings.get_idle_lock_enabled():
            return

        if not utils.user_can_lock():
            return

        lock_delay = settings.get_idle_lock_delay()

        if lock_delay == 0:
            self.on_lock_delay_timeout()
        else:
            trackers.timer_tracker_get().start_seconds("idle-lock-delay",
                                                       lock_delay,
                                                       self.on_lock_delay_timeout)

    def stop_lock_delay(self):
        """
        Cancels the lock delay timer.
        """
        trackers.timer_tracker_get().cancel("idle-lock-delay")

##### EventHandler/GrabHelper/FocusNavigator calls.

    def queue_dialog_key_event(self, event):
        """
        Forwards a captured key event to the stage->unlock dialog.
        """
        self.stage.queue_dialog_key_event(event)

    def propagate_tab_event(self, shifted):
        """
        Forwards a tab event to the focus navigator.
        """
        self.focus_nav.navigate(shifted)

    def propagate_activation(self):
        """
        Forwards an activation event (return) to the focus navigator.
        """
        self.focus_nav.activate_focus()

    def get_focused_widget(self):
        """
        Returns the currently focused widget from the FocusNavigator
        """
        return self.focus_nav.get_focused_widget()

# Session watcher handler:

    def on_session_idle_changed(self, proxy, idle):
        """
        Call back for the session client - initiates a slow fade-in
        for the stage when the session goes idle.  Cancels the stage fade-in
        if idle becomes False before it has completed its animation.
        """
        if idle and not status.Active:
            if self.grab_helper.grab_offscreen(False):
                self.spawn_stage("", c.STAGE_IDLE_SPAWN_TRANSITION, self.on_spawn_stage_complete)
            else:
                print("Can't fade in screensaver, unable to grab the keyboard")
        else:
            if not status.Active:
                if self.stage:
                    self.despawn_stage(c.STAGE_IDLE_CANCEL_SPAWN_TRANSITION, self.on_despawn_stage_complete)

                trackers.timer_tracker_get().start("release-grab-timeout",
                                                   c.GRAB_RELEASE_TIMEOUT,
                                                   self.on_release_grab_timeout)

    def on_release_grab_timeout(self):
        """
        Releases the initial grab during idle fade-in, when idle cancels prior to the screensaver
        becoming fully active.
        """
        if not status.Active:
            self.grab_helper.release()

        return False
Esempio n. 59
0
class Vacuum():

    def __init__(self):
        if not pygame.font: print 'Warning, fonts disabled'
        if not pygame.mixer: print 'Warning, sound disabled'
        self.initialise()
        self.loop()

    def initialise(self):
        """this function is called when the program starts.
           it initializes everything it needs, then runs in
           a loop until the function returns."""
        #Initialize Everything
        pygame.init()
        self.screen = pygame.display.set_mode((640, 480))
        pygame.display.set_caption('VacuumFire')
        pygame.mouse.set_visible(0)
        #icon
        icon, foo = utils.load_image('icon.png')
        pygame.display.set_icon(icon)

        self.game_paused = False
        #sounds
        self.sounds = {};
        self.sounds['music'] = utils.load_sound('archivo.ogg')
        self.sounds['warning'] = utils.load_sound('warning.wav')
        self.sounds['powerup'] = utils.load_sound('powerup.wav')
        self.sounds['music'].play()
        #Create The Backgound
        self.background = Background(self.screen.get_size())
        #game variables
        self.score = 0
        #Display The Background
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()


        #The player's ship
        self.ship = Ship()
        #The player's ship
        self.lifemeter = LifeMeter()
        self.player    = pygame.sprite.RenderPlain((self.ship))
        #group that stores all enemies
        self.enemies    = pygame.sprite.Group()
        #group that stores all powerups
        self.powerups    = pygame.sprite.Group()
        #group that stores all the lasers the player shoots
        self.fire        = pygame.sprite.Group()
        #group for information sprites in the screen, should be rendered the last one
        self.hud         = pygame.sprite.Group()
        self.explosions  = pygame.sprite.Group()
        self.hud.add(self.lifemeter)
        #The level
        self.level = Stage('level_1')
        self.font = utils.load_font('4114blasterc.ttf', 36)


        self.clock = pygame.time.Clock()

        self.game_started = False
        self.game_finished = False

    def handle_keys(self):
        #Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                #exit
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE and self.game_finished == True:
                pygame.quit()
                quit()
                
            if event.type == KEYDOWN:
                self.game_started = True
                if event.key == K_ESCAPE:
                    return false   #exit
                elif event.key == K_SPACE:
                    #shoot a laser if the max number is not reached
                    if Laser.num < Laser.max_lasers:
                        self.laser = Laser(self.ship)
                        self.fire.add(self.laser)
                elif event.key == K_LEFT:
                    self.ship.move_left()
                elif event.key == K_RIGHT:
                    self.ship.move_right()
                elif event.key == K_UP:
                    self.ship.move_up()
                elif event.key == K_DOWN:
                    self.ship.move_down()
                elif event.key == K_p:
                    self.game_paused = not self.game_paused

            if event.type == KEYUP:
                if event.key == K_LEFT:
                    self.ship.stop_move_left()
                elif event.key == K_RIGHT:
                    self.ship.stop_move_right()
                elif event.key == K_UP:
                    self.ship.stop_move_up()
                elif event.key == K_DOWN:
                    self.ship.stop_move_down()

        return True

    def process_powerups(self):
        #powerups got by the player, remove them, play a sound and apply them
        powerups_obtained  = pygame.sprite.spritecollide(self.ship, self.powerups, True)
        for powerup_obtained in powerups_obtained:
            #play powerup sound
            self.sounds['powerup'].play()
            #TODO powerup should be processed in ship
            if powerup_obtained.type == 1 and self.ship.powerup['speedup'] < 2:
                self.ship.powerup['speedup'] += 0.5 
                print "Increase speed to {0}".format(self.ship.powerup['speedup'])
            elif powerup_obtained.type == 2 and Laser.max_lasers < 8:
                print "Increase lasers to {0}".format(Laser.max_lasers)
                Laser.max_lasers += 1 
            elif powerup_obtained.type == 3 and self.ship.powerup['penetrate'] == False:
                print "Activate penetration"
                self.ship.powerup['penetrate'] = True
            else:
                print "No more powerups available"

    #Main Loop
    def loop(self):
        count = 0
        while 1:
            count = (count+1)%50
            self.clock.tick(25)

            #handle input events
            ok = self.handle_keys()
            if ok == False:
                return

            if self.game_started == False:
                start_text = self.font.render('Press any key to start', 2, (0,0,0))
                self.screen.blit(start_text, (150, 200))
                pygame.display.flip()
                continue

            if self.game_paused == 1:
                start_text = self.font.render('Game paused', 2, (255,255,255))
                self.screen.blit(start_text, (150, 200))
                pygame.display.flip()
                continue

            new_enemies = self.level.getenemies() 

            for enemy_y in new_enemies:
                #if random.randint(0,50) == 0:
                alien = Alien(enemy_y)
                alien.set_target(self.ship)
                self.enemies.add(alien)

            #aliens damaging the player, remove them
            damage  = pygame.sprite.spritecollide(self.ship, self.enemies, True)

            self.process_powerups()

            #check colisions with stage
            if self.level.checkcollide(self.ship.rect):
                #add some fancy explosions in the damage area
                self.explosions.add(Explosion(pygame.Rect(self.ship.rect.x,self.ship.rect.y,0,0)))
                damage.append(1)

            #Apply damages to the player
            if len(damage) > 0:
                self.background.warning()
                self.ship.damage()
                self.lifemeter.shake()
                self.explosions.add(Explosion(self.ship.rect))
                self.sounds['warning'].play()
                self.lifemeter.life = self.ship.life
                if self.lifemeter.life < 1:
                    self.game_finished = True
                    self.sounds['warning'].stop()

            #print (pygame.sprite.spritecollide(ship, level, True))

            #aliens hit by the fire, remove them
            penetration = self.ship.powerup['penetrate']
            for fireball in self.fire:
                hit = pygame.sprite.spritecollide(fireball, self.enemies, True)
                for dead in hit:
                    if dead.has_powerup():
                        powerup = Powerup(dead.rect, dead.value)
                        self.powerups.add(powerup)
                    self.explosions.add(Explosion(pygame.Rect(dead.rect.x,dead.rect.y,0,0)))
                    self.score+=dead.value*1000
                    if penetration == False:
                        fireball.kill()

            #draw the level

            all_sprites = pygame.sprite.Group()
            all_sprites.add(self.player.sprites())
            all_sprites.add(self.enemies.sprites())
            all_sprites.add(self.powerups.sprites())
            all_sprites.add(self.fire.sprites())
            all_sprites.add(self.hud.sprites())
            all_sprites.add(self.explosions.sprites())
            all_sprites.update()
            self.level.update()
            self.background.update()

            #Move and draw the background

            score_text = 'Score: {0}'.format((self.score))

            text = self.font.render(score_text, 1, (255, 255, 255))
            text_shadow = self.font.render(score_text, 1, (0,0,0))

            self.screen.blit(self.background, (0, 0))
            self.screen.blit(self.level, (0, 0))
            self.screen.blit(text_shadow, (12, 12))
            self.screen.blit(text, (10, 10))

            if self.game_finished == True:
                gameover_text = self.font.render("Game Over", 2, (255, 255, 255))
                self.screen.blit(gameover_text, (280, 200))
                gameover_text = self.font.render("Press Esc", 2, (255, 255, 255))
                self.screen.blit(gameover_text, (280, 230))
            else:
                all_sprites.draw(self.screen)

            #draw all the groups of sprites

            pygame.display.flip()
Esempio n. 60
0
class ScreensaverManager(GObject.Object):
    __gsignals__ = {
        'active-changed': (GObject.SignalFlags.RUN_LAST, None, (bool, )),
    }

    def __init__(self):
        super(ScreensaverManager, self).__init__()

        self.screen = Gdk.Screen.get_default()

        self.activated_timestamp = 0

        self.stage = None

        # Ensure our state
        status.Active = False
        status.Locked = False
        status.Awake = False

        self.grab_helper = GrabHelper(self)
        self.focus_nav = FocusNavigator()

        self.session_client = singletons.SessionClient
        trackers.con_tracker_get().connect(self.session_client,
                                           "idle-changed", 
                                           self.on_session_idle_changed)

        self.cinnamon_client = singletons.CinnamonClient

        singletons.LoginClientResolver(self)

##### Service handlers (from service.py)

    def is_locked(self):
        return status.Locked

    def lock(self, msg=""):
        if not status.Active:
            if self.set_active(True, msg):
                self.stop_lock_delay()
                if utils.user_can_lock():
                    status.Locked = True
        else:
            if utils.user_can_lock():
                status.Locked = True
            self.stage.set_message(msg)

    def unlock(self):
        self.set_active(False)
        status.Locked = False
        status.Awake = False

    def set_active(self, active, msg=None):
        if active:
            if not status.Active:
                self.cinnamon_client.exit_expo_and_overview()
                if self.grab_helper.grab_root(False):
                    if not self.stage:
                        self.spawn_stage(msg, c.STAGE_SPAWN_TRANSITION, self.on_spawn_stage_complete)
                    return True
                else:
                    status.Active = False
                    return False
            else:
                self.stage.set_message(msg)
                return True
        else:
            if self.stage:
                self.despawn_stage(c.STAGE_DESPAWN_TRANSITION, self.on_despawn_stage_complete)
            self.grab_helper.release()
            return True
        return False

    def get_active(self):
        return status.Active

    def get_active_time(self):
        if self.activated_timestamp != 0:
            return int(time.time() - self.activated_timestamp)
        else:
            return 0

    def simulate_user_activity(self):
        if not status.Active:
            return

        if status.Locked:
            self.stage.raise_unlock_widget()
            self.grab_helper.release_mouse()
        else:
            self.set_active(False)

        self.stage.maybe_update_layout()

#####

    def spawn_stage(self, away_message, effect_time=c.STAGE_SPAWN_TRANSITION, callback=None):
        try:
            self.stage = Stage(self.screen, self, away_message)
            self.stage.transition_in(effect_time, callback)
        except Exception:
            print("Could not spawn screensaver stage:\n")
            traceback.print_exc()
            self.grab_helper.release()
            status.Active = False
            self.cancel_timers()

    def despawn_stage(self, effect_time=c.STAGE_DESPAWN_TRANSITION, callback=None):
        self.stage.transition_out(effect_time, callback)

    def on_spawn_stage_complete(self):
        self.grab_stage()

        status.Active = True

        self.emit("active-changed", True)

        self.start_timers()

    def on_despawn_stage_complete(self):
        was_active = status.Active == True
        status.Active = False

        if was_active:
            self.emit("active-changed", False)

        self.cancel_timers()

        self.stage.destroy_stage()
        self.stage = None

    def grab_stage(self):
        self.grab_helper.move_to_window(self.stage.get_window(), True)

    def start_timers(self):
        self.activated_timestamp = time.time()
        self.start_lock_delay()

    def cancel_timers(self):
        self.activated_timestamp = 0
        self.stop_lock_delay()

    def cancel_unlock_widget(self):
        self.grab_stage()
        self.stage.cancel_unlock_widget();

    def on_lock_delay_timeout(self):
        status.Locked = True

        return False

    def start_lock_delay(self):
        if not settings.get_idle_lock_enabled():
            return

        if not utils.user_can_lock():
            return

        lock_delay = settings.get_idle_lock_delay()

        if lock_delay == 0:
            self.on_lock_delay_timeout()
        else:
            trackers.timer_tracker_get().start_seconds("idle-lock-delay",
                                                       lock_delay,
                                                       self.on_lock_delay_timeout)

    def stop_lock_delay(self):
        trackers.timer_tracker_get().cancel("idle-lock-delay")

##### EventHandler/GrabHelper/FocusNavigator calls

    def queue_dialog_key_event(self, event):
        self.stage.queue_dialog_key_event(event)

    def propagate_tab_event(self, shifted):
        self.focus_nav.navigate(shifted)

    def propagate_activation(self):
        self.focus_nav.activate_focus()

    def get_focused_widget(self):
        return self.focus_nav.get_focused_widget()

# Session watcher handler:

    def on_session_idle_changed(self, proxy, idle):
        if idle and not status.Active:
            if self.grab_helper.grab_offscreen(False):
                self.spawn_stage("", c.STAGE_IDLE_SPAWN_TRANSITION, self.on_spawn_stage_complete)
            else:
                print("Can't fade in screensaver, unable to grab the keyboard")
        else:
            if not status.Active:
                if self.stage:
                    self.despawn_stage(c.STAGE_IDLE_CANCEL_SPAWN_TRANSITION, self.on_despawn_stage_complete)

                trackers.timer_tracker_get().start("release-grab-timeout",
                                                   c.GRAB_RELEASE_TIMEOUT,
                                                   self.on_release_grab_timeout)

    def on_release_grab_timeout(self):
        if not status.Active:
            self.grab_helper.release()

        return False