Beispiel #1
0
    def run(self):
        ''' run all patterns in the playbook '''
        plays = []
        matched_tags_all = set()
        unmatched_tags_all = set()

        # loop through all patterns and run them
        self.callbacks.on_start()
        for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
            play = Play(self, play_ds, play_basedir, vault_password=self.vault_password)
            assert play is not None

            matched_tags, unmatched_tags = play.compare_tags(self.only_tags)

            matched_tags_all = matched_tags_all | matched_tags
            unmatched_tags_all = unmatched_tags_all | unmatched_tags

            # Remove tasks we wish to skip
            matched_tags = matched_tags - set(self.skip_tags)

            # if we have matched_tags, the play must be run.
            # if the play contains no tasks, assume we just want to gather facts
            # in this case there are actually 3 meta tasks (handler flushes) not 0
            # tasks, so that's why there's a check against 3
            if (len(matched_tags) > 0 or len(play.tasks()) == 3):
                plays.append(play)

        # if the playbook is invoked with --tags or --skip-tags that don't
        # exist at all in the playbooks then we need to raise an error so that
        # the user can correct the arguments.
        unknown_tags = ((set(self.only_tags) | set(self.skip_tags)) -
                        (matched_tags_all | unmatched_tags_all))

        for t in RESERVED_TAGS:
            unknown_tags.discard(t)

        if len(unknown_tags) > 0:
            for t in RESERVED_TAGS:
                unmatched_tags_all.discard(t)
            msg = 'tag(s) not found in playbook: %s.  possible values: %s'
            unknown = ','.join(sorted(unknown_tags))
            unmatched = ','.join(sorted(unmatched_tags_all))
            raise errors.AnsibleError(msg % (unknown, unmatched))

        for play in plays:
            ansible.callbacks.set_play(self.callbacks, play)
            ansible.callbacks.set_play(self.runner_callbacks, play)
            if not self._run_play(play):
                break

        ansible.callbacks.set_play(self.callbacks, None)
        ansible.callbacks.set_play(self.runner_callbacks, None)

        # summarize the results
        results = {}
        for host in self.stats.processed.keys():
            results[host] = self.stats.summarize(host)
        return results
Beispiel #2
0
    def __init__(self):
        QtCore.QObject.__init__(self)
        Play.__init__(self, continuous=True)
        self._play = None
        self._goalie_id = None
        self.add_transition(Behavior.State.start, Behavior.State.running,
                            lambda: True, 'immediately')

        # if a play fails for some reason, we can temporarily blacklist it, which removes it from play
        # selection for the next iteration, then enables it again
        self.temporarily_blacklisted_play_class = None
        self._currently_restarting = False
    def suma(nombre):

        sonido=Play(1024)
        Datos=sonido.open(nombre)
        sonido.start(Datos[0],Datos[1],Datos[2])
        sonido.play(Datos[3])
        sonido.closed()
Beispiel #4
0
    def play(self, reset_gamefile):
        self.players = set()
        self.hands = set()
        self.cards = set()
        self.me = None
        self.conviction = None

        self.gamefile = open('gamefile.txt', 'w+' if reset_gamefile else 'r+', buffering=1)
        self.prompt_queue = [x.rstrip("\n") for x in self.gamefile]

        setup = Setup()
        setup.run(self)

        play = Play()
        play.run(self)
Beispiel #5
0
 def open(self):
     init_analysis(self.main_window)
     self.main_window.analysis_next_btn.setEnabled(True)
     if self.source.media == 'file':
         self.source.base_name = get_base_file(self.file) 
         self.source.analysis_frames = cv2.VideoCapture(self.file)
     if self.source.media == 'camera':
         init_analysis_camera(self.main_window)
         print("Setting analysis frames for camera")
         # release camera resource for analysis
         self.source.setup_frames.release()
         self.source.analysis_frames = cv2.VideoCapture(config['camera'])
     # images folder
     directory = 'images/' + self.source.base_name
     create_dir(directory) 
     self.get_video()
     if self.source.media == 'file':
         self.setup.load_video(self.video.id)
     self.background = Background(self.source) 
     self.background.get_db(self.video.id)
     self.source.background = self.background
     self.polygon = Polygon(self.source, self.setup) 
     self.polygon.get_points(self.video.id)
     self.polygon.draw_setup(self.background.frame, self.polygon.points)
     self.source.polygon = self.polygon
     self.play = Play(self.source, self.setup)
     self.play.run_analysis()
     # set location
     self.location.set_location(self.video.address_id)
     # play
     self.click_analysis_play_btn()
	def scrapePlay(self, playLink, playType):
		title = self.strip(playLink.get_text())
		print("PLAY: "+str(title)+" a "+playType)
		play = Play(None, title, playType)
		url = playLink.attrs['href']
		playKey = url.split("/")[0]
		play.urlkey = playKey
		play = self.storePlay(play)

		scenes = self.getPage("http://shakespeare.mit.edu/"+url)
		links = scenes.findAll("a", href=re.compile("^("+playKey+")\.[0-9]\.[0-9]\.(html)"))
		for link in links:
			url = link.attrs["href"]
			urlSplit = url.split(".")
			scene = Scene(None, play, urlSplit[1], urlSplit[2])
			self.getScene(url, scene)
Beispiel #7
0
 def play(self):
     from play import Play
     self.value = self.eurl.get()
     self.player = Play(self.value, mode='quickplay')
     #  Stop scanning url field.
     self.after_cancel(self.quickplay_id)
     #  Disable play button while playing.
     self.bplay.config(state=DISABLED)
     #  Call listener method.
     self.listen_for_result()
Beispiel #8
0
    def run(self):
        ''' run all patterns in the playbook '''
        plays = []
        matched_tags_all = set()
        unmatched_tags_all = set()

        # loop through all patterns and run them
        self.callbacks.on_start()
        for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
            play = Play(self, play_ds, play_basedir)
            matched_tags, unmatched_tags = play.compare_tags(self.only_tags)
            matched_tags_all = matched_tags_all | matched_tags
            unmatched_tags_all = unmatched_tags_all | unmatched_tags

            # if we have matched_tags, the play must be run.
            # if the play contains no tasks, assume we just want to gather facts
            if (len(matched_tags) > 0 or len(play.tasks()) == 0):
                plays.append(play)

        # if the playbook is invoked with --tags that don't exist at all in the playbooks
        # then we need to raise an error so that the user can correct the arguments.
        unknown_tags = set(
            self.only_tags) - (matched_tags_all | unmatched_tags_all)
        unknown_tags.discard('all')

        if len(unknown_tags) > 0:
            unmatched_tags_all.discard('all')
            msg = 'tag(s) not found in playbook: %s.  possible values: %s'
            unknown = ','.join(sorted(unknown_tags))
            unmatched = ','.join(sorted(unmatched_tags_all))
            raise errors.AnsibleError(msg % (unknown, unmatched))

        for play in plays:
            if not self._run_play(play):
                break

        # summarize the results
        results = {}
        for host in self.stats.processed.keys():
            results[host] = self.stats.summarize(host)
        return results
Beispiel #9
0
    def test_get_ship_at_location(self):
        p = Play()
        player1 = Player()
        self._prefill_sample_ships(player1, p)
        exp = {'ship_type': 'Q', 'lives': 2}
        self.assertEqual(p.get_ship_at_location(player1, "A1"), exp)
        self.assertEqual(
            p.get_ship_at_location(player1, "A1")["ship_type"], "Q")
        self.assertEqual(p.get_ship_at_location(player1, "A1")["lives"], 2)

        self.assertEqual(p.get_ship_at_location(player1, "A5"), None)

        exp = {'ship_type': 'P', 'lives': 1}
        self.assertEqual(p.get_ship_at_location(player1, "D5"), exp)
        self.assertEqual(
            p.get_ship_at_location(player1, "D5")["ship_type"], "P")
        self.assertEqual(p.get_ship_at_location(player1, "D5")["lives"], 1)
Beispiel #10
0
def main():
    from play import Play
    p = Play()
    print('choose game:')
    print('1. tic tac toe')
    print('2. connectfour')
    print('3. chess')
    print('4. brasserie (default)')
    game = int(input() or 4) - 1
    getattr(p, ['ttt', 'c4', 'chess', 'brasserie'][game])()
    print('any key to close')
    input()
Beispiel #11
0
    def test_connect_three_me(self, current_play, passin_board, passin_log,
                              **kwargs):

        if not (current_play.player in self.connect_three_me): return -1

        available_plays = current_play.available_plays()

        for play_col_i in range(current_play.board.width):

            temp_play = Play(board = passin_board, \
                             state = copy.deepcopy(current_play.state), \
                             player_init = copy.copy(current_play.player))

            if not (play_col_i in available_plays): continue

            temp_play.make_play(play_col_i, switch_player=False)

            if temp_play.check_win(log=None):
                return play_col_i

        return -1
Beispiel #12
0
 def test_set_lives(self):
     player1 = Player()
     p = Play()
     self._prefill_sample_ships(player1, p)
     self.assertEqual(p.get_lives(player1, "A1"), 2)
     p.set_lives(player1, "A1", 1)
     self.assertEqual(p.get_lives(player1, "A1"), 1)
