コード例 #1
0
ファイル: flame.py プロジェクト: peterasujan/flame
def run(fires_toa, fires_fli, trial_directory):
    pygame.init()
    pygame.display.set_caption("Flame: Fire Simulator")

    fire = Fire(fires_toa, fires_fli)
    planner = HotspotPlanner(fire, trial_directory)

    entities = [
        fire,
        Vehicle(planner)
    ]

    screen = pygame.display.set_mode(fire.shape(), pygame.HWSURFACE | pygame.DOUBLEBUF)
    clock = pygame.time.Clock()
    print planner.is_done()

    # This makes sure the simulation begins at the start of the fire
    simulation_time = np.asarray(fire.time_of_arrival)
    simulation_time = np.sort(simulation_time[simulation_time >= 0])[0]
    MAX_SIM_TIME = config.MAX_SIM_TIME + simulation_time

    while simulation_time < MAX_SIM_TIME and planner.is_done() is False:
        # clock.tick(100)

        for entity in entities:
            entity.update(simulation_time)
            entity.draw(screen)

        # Draw frontier on alpha surface and blit it to the screen
        frontier_surf = pygame.Surface(fire.shape(), pygame.SRCALPHA)
        frontier = np.asarray(fire.frontier)
        for (x, y) in frontier.T:
            frontier_surf.set_at((x, y), (0, 255, 0, 20))
        screen.blit(frontier_surf, (0, 0))

        # Draw clusters on alpha surface and blit it to the screen
        cluster_surf = pygame.Surface(fire.shape(), pygame.SRCALPHA)
        clusters = fire.clusters.astype(np.uint)
        if clusters.any():
            for (x, y) in clusters:
                pygame.draw.circle(cluster_surf, (255, 0, 0, 128), (x, y), 6)
        screen.blit(cluster_surf, (0, 0))
        if len(vehicle.vis_plan) >0:
            vis_plan_surf = pygame.Surface(fire.shape(), pygame.SRCALPHA)
            vis_plan = np.array(vehicle.vis_plan)

            cur_x, cur_y = entities[1].location[0], entities[1].location[1]
            for (dx, dy) in vis_plan:
                cur_x += dx
                cur_y += dy

                vis_plan_surf.set_at((int(cur_x), int(cur_y)), (255, 0, 0, 255))
            screen.blit(vis_plan_surf, (0, 0))

        simulation_time += config.TIME_STEP

        pygame.display.flip()
コード例 #2
0
ファイル: avata.py プロジェクト: pugpe/auto_da_compadecida
 def __init__(self):
     self.background = Background()
     self.shot = Fire()
     self.senary = Senary()
     self.trilha = pygame.mixer.Sound(os.path.join("sound","trilha.wav"))
     self.tiro = pygame.mixer.Sound(os.path.join("sound",'tiro.wav'))
     self.porrada = pygame.mixer.Sound(os.path.join("sound",'porrada.wav'))
     self.morreu = pygame.mixer.Sound(os.path.join("sound",'morreu.wav'))
     self.trilha.play(-1)
     self.img = pygame.Surface((80,120))
     self.img = pygame.image.load(os.path.join("img",'joao1.png'))
     self.imgS = pygame.image.load(os.path.join("img",'joao2.png'))
     self.imgC = pygame.image.load(os.path.join("img",'joao1c.png'))
     self.imgSC = pygame.image.load(os.path.join("img",'joao2c.png'))
     self.img.set_colorkey((10,255,0),0)
     self.img.set_alpha(255,0)
     self.img2 = pygame.Surface((80,120))
     self.img2.set_colorkey((10,255,0),0)
     self.img2.set_alpha(255,0)
     self.pos = pygame.Rect((120,320,80,120))
     self.jump = 0
     self.jump_h = 11
     self.life = 5
     self.face = 1
     self.x = 0
     self.contx = 0
     self.step = 1
     self.score = 0
     self.moveActivedJump = 1 
     draw(self.img,(self.pos.left,self.pos.top))
     self.background.sky()
     self.drawLife()
コード例 #3
0
    def start(self):
        self.fire = Fire(self.app.ipcon)

        self.update_frame_rate()
        self.update_hue()
        self.update_start()
        self.update_end()

        self.fire.frame_rendered(0)
