コード例 #1
0
class IceTracks():

    api: API
    blaster: Blaster
    ice: IceCast
    mounts: List[str]

    def __init__(self):
        # Pull in some config
        config = configparser.ConfigParser()
        config.read(
            os.path.dirname(os.path.realpath(__file__)) + '/config.ini')
        self.mounts = config["icecast"]["mounts"].replace(" ", "").split(",")

        self.api = API(url_base=config["myradio"]["url_base"],
                       url=config["myradio"]["url"],
                       api_key=config["myradio"]["api_key"])
        self.blaster = Blaster()
        self.ice = IceCast(url=config["icecast"]["url"],
                           auth=(config["icecast"]["user"],
                                 config["icecast"]["pass"]))
        print("Welcome to IceTracks!")
        self.loop()

    def loop(self):
        while True:
            try:
                print("--- Loop ---")
                # Push default now playing API output to all configured icecast mounts.
                nowPlaying = self.api.getNowPlaying()
                currentShow = self.api.getCurrentShow()
                print("Timeslot is: ", currentShow)

                self.blaster.blast(nowPlaying, currentShow)

                print("Live is Playing: ", nowPlaying)
                for mount in self.mounts:
                    self.ice.poke_mount(mount, nowPlaying)

                # Now for currently hardcoded source -> mount mappings.
                jukebox = self.api.getNowPlaying(sources=[Source.j],
                                                 allow_off_air=True)
                print("\nJukebox is Playing: ", jukebox)
                self.ice.poke_mount("jukebox", jukebox)

                webstudio = self.api.getNowPlaying(sources=[Source.w],
                                                   allow_off_air=True)
                print("\nWebstudio is Playing: ", webstudio)
                self.ice.poke_mount("webstudio", webstudio)

            # General Catch All. Ideally we never crash, rather just ignore updates caused by exceptions
            except Exception as e:
                print("Failure, will try again in next loop. Exception: ", e)

            time.sleep(15)
            print("\n")
コード例 #2
0
ファイル: test_blast.py プロジェクト: Dannyb48/blaster
    def test_blastoff_parallel_invalid_task():
        """Run blaster blastoff method with an invalid task in parallel.

        This method tests the blaster blastoff method. (negative test)
        """
        blaster = Blaster(
            tasks=[
                {
                    'task': ValidCar,
                    'methods': ['exterior', 'interior']
                }
            ]
        )
        blaster.blastoff()
コード例 #3
0
ファイル: test_blast.py プロジェクト: Dannyb48/blaster
    def test_blastoff_serial_invalid_task():
        """Run blaster blastoff method with an invalid task in sequential.

        This method tests the blaster blastoff method. (negative test)
        """
        blaster = Blaster(
            tasks=[
                {
                    'task': ValidCar,
                    'methods': ['exterior', 'interior']
                }
            ]
        )
        blaster.blastoff(serial=True)
コード例 #4
0
ファイル: test_blast.py プロジェクト: Dannyb48/blaster
    def test_valid_blastoff_parallel():
        """Run blaster blastoff method with valid task in parallel.

        This method tests the blaster blastoff method. (positive test)
        """
        blaster = Blaster(
            tasks=[
                {
                    'name': 'car',
                    'task': ValidCar,
                    'methods': ['exterior', 'interior']
                }
            ]
        )
        blaster.blastoff()
コード例 #5
0
    def __init__(self):
        # Pull in some config
        config = configparser.ConfigParser()
        config.read(
            os.path.dirname(os.path.realpath(__file__)) + '/config.ini')
        self.mounts = config["icecast"]["mounts"].replace(" ", "").split(",")

        self.api = API(url_base=config["myradio"]["url_base"],
                       url=config["myradio"]["url"],
                       api_key=config["myradio"]["api_key"])
        self.blaster = Blaster()
        self.ice = IceCast(url=config["icecast"]["url"],
                           auth=(config["icecast"]["user"],
                                 config["icecast"]["pass"]))
        print("Welcome to IceTracks!")
        self.loop()