Beispiel #13
0
    def run(self):
        ''' run all patterns in the playbook '''
        plays = []
        matched_tags_all = set()
        unmatched_tags_all = set()

        # loop through all patterns and run them
        self.callbacks.on_start()
        for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
            play = Play(self, play_ds, play_basedir)
            matched_tags, unmatched_tags = play.compare_tags(self.only_tags)
            matched_tags_all = matched_tags_all | matched_tags
            unmatched_tags_all = unmatched_tags_all | unmatched_tags

            # if we have matched_tags, the play must be run.
            # if the play contains no tasks, assume we just want to gather facts
            if (len(matched_tags) > 0 or len(play.tasks()) == 0):
                plays.append(play)

        # if the playbook is invoked with --tags that don't exist at all in the playbooks
        # then we need to raise an error so that the user can correct the arguments.
        unknown_tags = set(self.only_tags) - (matched_tags_all | unmatched_tags_all)
        unknown_tags.discard('all')

        if len(unknown_tags) > 0:
            unmatched_tags_all.discard('all')
            msg = 'tag(s) not found in playbook: %s.  possible values: %s'
            unknown = ','.join(sorted(unknown_tags))
            unmatched = ','.join(sorted(unmatched_tags_all))
            raise errors.AnsibleError(msg % (unknown, unmatched))

        for play in plays:
            if not self._run_play(play):
                break

        # summarize the results
        results = {}
        for host in self.stats.processed.keys():
            results[host] = self.stats.summarize(host)
        return results
Beispiel #14
0
 def player_plays(self, current_player: Player):
     print(f"Player {current_player}'s turn")
     cards_played = current_player.read_play("Choose cards by index to play or pass")
     if cards_played:
         play = Play(cards_played)
         if not play.is_legal_play():
             print("Illegal play attempted! Stop cheating!!!")
             current_player.add_cards(cards_played)
             return self.player_plays(current_player)
         try:
             self.last_play = play
         except IllegalPlayError as e:
             print(e)
             current_player.add_cards(cards_played)
             return self.player_plays(current_player)
         # Legal if we get here
         self.player_passed(False)
     else:
         if not self.last_play and current_player.cards_in_hand() > 0:
             print("You can't pass on your lead!")
             return self.player_plays(current_player)
         self.player_passed(True)
Beispiel #15
0
    def run(self):
        ''' run all patterns in the playbook '''

        # loop through all patterns and run them
        self.callbacks.on_start()
        for play_ds in self.playbook:
            self.SETUP_CACHE = {}
            self._run_play(Play(self, play_ds))

        # summarize the results
        results = {}
        for host in self.stats.processed.keys():
            results[host] = self.stats.summarize(host)
        return results
Beispiel #16
0
    def playRound(self):
        currentPlay = Play()
        currentPlayerIndex = self.players.index(self.currentDealer)
        currentPlayer = self.players[currentPlayerIndex]
        for player in self.players:
            player.createPlayHand()
        lastPlayerToPlay = None
        while True:
            # Determine is anyone has cards left
            someoneHasCards = False
            for player in self.players:
                if (len(player.playHand) > 0):
                    someoneHasCards = True
            if (not someoneHasCards):
                break

            # Get the next player
            if ((currentPlayerIndex + 1) % len(self.players) == 0):
                currentPlayerIndex = 0
                currentPlayer = self.players[0]
            else:
                currentPlayerIndex += 1
            currentPlayer = self.players[currentPlayerIndex]

            # If player can play, play
            if (currentPlayer.canPlay(currentPlay.pointLimit)):
                cardPlayed = currentPlayer.play(currentPlay.pointLimit)
                currentPlay.append(cardPlayed)
                print('{0} plays {1}'.format(currentPlayer.name, cardPlayed))
                currentPlayer.score += currentPlay.calculateExtraPoints()
                lastPlayerToPlay = currentPlayer
                print(currentPlay.points)
            else:
                if (currentPlayer == lastPlayerToPlay):
                    currentPlayer.score += 1
                    print('{0}: One for last'.format(currentPlayer.name))
                    currentPlay.reset()
                else:
                    print('{0} GO'.format(currentPlayer.name))
        currentPlayer.score += 1
        print('{0}: One for last'.format(currentPlayer.name))
        currentPlay.reset()
Beispiel #17
0
 def open(self):
     self.source.base_name = get_base_file(self.file) 
     # background folder
     directory = 'backgrounds/' + self.source.base_name
     create_dir(directory) 
     init_setup_new(self.main_window)
     self.source.setup_frames = cv2.VideoCapture(self.file)
     self.get_data()
     self.populate_setup()
     self.address_window = AddressWindow(self, self.main_window)
     self.polygon = Polygon(self, self.source)
     self.draw_status = False
     self.play = Play(self.source, self)
     self.play.run_setup()
     self.background = Background(self.source)
Beispiel #18
0
 def do_add(self, name_of_play, short_description, director,
            list_of_actors):
     new_play = Play()
     new_play.name = name_of_play
     new_play.description = short_description
     new_play.director = director
     new_play.actor_list = list_of_actors
     self.manager.transition = SlideTransition(direction="left")
     self.manager.current = 'connected'
     movies.append(new_play)
def move():
    data = PublicGameState(ext_dict=bottle.request.json)
    pos00 = int(data.publicPlayers[0]['position'][1])
    data.publicPlayers[0]['position'][1] = int(
        data.publicPlayers[0]['position'][0])
    data.publicPlayers[0]['position'][0] = pos00
    pos10 = int(data.publicPlayers[1]['position'][1])
    data.publicPlayers[1]['position'][1] = int(
        data.publicPlayers[1]['position'][0])
    data.publicPlayers[1]['position'][0] = pos10
    side = data.agent_id
    my_player = PublicPlayer(jsonString=data.publicPlayers[side])
    enemy = PublicPlayer(jsonString=data.publicPlayers[(side + 1) % 2])

    field = data.gameField
    return Play(side, field, my_player, enemy).take_turn()
Beispiel #20
0
 def camera(self):
     print("Camera in setup")
     # background folder
     directory = 'backgrounds/' + self.source.base_name
     create_dir(directory) 
     self.status = True
     init_setup_new(self.main_window)
     self.source.setup_frames = cv2.VideoCapture(config['camera'])
     self.get_data()
     self.populate_setup()
     self.address_window = AddressWindow(self, self.main_window)
     self.polygon = Polygon(self, self.source)
     self.draw_status = False
     self.play = Play(self.source, self)
     self.play.run_setup()
     self.background = Background(self.source)
Beispiel #21
0
def get_plays(data):
    plays = []
    ball_carriers = []
    for row in data:
        nodes = []
        edges = []
        label = row[0][0]
        offense = []
        defense = []
        num_nodes = 0
        for i in range(len(row)):
            node = []

            if row[i][1] in defense_positions:
                defense.append(num_nodes)
            else:
                offense.append(num_nodes)

            if row[i][2] == "away":
                node.append(0)
            else:
                node.append(1)
            node.append(float(row[i][3]))  # x position
            node.append(float(row[i][4]))  # y position
            node.append(float(row[i][5]))  # speed (yards per second)
            node.append(float(row[i][6]))  # acceleration (yards per second^2)
            node.append(float(row[i][7]))  # distance traveled since snap
            try:
                node.append(float(row[i][8]))  # orientation
            except ValueError:
                node.append(0)
            try:
                node.append(float(row[i][9]))  # direction
            except ValueError:
                node.append(0)
            node.append(float(row[i][10]))  # weight
            num_nodes += 1
            nodes += [node]

        for o in offense:
            for d in defense:
                edges.append([o, d])
        label = np.array(label).astype(np.long)
        plays += [Play(np.array(nodes, dtype=np.float32), edges, label)]

    return plays, np.array(ball_carriers)
Beispiel #22
0
    def play_match(self):
        player1 = Player("Player-1")
        player2 = Player("Player-2")
        p = Play()
        ba = BattleArea(5, "E")
        player1.battle_area = ba.battle_area()
        player2.battle_area = ba.battle_area()

        s = Ship("Q")
        p.fill_ship(s, 1, 1, "A1", player1)
        p.fill_ship(s, 1, 1, "B2", player2)

        s = Ship("P")
        p.fill_ship(s, 2, 1, "D4", player1)
        p.fill_ship(s, 2, 1, "C3", player2)

        player1.targets = 'A1 B2 B2 B3'.split()
        player2.targets = 'A1 B2 B3 A1 D1 E1 D4 D4 D5 D5'.split()

        p.start_match(player1, player2)
Beispiel #23
0
    def plays(self):
        """
        All plays (see Play class documentation) in a corpus.
        """
        corpus_content = requests.get(self.url).json()

        plays = []
        for drama in corpus_content['dramas']:
            printed_year = drama['printYear'] and int(drama['printYear'])
            written_year = drama['writtenYear'] and int(drama['writtenYear'])
            normalized_year = drama['yearNormalized'] and int(
                drama['yearNormalized'])

            plays.append(
                Play(self, drama['name'], drama['title'],
                     drama['author']['name'], printed_year, written_year,
                     normalized_year))

        return plays