コード例 #4
0
def main():
    currentLevel = 1

    while currentLevel < 9:

        timer = pygame.time.Clock()
        screen = pygame.display.set_mode(DISPLAY, FLAGS,
                                         DEPTH)  # Set the screen information
        screen_rect = screen.get_rect()
        pygame.mouse.set_visible(False)
        cutScreenImage = pygame.transform.scale(
            pygame.image.load("images/cutScreens/" + str(currentLevel) +
                              ".png"), (WIN_WIDTH, WIN_HEIGHT))

        screen.blit(cutScreenImage, (0, 0))
        pygame.display.update()
        pygame.time.delay(3000)

        # Load Level class and store info
        level = Level(currentLevel)
        level.setLevelObs(currentLevel)
        song = level.getSong()
        background = level.getBackground()
        boss = level.getBoss()
        enemies = level.getEnemies()
        powerUps = level.getPowerUps()

        # Create Player
        player = Player()
        if currentLevel == 4:
            player.setSpeed(4)
        # Load music
        song.play()
        print "song Starteddd"

        # Load Level Objects with platforms
        """KEY FOR LEVELS
        P = Platform
        C = player starting position
        F = Fire
        E = Enemy
        B = Boss
        U = Power Up
        """
        platforms = []

        entities = pygame.sprite.Group()
        powerUpSprites = pygame.sprite.Group()
        fires = pygame.sprite.Group()
        enemySprites = pygame.sprite.Group()
        bossSprite = pygame.sprite.Group()
        bulletSprites = pygame.sprite.Group()

        x = 0
        y = 0

        level = open('levels/level' + str(currentLevel) + '.txt', 'r')

        powerCounter = 0
        enemyCounter = 0

        for row in level:
            for col in row:
                if col == "P":
                    p = Platform(x, y)  # Place a platform at the given x,y
                    platforms.insert(0, p)  # Insert it into the platforms list
                    entities.add(p)  # Add to entities so it appears on screen
                if col == "C":
                    player.setXpos(x)
                    player.setYpos(
                        y
                    )  # Set the player along with the x,y of the starting position
                    player.createRect()
                    entities.add(player)
                if col == "F":
                    fire = Fire(x, y)  # Load a fire at the x,y found
                    entities.add(fire)  # Add the fire to the entities
                    fires.add(
                        fire
                    )  # Add the fire to the spike sprite group for collison purposes
                if col == "U":
                    pUp = powerUps[
                        powerCounter]  # Load a power up image at the given x,y
                    pUp.setXpos(x)
                    pUp.setYpos(y)
                    pUp.createRect()
                    entities.add(pUp)  # Power up to the entities
                    powerUpSprites.add(
                        pUp)  # add power up to the powerUps sprite group
                    powerCounter += 1
                if col == "E":
                    enemy = enemies[
                        enemyCounter]  # Load an enemy image at the given x,y
                    enemy.setXpos(x)
                    enemy.setYpos(y)
                    enemy.createRect()
                    entities.add(enemy)  # Add the enemy to the entities
                    enemySprites.add(
                        enemy)  # add enemy to the enemies sprite group
                    enemyCounter += 1
                if col == "B":
                    boss.setXpos(x)  # Load a boss image at the given x,y
                    boss.setYpos(y)
                    boss.createRect()
                    entities.add(boss)  # Add the boss to the entities
                    bossSprite.add(boss)  # add boss to the boss sprite group

                x += 32
            y += 32
            x = 0

        # Load Background for level
        background_rect = background.get_rect()

        total_level_width = len('level'[0]) * 32
        total_level_height = len('level') * 32
        camera = Camera(complex_camera, total_level_width, total_level_height)

        bossDead = False
        nextLevel = True
        playerAlive = True

        #animation needs
        FPS = 60
        cycletime = 0
        newnr = 0
        oldnr = -1
        picnr = 0
        interval = .075

        #interaction needs
        buttonPressed = False
        upPressed = False
        rightPressed = False
        leftPressed = False
        spacePressed = False
        direction = True  #True means right

        while bossDead == False and playerAlive == True:
            pygame.display.set_caption("Seven Deadly | " + " | FPS: " +
                                       str(int(timer.get_fps())))
            asize = ((screen_rect.w // background_rect.w + 1) *
                     background_rect.w,
                     (screen_rect.h // background_rect.h + 1) *
                     background_rect.h)
            bg = pygame.Surface(asize)

            # Create the background
            for x in range(0, asize[0], background_rect.w):
                for y in range(0, asize[1], background_rect.h):
                    screen.blit(background, (x, y))

            # Load controls
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    raise SystemExit()
                if event.type == pygame.KEYDOWN:
                    buttonPressed = True
                    if event.key == K_RIGHT:
                        rightPressed = True
                        direction = True
                        if event.key == K_UP:
                            upPressed = True
                    if event.key == K_LEFT:
                        leftPressed = True
                        direction = False
                        if event.key == K_UP:
                            upPressed = True
                    if event.key == K_UP:
                        upPressed = True
                    if event.key == K_SPACE:
                        spacePressed = True
                        bullet = player.attackLaunch()
                        bulletSprites.add(bullet)
                        entities.add(bullet)

                elif event.type == pygame.KEYUP:
                    if event.key == K_RIGHT:
                        rightPressed = False
                    if event.key == K_LEFT:
                        leftPressed = False
                    if event.key == K_UP:
                        upPressed = False
                    if rightPressed and leftPressed and upPressed and spacePressed == False:
                        buttonPressed = False

            for joe in bulletSprites:
                joe.update(screen, bg)
                hitSprites = pygame.sprite.spritecollide(
                    joe, entities, False, pygame.sprite.collide_mask)
                for sprite in hitSprites:
                    for plats in platforms:
                        if sprite == plats:
                            entities.remove(joe)
                            bulletSprites.remove(joe)
                    for enemy in enemySprites:
                        if sprite == enemy:
                            bullet.attackHit(enemy)
                            entities.remove(joe)
                            bulletSprites.remove(joe)
                            if enemy.getHealth() <= 0:
                                entities.remove(enemy)
                    for boss in bossSprite:
                        if sprite == boss:
                            bullet.attackHit(boss)
                            entities.remove(joe)
                            bulletSprites.remove(joe)
                            if boss.getHealth() <= 0:
                                entities.remove(boss)
                                bossDead = True

            #Animate
            if buttonPressed:
                milliseconds = timer.tick(FPS)
                seconds = milliseconds / 1000.0
                cycletime += seconds
                if cycletime > interval:
                    cycletime = 0
                    newnr += 1

                if upPressed:
                    picnr = newnr % len(player.jonJump)

                if rightPressed:
                    picnr = newnr % len(player.jonWalkRight)
                    if upPressed:
                        picnr = newnr % len(player.jonJump)

                if leftPressed:
                    picnr = newnr % len(player.jonWalkLeft)
                    if upPressed:
                        picnr = newnr % len(player.jonJump)

                oldnr = newnr

            # Play the level
            for power in powerUpSprites:
                if pygame.sprite.spritecollide(player, powerUpSprites, True,
                                               pygame.sprite.collide_mask):
                    power.collected(player)
                    print player.getHealth()

            # Enemy attacking
            for enemy in enemySprites:
                if player.getDist(enemy) < 100:
                    enemy.attackLaunch(player)

            hitSprite = pygame.sprite.spritecollide(player, enemySprites,
                                                    False,
                                                    pygame.sprite.collide_mask)
            for sprite in hitSprite:
                enemy.attackHit(player)

            # Boss attacking
            for boss in bossSprite:
                x = 5

            # Player range limits?
            # Update healths?

            # Player collision with fire; if true, 50 damage the player
            if pygame.sprite.spritecollide(player, fires, False,
                                           pygame.sprite.collide_mask):
                player.setHealth(player.getHealth() - 50)

            if player.getHealth() <= 0:
                nextLevel = False
                playerAlive = False

            camera.update(player)

            # Update the player and everything else
            player.update(upPressed, leftPressed, rightPressed, platforms,
                          screen, bg, direction, picnr)

            for e in entities:
                screen.blit(e.image, camera.apply(e))

            pygame.display.update()  # Update the display

        if nextLevel == True:
            currentLevel += 1

        else:
            currentLevel = currentLevel

        pygame.display.update()

        song.stop()
    print "You Win"
    quit()
コード例 #5
0
def main():
    Fire(gen_worksheet)
コード例 #6
0
 def fire(self, class_name):
     """
     fire is a function that will turn any Python class into a command line interface
     """
     from fire import Fire
     Fire(class_name)
コード例 #7
0
    Args:
        username (str): user name
        data_dir (str): directory to save data of all users

    Examples:
        >>> ./tool.py add --username=main
    """

    def __init__(self, username="******", data_dir="data"):
        kaipred = KAIPred(data_dir=data_dir)
        # Set password with dialog or clipboard
        password = ""
        kaipred.login(username=username, password=password)
        self.user = kaipred.login_user

    def add(self):
        """
        Add records of the user to the database.
        """
        print(self.user.filepath("a.txt"))

    def show(self):
        """
        Show records of the user.
        """
        NotImplementedError


if __name__ == "__main__":
    Fire(KAIPredTool)
コード例 #8
0
def cli():
    Fire(split_corpus)
コード例 #9
0
ファイル: train_siamrpn.py プロジェクト: selonsy/siamfpn
import os
import sys
import setproctitle

from fire import Fire

sys.path.append(os.getcwd())
from net.train import train
from IPython import embed

if __name__ == '__main__':
    program_name = 'sjl train ' + os.getcwd().split('/')[-1]
    setproctitle.setproctitle(program_name)
    Fire(train)
コード例 #10
0
                    batch_size=batch_size,
                    transform=preprocess,
                    train=True,
                    size=shape,
                    aug=augment,
                    file_list='data/train.csv')

    val = Dataset(n_fold=n_fold,
                  batch_size=batch_size,
                  transform=preprocess,
                  train=False,
                  size=shape,
                  aug=augment,
                  file_list='data/train.csv')

    model.fit_generator(
        train,
        epochs=100,
        steps_per_epoch=steps,
        validation_data=val,
        workers=8,
        validation_steps=steps // 10,
        use_multiprocessing=False,
        callbacks=get_callbacks(n_fold),
        max_queue_size=50,
    )


if __name__ == '__main__':
    Fire(fit_model)
コード例 #11
0
ファイル: main.py プロジェクト: Rhcsky/MetaLearning-pytorch
# running all process. download data, data set, data loader, train, validation, test
def run():
    download_data()

    # Make options
    config = get_config()

    # Make Trainer
    trainer = Trainer(config)

    # train
    train(config, trainer)

    # test
    test(config, trainer)


def download_data():
    print("Download omniglot dataset...", end="")
    download_omniglot_data()

    print("Prepare dataset...", end="")
    prepare_data()

    print("DONE")


if __name__ == '__main__':
    Fire({"run": run, "download-data": download_data, "train": train, "test": test})
コード例 #12
0
        model = cls(hparams)
        model.load_state_dict(checkpoint["state_dict"])

        # give model a chance to load something
        model.on_load_checkpoint(checkpoint)

        return model


def main(hparams):
    if hparams.seed:
        set_determenistic(hparams.seed)

    pipeline = ImageNetLightningPipeline(hparams)

    trainer = object_from_dict(
        hparams.trainer,
        checkpoint_callback=object_from_dict(hparams.checkpoint),
        logger=object_from_dict(hparams.logger),
    )

    if hparams.evaluate:
        trainer.run_evaluation()
    else:
        trainer.fit(pipeline)


if __name__ == "__main__":
    cfg = Dict(Fire(fit))
    main(cfg)
コード例 #13
0
ファイル: __main__.py プロジェクト: TomFaulkner/codegen
        print(t.render(**config))
    else:
        render = t.render(**config)
        with open(f"{config['path']['output']}", 'w') as f:
            f.write(render)


def run_dir(dir_: str):
    for file in scan_dir(dir_):
        proc_file(file)


def run_file(file: str):
    proc_file(file)


def preview_file(file: str):
    proc_file(file, stdio=True)


if __name__ == "__main__":
    Fire({
        'dir': run_dir,
        'file': run_file,
        'preview_file': preview_file,
        'version': lambda: __version__
    })

    # black format option (or pipe to black for stdio)
    # lint option, and optionally fail on write if lint fails
コード例 #14
0
def extract(scp_file: str,
            output_ark: str,
            sr: int = None,
            win_length: int = 25,
            hop_length: int = 10,
            n_fft: int = 512):
    # Win length and hop_length are given in ms
    # scpfile is formatted as KEY VALUE where key is name and value is .wav filepath
    with open(scp_file, 'r') as rp, open(output_ark, 'wb') as wp:
        for line in tqdm(rp, total=get_num_lines(scp_file)):
            key, fpath = line.split()[:2]
            # Also supports 24 bit
            y, file_sr = sf.read(fpath, dtype='float32')
            # y, file_sr = librosa.load(fpath, sr=sr)
            # Adjust window length
            cur_win_length = file_sr * win_length // 1000
            cur_hop_length = file_sr * hop_length // 1000
            S = librosa.core.stft(y,
                                  n_fft=n_fft,
                                  win_length=cur_win_length,
                                  hop_length=cur_hop_length)
            S = np.log(np.abs(S)**2 + 1e-12)
            feature = S.transpose()
            #  components and acitivations
            kaldi_io.write_mat(wp, feature, key=key)


if __name__ == '__main__':
    Fire(extract)
コード例 #15
0
ファイル: flame.py プロジェクト: osurdml/flame
def run(fires_toa, fires_fli, trial_directory):
    #Start GPS Node

    gps_file = open('gps.csv', 'wb')
    a = csv.writer(gps_file)
    header = [['latitude', 'longitude']]
    a.writerows(header)

    global home_offset, home_offset_flag
    if config.USING_ROS:
        rospy.init_node('waypoint')
    #rospy.Subscriber('/mavros/mission/waypoints', WaypointList, handle_waypoints)
    pygame.init()
    pygame.display.set_caption("Flame: Fire Simulator")

    fire = Fire(fires_toa, fires_fli)
    planner = HotspotPlanner(fire, trial_directory)

    entities = [
        fire,
        Vehicle(planner)
    ]

    screen = pygame.display.set_mode(fire.shape(), pygame.HWSURFACE | pygame.DOUBLEBUF)
    clock = pygame.time.Clock()
    print planner.is_done()

    # This makes sure the simulation begins at the start of the fire
    simulation_time = np.asarray(fire.time_of_arrival)
    simulation_time = np.sort(simulation_time[simulation_time >= 0])[0]+3
    MAX_SIM_TIME = config.MAX_SIM_TIME + simulation_time

    #Waypoint set up
    old_time = 0.0
    time_difference = 0.0
    if config.USING_ROS:
        get_gps()
    #rospy.loginfo("Got home: %s", home_offset)
    test_scale_multiplier =10
    scaling_factor_x = .078534/364576.4709016314  *test_scale_multiplier  #(feet/pixel)/(feet/degree)
    scaling_factor_y = .078534/260659.33267246236 *test_scale_multiplier #(feet/pixel)/(feet/degree)

    map_offset_x = home_offset.y_long - config.STARTING_LOCATION[0]*scaling_factor_x
    map_offset_y = home_offset.x_lat + config.STARTING_LOCATION[1]*scaling_factor_y


    while simulation_time < MAX_SIM_TIME and planner.is_done() is False:
        # clock.tick(100)

        loop_start_time = time.time()

        for entity in entities:
            entity.update(simulation_time)
            entity.draw(screen)

        # Draw frontier on alpha surface and blit it to the screen
        frontier_surf = pygame.Surface(fire.shape(), pygame.SRCALPHA)
        frontier = np.asarray(fire.frontier)
        for (x, y) in frontier.T:
            frontier_surf.set_at((x, y), (0, 255, 0, 20))
        screen.blit(frontier_surf, (0, 0))

        # Draw clusters on alpha surface and blit it to the screen
        cluster_surf = pygame.Surface(fire.shape(), pygame.SRCALPHA)
        clusters = fire.clusters.astype(np.uint)
        if clusters.any():
            for (x, y) in clusters:
                pygame.draw.circle(cluster_surf, (255, 0, 0, 128), (x, y), 6)
        screen.blit(cluster_surf, (0, 0))
        if len(vehicle.vis_plan) >0:
            vis_plan_surf = pygame.Surface(fire.shape(), pygame.SRCALPHA)
            vis_plan = np.array(vehicle.vis_plan)

            cur_x, cur_y = entities[1].location[0], entities[1].location[1]
            for (dx, dy) in vis_plan:
                cur_x += dx
                cur_y += dy

                vis_plan_surf.set_at((int(cur_x), int(cur_y)), (255, 0, 0, 255))
            screen.blit(vis_plan_surf, (0, 0))

        time_since = time.time() - old_time
        print "time_since: ", time_since
        if (time_since > config.UPDATE_RATE) & config.USING_ROS:

            #conversion to GPS
            print "FIRE SHAPE:"
            print fire.shape()
            print "UAV LOCATION:"
            print entities[1].location
            long_cor = entities[1].location[0]*scaling_factor_x + map_offset_x
            lat_cor = -entities[1].location[1]*scaling_factor_y + map_offset_y 

            # b = open('gps.csv', 'ab')
            #a = csv.writer(b)
            #data = [[lat_cor, long_cor]]
            #a.writerows(data)
            #Send Waypoint
            #rospy.loginfo("waiting for MAVROS PUSH service")

            rospy.wait_for_service('/mavros/set_mode')
            mode = 220 #auto mode = 220. Guided_Mode = 216
            #mode = MAV_MODE(mode)
            mode_set = rospy.ServiceProxy('/mavros/set_mode', SetMode)
            resp = mode_set(0,'3')
            rospy.loginfo("SETTING TO AUTO: %s", resp)

            rospy.wait_for_service('/mavros/mission/push')
            waypoints = [home_offset, Waypoint(frame=Waypoint.FRAME_GLOBAL_REL_ALT,
                            command=Waypoint.NAV_WAYPOINT,
                            is_current=True,autocontinue=True,
                            x_lat=lat_cor, y_long=long_cor, z_alt=6)
                        ]
            #waypoint = Waypoint(frame=Waypoint.FRAME_GLOBAL_REL_ALT,
            #                command=Waypoint.NAV_WAYPOINT,
            #                is_current=True,
            #                x_lat=lat_cor, y_long= long_cor, z_alt=6)

            waypoint_goto = rospy.ServiceProxy('/mavros/mission/push', WaypointPush)
            resp = waypoint_goto(waypoints)
            #rospy.loginfo(resp)
            #rospy.loginfo("Sent Waypoints: %s", resp)
            old_time = time.time()


        #Advance one timestep
        simulation_time += config.TIME_STEP

        #Wait for the deadline
        loop_time = time.time() - loop_start_time
        while loop_time <= config.DEADLINE:
            loop_time = time.time() - loop_start_time
        pygame.display.flip()
コード例 #16
0
def main():
    """Run command line interface applications."""
    Fire(cli)
コード例 #17
0
ファイル: cli.py プロジェクト: Egnod/koroviev
def start_cli():
    Fire(CLI)
コード例 #18
0
ファイル: attack.py プロジェクト: cortwave/nips-adversarial
        fmodel, criterion=foolbox.criteria.Misclassification())
    adversarial = attack(img, label)

    if adversarial is not None:
        adversarial = postprocess(adversarial)
        return clip_epsilon(raw, adversarial, eps=eps)
    return raw


def main(input_dir, output_dir, max_epsilon):
    kmodel = load_model('./inception.h5')
    fmodel = foolbox.models.KerasModel(kmodel,
                                       bounds=(-1, 1),
                                       preprocessing=(0, 1))

    for i, fname in enumerate(glob(input_dir + '/*')):
        hacked = process_image(kmodel=kmodel,
                               fmodel=fmodel,
                               eps=max_epsilon,
                               img_path=fname)
        out_name = path.join(output_dir, fname.split('/')[-1])
        array_to_img(hacked).save(out_name)
        if not i % 100:
            logger.info('{} images processed'.format(i))

    logger.info('Done!')


if __name__ == '__main__':
    Fire(main)
コード例 #19
0
ファイル: flasher.py プロジェクト: XeTK/BMW-BMS46-Flasher

    buffer = bytearray()

    bar = Bar('Reading', max=chunks)
    # Get all full sized chunks.
    for chunk in range(chunks):
        address = chunk * CHUNK_SIZE
        command = get_chunk(address, CHUNK_SIZE)
        result = read(command, serial_port, flipped)
        buffer.extend(result)
        bar.next()

    bar.finish()

    # Get remainder.
    if remainder != 0:
        address = number_of_bytes - remainder
        command = get_chunk(address, remainder)
        result = read(command, flipped)
        buffer.extend(result)

    # Write to file.
    f = open(filename, 'w+b')
    f.write(buffer)
    f.close()

# Entry point.
if __name__ == '__main__':
    Fire(run)
コード例 #20
0
            random_text = rand_item["answer_text"]

            distractors, classification_items = get_distractors(
                item["linearized_amr"],
                item["answer_text"],
                swapping_candidates,
                cutting_candidates,
                random_text,
                num_candidates=num_candidates,
                max_per_operation=max_per_operation,
            )
            classification_data.extend(classification_items)

            item["answer_text"] = distractors + [item["answer_text"]]

        json.dump(items,
                  open(out_folder / (splits[split] + ".json"), "w"),
                  indent=2)
        write_classification_data(classification_data, classification_dir,
                                  splits[split].replace(".json", ""))

    generate_from_json(out_folder,
                       out_folder / "special_tokens.txt",
                       fields={"linearized_amr": "amr"})
    fix_text_in_dir(out_folder)


if __name__ == "__main__":
    Fire(preprocess)
コード例 #21
0

class CommandLine:

    def __init__(self) -> None:

        # Blog
        self.blog_content = NogiBlogContent(engine, metadata, role='writer')
        self.blog_summary = NogiBlogSummary(engine, metadata, role='writer')
        self.blog_member = NogiMembers(engine, metadata)

        # GCS
        self.gcs = GCS()

    def crawl(self, bucket: str = 'nogi-test'):
        _members = self.blog_member.get_current_members()
        shuffle(_members)
        for member in tqdm(_members):
            Updater(member=member, blog_db=self.blog_summary).run()
            PostExecutor(
                member=member,
                summary_db=self.blog_summary,
                content_db=self.blog_content,
                gcs_client=self.gcs,
                bucket=bucket
            ).run()


if __name__ == "__main__":
    Fire(CommandLine)
コード例 #22
0
        },  # , 'onsite-paramters': prm.params},
        attrs={
            key: data[key]
            for key in data.keys() if key not in ['gf_iw', 'self_iw', 'occ']
        })

    layer_data.attrs[Dim.it] = _get_iter(infile)

    logging.debug("Safe new 'h5' file.")
    save_dataset(layer_data,
                 dir_=infile.parent,
                 name=infile.stem,
                 use_date=False)

    logging.debug("Move old file %s to 'old.npz'.", infile.name)
    infile.rename(copy)
    logging.info("Converted %s to 'h5' file %s", infile.name,
                 infile.stem + '.h5')


if __name__ == '__main__':
    try:
        from fire import Fire
    except ImportError:
        logging.info(
            "'Fire' found, fall back to basic 'sys' argument handling.")
        import sys
        npz2h5(sys.argv[1])
    else:
        Fire(npz2h5)
コード例 #23
0
handler.setFormatter(
    colorlog.ColoredFormatter(
        '%(log_color)s[%(asctime)s - %(levelname)s]:%(message)s'))
logger = colorlog.getLogger('Crawler-Startup')
logger.addHandler(handler)
logger.setLevel(logging.INFO)


class CrawlerGo:
    def start(self, period='10D', spider='ghevent', loglevel="INFO"):
        '''

        :param period: crawling period for events
        :param spider: spider name
        :param loglevel: INFO , DEBUG ...
        :return:
        '''
        settings = Settings()
        settings_module_path = 'gharchive.settings'
        settings.setmodule(settings_module_path, priority='project')
        settings = get_project_settings()
        settings.set("LOG_LEVEL", loglevel)
        settings.set("GHARCHIVEPERIOD", period)
        process = CrawlerProcess(settings)
        process.crawl(spider)
        process.start()


if __name__ == '__main__':
    Fire(CrawlerGo)
コード例 #24
0
    stage0 += comment('Installing vglrun and TurboVNC')
    stage0 += packages(apt=[
        'ubuntu-desktop', 'vim', 'mesa-utils', 'python3-pip', 'python3-pyqt5',
        'pyqt5-dev', 'python3-tk'
    ])
    stage0 += shell(commands=[
        'wget https://swift.rc.nectar.org.au/v1/AUTH_810/CVL-Singularity-External-Files/turbovnc_2.2.5_amd64.deb && dpkg -i turbovnc_2.2.5_amd64.deb && rm turbovnc_2.2.5_amd64.deb',
        'wget https://swift.rc.nectar.org.au/v1/AUTH_810/CVL-Singularity-External-Files/virtualgl_2.6.4_amd64.deb && dpkg -i virtualgl_2.6.4_amd64.deb && rm virtualgl_2.6.4_amd64.deb',
        'apt update', 'apt -y upgrade'
    ])
    stage0 += packages(apt=[
        "qt5-qmake", 'qtmultimedia5-dev', 'libqt5multimediawidgets5',
        'libqt5multimedia5-plugins', 'libqt5multimedia5', 'libglew-dev',
        'glew-utils', 'libqglviewer-dev-qt5', 'libnetcdf-dev',
        'libnetcdf-cxx-legacy-dev', 'freeglut3-dev', 'libassimp-dev'
    ])
    stage0 += shell(commands=[
        'mkdir -p /opt/', "cd /opt",
        'git clone --branch v-2.7linux https://github.com/nci/drishti.git',
        'cd drishti/drishti', 'qmake -qt=5',
        'export LDFLAGS="$LDFLAGS -L/usr/lib/x86_64-linux-gnu/ -lassimp"',
        'ln -s /usr/lib/x86_64-linux-gnu/libQGLViewer-qt5.so /usr/lib/x86_64-linux-gnu/libQGLViewer.so',
        'make'
    ])

    return stage0


if __name__ == '__main__':
    Fire(build)
コード例 #25
0
    # df.Value = df['Value'].str.extract("(\d*\.?\d+)").astype(float)
    df.Date = pd.to_datetime(df.Date)
    lb = LabelBinarizer()
    df = df.join(
        pd.DataFrame(lb.fit_transform(df['Category']),
                     columns=lb.classes_,
                     index=df.index))
    return df


# Export dataframe to excel file, using date as title
def xport_frame(df):
    timestr = time.strftime("%Y%m%d")
    excel = df.to_excel(f"output/{timestr}.xlsx")


# One function to rule them all.
def convert():
    frame = html_to_frames()
    df = frame_cleaner(frame)
    xport_frame(df)


#convert()

# Use Fire to make it a CLI
if __name__ == '__main__':
    Fire({
        'convert': convert,
    })
コード例 #26
0
        test_name=test_name,
        save_fig=True
    )

    et.plot_confusion_matrix(
        y_test_flat,
        y_pred_flat,
        classes=class_names,
        normalize=True,
        test_name=test_name,
        save_fig=True
    )

    # empty line
    print("")

    # before calculating metrics,
    # delete all pixel of 'inclassifiable' category
    mask_array = np.ma.masked_equal(y_test_flat, 8.)
    y_pred_flat = y_pred_flat[~mask_array.mask]
    y_test_flat = y_test_flat[~mask_array.mask]

    # get metrics
    et.print_metrics(y_test_flat, y_pred_flat, test_name)

    return None


if __name__ == '__main__':
    Fire(get_ensemble_metrics)
コード例 #27
0
ファイル: main.py プロジェクト: SpaceKingJo/project
def main():


    open_canvas()
    global mainback
    mainback = Mainback()
    global start
    start = False

    while(start == False):
        handle_events()
        clear_canvas()
        mainback.draw()
        update_canvas()
        delay(0.08)

    #클래스 선언
    global hero
    hero = Hero()
    rabbit = Rabbit()
    rabbit_group = [Rabbit() for i in range(600)]
    land = Land()
    wood = Wood()
    global torch
    torch = Torch()
    global fire
    fire = Fire()
    eskimo = Eskimo()
    attack_fire = Attack_fire()
    attack_fire_group = [Attack_fire() for i in range(100)]
    background = BackGround()
    global ui
    ui = Ui()
    firewood = Firewood()
    firewood_group = [Firewood() for i in range(600)]

    #변수 선언
    rabbit_group_counter = 0
    rabbit_group_collision_counter = 0
    attack_group_counter = 0
    attack_group_update_counter = 0
    attack_group_collision_counter = 0
    rabbit_alive_counter = 0
    attack_group_alive_check = False
    attack_group_alive_counter = 0
    attack_group_limit = 20
    rabbit_group_draw_counter = 0
    firewood_num_counter = 0
    firewood_num_update_counter = 0
    firewood_collide_counter = 0
    rabbit_group_counter2 = 0
    rabbit_jump = False
    rabbit_num = 10
    firewood_num = 10
    rack_block = 0
    eskimo_counter = 0


    global running
    running = True



    while running:
        #핸들 이벤트
        handle_events()

        #업데이트
        hero.update()
        background.update()
        land.update()
        wood.update()
        fire.update()
        torch.update()
        eskimo.update()
        ui.update(hero.x, hero.y, hero.ability)
        for rabbit in rabbit_group: # 토끼 업데이트
            if(rabbit_group_counter == rabbit_num):
                rabbit_group_counter = 0
                break
            if(rabbit.alive):
                rabbit.update()
            rabbit_group_counter += 1

        # for rabbit in rabbit_group: # 토끼 업데이트
        #     if(rabbit_group_counter2 == 1):
        #         print("%d" % rabbit.x)
        #         break
        #     rabbit_group_counter2 += 1

        for attack_fire in attack_fire_group: # 공격불 업데이트
            if(attack_group_update_counter == hero.attack_num):
                attack_fire.init_direction()
                attack_fire.alive = True # 공격불이 활성화 됨
                attack_fire.init_fire()
                attack_group_update_counter = 0
                break
            if(attack_fire.alive):
                attack_fire.update()
            attack_group_update_counter += 1

        for firewood in firewood_group: # 장작 업데이트
            if(firewood_num_update_counter == firewood_num):
                firewood_num_update_counter = 0
                break
            firewood.update()
            firewood_num_update_counter += 1

        #함수
        for rabbit in rabbit_group: #토끼와 히어로의 충돌체크
            if(rabbit_group_collision_counter == rabbit_num):
                rabbit_group_collision_counter = 0
                break
            if(collision(rabbit, hero)):
                rabbit.y += 50
                mainback.hero_die = True
                mainback.die_sound()
                running = False
            rabbit_group_collision_counter += 1

        for rabbit in rabbit_group: # 토끼와 공격불의 충돌체크
            if(rack_block == rabbit_num):
                rack_block = 0
                break
            for attack_fire in attack_fire_group:
                if(attack_group_collision_counter == hero.attack_num):
                    attack_group_collision_counter = 0
                    break
                if(collision(rabbit, attack_fire) and rabbit.alive and attack_fire.alive):
                    attack_fire.alive = False
                    rabbit.alive = False
                    rabbit.die = True
                    hero.kill += 1
                attack_fire.die = False
                attack_group_collision_counter += 1
            rack_block += 1

        for attack_fire in attack_fire_group:
            if(eskimo_counter == hero.attack_num):
                eskimo_counter = 0
                break
            if(collision(eskimo, attack_fire)):
                 attack_fire.alive = False
                 eskimo.x -= 10
                 eskimo.hp -= 1
                 if(eskimo.hp == 0):
                    mainback.eskimo_die = True
                    running = False
                    mainback.win_sound()
            attack_fire.die = False
            eskimo_counter += 1
        if(collision(wood, hero)): # 나무와 주인공 충돌체크
            fire.collide = True
            if(ui.firewood_num != 0):
                fire.life += ui.firewood_num*250
                ui.firewood_num = 0
        else:
            fire.collide = False


        if(collision(eskimo, hero)): # 주인공과 에스키모 충돌체크
            mainback.hero_die = True
            running = False
            mainback.die_sound()

        for firewood in firewood_group: # 장작과 주인공 충돌체크
            if(firewood_collide_counter == firewood_num):
                firewood_collide_counter = 0
                break
            if(collision(firewood, hero) and firewood.die == False):
                ui.firewood_num += 1
                firewood.die = True
            firewood_collide_counter += 1

        for rabbit in rabbit_group: # 토끼 출현!
            if(rabbit_alive_counter == rabbit_num):
                break
            if(rabbit.die == False):
                rabbit.alive = True
                rabbit_alive_counter += 1

        if(fire.die): # 불이 꺼지면 토끼들이 마구마구 몰려온다.
            rabbit_num = 500

        for attack_fire in attack_fire_group: # 불 스킬 존재 유무
            if(attack_fire.alive):
                attack_group_alive_counter = 0
                break
            attack_group_alive_counter += 1
            if(attack_group_alive_counter == hero.attack_num):
                hero.attack_num = 0


        for attack_fire in attack_fire_group: # 화면 밖을 벗어나면 불 스킬 사망 판정
            if(attack_fire.x >= 900 or attack_fire.x <= -100):
                attack_fire.alive = False
        print("stage = %d" % background.stage)
        #스테이지
        if(hero.kill == 10 and background.stage == 1):
            print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
            rabbit_num += 20
            hero.ability += 10
            firewood_num += 5
            background.stage = 2
        if(hero.kill == 30 and background.stage == 2):
            rabbit_num += 30
            firewood_num += 10
            hero.ability += 10
            background.stage = 3
            background.stage3_music()
        if(hero.kill == 60 and background.stage == 3):
            rabbit_num += 40
            firewood_num += 15
            hero.ability += 10
            background.stage = 4
        if(hero.kill == 80 and background.stage == 4):
            rabbit_num += 50
            firewood_num += 20
            hero.ability += 10
            background.stage = 5
            eskimo.alive = True
            background.stage5_music()
        if(background.stage == 5):
            rabbit_jump = True

        if(rabbit_jump):
             for rabbit in rabbit_group:
                 rabbit.y += 5

        # print("%d" % hero.attack_num)
        print("킬 수 : %d num : %d" % (hero.kill, rabbit_num))
        clear_canvas()


        #그리기
        background.draw()
        fire.draw()
        wood.draw()
        torch.draw()
        hero.draw()
        eskimo.draw()
        # eskimo.draw_bb()
        # hero.draw_bb()
        for rabbit in rabbit_group: # 적토끼 출력
            if(rabbit_group_draw_counter == rabbit_num):
                rabbit_group_draw_counter = 0
                break
            if(rabbit.alive):
                rabbit.draw()
            rabbit_group_draw_counter += 1
            # rabbit.draw_bb()
        for attack_fire in attack_fire_group: # 공격 불 출력
            if(attack_group_counter == hero.attack_num):
                attack_group_counter = 0
                break
            if(attack_fire.alive):
                attack_fire.draw()
            # attack_fire.draw_bb()
            attack_group_counter += 1
        for firewood in firewood_group: # 장작 출력
            if(firewood_num_counter == firewood_num):
                firewood_num_counter = 0
                break
            firewood.draw()
            firewood_num_counter += 1
        land.draw()
        ui.draw()



        update_canvas()

        delay(0.06)

    while(mainback.hero_die or mainback.eskimo_die):
        handle_events()
        clear_canvas()
        mainback.draw()
        update_canvas()
        delay(0.08)



    close_canvas()
コード例 #28
0
pdf_dateien = (i for i in punkt.iterdir()
               if i.name.lower().endswith('.pdf') and i.is_file() and (
                   not schon_fertig.search(
                       run(['pdfinfo', (punkt / i).as_posix()],
                           cwd=punkt,
                           text=True,
                           capture_output=True).stdout)))


def alle_neuen_konvertieren(suffix_dateien: Path, konv: Callable, ocr=True):
    kopien = mkdtemp(prefix='tmp_kopien_zumLoeschen', dir=punkt)
    for i in suffix_dateien:
        copy2(i, kopien)
        konv(i, ocr)
    try:
        rmdir(kopien)
    except OSError:
        pass


# @snoop(prefix='ß__ ')
def pdf_nur_neu_hinzugekommene():
    umbenennen()
    alle_neuen_konvertieren(pdf_dateien, konvertierung)


if __name__ == "__main__":
    from fire import Fire

    Fire()
コード例 #29
0
ファイル: copy.py プロジェクト: byu-dml/d3m-analytics
        # We'll write the data to the lab db in batches.
        write_buffer = MongoWriteBuffer(aml_collection, batch_size)

        # Iterate over this index in batches, only querying the subset of fields we care about.
        for id_chunk in chunk(ids_of_docs_to_copy,
                              batch_size,
                              show_progress=True):
            hits = (d3m_db.search(index=index_name).query(
                "ids", values=list(id_chunk)).source(
                    elasticsearch_fields[index]).params(
                        size=batch_size,
                        request_timeout=request_timeout).execute())

            for hit in hits:
                doc = hit.to_dict()
                # Mongodb will use the same primary key elastic search does.
                doc["_id"] = hit.meta.id
                write_buffer.queue(
                    # Insert the doc, or if another document already exists with the same _id,
                    # then replace it.
                    ReplaceOne(filter={"_id": doc["_id"]},
                               replacement=doc,
                               upsert=True))

        # Write and flush any leftovers.
        write_buffer.flush()


if __name__ == "__main__":
    Fire(copy_indexes)
コード例 #30
0
        return aligner.Aligner.load_from_checkpoint(filepath)

    def single(self, ckpt, dumpdir):
        ckpt = glob(ckpt, recursive=True)
        assert len(ckpt) == 1, ckpt
        aligner = self.load_checkpoint(ckpt[0])
        os.makedirs(dumpdir, exist_ok=True)
        aligner.model.save_pretrained(dumpdir)
        aligner.tokenizer.save_pretrained(dumpdir)

    def linear(
        self,
        root_dir="/bigdata",
        data="opus",
        model="bert-base-multilingual-cased",
        name="linear-orth0.01",
    ):
        langs = "ar de es fr hi ru vi zh".split()
        _dir = f"{root_dir}/checkpoints/alignment/{data}"
        mapping = nn.ModuleDict()
        for lang in tqdm(langs):
            ckpt = f"{_dir}/en-{lang}-subset1/{model}-sim_linear/{name}/version_0/mapping.pth"
            mapping[lang] = torch.load(ckpt)
        os.makedirs(f"mapping/{name}", exist_ok=True)
        torch.save(mapping, f"mapping/{name}/{model}.pth")


if __name__ == "__main__":
    Fire(Main)
コード例 #31
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from fire import Fire
from syncshell.cli import Application

if __name__ == "__main__":
    Fire(Application)
コード例 #32
0
        self.screens_dir = screens_dir
        if not screens_dir:
            self.screens_dir = path.abspath(path.join(path.dirname(__file__), pardir, 'public', 'screens'))
        self.used_dir = path.abspath(path.join(self.screens_dir, 'used'))
        self.project_dir = path.abspath(path.join(path.dirname(__file__), '..'))
        if environ.get('USED_SCREENS_FILE'):
            self.default_file = path.abspath(path.join(self.project_dir, environ.get('USED_SCREENS_FILE')))

    def make_screens_list(self, screens_file=None):
        with open(screens_file if screens_file else self.default_file, 'a') as used:
            for f in listdir(self.used_dir):
                if path.isfile(path.join(self.used_dir, f)):
                    used.write(f + '\n')

    def update_screens_dir(self, used_screens_file=None, screens_dir=None):
        with open(used_screens_file if used_screens_file else self.default_file) as used_screens:
            lines = [l.strip() for l in used_screens.readlines()]
            for image_name in lines:
                image_dir = path.join(self.screens_dir, image_name)
                if path.isfile(image_dir):
                    new_image_dir = path.abspath(path.join(self.used_dir, image_dir.rsplit('/', 1)[-1]))
                    rename(image_dir, new_image_dir)

    def get_random_image(self):
        random_file = choice([f for f in listdir(self.screens_dir) if path.isfile(path.join(self.screens_dir, f))])
        return path.abspath(path.join(self.screens_dir, random_file))


if __name__ == '__main__':
    Fire(ScreensManager)
コード例 #33
0
ファイル: avata.py プロジェクト: pugpe/auto_da_compadecida
class Avata:
    def __init__(self):
        self.background = Background()
        self.shot = Fire()
        self.senary = Senary()
        self.trilha = pygame.mixer.Sound(os.path.join("sound","trilha.wav"))
        self.tiro = pygame.mixer.Sound(os.path.join("sound",'tiro.wav'))
        self.porrada = pygame.mixer.Sound(os.path.join("sound",'porrada.wav'))
        self.morreu = pygame.mixer.Sound(os.path.join("sound",'morreu.wav'))
        self.trilha.play(-1)
        self.img = pygame.Surface((80,120))
        self.img = pygame.image.load(os.path.join("img",'joao1.png'))
        self.imgS = pygame.image.load(os.path.join("img",'joao2.png'))
        self.imgC = pygame.image.load(os.path.join("img",'joao1c.png'))
        self.imgSC = pygame.image.load(os.path.join("img",'joao2c.png'))
        self.img.set_colorkey((10,255,0),0)
        self.img.set_alpha(255,0)
        self.img2 = pygame.Surface((80,120))
        self.img2.set_colorkey((10,255,0),0)
        self.img2.set_alpha(255,0)
        self.pos = pygame.Rect((120,320,80,120))
        self.jump = 0
        self.jump_h = 11
        self.life = 5
        self.face = 1
        self.x = 0
        self.contx = 0
        self.step = 1
        self.score = 0
        self.moveActivedJump = 1 
        draw(self.img,(self.pos.left,self.pos.top))
        self.background.sky()
        self.drawLife()
    def move(self,key):
        self.background.redraw()
        if key == 273 and (self.jump_h == 11 or not self.moveActivedJump):
            self.jump = 1
            if self.moveActivedJump:
                self.jump_h = 0
            else:
                self.jump_h = 4
        elif key == 275:
            self.moveActived = 1
            self.step *= -1
            for i in range(len(self.senary.stone)-1):
                if self.pos.collidepoint(self.senary.stone[i].left-10,self.senary.stone[i].top):
                    self.moveActived = 0
            if self.moveActived:
                if self.pos.left >= 200:
                    self.background.move(key)
                    self.senary.move(-1)
                else:
                    self.pos.move_ip(10,0)
                self.face = 1
        elif key == 276:
            self.moveActived = 1
            self.step *= -1
            for i in range(len(self.senary.stone)-1):
                if self.pos.collidepoint(self.senary.stone[i].right,self.senary.stone[i].top):
                    self.moveActived = 0
            if self.moveActived:
                if self.pos.left == 100:
                    self.background.move(key)
                    self.senary.move(1)
                else:
                    self.pos.move_ip(-10,0)
                self.face = 0
        if self.jump:
            self.pos.move_ip(0,-20)
        if self.jump_h < 10: self.jump_h +=1
        self.moveActivedJump = 1
        for i in range(len(self.senary.stone)-1):
            if self.pos.collidepoint(self.senary.stone[i].right,self.senary.stone[i].top-10) or self.pos.collidepoint(self.senary.stone[i].left,self.senary.stone[i].top-10):
                self.moveActivedJump = 0
        if self.jump_h == 10 and self.moveActivedJump:
            if self.pos.top < 320:
                self.pos.move_ip(0,20)
            else : self.jump_h += 1
            self.jump = 0
        if key == 32:
            self.tiro.play()
            self.shot.fire(self.pos.center,self.face,1)
        self.ia()
        if len(self.shot.dir):
            self.shot.move()
            i=-1
            while i != len(self.shot.dir)-1:
                i+=1
                for j in range(len(self.senary.stone)-1):
                    if self.shot.pos[i].colliderect(self.senary.stone[j]):
                        self.shot.dir.pop(i)
                        self.shot.pos.pop(i)
                        self.shot.origem.pop(i)
                        i-=1
                        break
            i=-1
            while i != len(self.shot.dir)-1:
                i+=1 
                for j in range(len(self.senary.inimigo)-1):
                    if self.shot.pos[i].colliderect(self.senary.inimigo[j]) and self.shot.origem[i]:
                        self.senary.inimigoLife[j] -=1
                        self.score += 50
                        if not self.senary.inimigoLife[j]:
                            self.senary.inimigo.pop(j)
                            self.senary.inimigoLife.pop(j)
                            self.senary.inimigoDir.pop(j)
                            self.senary.inimigoStep.pop(j)
                            self.score += 300
                        self.shot.dir.pop(i)
                        self.shot.pos.pop(i)
                        self.shot.origem.pop(i)
                        self.background.score = self.background.font.render(str(self.score),1,(0,0,0))
                        i-=1
                        break
            i=-1
            while i != len(self.shot.dir)-1:
                i+=1
                if self.shot.pos[i].colliderect(self.pos):
                    self.shot.dir.pop(i)
                    self.shot.pos.pop(i)
                    self.shot.origem.pop(i)
                    self.lifes()
                    i-=1
                    break
        if len(self.senary.life):
            for i in range(len(self.senary.life)-1):
                if self.senary.life[i].colliderect(self.pos):
                    self.senary.life.pop(i)
                    self.life+=5
                    self.lifes()
                    break
        if self.face:
            if self.step == 1:
                draw(self.img,(self.pos.left,self.pos.top))
            else:
                draw(self.imgS,(self.pos.left,self.pos.top))
        else:
            if self.step == 1:
                draw(self.imgC,(self.pos.left,self.pos.top))
            else:
                draw(self.imgSC,(self.pos.left,self.pos.top))
        rand = random.randint(0,80)
        if rand > 76 and rand < 79:
            self.senary.constructorAdd(0)
        elif rand == 80:
            self.senary.constructorAdd(1)
        self.senary.draw()
        if self.senary.stone[0].left == -2700:
                self.senary.move(350)
    def lifes(self):
        self.porrada.play()
        self.life -= 1
        self.background.sky()
        self.drawLife()
        if self.life == 0:
                self.dead()
    def ia(self):
        self.senary.contIA+=1
        if not self.senary.contIA % 10:
            for i in range(len(self.senary.inimigo)-1):
                self.inimigoGO = 1
                for j in range(len(self.senary.stone)-1):
                    if self.senary.inimigo[i].colliderect(self.senary.stone[j]):
                        self.inimigoGO = 0
                        break
                if not self.inimigoGO:
                    self.senary.inimigoDir[i]*=-1
                self.senary.inimigoStep[i] *=-1
                self.senary.inimigo[i].move_ip(10*self.senary.inimigoDir[i],0)
        if self.senary.contIA == 50:
            for i in range(len(self.senary.inimigo)-1):
                self.shot.fire(self.senary.inimigo[i].center,0,0)
            self.senary.contIA = 0
    def drawLife(self):
        for i in range(self.life):
            draw(self.background.imgRapadura,(50*i+20,40))
    def dead(self):
        key = 0
        self.trilha.stop()
        self.morreu.play()
        while(key!=13):
            for event in pygame.event.get():
                if  event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == KEYDOWN:
                    key = event.key            
        sys.exit()
コード例 #34
0
    video_dir = os.path.join(data_dir, 'Data/VID')
    all_videos = glob(os.path.join(video_dir, 'train/ILSVRC2015_VID_train_0000/*')) + \
                 glob(os.path.join(video_dir, 'train/ILSVRC2015_VID_train_0001/*')) + \
                 glob(os.path.join(video_dir, 'val/*'))
    '''
    all_videos = glob(os.path.join(video_dir, 'train','*','*'))
    all_videos的最后一级是包含图片的文件夹,即图片的上一级
    '''
    meta_data = []
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    with Pool(processes=num_threads) as pool:
        for ret in tqdm(pool.imap_unordered(
                functools.partial(worker, output_dir), all_videos),
                        total=len(all_videos)):
            # functools.partial(worker, output_dir)
            # 因为pool.imap_unordered只能接收一个参数,故需要固定一个参数.
            meta_data.append(ret)

    # save meta data
    pickle.dump(meta_data, open(os.path.join(output_dir, "meta_data.pkl"),
                                'wb'))
    # meta_data.pkl保存的是video_name和trajs


if __name__ == '__main__':
    Fire(processing)
    # 在命令行执行时如下操作:
    # python3 creat_dataset.py --data_dir *** --output_dir *** --num_threads **
    # 其中data_dir和output_dir后参数必有
コード例 #35
0
        "lr_decay_rate": lr_decay_rate,
        "lr_decay_steps": lr_decay_steps,
        "size": size,
    })

    model = TransferModel(constants.NCLASSES, size, batch_size, **model_params)
    model.compile(
        optimizer=Adam(learning_rate=ExponentialDecay(
            learning_rate, lr_decay_steps, lr_decay_rate)),
        loss="categorical_crossentropy",
        metrics=["categorical_accuracy"],
    )

    # Train the model (just the new layers on top of the transfer model)
    model.fit_head(
        train_set,
        "dev",
        epochs=epochs,
        callbacks=[WandbCallback(save_model=False)],
    )

    # Log the scores
    wandb.join()

    if make_submission:
        return model.predict_on_test()


if __name__ == "__main__":
    Fire(transfer_train)
コード例 #36
0
ファイル: create_lmdb.py プロジェクト: shiyongde/Siamese-RPN
def worker(video_name):
    image_names = glob(video_name + '/*')
    kv = {}
    for image_name in image_names:
        img = cv2.imread(image_name)
        try:
            _, img_encode = cv2.imencode('.jpg', img)
        except:
            embed()
        img_encode = img_encode.tobytes()
        kv[hashlib.md5(image_name.encode()).digest()] = img_encode
    return kv


def create_lmdb(data_dir='/mnt/datasets/vid/ILSVRC_VID_CURATION',
                output_dir='/mnt/datasets/vid/ILSVRC_VID_CURATION.lmdb',
                num_threads=mp.cpu_count()):
    video_names = glob(data_dir + '/*')
    video_names = [x for x in video_names if os.path.isdir(x)]
    db = lmdb.open(output_dir, map_size=int(50e9))
    with Pool(processes=num_threads) as pool:
        for ret in tqdm(pool.imap_unordered(functools.partial(worker), video_names), total=len(video_names)):
            with db.begin(write=True) as txn:
                for k, v in ret.items():
                    txn.put(k, v)


if __name__ == '__main__':
    Fire(create_lmdb)
コード例 #37
0
class FireWidget(QWidget, Ui_Fire):
    fire = None

    def __init__(self, parent, app):
        super(QWidget, self).__init__()
        self.app = app

        self.setupUi(self)

        self.slider_frame_rate.valueChanged.connect(self.slider_frame_rate_changed)
        self.slider_hue.valueChanged.connect(self.slider_hue_changed)
        self.slider_start.valueChanged.connect(self.slider_start_changed)
        self.slider_end.valueChanged.connect(self.slider_end_changed)

        self.spinbox_frame_rate.valueChanged.connect(self.spinbox_frame_rate_changed)
        self.spinbox_hue.valueChanged.connect(self.spinbox_hue_changed)
        self.spinbox_start.valueChanged.connect(self.spinbox_start_changed)
        self.spinbox_end.valueChanged.connect(self.spinbox_end_changed)

        self.button_default.pressed.connect(self.default_pressed)

        self.update_frame_rate_timer = QTimer(self)
        self.update_frame_rate_timer.timeout.connect(self.update_frame_rate)

        self.default_pressed()

    def start(self):
        self.fire = Fire(self.app.ipcon)

        self.update_frame_rate()
        self.update_hue()
        self.update_start()
        self.update_end()

        self.fire.frame_rendered(0)

    def stop(self):
        if self.fire:
            self.fire.stop_rendering()
            self.fire = None

    def spinbox_frame_rate_changed(self, frame_rate):
        self.slider_frame_rate.setValue(frame_rate)
        self.update_frame_rate_timer.start(100)

    def spinbox_hue_changed(self, hue):
        self.slider_hue.setValue(int(hue*10))
        self.update_hue()

    def spinbox_start_changed(self, start):
        self.slider_start.setValue(start)
        self.update_start()

    def spinbox_end_changed(self, end):
        self.slider_end.setValue(end)
        self.update_end()

    def slider_frame_rate_changed(self, frame_rate):
        self.spinbox_frame_rate.setValue(frame_rate)

    def slider_hue_changed(self, hue):
        self.spinbox_hue.setValue(hue/10.0)

    def slider_start_changed(self, start):
        self.spinbox_start.setValue(start)

    def slider_end_changed(self, end):
        self.spinbox_end.setValue(end)

    def default_pressed(self):
        self.spinbox_frame_rate.setValue(50)
        self.spinbox_hue.setValue(1.2)
        self.spinbox_start.setValue(64)
        self.spinbox_end.setValue(255)

    def update_frame_rate(self):
        self.update_frame_rate_timer.stop()

        config.FIRE_FRAME_RATE = self.spinbox_frame_rate.value()

        if self.fire:
            self.fire.update_frame_rate()

    def update_hue(self):
        config.FIRE_HUE_FACTOR = self.spinbox_hue.value()

    def update_start(self):
        config.FIRE_RAND_VALUE_START = self.spinbox_start.value()

    def update_end(self):
        config.FIRE_RAND_VALUE_END = self.spinbox_end.value()