コード例 #6
0
ファイル: test_blast.py プロジェクト: Dannyb48/blaster
    def test_blastoff_serial_failure():
        """Run blaster blastoff method with a task raising a failure in
        sequential.

        This method tests the blaster blastoff method with a task raising an
        exception. (negative test)
        """
        blaster = Blaster(
            tasks=[
                {
                    'name': 'car',
                    'task': InvalidCar,
                    'methods': ['exterior', 'interior']
                }
            ]
        )
        blaster.blastoff(serial=True, raise_on_failure=True)
コード例 #7
0
 def SvcDoRun(self):
     import servicemanager
     self.sender = Blaster(self.options.server, 3412, [])
     try:
         logging.info("login as %s", self.options.login)
         callback = BlasterCallback_i(self.options)
         self.sender.login(self.options.login, self.options.password,
                           callback)
         logging.info("sessionId: %s", self.sender.sessionId)
         logging.info("serverIOR: %s", self.sender.serverIOR)
         logging.info("callbackIOR: %s", self.sender.callbackior)
         logging.info("start uploading")
         self.sender.orb.run()
         logging.info("done")
         self.ReportServiceStatus(win32service.SERVICE_STOPPED)
     except:
         logging.exception("fatal error")
コード例 #8
0
ファイル: test_blast.py プロジェクト: Dannyb48/blaster
    def test_create_blaster_object():
        """Create a blaster object.

        This method tests creating a blaster object from the Blaster class.
        Once the object is created, it will verify it is an instance of the
        Blaster class.
        """
        blaster = Blaster(list())
        assert_is_instance(blaster, Blaster)
コード例 #9
0
ファイル: test_blast.py プロジェクト: Dannyb48/blaster
    def test_blaster_limit_processes(self):
        """Run blaster blastoff method limiting number of processes.

        This method tests the blaster blastoff method to limit the number of
        processes to launch based on the total number of tasks to call.
        (positive test)
        """
        tasks = list()
        for i in range(10):
            i += 1
            tasks.append(
                {
                    'name': 'car',
                    'task': ValidCar,
                    'methods': ['exterior', 'interior']
                }
            )
        blaster = Blaster(tasks=tasks)
        blaster.blastoff()
コード例 #10
0
ファイル: utils.py プロジェクト: zhaoxia413/plsdb
def call_blaster(record, fasta, db_path, blast, cov, ident):
    import os
    from Bio import SeqIO
    from blaster import Blaster
    tmp_fasta = '%s.fasta.tmp' % record.id
    tmp_blaster = '%s.blaster.tmp' % record.id

    # Create FASTA
    SeqIO.write(record, tmp_fasta, 'fasta')

    # Call Blaster
    if os.path.exists(tmp_blaster):
        os.remove(tmp_blaster)
    results = Blaster(
        inputfile=tmp_fasta,
        databases=['sequences'],  # created by Abricate, *.fsa link
        db_path=db_path,
        out_path=tmp_blaster,
        min_cov=cov / 100.0,  # expects 0.0 .. 1.0
        threshold=ident / 100.0,  # expects 0.0 .. 1.0
        blast=blast,
        cut_off=False)

    # Collect results
    if results.results['sequences'] == 'No hit found':
        os.remove(tmp_fasta)
        os.remove(tmp_blaster)
        return

    df = []
    for result in results.results['sequences'].values():
        df.append({
            'qseqid': result['contig_name'].split(' ')[0],
            'qstart': result['query_start'],
            'qend': result['query_end'],
            # 'qlen':,
            'sseqid': result['sbjct_header'].split(' ')[0],
            'stitle': result['sbjct_header'],
            'sstart': result['sbjct_start'],
            'send': result['sbjct_end'],
            'slen': result['sbjct_length'],
            'evalue': result['evalue'],
            'pident': result['perc_ident'],
            'length': result['HSP_length'],
            'gaps': result['gaps'],
            'cov': result['perc_coverage']
        })

    # rm tmp files
    os.remove(tmp_fasta)
    os.remove(tmp_blaster)
    return df