Beispiel #24
0
    def parse_result(result, game, play_num, player, home):
        res_elements = result.split('/')
        desc = res_elements[0]
        play_id = ''
        outs = 0
        finished_at_bases = [0, 0, 0, 0]  # -1: out, 0: not on base, 4: scored

        mod = desc
        r1 = re.findall(event_regex, mod)
        if len(res_elements) > 1:
            mod = res_elements[-1]

        # find event if field out
        if not (len(r1) > 0 and r1[0] in events) and desc[0].isdigit() and len(res_elements) > 1:
            r1 = re.findall(event_regex, mod)
            if not (len(r1) > 0 and r1[0] in events) and len(res_elements) > 2:
                mod = res_elements[-2]
                r1 = re.findall(event_regex, mod)
        if len(r1) > 0 and r1[0] in events:
            play_id = r1[0]

        # initialize finished_at_bases values
        for runner in GamesParse.onBases:
            if len(runner) > 0 and runner != GamesParse.onBases[0]:
                index = GamesParse.onBases.index(runner)
                finished_at_bases[index] = index

        # handle strikeout/walk plus baserunning
        if play_id[:2] in ['K+', 'W+'] and play_id[2:] in ['SB', 'CS', 'OA', 'PO'] or play_id[:3] == 'IW+':
            # cache current runners on base
            temp_on_bases = GamesParse.onBases
            run_result = result[result.index('+') + 1:]
            # recurse on running events  and only process batter event moving forward
            (run_play, run_outs, run_only) = GamesParse.parse_result(run_result, game, play_num, player, home)
            finished_at_bases[1] = run_play.finished_1B
            finished_at_bases[2] = run_play.finished_2B
            finished_at_bases[3] = run_play.finished_3B
            result = play_id
            # replace modified on base values with cached values
            GamesParse.onBases = temp_on_bases

        # identify baserunning
        baserunning_only = play_id in ['CS', 'SB', 'DI', 'WP', 'PB', 'BK']
        # base movement
        if play_id in ['S', 'W', 'IW', 'E', 'HP', 'FLE', 'FC'] or any(result.find(x) > -1 for x in ['/FO/', 'K+PB', 'K+WP']):
            finished_at_bases[0] = 1
        elif play_id in ['D', 'DGR']:
            finished_at_bases[0] = 2
        elif play_id == 'T':
            finished_at_bases[0] = 3
        elif play_id == 'HR':
            finished_at_bases[0] = 4
        elif not baserunning_only:
            finished_at_bases[0] = -1

        # replace home and batter with digits
        base_mod_result = result.replace('B', '0').replace('H', '4')

        # out/advance from steal/caught stealing/picked off
        if play_id == 'SB':
            finished_at_bases[int(result[2]) - 1] = int(result[2])
        elif play_id == 'CS' or play_id == 'POCS':
            index = len(play_id)
            finished_at_bases[int(result[index]) - 1] = -1
        elif play_id == 'PO':
            finished_at_bases[int(result[index])] = -1

        # runners advance, ex. 1-3 runner at first advances to third
        r2 = re.findall(r'[0123]-[1234]', base_mod_result)
        for adv in r2:
            finished_at_bases[int(adv[0])] = int(adv[2])

        # explicit outs in the field, ex. (1)
        r3 = re.findall(r'\([0123]\)', base_mod_result)
        for out in r3:
            finished_at_bases[int(out[1])] = -1

        # outs on the basepaths, ex. 2X4(82) runner at second thrown out at home, from CF to catcher
        # descriptions of fielders with "E" indicate safe on error - 2X4(8E2) runner safe at home, throwing error by CF
        r4 = re.findall(r'[0123]X[1234]', base_mod_result)
        for out in r4:
            out_pos = base_mod_result.index(out)
            r4 = re.findall(r'^\([0-9]+E*[0-9]\)', base_mod_result[out_pos + len(out):])
            if len(r4) == 1:
                if r4[0].find('E') > 0:
                    finished_at_bases[int(out[0])] = int(out[2])
                else:
                    finished_at_bases[int(out[0])] = -1

        play = Play(game, play_num, player, '', home, 0, 0,
                    GamesParse.onBases[1], GamesParse.onBases[2], GamesParse.onBases[3],
                    play_id,
                    finished_at_bases[0],
                    finished_at_bases[1],
                    finished_at_bases[2],
                    finished_at_bases[3])

        # set current on-base ids
        temp_on_bases = list(GamesParse.onBases)
        GamesParse.onBases = ['', '', '', '']
        for x in finished_at_bases:
            if x in [1, 2, 3]:
                GamesParse.onBases[x] = temp_on_bases[finished_at_bases.index(x)]
        outs = finished_at_bases.count(-1)
        return play, outs, baserunning_only
        self.rating_run_outside_off = determine_off_rating(1,5,1,3)
        self.rating_run_outside_def = determine_def_rating(3,5,1,1)
        self.rating_pass_short_off = determine_off_rating(4,2,3,1) 
        self.rating_pass_short_def = determine_def_rating(1,5,3,1) 
        self.rating_pass_medium_off = determine_off_rating(4,0,4,2)
        self.rating_pass_medium_def = determine_def_rating(2,2,4,2)
        self.rating_pass_long_off = determine_off_rating(4,0,3,3) 
        self.rating_pass_long_def = determine_def_rating(3,1,3,3) 
        self.rating_special_teams_off = self.rating_sp
        self.rating_special_teams_def = ceil((self.rating_sp - 60) / 4)

        ##Testing
        print self.city, self.nickname, self.rating_run_inside_off,self.rating_run_inside_def,self.rating_run_outside_off,self.rating_run_outside_def,self.rating_pass_short_off,self.rating_pass_short_def,self.rating_pass_medium_off,self.rating_pass_medium_def,self.rating_pass_long_off,self.rating_pass_long_def,self.rating_special_teams_off,self.rating_special_teams_def
        ##Testing
        

def get_next_team_id():
    global next_team_id
    team_id = next_team_id
    next_team_id += 1
    return team_id

team1 = Team("Austin","Easy")
team2 = Team("Chicago","Grown Men")

for i in range (100):
    p = Play()
    p.onside_kickoff(team1,team2,3)

#print team1.id,team1.city,team1.nickname,team1.rating_qb,team1.rating_rb,team1.rating_wr,team1.rating_ol,team1.rating_dl,team1.rating_lb,team1.rating_cb,team1.rating_s,team1.rating_sp
#print team2.id,team2.city,team2.nickname,team2.rating_qb,team2.rating_rb,team2.rating_wr,team2.rating_ol,team2.rating_dl,team2.rating_lb,team2.rating_cb,team2.rating_s,team2.rating_sp
            brain.schedule_lr()
            brain.schedule_clip_range(iteration)
            episode_reward = evaluate_policy(env_name, brain, state_shape)

            if iteration == 1:
                running_reward = episode_reward
            else:
                running_reward = 0.99 * running_reward + 0.01 * episode_reward

            if iteration % log_period == 0:
                print(f"Iter: {iteration}| "
                      f"Ep_reward: {episode_reward:.3f}| "
                      f"Running_reward: {running_reward:.3f}| "
                      f"Total_loss: {total_loss:.3f}| "
                      f"Explained variance:{ev:.3f}| "
                      f"Entropy: {entropy:.3f}| "
                      f"Iter_duration: {time.time() - start_time:.3f}| "
                      f"Lr: {brain.scheduler.get_last_lr()}| "
                      f"Clip_range:{brain.epsilon:.3f}")
                brain.save_params(iteration, running_reward)

            with SummaryWriter(env_name + "/logs") as writer:
                writer.add_scalar("running reward", running_reward, iteration)
                writer.add_scalar("episode reward", episode_reward, iteration)
                writer.add_scalar("explained variance", ev, iteration)
                writer.add_scalar("loss", total_loss, iteration)
                writer.add_scalar("entropy", entropy, iteration)
    else:
        play = Play(env_name, brain)
        play.evaluate()
Beispiel #27
0
class PyBlaster:
    """Daemon for PiBlaster project"""

    def __init__(self):
        """Whole project is run from this constructor
        """

        # +++++++++++++++ Init +++++++++++++++ #

        self.keep_run = 0  # used in run for daemon loop, reset by SIGTERM

        self.log = Log(self)
        self.settings = Settings(self)
        self.led = LED(self)
        self.dbhandle = DBHandle(self)
        self.mixer = AlsaMixer(self)
        self.usb = UsbManager(self)
        self.rfcomm = RFCommServer(self)
        self.cmd = EvalCmd(self)
        self.listmngr = PlayListManager(self)
        self.play = Play(self)
        self.lirc = LircThread(self)
        self.buttons = Buttons(self)
        self.keep_run = 1
        self.ret_code = 0  # return code to command line (10 = shutdown)

        self.led.reset_leds()

        # invoke arg parser and parse config or create new config if not found
        self.settings.parse()

        # check if we can load database, create otherwise
        self.dbhandle.dbconnect()

        # restore alsa mixer settings
        self.mixer.restore_mixer()

        # load connected usb before bluetooth
        self.usb.check_new_usb()

        # initialize sound mixer
        self.play.init_mixer()

        # load latest playlist from database
        self.listmngr.load_active_playlist()

        # open cmd fifo to read commands
        self.cmd.open_fifo()

        # fire up bluetooth service
        self.rfcomm.start_server_thread()

        # start lirc thread
        self.lirc.start()

        # fire up one thread per each button
        self.buttons.start()

        # +++++++++++++++ Daemoninze +++++++++++++++ #

        self.check_pidfile()
        self.daemonize()
        self.create_pidfile()

        self.led.show_init_done()

        # +++++++++++++++ Daemon loop +++++++++++++++ #

        self.run()

        # +++++++++++++++ Finalize +++++++++++++++ #

        self.listmngr.save_active()
        self.led.cleanup()
        self.delete_pidfile()

    def run(self):
        """Daemon loop"""

        # Expensive operations like new usb drive check
        # should not be run every loop run.
        poll_count = 0

        # -e flag is set, run only init and exit directly.
        self.keep_run = 0 if self.settings.exitafterinit else 1

        reset_poll_count = self.settings.keep_alive_count * 30 * 4

        # # # # # # DAEMON LOOP ENTRY # # # # # #

        while self.keep_run:

            poll_count += 1

            # Check cmd fifo for new commands.
            if poll_count % 10 == 0:
                # each 300 ms is enough
                self.cmd.read_fifo()

            # Check button events
            if self.buttons.has_button_events():
                self.buttons.read_buttons()

            # Check bluetooth channel for new messages/connections.
            self.rfcomm.check_incomming_commands()

            # Check if lirc thread has command in queue
            if self.lirc.queue_not_empty():
                ircmd = self.lirc.read_command()
                if ircmd is not None:
                    self.cmd.evalcmd(ircmd, "lirc")

            # Check if song has ended
            if poll_count % 4 == 0:
                # every 120 ms
                self.play.check_pygame_events()

            time.sleep(self.settings.polltime / 1000.)  # 30ms default in
                                                        # config

            if poll_count % self.settings.keep_alive_count == 0:
                self.led.set_led_green(1)

            if (poll_count - self.settings.flash_count) % \
                    self.settings.keep_alive_count == 0:
                self.led.set_led_green(0)

            # Check for new USB drives.
            if poll_count % 30 == 0:
                # If new usb device found, new usbdev instance will be created,
                # including dir and mp3 entries.
                # If usb device got lost, all its entries will be removed.
                # To check every ~900ms is enough
                self.usb.check_new_usb()

            # Multiple of all poll counts reached:
            # may reset poll count at reset_poll_count.
            if poll_count >= reset_poll_count:
                poll_count = 0

            # end daemon loop #

        # # # # # # DAEMON LOOP EXIT # # # # # #

        # join remaining threads
        self.mixer.save_mixer()
        self.lirc.join()
        self.buttons.join()
        self.rfcomm.join()

        self.log.write(log.MESSAGE, "---- closed regularly ----")

    # end run() #

    def daemonize(self):
        """Fork process and disable print in log object"""

        signal.signal(signal.SIGTERM, self.term_handler)
        signal.signal(signal.SIGINT, self.term_handler)

        if not self.settings.daemonize:
            self.log.init_log()
            return

        self.log.write(log.DEBUG1, "daemonizing")

        try:
            pid = os.fork()
        except OSError:
            self.log.write(log.EMERGENCY, "Failed to fork daemon")
            raise

        if pid == 0:
            os.setsid()
            try:
                pid = os.fork()
            except OSError:
                self.log.write(log.EMERGENCY, "Failed to fork daemon")
                raise

            if pid == 0:
                os.chdir("/tmp")
                os.umask(0)
            else:
                os._exit(0)
        else:
            os._exit(0)

        self.settings.is_daemonized = True
        self.log.init_log()
        self.log.write(log.MESSAGE, "daemonized.")

    # end daemonize() #

    def term_handler(self, *args):
        """ Signal handler to stop daemon loop"""
        self.keep_run = 0

    def check_pidfile(self):
        """Check if daemon already running, throw if pid file found"""

        if os.path.exists(self.settings.pidfile):
            self.log.write(log.EMERGENCY, "Found pid file for pyblaster, "
                           "another process running?")
            raise Exception("pid file found")

    def create_pidfile(self):
        """Write getpid() to file after daemonize()"""

        try:
            fpid = open(self.settings.pidfile, "w")
        except IOError:
            self.log.write(log.EMERGENCY, "failed to create pidfile %s" %
                           self.settings.pidfile)
            raise

        fpid.write("%s\n" % os.getpid())

    def delete_pidfile(self):
        """Try to remove pid file after daemon should exit"""

        if os.path.exists(self.settings.pidfile):
            try:
                os.remove(self.settings.pidfile)
            except OSError:
                self.log.write(log.EMERGENCY, "failed to remove pidfile %s" %
                               self.settings.pidfile)
                raise

    def kill_other_pyblaster(self):
        """Check if pid found in pid file and try to kill this (old) process"""

        if not os.path.exists(self.settings.pidfile):
            return

        try:
            f = open(self.settings.pidfile, "r")
        except IOError:
            self.log.write(log.EMERGENCY, "failed to read pidfile %s" %
                           self.settings.pidfile)
            raise

        pid = int(f.readline().strip())

        print("Trying to kill old process with pid %s..." % pid)

        try:
            os.kill(pid, signal.SIGTERM)
        except OSError:
            self.log.write(log.EMERGENCY,
                           "failed to kill process with pid %s" % pid)
            raise

        exit(0)
Beispiel #28
0
        # scImage(self.window, "launcher/background.jpg", (0,0), SIZE)

        self.launcher.drawObjects(self.window)

        pygame.display.update()

    # Gameloop
    def loop(self):
        while self.running:
            self.update()
            self.render()

    # Start project
    def startProject(self, projectName):
        self.path = self.pathToProjects + projectName
        self.end()

    # Turn off the launcher
    def end(self):
        self.running = False


# Start launcher
main = Main()
path = main.path
pygame.quit()

if path != "":
    # Start project
    Play(path)
    pygame.quit()