コード例 #11
0
ファイル: main.py プロジェクト: Anshroid/SeaInvaders
def run():
    ## GAME SIZE CONSTANTS
    DIMENSIONS = (870, 520)
    MENUCOORDS = (20, 20)
    ACTUALMENUCOORDS = (40, 40)
    MENUDIMENSIONS = (830, 480)
    ACTUALMENUDIMENSIONS = (790, 440)

    ## GENERAL CONSTANTS
    BLACK = (0,0,0)
    RED = (255,0,0)
    GREEN = (0,255,0)
    BLUE = (0,0,255)
    WHITE = (255,255,255)
    TRANSPARENT_GREEN = (0,255,0)

    ## CUSTOMISATION
    FPS = 30
    SPAWNING_SPEED = 0.25 # spawns per second
    SPEED = 6 # pixels per frame
    BULLET_COOLDOWN = 30 # frames
    BULLET_SPEED = 4
    MAX_STILLFRAMES = 180

    ## TRANSPARENCIES (ALPHA)
    text_transparency = 255
    button_transparency = 255
    innerm_transparency = 255
    outerm_transparency = 128
    menu_transparencies = [text_transparency, button_transparency, innerm_transparency, outerm_transparency]

    ## GAME FLOW
    running = True
    game = Game(DIMENSIONS, FPS)
    clock = pygame.time.Clock()

    ## MENU CONTROL
    menu = "menu"
    menustatus = False
    infade = False
    outfade = False

    ## INITIALISATION
    pygame.init()
    screen = pygame.display.set_mode(DIMENSIONS)
    pygame.display.set_caption("Sea Invaders!")
    icon = pygame.image.load("assets/icon/icon.jpg")
    pygame.display.set_icon(icon)

    ## BACKGROUND
    sea = pygame.image.load("assets/background/sea.jpg").convert()

    ## CALLBACKS
    def play_resume():
        """Updates and returns the new menustatus. Since this callback is only called to resume the game, sets menustatus to false."""
        menustatus = False
        return menustatus

    ## BUTTONS
    startbtn = Button((300, 48), (285,240), play_resume)

    ## MENU
    menufont = pygame.font.Font("assets/fonts/PressStart2P.ttf", 40)
    menutext = "Sea Invaders!"
    btnfont = pygame.font.Font("assets/fonts/PressStart2P.ttf", 35)
    btntext = "Start!"
    menuobj_alpha = pygame.Surface(MENUDIMENSIONS, flags=SRCALPHA)
    menuobj = pygame.Surface(ACTUALMENUDIMENSIONS, flags=SRCALPHA)
    score = pygame.font.Font("assets/fonts/PressStart2P.ttf", 25)

    ## FISH SPAWNER INITIALISATION
    spawner = FishController(SPAWNING_SPEED, SPEED, MAX_STILLFRAMES)
    blaster = Blaster(BULLET_COOLDOWN, BULLET_SPEED)


    ## MAINLOOP
    while running:
        ## PER-FRAME LOGIC
        menu_transparencies = [text_transparency, button_transparency, innerm_transparency, outerm_transparency]
        prev_menustatus = menustatus

        ## RENDER BACKGROUND
        screen.blit(sea, (0,0))
        screen.blit(sea, (435,0))

        ## RENDER MENU (INCLUDING TRANSPARENCY)
        menuobj_alpha.fill((0,255,0,outerm_transparency))
        menuobj.fill((0,255,0,innerm_transparency))
        menuobj_alpha.blit(menuobj, (ACTUALMENUCOORDS[0] - MENUCOORDS[0], ACTUALMENUCOORDS[1] - MENUCOORDS[1]))
        menutextsurface = menufont.render(menutext, True, RED)
        menutext_surf = pygame.Surface((menutextsurface.get_rect().width, menutextsurface.get_rect().height))
        menutext_surf.blit(menutextsurface, pygame.Rect(0, 0, 10, 10), special_flags=pygame.BLEND_RGBA_MULT)
        menutext_surf.set_alpha(text_transparency)
        menuobj_alpha.blit(menutext_surf, ((MENUDIMENSIONS[0]/2)-(menutext_surf.get_rect().width/2), 60))
        if menustatus:
            screen.blit(menuobj_alpha, MENUCOORDS)
    
        ## RENDER BUTTONS
        #btntextsurface = menufont.render(menutext, True, GREEN)
        #btntext_surf = pygame.Surface((btntextsurface.get_rect().width, btntextsurface.get_rect().height))
        #btntext_surf.blit(btntextsurface, pygame.Rect(0, 0, 10, 10), special_flags=pygame.BLEND_RGBA_MULT)
        if menustatus:
            startbtn.draw_self(screen, (255,0,0,button_transparency))#, btntext_surf)

        ## PROCESS MENU
        menustatus = startbtn.process(menustatus)

        ## EVENT PROCESSING
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit(0)
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    if not infade and not outfade:
                        if menustatus:
                            menustatus = False
                        else:
                            menustatus = True

        ## CUSTOM EVENT PROCESSING

        ## MENU LOGIC
        if game.score < 0:
            menustatus = True
            game.score = 0
            ObjectCollector.clear_all()


        if menustatus:
            pygame.mouse.set_visible(True)
        else:
            pygame.mouse.set_visible(False)

        if not menustatus:
            if prev_menustatus:
                outfade = True

        if menustatus:
            if not prev_menustatus:
                infade = True

        ## PROCESS OBJECTS
        if not prev_menustatus:
            if outfade == False:
                game, screen = ObjectCollector.process_all(game, screen)

        ## FADING LOGIC
        if outfade:
            for i in range(len(menu_transparencies)):
                menu_transparencies[i] -= 8
            text_transparency = menu_transparencies[0]
            button_transparency = menu_transparencies[1]
            innerm_transparency = menu_transparencies[2]
            outerm_transparency = menu_transparencies[3]
            if text_transparency < 0: 
                text_transparency = 0
            if outerm_transparency < 0: 
                outerm_transparency = 0
            if innerm_transparency < 0: 
                innerm_transparency = 0
            if button_transparency < 0: 
                button_transparency = 0
            if button_transparency == 0 and innerm_transparency == 0 and outerm_transparency == 0:
                outfade = False
                startbtn.visible = False

        if infade:
            for i in range(len(menu_transparencies)):
                menu_transparencies[i] += 8
            text_transparency = menu_transparencies[0]
            button_transparency = menu_transparencies[1]
            innerm_transparency = menu_transparencies[2]
            outerm_transparency = menu_transparencies[3]
            if outerm_transparency > 128: 
                outerm_transparency = 128
            if innerm_transparency > 255: 
                innerm_transparency = 255
            if button_transparency > 255: 
                button_transparency = 255
            if button_transparency == 255 and innerm_transparency == 255 and outerm_transparency == 128:
                infade = False
                startbtn.visible = True

        ## RENDER SCORE
        score_surf = score.render(str(game.score), True, WHITE)
        screen.blit(score_surf, (70, 70))

        ## UPDATE DISPLAY
        pygame.display.update(screen.get_rect())

        ## FPS TRACKING
        clock.tick(FPS)
        game.increment_frames()