Beispiel #29
0
class Setup:
    def __init__(self, source):
        self.source = source
        self.files = source.setup_list
        self.main_window = source.main_window
        self.dbs = source.dbs
        self.admin = source.admin
        self.pointer = 0
        self.sentinel = len(self.files)
        self.line_status = False
        self.draw_status = False
        self.status = False 
        self.analysis = None

        # init setup ui
        init_address(self.main_window)

        # enable address button
        self.main_window.setup_address_btn.setEnabled(True)
        
        # signals
        # connect setup save button
        self.main_window.connect(self.main_window.setup_save_btn, \
            SIGNAL("clicked()"), self.save_setup)
        self.main_window.setup_save_btn.setEnabled(True)
        # connect address button
        self.main_window.connect(self.main_window.setup_address_btn, \
            SIGNAL("clicked()"), self.click_address_btn)
        # setup play button
        self.main_window.connect(self.main_window.setup_play_btn, \
            SIGNAL("clicked()"), self.click_setup_play_btn)
        # setup pause button
        self.main_window.connect(self.main_window.setup_pause_btn, \
            SIGNAL("clicked()"), self.click_setup_pause_btn)
        # setup background button
        self.main_window.connect(self.main_window.setup_bg_btn, \
            SIGNAL("clicked()"), self.click_setup_bg_btn)
        # setup reset button
        self.main_window.connect(self.main_window.setup_reset_btn, \
            SIGNAL("clicked()"), self.click_reset_btn)
        # setup draw button
        self.main_window.connect(self.main_window.setup_draw_btn, \
            SIGNAL("clicked()"), self.click_draw_btn)
        # setup line button
        self.main_window.connect(self.main_window.setup_line_btn, \
            SIGNAL("clicked()"), self.click_line_btn)

        # setup frame mousePressEvent overide
        self.main_window.setup_frame.mousePressEvent = \
            self.setup_frame_click

    def get_data(self):
        if self.source.media == "file":
            print("Gathering video properties")
            self.path = self.file
            self.metadata = get_metadata(self.file)
            self.base_name = get_base_name(self.file)
            self.fps = get_fps(self.metadata)
            self.duration = get_duration(self.metadata)
            self.resolution = get_resolution(self.metadata)
            self.format = get_format(self.metadata)
        if self.source.media == "camera":
            self.base_name = self.source.base_name 
            self.path = self.source.path 
            self.metadata = None
            self.fps = None
            self.duration = None
            self.resolution = None
            self.format = None

    def valid_setup(self):
        rv = True
        message = ''
        # address
        if self.address_window.valid_address():
            print("Creating address for video in db")
            self.address_window.create_address()
            self.address = self.address_window.address
        else:
            message = message + "Address is incomplete!\n"
            rv = False
        # background
        if self.background.path is None:
            message = message + "Background image is None!\n"
            rv = False
        # polygon
        if self.polygon.no_of_points <= 3:
            message = message + "Polygon is not yet set!\n"
            rv = False
        if rv is False:
            print(message)
            self.dialog = DialogWindow("Setup", message)
        return rv

    def save_db(self):
        file = self.base_name
        path = self.path
        background = self.background.path
        fps = self.fps
        duration = None
        created_time = None
        admin_id = self.admin.id
        address_id = self.address.id

        video = Video(file, path, background, \
            fps, duration, created_time, admin_id, \
            address_id)
        
        self.video = video 
        print("Creating video in db", video)
        s = self.dbs
        s.add(video)
        s.commit()

        # save polygon after acquiring video 
        self.polygon.save_db()

    def start_analysis(self):
        print("Nothing to setup!")
        self.dialog = DialogWindow("Setup", "Setup is finished!")
        self.status = False
        print("Start analysis here")
        self.analysis = Analysis(self.source, self)
        self.source.analysis = self.analysis

    def save_setup(self):
        print("Clicked save setup button")
        if self.valid_setup():
            self.save_db()
            if self.status == True:
                if self.source.media == 'file':
                    self.sequencer()
                if self.source.media == 'camera':
                   self.start_analysis() 

    def click_address_btn(self):
        self.address_window.ui.show()

    def populate_setup(self):
        self.main_window.name_lbl.setText(self.base_name)
        self.main_window.fps_lbl.setText(self.fps)
        self.main_window.duration_lbl.setText(self.duration)
        self.main_window.resolution_lbl.setText(self.resolution)
        self.main_window.format_lbl.setText(self.format)
        self.main_window.statusbar.showMessage("Path: %s" % self.path)

    def open(self):
        self.source.base_name = get_base_file(self.file) 
        # background folder
        directory = 'backgrounds/' + self.source.base_name
        create_dir(directory) 
        init_setup_new(self.main_window)
        self.source.setup_frames = cv2.VideoCapture(self.file)
        self.get_data()
        self.populate_setup()
        self.address_window = AddressWindow(self, self.main_window)
        self.polygon = Polygon(self, self.source)
        self.draw_status = False
        self.play = Play(self.source, self)
        self.play.run_setup()
        self.background = Background(self.source)

    def sequencer(self):
        init_setup(self.main_window)
        if self.pointer != len(self.files):
            self.status = True
            self.file = self.files[self.pointer]
            self.path = self.file
            self.open()
            self.pointer += 1
        else:
            self.start_analysis()

    def camera(self):
        print("Camera in setup")
        # background folder
        directory = 'backgrounds/' + self.source.base_name
        create_dir(directory) 
        self.status = True
        init_setup_new(self.main_window)
        self.source.setup_frames = cv2.VideoCapture(config['camera'])
        self.get_data()
        self.populate_setup()
        self.address_window = AddressWindow(self, self.main_window)
        self.polygon = Polygon(self, self.source)
        self.draw_status = False
        self.play = Play(self.source, self)
        self.play.run_setup()
        self.background = Background(self.source)

    def click_setup_play_btn(self):
        print("Clicked setup play button!")
        self.play.setup_status = True
        self.play.setup_timer.start()
        self.main_window.setup_pause_btn.setEnabled(True)
        self.main_window.setup_play_btn.setEnabled(False)

    def click_setup_pause_btn(self):
        print("Clicked setup pause button!")
        self.play.setup_status = False 
        self.play.setup_timer.stop()
        self.main_window.setup_pause_btn.setEnabled(False)
        self.main_window.setup_play_btn.setEnabled(True)

    def click_setup_bg_btn(self):
        print("Clicked capture background button")
        self.background.capture_frame()

    def click_draw_btn(self):
        print("Clicked draw button")
        self.line_status = False
        self.draw_status = True
        if self.play.setup_status == False:
            self.play.run_setup_pause()
        self.main_window.setup_draw_btn.setEnabled(False)
        self.main_window.setup_line_btn.setEnabled(True)
        # get area of polygon
        area = self.polygon.compute_area()
        self.main_window.area_lbl.setText(str(self.polygon.area))

    def click_line_btn(self):
        print("Clicked line button")
        self.line_status = True 
        self.draw_status = False 
        if self.play.setup_status == False:
            self.play.run_setup_pause()
        self.main_window.setup_line_btn.setEnabled(False)
        self.main_window.setup_draw_btn.setEnabled(True)
        self.main_window.area_lbl.setText("") 

    def click_reset_btn(self):
        print("Clicked reset button")
        self.polygon.reset()
        if self.play.setup_status == False:
            self.play.run_setup_reset()
        self.main_window.setup_reset_btn.setEnabled(False)
        self.main_window.setup_line_btn.setEnabled(False)
        self.main_window.setup_draw_btn.setEnabled(False)
        self.line_status = False 
        self.draw_status = False

    def setup_frame_click(self, event):
        if self.play.setup_status == True:
            print("Pause the source before assigning coordinates")
        else:
            print("Clicked setup frame") 
            x = event.pos().x()
            y = event.pos().y()
            print(x, y)
            print(event.pos())
            point = (x, y)
            self.polygon.append(point)
            self.polygon.get_no_points()
            if self.polygon.no_of_points > 0:
                self.main_window.setup_reset_btn.setEnabled(True)
            if self.polygon.no_of_points > 1:
                self.line_status = True
            if self.polygon.no_of_points > 2:
                self.main_window.setup_draw_btn.setEnabled(True)
            self.play.run_setup_pause()

    def get_video(self):
        return self.video

    def load_video(self, video_id):
        load = False
        s = self.dbs
        result = s.query(Video).filter(Video.id == video_id)
        if result.count() == 1:
            video = result.first() 
            load = True
        elif result.count() > 1:
            print("Found more than 1 match in database!")
        else:
            print("No match found in database!")
        if load == True: 
            self.path = video.path
            self.base_name = video.name 
            self.fps = str(video.fps) 
            self.duration = video.duration
            # address
            self.address_window = AddressWindow(self, self.main_window)
            self.address_window.get_address(video.address_id)
            # polygon
            self.polygon = Polygon(self, self.source)
            self.polygon.get_points(video.id)
            self.polygon.compute_area()
            area = self.polygon.area
            self.main_window.area_lbl.setText(str(abs(area)))
            self.metadata = get_metadata(self.path)
            self.duration = get_duration(self.metadata)
            self.resolution = get_resolution(self.metadata)
            self.format = get_format(self.metadata)
            # load in setup
            self.populate_setup()
Beispiel #30
0
    def __init__(self):
        """Whole project is run from this constructor
        """

        # +++++++++++++++ Init +++++++++++++++ #

        self.keep_run = 0  # used in run for daemon loop, reset by SIGTERM

        self.log = Log(self)
        self.settings = Settings(self)
        self.led = LED(self)
        self.dbhandle = DBHandle(self)
        self.mixer = AlsaMixer(self)
        self.usb = UsbManager(self)
        self.rfcomm = RFCommServer(self)
        self.cmd = EvalCmd(self)
        self.listmngr = PlayListManager(self)
        self.play = Play(self)
        self.lirc = LircThread(self)
        self.buttons = Buttons(self)
        self.keep_run = 1
        self.ret_code = 0  # return code to command line (10 = shutdown)

        self.led.reset_leds()

        # invoke arg parser and parse config or create new config if not found
        self.settings.parse()

        # check if we can load database, create otherwise
        self.dbhandle.dbconnect()

        # restore alsa mixer settings
        self.mixer.restore_mixer()

        # load connected usb before bluetooth
        self.usb.check_new_usb()

        # initialize sound mixer
        self.play.init_mixer()

        # load latest playlist from database
        self.listmngr.load_active_playlist()

        # open cmd fifo to read commands
        self.cmd.open_fifo()

        # fire up bluetooth service
        self.rfcomm.start_server_thread()

        # start lirc thread
        self.lirc.start()

        # fire up one thread per each button
        self.buttons.start()

        # +++++++++++++++ Daemoninze +++++++++++++++ #

        self.check_pidfile()
        self.daemonize()
        self.create_pidfile()

        self.led.show_init_done()

        # +++++++++++++++ Daemon loop +++++++++++++++ #

        self.run()

        # +++++++++++++++ Finalize +++++++++++++++ #

        self.listmngr.save_active()
        self.led.cleanup()
        self.delete_pidfile()
class Gui(QtGui.QMainWindow,QtGui.QWidget):

	def __init__(self):
		super(Gui, self).__init__()
		self.speaker = ""
		self.directory = ""
		self.type = ""
		self.line=0
		self.text=[]
		self.decode=""
		self.fname="output"
		self.rec=0
		self.initUI()
		self.file = ""

	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		self.figure = plt.figure(1)
		self.canvas = FigureCanvas(self.figure)
		self.toolbar = NavigationToolbar(self.canvas, self)
		self.centralwidget = QtGui.QWidget(self)
		self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
		self.verticalLayout.addWidget(self.toolbar)
		self.verticalLayout.addWidget(self.canvas)
		self.centralwidget.setGeometry(10,10,825,330)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		chUser = QtGui.QAction('&Change Speaker', self)
		chUser.setStatusTip('Change Speaker')
		chUser.triggered.connect(self.changeUser)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		Ascii = QtGui.QAction('&ASCII', self)
		Ascii.setStatusTip('ascii')
		Ascii.triggered.connect(self.encodeASCII)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,360,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,480)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,480)
		self.Record.setEnabled(False)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,480)
		self.Stop.setEnabled(False)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,480)
		self.Play.setEnabled(False)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,480)
		self.Back.setEnabled(False)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,480)
		self.Next.setEnabled(False)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(chUser)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(Ascii)
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Akshar Voice Recorder')
		self.user = User(self)

	def showDialogOpen(self):
		plt.clf()
		self.canvas.draw()
		self.statusBar().showMessage('Open a File')
		self.fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file')
		if(self.fname!=""):
			self.Record.setEnabled(True)
			self.Play.setEnabled(True)
			self.Next.setEnabled(True)
			self.Back.setEnabled(True)
			self.directory=str(self.file)+"/"+str(self.speaker)+"_"+str(self.type)+"_"+str(self.fname).split("/")[-1]
			if not os.path.exists(self.directory):
				os.makedirs(self.directory)
			del self.text[:]
			f = open(self.fname, 'r')
			for lines in f:
				self.text.append(lines)
			f.close
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('ascii'))
			self.line=0
		else:
			self.Record.setEnabled(False)
			self.Play.setEnabled(False)
			self.Next.setEnabled(False)
			self.Back.setEnabled(False)
		self.statusBar().showMessage('')

	def showNext(self):
		plt.clf()
		self.canvas.draw()
		self.line+=1
		if(len(self.text)>self.line):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showBack(self):
		plt.clf()
		self.canvas.draw()
		self.line-=1
		if(len(self.text)>=self.line and self.line>=0):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showAbout(self):
		self.popup1=About()
		self.popup1.exec_()

	def encodeUTF8(self):
		self.decode="utf-8"

	def encodeUTF16(self):
		self.decode="utf-16"

	def encodeASCII(self):
		self.decode="ascii"

	def changeUser(self):
		self.user.__init__(self)

	def record(self):
		plt.clf()
		self.canvas.draw()
		self.statusBar().showMessage('Recording')
		self.rec=1
		self.Record.setEnabled(False)
		self.Stop.setEnabled(True)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.vrThread.start()
		self.vr.record(self.directory, self.text[self.line].split(")")[0], self)

	def stop(self):
		self.statusBar().showMessage('')
		if self.rec == 1:
			self.vr.stop()
			self.vrThread.exit()
			self.vrThread.wait()
			self.vrThread.quit()
		elif self.rec == 2:
			self.pl.stop()
			self.plThread.exit()
			self.plThread.wait()
			self.plThread.quit()
		self.Record.setEnabled(True)
		self.Open.setEnabled(True)
		self.Play.setEnabled(True)
		self.Next.setEnabled(True)
		self.Back.setEnabled(True)
		self.rec=0

	def play(self):
		self.statusBar().showMessage('Playing')
		self.rec=2
		self.Record.setEnabled(False)
		self.Stop.setEnabled(True)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.plThread.start()
		self.pl.play(self.text[self.line].split(")")[0], self)
	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		self.figure = plt.figure(1)
		self.canvas = FigureCanvas(self.figure)
		self.toolbar = NavigationToolbar(self.canvas, self)
		self.centralwidget = QtGui.QWidget(self)
		self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
		self.verticalLayout.addWidget(self.toolbar)
		self.verticalLayout.addWidget(self.canvas)
		self.centralwidget.setGeometry(10,10,825,330)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		chUser = QtGui.QAction('&Change Speaker', self)
		chUser.setStatusTip('Change Speaker')
		chUser.triggered.connect(self.changeUser)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		Ascii = QtGui.QAction('&ASCII', self)
		Ascii.setStatusTip('ascii')
		Ascii.triggered.connect(self.encodeASCII)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,360,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,480)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,480)
		self.Record.setEnabled(False)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,480)
		self.Stop.setEnabled(False)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,480)
		self.Play.setEnabled(False)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,480)
		self.Back.setEnabled(False)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,480)
		self.Next.setEnabled(False)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(chUser)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(Ascii)
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Akshar Voice Recorder')
		self.user = User(self)
Beispiel #33
0
    def __call__(self , mode = "Train"):
        game_state = Play()
        D = deque()
        do_nothing = 3
        frame, action, done = game_state.frame_step(do_nothing)
        frame = self.__class__._preprocess_image(frame)
        stack_frame = np.stack((frame, frame, frame, frame), axis=2)
        #In Keras, need to reshape
        stack_frame = stack_frame.reshape(1, stack_frame.shape[0], stack_frame.shape[1], stack_frame.shape[2])  #1*80*80*4
        if mode == 'Run':
            OBSERVE = 999999999
            epsilon = FINAL_EPSILON
            print ("Now we load weight")
            self.model.load_weights("model.h5")
            print ("Weight load successfully")
        else:                       #We go to training mode
            OBSERVE = OBSERVATION
            epsilon = INITIAL_EPSILON

        t = 0
        while True:
            loss = 0
            Q_sa = 0
            action_index = 0
            reward = 0
            a_t = ACTIONS
            #choose an action epsilon greedy
            if t % FRAME_PER_ACTION == 0:
                if random.random() <= epsilon:
                    print("----------Random Action----------")
                    action_index = random.randrange(ACTIONS)
                    a_t = action_index
                else:
                    q = self.model(stack_frame,training=False)
                    max_Q = np.argmax(q)
                    a_t=max_Q

            #We reduced the epsilon gradually
            if epsilon > FINAL_EPSILON and t > OBSERVE:
                epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE

            #run the selected action and observed next state and reward
            frame1_colored, reward, done = game_state.frame_step(a_t)

            #Restart game if game is over
            if done:
                game_state.restart()

            frame1 = self._preprocess_image(frame1_colored)
            frame1 = frame1.reshape(1, frame1.shape[0], frame1.shape[1], 1) #1x80x80x1
            stack_frame1 = np.append(frame1, stack_frame[:, :, :, :3], axis=3)

            # store the transition in D
            D.append((stack_frame, action_index, reward, stack_frame1, done))
            if len(D) > REPLAY_MEMORY:
                D.popleft()

            #only train if done observing
            if t > OBSERVE:
                #sample a minibatch to train on
                minibatch = random.sample(D, BATCH)

                #Now we do the experience replay
                state_t, action_t, reward_t, state_t1, done = zip(*minibatch)
                state_t = np.concatenate(state_t)
                state_t1 = np.concatenate(state_t1)
                targets = self.model(state_t , training=False)
                _targets = np.zeros_like(targets)
                Q_sa = self.model(state_t1, training=False)
                _targets[range(BATCH), action_t] = reward_t + GAMMA*np.max(Q_sa, axis=1)*np.invert(done)
                with tf.GradientTape() as tape:
                    _loss = self._train_step(state_t,_targets)
                    gradients = tape.gradient(_loss, self.model.trainable_variables)
                    self.optimizer.apply_gradients(zip(gradients, self.model.trainable_variables))
                    print("APPLIED GRADIENT")


            stack_frame = stack_frame1
            t = t + 1

            # save progress every 10000 iterations
            #BUG
            if t % 1000 == 0:
                print("Now we save model")
                self.model.save_weights("model.h5", overwrite=True)
                #with open("model.json", "w") as outfile:
                    #json.dump(self.model.to_json(), outfile)

            if t <= OBSERVE:
                state = "observe"
            elif t > OBSERVE and t <= OBSERVE + EXPLORE:
                state = "explore"
            else:
                state = "train"
            print('Done = ', done)

            print("TIMESTEP", t, "/ STATE", state, \
                "/ EPSILON", epsilon, "/ ACTION", action_index, "/ REWARD", reward, \
                "/ Q_MAX " , np.max(Q_sa), "/ Loss ", loss)

        print("Episode finished!")
        print("************************")
Beispiel #34
0
from play import Play
#from tutorial.ttypes import *

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:
    # Make socket
    transport = TSocket.TSocket('localhost', 9090)

    # Buffering is critical. Raw sockets are very slow
    transport = TTransport.TBufferedTransport(transport)

    # Wrap in a protocol
    protocol = TBinaryProtocol.TBinaryProtocol(transport)

    # Create a client to use the protocol encoder
    client = Play.Client(protocol)

    # Connect!
    transport.open()

    num = 100000
    for i in range(num):
        s = client.ping()

except Thrift.TException, tx:
    print '%s' % (tx.message)
Beispiel #35
0
        self._count = 0
        self._st_time = time.time()

    def ping(self):
        self._count += 1
        if self._count % 10000 == 0:
            right_now = time.time()
            print self._count / (right_now - self._st_time)
            self._st_time = right_now
            self._count = 0

        #print "ping!"
        return 123