コード例 #12
0
        bindata = f.read()
    for i in range(len(bindata) // 4):
        ocd.writemem(startadr + i * 4,
                     struct.unpack('<I', bindata[i * 4:(i + 1) * 4])[0])


if __name__ == '__main__':
    if (argv[1] == 'f'):
        engine = JtagEngine(trst=False, frequency=10E3)
        engine.configure('ftdi://olimex:ft2232h/1')
    elif (argv[1] == 's'):
        ctrl = JtagSimController()
        ctrl.configure(7894)
        engine = JtagOCDEngine(ctrl)
    elif (argv[1] == 'v'):
        ctrl = Blaster()
        engine = JtagOCDEngine(ctrl)

    tool = JtagTool(engine)
    time.sleep(1)
    engine.reset()
    id = tool.idcode()
    print("ID:%08x" % id)
    engine.go_idle()
    engine.capture_ir()
    arch = archmap.get(argv[2], archmap['murax'])
    if argv[1] != 'v':
        irlen = tool.detect_register_size()
    else:
        irlen = arch.irsize
    ocd = arch.Ocd(engine, irlen)
コード例 #13
0
def fire_blaster(ai_settings, screen, ship, blaster_rays):
    if len(blaster_rays) < ai_settings.blaster_rays_allowed:
        new_ray = Blaster(ai_settings, screen, ship)
        blaster_rays.add(new_ray)
コード例 #14
0
                'furnish',
                'post_build_tasks',
                'enjoy'
            ],
            'style': 'ranch'
        },
        {
            'name': 'House 5',
            'task': House,
            'methods': [
                'foundation',
                'frame',
                'roof',
                'furnish',
                'post_build_tasks',
                'enjoy'
            ],
            'style': 'split'
        }
    ]

    # create blaster object
    blast = Blaster(tasks)

    # blast off tasks in parallel
    data = blast.blastoff()

    # log results
    sleep(2)
    pprint(data, indent=4)