handler = PlayHandler()
processor = Play.Processor(handler)
transport = TSocket.TServerSocket(port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

# You could do one of these for a multithreaded server
server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
#server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)

print 'Starting the server...'
server.serve()
print 'done.'
Beispiel #36
0
class Analysis:
    def __init__(self, source, setup):
        self.dbs = source.dbs
        self.main_window = source.main_window
        self.source = source
        self.setup = setup
        if self.source.media == 'file':
            self.files = source.files
        self.main_window.tabs.setCurrentIndex(1)
        self.pointer = 0
        self.location = Location(self.main_window, self.source)

        # signals
        # play button
        self.main_window.connect(self.main_window.analysis_play_btn, \
            SIGNAL("clicked()"), self.click_analysis_play_btn)
        # pause button
        self.main_window.connect(self.main_window.analysis_pause_btn, \
            SIGNAL("clicked()"), self.click_analysis_pause_btn)
        # stop button
        self.main_window.connect(self.main_window.analysis_stop_btn, \
            SIGNAL("clicked()"), self.click_analysis_stop_btn)
        # next button
        self.main_window.connect(self.main_window.analysis_next_btn, \
            SIGNAL("clicked()"), self.click_analysis_next_btn)
        # debug speed button
        self.main_window.connect(self.main_window.speed_btn, \
            SIGNAL("clicked()"), self.click_speed_btn)
        # debug road status button
        self.main_window.connect(self.main_window.road_status_btn, \
            SIGNAL("clicked()"), self.click_road_status_btn)
        # haar collect button
        self.main_window.connect(self.main_window.haar_capture_btn, \
            SIGNAL("clicked()"), self.click_haar_capture_btn)
        # haar classifier button
        self.main_window.connect(self.main_window.classifier_btn, \
            SIGNAL("clicked()"), self.click_classifier_btn)

        # choose media source
        if self.source.media == 'file':
            self.sequencer()
        if self.source.media == 'camera':
            self.open()

    def release_media(self):
        print("Releasing media")
        if self.source.setup_frames != None:
            self.source.setup_frames.release()
        self.source.analysis_frames.release()

    def sequencer(self):
        init_setup(self.main_window)
        if self.pointer != len(self.files):
            self.file = self.files[self.pointer]
            self.open()
            self.pointer += 1
        else:
            print("Nothing to analyse!")
            self.dialog = DialogWindow("Analysis", "Analysis is finished!")
            init_main(self.main_window)
            # self.main_window.tabs.hide()
            self.play.analysis_timer.stop()
            self.release_media()

    def open(self):
        init_analysis(self.main_window)
        self.main_window.analysis_next_btn.setEnabled(True)
        if self.source.media == 'file':
            self.source.base_name = get_base_file(self.file) 
            self.source.analysis_frames = cv2.VideoCapture(self.file)
        if self.source.media == 'camera':
            init_analysis_camera(self.main_window)
            print("Setting analysis frames for camera")
            # release camera resource for analysis
            self.source.setup_frames.release()
            self.source.analysis_frames = cv2.VideoCapture(config['camera'])
        # images folder
        directory = 'images/' + self.source.base_name
        create_dir(directory) 
        self.get_video()
        if self.source.media == 'file':
            self.setup.load_video(self.video.id)
        self.background = Background(self.source) 
        self.background.get_db(self.video.id)
        self.source.background = self.background
        self.polygon = Polygon(self.source, self.setup) 
        self.polygon.get_points(self.video.id)
        self.polygon.draw_setup(self.background.frame, self.polygon.points)
        self.source.polygon = self.polygon
        self.play = Play(self.source, self.setup)
        self.play.run_analysis()
        # set location
        self.location.set_location(self.video.address_id)
        # play
        self.click_analysis_play_btn()

    def click_analysis_play_btn(self):
        print("Clicked play button in analysis!")
        self.play.analysis_status = True
        self.play.analysis_timer.start()
        self.main_window.analysis_pause_btn.setEnabled(True)
        self.main_window.analysis_play_btn.setEnabled(False)
        self.play.timer.status = True
        self.play.timer.start()

    def click_analysis_pause_btn(self):
        print("Clicked pause button in analysis!")
        self.play.analysis_status = False 
        self.play.analysis_timer.stop()
        self.main_window.analysis_pause_btn.setEnabled(False)
        self.main_window.analysis_play_btn.setEnabled(True)

    def click_analysis_stop_btn(self):
        print("Clicked stop button in analysis!")
        self.play.analysis_status = False 
        self.play.analysis_timer.stop()
        stop_analysis(self.main_window)
        init_setup(self.main_window)
        # release media source
        self.release_media()
        self.main_window.tabs.setCurrentIndex(0)

    def get_video(self):
        if self.source.media == 'file':
            self.base_name = get_base_name(self.file)
        if self.source.media == 'camera':
            self.base_name = self.source.base_name
        s = self.dbs
        result = s.query(Video).filter(Video.name == self.base_name)
        if result.count() == 0:
            print("No video record found in database")
            self.video = None
        elif result.count() == 1:
            print("Found 1 record in database")
            self.video = result.first()
            self.source.video = self.video
            print(self.video)
            # get location of source
            self.source.location = s.query(Address).filter(Address.id \
                == self.video.address_id).first()
            print("Location of source is ", self.source.location)
        else:
            self.video = None

    def click_analysis_next_btn(self):
        print("Clicked next button in analysis!")
        self.sequencer()

    def click_speed_btn(self):
        if self.play.speed_debug == True:
            self.play.speed_debug = False
        else:
            self.play.speed_debug = True
        self.main_window.speed_debug_lbl.setText(\
            str(self.play.speed_debug))
        print("Speed debug status:", self.play.speed_debug)

    def click_road_status_btn(self):
        if self.play.road_status_debug == True:
            self.play.road_status_debug = False
        else:
            self.play.road_status_debug = True
        self.main_window.road_status_debug_lbl.setText(\
            str(self.play.road_status_debug))
        print("Speed debug status:", self.play.road_status_debug)

    def click_haar_capture_btn(self):
        print("Clicked haar capture button")
        if self.play.haar_collect == True:
            self.play.haar_collect = False
        else:
            self.play.haar_collect = True
        self.main_window.haar_capture_lbl.setText(\
            str(self.play.haar_collect))
        print("Haar collect status:", self.play.haar_collect)

    def click_classifier_btn(self):
        print("Clicked haar classifier button")
        if self.play.haar_activate == True:
            self.play.haar_activate = False
        else:
            self.play.haar_activate = True
        self.main_window.classifier_lbl.setText(\
            str(self.play.haar_activate))
        print("Haar activate status:", self.play.haar_activate)
Beispiel #37
0
import pygame,sys
from settings import Settings
from pygame.locals import *
from play import Play
from pipe import Pipe

pygame.init()
py_setings = Settings()

screen = pygame.display.set_mode((py_setings.screen_width,py_setings.screen_height))

# 设置标题
pygame.display.set_caption("FlyBird")

#生成一个像素鸟对象
play = Play(screen)

#生成一组管道对象
pipe = Pipe()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    if event.type == MOUSEMOTION:
        play.rect = event.pos



Beispiel #38
0
 def play(self):
     dialog = Play(self)
     dialog.exec()
	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.spectro()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,30,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,160)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,160)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,160)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,160)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,160)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,160)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Voice Recorder')
		#self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.show()
Beispiel #40
0
                n_actions=n_actions,
                memory_size=memory_size,
                batch_size=batch_size,
                gamma=gamma,
                alpha=alpha,
                lr=lr,
                action_bounds=action_bounds,
                reward_scale=reward_scale)

if TRAIN:
    for episode in range(1, MAX_EPISODES + 1):
        state = env.reset()
        episode_reward = 0
        done = 0
        start_time = time.time()
        while not done:
            action = agent.choose_action(state)
            next_state, reward, done, _ = env.step(action)
            agent.store(state, reward, done, action, next_state)
            value_loss, q_loss, policy_loss = agent.train()
            if episode % 250 == 0:
                agent.save_weights()
            episode_reward += reward
            state = next_state
        log(episode, start_time, episode_reward, value_loss, q_loss,
            policy_loss, len(agent.memory))

else:
    player = Play(env, agent)
    player.evaluate()
Beispiel #41
0
from bot import Bot
from time import sleep
import traceback
from play import Play
bot = Bot()
play = Play(bot)
first=True

bot.sock.empty_socket()



try:

    print("logging in")
    bot.login(True)
    print("logged in")


    while bot.sock.is_connected:
        # TODO: need to do the below until the end of the betting
        # Need to wait for status 
        print("waiting for message")
        b = bot.receive()
        print(b)
        # Get power auction.
        # Recieve auction token
        if b == "auction":
            print("Got auction")
            play.decide_auction()
            # bot.auction_response()
Beispiel #42
0
from assets.PPlay.keyboard import Keyboard
from pygame.time import Clock
from menu import Menu
from play import Play
from fps import Fps
from rank import Rank
from difficulty import Difficulty
import GVar

window = Window(GVar.WIDTH, GVar.HEIGHT)
window.set_title("Space Invaders")
window.set_background_color((0, 0, 0))

keyboard = Keyboard()
menu = Menu(window)
play = Play(window, "./assets/lvl/level_1.txt")
difficulty_menu = Difficulty(window)
rank = Rank(window)
clock = Clock()
fps = Fps(window)

window.update()
while GVar.STATE != 4:
    window.set_background_color((0, 0, 0))
    if keyboard.key_pressed("esc"):
        GVar.STATE = 0
        play.__init__(window, "./assets/lvl/level_1.txt")
    if GVar.STATE == 0:
        menu.run()
    if GVar.STATE == 1:
        if GVar.DIFC_CHOSEN == True:
Beispiel #43
0
class Main:
    def __init__(self):
        pygame.init()

        # Game screen
        self.screen = pygame.display.set_mode(SIZE)
        pygame.display.set_caption("VN")

        # Game icon
        gameIcon = loadImage(folder + "assets/icon.png")
        pygame.display.set_icon(gameIcon)

        # Clock
        self.clock = pygame.time.Clock()

        # For the future
        self.screens = {}
        self.currentScreen = ""
        self.screens["main"] = False
        # self.screens[self.currentScreen]

        self.loading()

    # Loading data
    def loading(self):
        # Instances of classes
        self.play = Play(self.screen)

        # Start game
        self.start()

    # Game start
    def start(self):
        loop.running = True
        loop.mainloop = True
        self.gameloop()

    # Handling events
    def events(self):
        for event in pygame.event.get():
            # Disabling the game
            if event.type == pygame.QUIT:
                self.end()

            # Playing events
            if loop.playloop:
                self.play.events(event)

            # Handling button events
            for button in buttons:
                # Handling button click
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if button.rect.collidepoint(event.pos):
                        create(self.buttonAction(button.name))

                # Hovering over the button
                if event.type == pygame.MOUSEMOTION:
                    if (button.rect.collidepoint(event.pos)):
                        button.hover = True
                    else:
                        button.hover = False

            # Handling cells events
            for cell in cells:
                cell.events(event)

    # Actions for buttons
    def buttonAction(self, name):
        screen = ""
        if name == "hsave" or name == "hload": return

        # Exit button
        if name == "exit" or name == "hexit": self.end()
        # Start play button
        if name == "play":
            createPlay()
            self.play.loading()
            screen = "play"
        # Load button
        if name == "load":
            if loop.loadloop:
                screen = "main"
            else:
                screen = "load"
        # Settings button
        if name == "settings":
            if loop.settingsloop:
                screen = "main"
            else:
                screen = "settings"
        # Back to main menu
        if name == "back" or name == "hmenu":
            screen = "main"

        return screen

    # Intermediant calculations
    def update(self):
        # Updates per second
        self.clock.tick(FPS)

        # Handling events
        self.events()

    # Rendering game objects
    def render(self):
        # Background color
        self.screen.fill(WHITE)

        # Rendering main screen
        if loop.mainloop or loop.loadloop or loop.settingsloop:
            # Background image
            scImage(self.screen, folder + "assets/gui/backgroundmenu.jpg",
                    (0, 0), SIZE)

        # Rendering play screen
        if loop.playloop:
            self.play.draw()

        # Rendering interface
        drawInterface(self.screen)

        pygame.display.update()

    # Gameloop
    def gameloop(self):
        while loop.running:
            self.update()
            self.render()

    # End of the game
    def end(self):
        loop.running = False
from play import LoadWords, Play

# this will play the game.

if __name__ == '__main__':
    load_word = LoadWords()
    # get the word list.
    word_list = load_word.load_words()
    play = Play()
    # human plays the game.
    play.play_game(word_list)
Beispiel #45
0
    def loading(self):
        # Instances of classes
        self.play = Play(self.screen)

        # Start game
        self.start()
Beispiel #46
0
    def run(self):
        ''' run all patterns in the playbook '''
        plays = []
        matched_tags_all = set()
        unmatched_tags_all = set()

        # loop through all patterns and run them
        self.callbacks.on_start()
        for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
            play = Play(self,
                        play_ds,
                        play_basedir,
                        vault_password=self.vault_password)
            assert play is not None

            matched_tags, unmatched_tags = play.compare_tags(self.only_tags)

            matched_tags_all = matched_tags_all | matched_tags
            unmatched_tags_all = unmatched_tags_all | unmatched_tags

            # Remove tasks we wish to skip
            matched_tags = matched_tags - set(self.skip_tags)

            # if we have matched_tags, the play must be run.
            # if the play contains no tasks, assume we just want to gather facts
            # in this case there are actually 3 meta tasks (handler flushes) not 0
            # tasks, so that's why there's a check against 3
            if (len(matched_tags) > 0 or len(play.tasks()) == 3):
                plays.append(play)

        # if the playbook is invoked with --tags or --skip-tags that don't
        # exist at all in the playbooks then we need to raise an error so that
        # the user can correct the arguments.
        unknown_tags = ((set(self.only_tags) | set(self.skip_tags)) -
                        (matched_tags_all | unmatched_tags_all))

        for t in RESERVED_TAGS:
            unknown_tags.discard(t)

        if len(unknown_tags) > 0:
            for t in RESERVED_TAGS:
                unmatched_tags_all.discard(t)
            msg = 'tag(s) not found in playbook: %s.  possible values: %s'
            unknown = ','.join(sorted(unknown_tags))
            unmatched = ','.join(sorted(unmatched_tags_all))
            raise errors.AnsibleError(msg % (unknown, unmatched))

        for play in plays:
            ansible.callbacks.set_play(self.callbacks, play)
            ansible.callbacks.set_play(self.runner_callbacks, play)
            if not self._run_play(play):
                break

        ansible.callbacks.set_play(self.callbacks, None)
        ansible.callbacks.set_play(self.runner_callbacks, None)

        # summarize the results
        results = {}
        for host in self.stats.processed.keys():
            results[host] = self.stats.summarize(host)
        return results
class Gui(QtGui.QMainWindow,QtGui.QWidget):

	def __init__(self):
		super(Gui, self).__init__()
		self.initUI()
		self.line=0
		self.text=[]
		self.decode=""
		self.fname="output"
		self.rec=0

	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.spectro()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,30,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,160)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,160)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,160)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,160)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,160)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,160)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Voice Recorder')
		#self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.show()

	def showDialogOpen(self):
		self.statusBar().showMessage('Open a File')
		self.fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file','/home')
		if(self.fname!=""):
			del self.text[:]
			f = open(self.fname, 'r')
			for lines in f:
				self.text.append(lines)
			f.close
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
			self.line=0
		self.statusBar().showMessage('')

	def showNext(self):
		self.line+=1
		if(len(self.text)>self.line):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showBack(self):
		self.line-=1
		if(len(self.text)>=self.line and self.line>=0):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showAbout(self):
		self.popup1=About()
		self.popup1.exec_()

	def encodeUTF8(self):
		self.decode="utf-8"

	def encodeUTF16(self):
		self.decode="utf-16"

	def record(self):
		self.statusBar().showMessage('Recording')
		self.rec=1
		self.Record.setEnabled(False)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.vrThread.start()
		self.vr.record(self.fname, self.line)

	def stop(self):
		self.statusBar().showMessage('')
		if self.rec == 1:
			self.vr.stop()
			self.vrThread.exit()
			self.vrThread.wait()
			self.vrThread.quit()
		elif self.rec == 2:
			self.pl.stop()
			self.plThread.exit()
			self.plThread.wait()
			self.plThread.quit()
		self.Record.setEnabled(True)
		self.Open.setEnabled(True)
		self.Play.setEnabled(True)
		self.Next.setEnabled(True)
		self.Back.setEnabled(True)
		self.rec=0

	def play(self):
		self.statusBar().showMessage('Playing')
		self.rec=2
		self.Record.setEnabled(False)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.plThread.start()
		self.pl.play(self.fname, self.line, self)

	def spectro(self):
		self.centralwidget = QtGui.QWidget(self)
		self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
		self.qwtPlot = Qwt.QwtPlot(self.centralwidget)
		self.verticalLayout.addWidget(self.qwtPlot)
		self.centralwidget.setGeometry(10,200,825,330)

		self.c=Qwt.QwtPlotCurve()  
		self.c.attach(self.qwtPlot)

		self.qwtPlot.setAxisScale(self.qwtPlot.yLeft, 0, 32000)

		self.timer = QTimer()
		self.timer.start(1.0)

		self.connect(self.timer, SIGNAL('timeout()'), self.plotSomething) 

		self.SR=SwhRecorder()
		self.SR.setup()
		self.SR.continuousStart()

	def plotSomething(self):
		if self.SR.newAudio==False: 
			return
		xs,ys=self.SR.fft()
		self.c.setData(xs,ys)
		self.qwtPlot.replot()
		self.SR.newAudio=False

	def closeEvent(self, event):
		self.SR.close()
		QtGui.qApp.quit()
Beispiel #48
0
    if MPI.COMM_WORLD.Get_rank() == 0:

        with SummaryWriter("logs") as writer:
            for i, success_rate in enumerate(t_success_rate):
                writer.add_scalar("Success_rate", success_rate, i)

        plt.style.use('ggplot')
        plt.figure()
        # plt.subplot(311)
        # plt.grid()
        plt.plot(np.arange(0, MAX_EPOCHS), t_success_rate)
        plt.title("Success rate")

        # plt.subplot(312)
        # plt.plot(np.arange(0, MAX_EPOCHS), total_ac_loss)
        # plt.title("Actor loss")
        #
        # plt.subplot(313)
        # plt.plot(np.arange(0, MAX_EPOCHS), total_cr_loss)
        # plt.title("Critic loss")

        plt.savefig("success_rate.png")
        plt.show()

elif Play_FLAG:
    player = Play(env, agent, max_episode=100)
    player.evaluate()

env.close()
Beispiel #49
0
from menu import Menu
from play import Play
from dificuldade import Dificuldade
from PPlay.window import Window
import globais

janela = Window(globais.WIDTH, globais.HEIGHT)
janela.set_title("Space Invadors")
janela.set_background_color((0, 0, 0))

menu = Menu(janela)
play = Play(janela)
dificuldade = Dificuldade(janela)

while globais.JOGO_RODANDO:
    janela.set_background_color((0, 0, 0))

    if (globais.PAGINA_ATUAL == 0):
        menu.setMenu()
    elif (globais.PAGINA_ATUAL == 1):
        play.setPlay()
    elif (globais.PAGINA_ATUAL == 2):
        dificuldade.setDificuldade()

    janela.update()