コード例 #15
0
class XMLBlasterFileSenderService(win32serviceutil.ServiceFramework):
    _svc_name_ = "XMLBlasterFileSenderService"
    _svc_display_name_ = "XMLBlaster File Sender Service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        parser = OptionParser(
            "usage: \%prog [-d <directory>] [-s <server>] [-l <login>] [-p <password>]"
        )
        parser.add_option("-d",
                          "--directory",
                          dest="directory",
                          help="upload directory",
                          default=".\\")
        parser.add_option("-s",
                          "--server",
                          dest="server",
                          help="auth server host",
                          default="localhost")
        parser.add_option("-l",
                          "--login",
                          dest="login",
                          help="login",
                          default="")
        parser.add_option("-p",
                          "--password",
                          dest="password",
                          help="password",
                          default="")
        parser.add_option("-c",
                          "--config",
                          dest="config",
                          help="config file",
                          default="")
        parser.add_option("-f",
                          "--filelog",
                          dest="filelog",
                          help="log file name",
                          default="service.log")
        argv = eval(
            win32serviceutil.GetServiceCustomOption(
                XMLBlasterFileSenderService, "argv", "[]"))
        (self.options, args) = parser.parse_args(argv)
        self.setupLog()
        logging.info("argv=%s", argv)

    def setupLog(self):
        from warnings import filterwarnings
        filterwarnings("ignore", category=DeprecationWarning, module="logging")
        if self.options.config:
            logging.fileConfig(self.options.config)
        else:
            hdlr = logging.FileHandler(self.options.filelog)
            fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
            hdlr.setFormatter(fmt)
            logging.getLogger().addHandler(hdlr)
            logging.getLogger().setLevel(logging.INFO)

    def SvcDoRun(self):
        import servicemanager
        self.sender = Blaster(self.options.server, 3412, [])
        try:
            logging.info("login as %s", self.options.login)
            callback = BlasterCallback_i(self.options)
            self.sender.login(self.options.login, self.options.password,
                              callback)
            logging.info("sessionId: %s", self.sender.sessionId)
            logging.info("serverIOR: %s", self.sender.serverIOR)
            logging.info("callbackIOR: %s", self.sender.callbackior)
            logging.info("start uploading")
            self.sender.orb.run()
            logging.info("done")
            self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        except:
            logging.exception("fatal error")

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        logging.info("logout")
        self.sender.logout()
        logging.info("stop uploading")
        self.sender.orb.shutdown(True)

    def SvcPause(self):
        logging.info("pause")
        self.sender.poa._get_the_POAManager().hold_requests(True)
        self.ReportServiceStatus(win32service.SERVICE_PAUSED)

    def SvcContinue(self):
        logging.info("continue")
        self.sender.poa._get_the_POAManager().activate()
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
コード例 #16
0
        'House 4',
        'task':
        House,
        'methods': [
            'foundation', 'frame', 'roof', 'furnish', 'post_build_tasks',
            'enjoy'
        ],
        'style':
        'ranch'
    }, {
        'name':
        'House 5',
        'task':
        House,
        'methods': [
            'foundation', 'frame', 'roof', 'furnish', 'post_build_tasks',
            'enjoy'
        ],
        'style':
        'split'
    }]

    # create blaster object
    blast = Blaster(tasks)

    # blast off tasks in sequential
    data = blast.blastoff(serial=True)

    # log results
    sleep(2)
    pprint(data, indent=4)