Esempio n. 1
0
    def __init__(self, d):
        self.d = d
        self.setting = Settings(self.d)
        self.path = image_comparison.get_path()

        self.log_data = []
        self.ts_wifi_report_data = []
Esempio n. 2
0
 def __init__(self, filePath=None, primaryLabel=None):
     Settings.__init__(self, filePath)
     self._primaryLabel = primaryLabel
     self._sortKeys = None
     self._altIndex = None
     if filePath != None:
         self._primaryLabel = self.read(filePath, primaryLabel)
Esempio n. 3
0
 def run(self) -> None:
     try:
         self.__threadLock.acquire()
         self.__window.statusBar.SetStatusText("正在检查更新...", 2)
         self.__threadLock.release()
         newInfo = FetchNewVersion()
         newVersion = LooseVersion(newInfo['version'])
         currentVersion = LooseVersion(Settings.version())
         self.__threadLock.acquire()
         Settings.settings["lastCheckUpdateTime"] = Now()
         if currentVersion < newVersion:
             MessageBox("当前版本为%s, 检查到新版本%s" %
                        (Settings.version(), newInfo["version"]))
             if newInfo["registry"]["type"] == "list":
                 LaunchDefaultBrowser(newInfo["registry"]["url"])
             self.__window.statusBar.SetStatusText(
                 "检查到新版本" + newInfo['version'], 2)
         else:
             self.__window.statusBar.SetStatusText("当前版本为最新版本", 2)
         self.__threadLock.release()
     except Exception as e:
         self.__window.statusBar.SetStatusText("", 2)
         self.__threadLock.acquire()
         self.__window.statusBar.SetStatusText("检查更新出错", 2)
         MessageBox(str(e), "检查更新时出现错误", ICON_ERROR)
         self.__threadLock.release()
Esempio n. 4
0
 def __init__(self, d):
     self.d = d
     self.gmail = Gmail(self.d)
     self.path = image_comparison.get_path()
     self.log_data = []
     self.settings = Settings(d)
     self.gmail_report_details = []
Esempio n. 5
0
 def __init__(self, filePath=None, primaryLabel=None):
     Settings.__init__(self,filePath)
     self._primaryLabel=primaryLabel
     self._sortKeys = None
     self._altIndex = None
     if filePath != None:
         self._primaryLabel = self.read(filePath, primaryLabel)
Esempio n. 6
0
 def OnButtonClicked(self, event):
     if event.GetId() == self.cancelButton.GetId():
         self.Close()
         return
     name = self.nameInput.GetValue()
     url = self.urlInput.GetValue()
     isOnline = self.onlineRadio.GetValue()
     if not isOnline:
         url = None
     if not name or len(name) < 1:
         MessageBox("请输入Hosts名称", "提示", ICON_WARNING)
     elif isOnline and (not url or len(url) < 1):
         MessageBox("请输入在线Hosts地址", "提示", ICON_WARNING)
     else:
         if not self.iconComboBox.GetValue():
             self.iconComboBox.SetValue("logo")
         if self.__hosts:
             self.__hosts["name"] = name
             self.__hosts["url"] = url
             self.__hosts["lastUpdateTime"] = Now()
             self.__hosts["icon"] = self.iconComboBox.GetValue()
             hostsId = self.__hosts['id']
         else:
             hostsId = 0x1994 + len(Settings.settings["hosts"])
             Settings.settings["hosts"].append(
                 hostsDict(hostsId,
                           name,
                           url=url,
                           lastUpdateTime=Now(),
                           content="# Created by mHosts v%s, %s\n" %
                           (Settings.version(), Now()),
                           icon=self.iconComboBox.GetValue()))
         Settings.Save()
         self.__window.InitHostsTree(select=hostsId)
         self.Close()
Esempio n. 7
0
    def __init__(self, application):
        super().__init__()

        self._loading = True
        self.application = application
        self.settings = Settings(self)
        self.workflows = Workflows(self)
        self.undo_stack = QUndoStack(self)
        self.refresh_timer = QTimer()

        self._init_widgets()

        self.main_window_actions = MainWindowActions(self)

        self._init_window()
        self._init_toolbars()

        self.settings.restore()
        if self.settings.signature_key is None:
            self.settings.signature_key = genkey()

        self.show()
        self._update_action_toggles()

        # Update the GUI so that everything matches the model
        cell_attributes = self.grid.model.code_array.cell_attributes
        attributes = cell_attributes[self.grid.current]
        self.on_gui_update(attributes)

        self._loading = False
        self._previous_window_state = self.windowState()
    def __init__(self):

        # Declare settings
        self.cfg = Settings()

        # Declare library
        self.sf = Salesforce(self.cfg.get_salesforce_credentials())
Esempio n. 9
0
    def start():
        choosing = True
        while choosing:
            os.system('cls')
            print(color.BLUE + """

            Aplicación de Vacunas       

            """)
            print(color.WHITE + """
            1- Registrar vacunado
            2- Exportar
            3- Configuración 
            4- Salir
            """)
            option = input('Digite la opción que prefiera: ')
            if option == '1':
                PatientService.add()
            elif option == '2':
                PatientService.export()
            elif option == '3':
                Settings.start()
            elif option == '4':
                choosing = False
            else:
                input(color.RED + 'Elija una opción existente')
Esempio n. 10
0
 def write_to_settings(self):
     if constants.CACHE_CREDENTIALS:
         Settings.set_credentials({
             "login_date": self.login_date,
             "access_token": self.access_token,
             "refresh_token": self.refresh_token,
             "first_name": self.first_name,
             "last_name": self.last_name,
             "email": self.email
         })
Esempio n. 11
0
 def __init__(self):
     super(JiraToMd, self).__init__()
     sprint_id = int(input("Enter Sprint ID: "))
     epic_id = str(input("Enter EPIC ID: "))
     self.sprint_id = sprint_id
     self.epic_id = epic_id
     self.jira_service = JiraServices()
     self.settings = Settings()
     self.datetime_service = DateTimeService()
     self.make_md_file()
Esempio n. 12
0
 def __init__(self, d):
     self.d = d
     self.nictalk = NicTalk(self.d)
     self.camtalk = CamTalk(self.d)
     self.qq = Tx_QQ(self.d)
     self.clock = Clock(self.d)
     self.camera = Camera(self.d)
     self.settings = Settings(self.d)
     self.message = Message1(self.d)
     self.path = os.path.abspath(os.path.join(
         os.getcwd(), "../..")) + "\\enter_resource\\"
     self.language = self.settings.change_language()
     self.settings.display_setting()
Esempio n. 13
0
def main():
	"""
	Just the test
	This method is a good resource on how to handle the results.
	Save images in this method if you have to.
	"""

	filename = sys.argv[1]
	image = highgui.cvLoadImage (filename)

	cutRatios = [lib.PHI]
	#cutRatios = [0.618]
	settings = Settings(cutRatios)
	image = highgui.cvLoadImage (filename)
	thickness = 4
	settings.setMarginPercentage(0.025)
	settings.setMethod(sys.argv[3])
	cut = int(sys.argv[2])
	winname = sys.argv[1]
	#settings.setThresholds(100,150)
	# Set the color for the boxes
	#color = lib.COL_BLACK
	#color = lib.COL_WHITE
	#color = lib.COL_RED
	color = lib.COL_GREEN
	#color = lib.COL_BLUE

	blobImg = blobResult(image, settings, cut)
	boxxImg = boundingBoxResult(image, settings, cut, thickness, color)
	cutt = lib.findMeans(cv.cvGetSize(image), settings.cutRatios[0])[cut]
	# cuttet verdi, dog skal det vi generaliseres lidt
	oriantesen = cutt.getPoints()[0].x == cutt.getPoints()[1].x
	if oriantesen:
		cutPixel = cutt.getPoints()[1].x
	else:
		cutPixel = cutt.getPoints()[1].y
	
	if oriantesen:
	#	print 'hej'
		cv.cvLine(boxxImg, cv.cvPoint(cutPixel, cutt.getPoints()[0].y), cv.cvPoint(cutPixel, cutt.getPoints()[1].y), lib.COL_RED)
	else:
		cv.cvLine(boxxImg, cv.cvPoint(cutt.getPoints()[0].x, cutPixel), cv.cvPoint(cutt.getPoints()[1].x, cutPixel), lib.COL_RED)
	# Save images
	highgui.cvSaveImage('flood_cut_%s.png' % cut, boxxImg)
	highgui.cvSaveImage('blobs_cut_%s.png' % cut, blobImg)

	# Show images
	compareImages(blobImg, boxxImg, "blob", winname)
 def initiate_unknown_package_ingestion(self):
     """Ingestion of Unknown dependencies."""
     if Settings().disable_unknown_package_flow:
         logger.warning('Skipping unknown flow %s',
                        self.get_all_unknown_packages())
         return
     logger.error('Ingestion is Not active for Golang.')
Esempio n. 15
0
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    pygame.display.set_caption('Alien Invasion')

    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    ship = Ship(ai_settings, screen)
    play_button = Button(ai_settings, screen, 'Play')

    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, aliens, ship)
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # 开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, ship, bullets, stats, play_button,
                        aliens, sb)
        if not stats.game_over:
            ship.update()
            gf.update_bullets(ai_settings, screen, bullets, aliens, ship,
                              stats, sb)
            gf.update_aliens(ai_settings, screen, aliens, bullets, ship, stats,
                             sb)
        gf.update_screen(ai_settings, screen, ship, bullets, aliens, stats,
                         play_button, sb)
Esempio n. 16
0
    def top_menu_caller(self, widget, branch_id, name):
        if name == "trial":
            cash = accounting.TrialBalance(branch_id, self.notebook.accounts, self.window)
            cash.show_all()
        if name == "calc":
            calculator.Calc("Calculator", self.window)

        if name == "settings":
            Settings(branch_id,
                     self.definitions.get_date(), "Settings", self.window, Gtk.DialogFlags.MODAL,
                     (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                      Gtk.STOCK_OK, Gtk.ResponseType.OK))

        if name == "purchase":
            Purchases(branch_id, self.notebook.sales.get_date())

        if name == "add_item":
            Item(branch_id, "Add item", self.window, Gtk.DialogFlags.MODAL,
                 (Gtk.STOCK_OK, Gtk.ResponseType.OK,
                  Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))
            self.notebook.sales.update_inventory()
            self.notebook.sales.dip.update_tanks()
            self.notebook.sales.lub.update_inventory()

        if name == "print":
            response = self.printwindow.run()
            if response == Gtk.ResponseType.OK:
                print("printing")
            elif response == Gtk.ResponseType.CANCEL:
                pass
            self.printwindow.hide()
Esempio n. 17
0
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # 创建一艘飞船
    ship = Ship(ai_settings, screen)

    # 创建一个用于存储子弹的编组
    bullets = Group()

    aliens = Group()

    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # 开始游戏的主循环
    while True:
        # 监视键盘和鼠标事件
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
        gf.update_aliens(ai_settings, ship, aliens)
        gf.update_screen(ai_settings, screen, ship, aliens, bullets)
        time.sleep(0.01)
Esempio n. 18
0
async def games_list(request: Request, db: Session = Depends(get_db)):
    settings = Settings()
    games = db.query(Game)
    return settings.templates.TemplateResponse('games/list.jinja', {
        'request': request,
        'games': games
    })
Esempio n. 19
0
def run_game():
    """Main entry point for Py-Climber"""

    # Startup pygame object
    pygame.init()

    random.seed()

    # Load our settings object and image resources, disk I/O that can be done in advance
    settings = Settings()
    image_res = ImageResources(settings)
    # Add to the cache so it's accessible where needed
    settings.image_res = image_res

    # Create the main screen to render to based on settings
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption(settings.caption)

    # Create a 2D tilemap - this takes a list of indices and an image list to produce a tiled surface
    tile_map = Tilemap(settings, screen, settings.map_indicies,
                       image_res.tile_images, image_res.block_image,
                       image_res.blob_exit_images,
                       image_res.player_sprite_images,
                       image_res.enemy_blob_images)

    # Overwrite default indices with generated map
    tile_map.generate_basic_map(settings.map_number_floors,
                                settings.map_number_subfloors)

    # Reset the game
    gf.reset_game(tile_map)

    # Use pygame's simple loop management for a fixed 30 FPS
    clock = pygame.time.Clock()
    while True:
        # Should make sure each frame spends at least 1/30 seconds in this loop
        # downside is wasted sleep on fast hardware and slow hardware will lag
        # but slow hardware will always lag and implementing a time-delta based
        # loop for this simple game is IMHO overkill.
        clock.tick(30)

        # Process system events (key-presses, joystick, etc)
        gf.check_events(settings, screen, tile_map)

        # Update the game (this will update all sub-object and render them to the screen)
        gf.update_screen(settings, screen, tile_map)
Esempio n. 20
0
    def __init__(self, application, args, unit_test=False):
        super().__init__()

        self._loading = True
        self.application = application
        self.unit_test = unit_test

        self.settings = Settings(self)
        self.workflows = Workflows(self)
        self.undo_stack = QUndoStack(self)
        self.refresh_timer = QTimer()

        self._init_widgets()

        self.main_window_actions = MainWindowActions(self)

        self._init_window()
        self._init_toolbars()

        self.settings.restore()
        if self.settings.signature_key is None:
            self.settings.signature_key = genkey()

        # Update recent files in the file menu
        self.menuBar().file_menu.history_submenu.update()

        if not self.unit_test:
            self.show()

        self._update_action_toggles()

        # Update the GUI so that everything matches the model
        cell_attributes = self.grid.model.code_array.cell_attributes
        attributes = cell_attributes[self.grid.current]
        self.on_gui_update(attributes)

        self._loading = False
        self._previous_window_state = self.windowState()

        # Open initial file if provided by the command line
        if args.file is not None:
            if self.workflows.filepath_open(args.file):
                self.workflows.update_main_window_title()
            else:
                msg = "File '{}' could not be opened.".format(args.file)
                self.statusBar().showMessage(msg)
Esempio n. 21
0
def getSettingsForRunId(runId):
	"""Return the settings instance for a given run"""
	runInstance = Run.selectBy(id=runId)[0]

	# Get the cut ratios
	cutRatios = getCutRatiosForRunId(runId)

	settings = Settings(cutRatios)
	settings.setThresholds(runInstance.trsh1, runInstance.trsh2)
	settings.setLo(runInstance.lo)
	settings.setUp(runInstance.up)
	settings.setMarginPercentage(runInstance.marginPercentage)

	return settings
Esempio n. 22
0
    def ApplyHosts(self, hostsId: int):
        commonHostsLines = "# hosts file apply by mHosts v%s, %s\n " % (
            Settings.version(), Now())
        currentHostsLines = ""
        currentHosts = None

        for hosts in Settings.settings["hosts"]:
            if hosts["id"] == hostsId:
                currentHostsLines += "# ---------------- %(name)s ----------------%(br)s%(content)s%(br)s" % {
                    "name": hosts['name'],
                    "br": os.linesep,
                    "content": hosts['content']
                }
                currentHosts = hosts
            if hosts["alwaysApply"]:
                commonHostsLines += "# ---------------- %(name)s ----------------%(br)s%(content)s%(br)s" % {
                    "name": hosts['name'],
                    "br": os.linesep,
                    "content": hosts['content']
                }

        hostsToApply = commonHostsLines + os.linesep + currentHostsLines
        try:
            if Hosts.Save2System(ParseHosts(hostsToApply)):
                for hosts in Settings.settings["hosts"]:
                    hosts["active"] = hosts["id"] == hostsId
                refreshDnsRes = Hosts.TryFlushDNSCache()
                MessagePanel.Send("Hosts已设置为" + currentHosts["name"] +
                                  "\nDNS缓存刷新" +
                                  ("成功" if refreshDnsRes else "失败"),
                                  "保存成功",
                                  dpi=(self.dpiX, self.dpiY))
            else:
                MessageBox("保存失败", "提示", ICON_ERROR)
            self.InitHostsTree(ID_SYSTEM_HOSTS)
            Settings.Save()
        except Exception as e:
            message = str(e)
            if "Permission denied" in message:
                MessageBox("尝试写入hosts时权限不足, 保存失败, 请以管理员身份运行该软件", "权限不足",
                           ICON_ERROR)
            else:
                MessageBox(message, "保存时出错", ICON_ERROR)
Esempio n. 23
0
 def read_from_settings(self):
     if constants.CACHE_CREDENTIALS:
         credentials = Settings.get_credentials()
         self.login_date = credentials.get("login_date", None)
         self.access_token = credentials.get("access_token", None)
         self.refresh_token = credentials.get("refresh_token", None)
         self.first_name = credentials.get("first_name", None)
         self.last_name = credentials.get("last_name", None)
         self.email = credentials.get("email", None)
         self.authenticated = self.access_token is not None
Esempio n. 24
0
 def fill_settings(self):
     sett = Settings()
     sett.font["scale"] = (float)(self.entires["fontScale"].get_value())
     sett.font["haloScale"] = (float)(self.entires["haloScale"].get_value())
     sett.font["path"] = (str)(self.entires["fontPath"].get_filename())
     sett.font["color"] = convert_to_rgb(self.entires["fontColor"].get_rgba())
     sett.font["haloColor"] = convert_to_rgb(self.entires["haloColor"].get_rgba())
     sett.dirName = (str)(self.entires["dirName"].get_text())
     return sett
Esempio n. 25
0
def start_test():
    # read config file
    settings = Settings("../config/test_config.json")

    # tell scraper about the settings
    scraper.settings_ref = settings

    # scrape
    ret = scraper.craw_all()
    for obj in ret:
        print(obj)
Esempio n. 26
0
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Urban Terror DemoRecorder")
        self.setGeometry(0, 0, 500, 200)

        self.settings = Settings()

        self.path = ""
        self.format = ""

        # Path
        self.layout = QVBoxLayout()

        self.initPath()
        self.initDemosFormat()
        self.initSubmitButton()

        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)
Esempio n. 27
0
def run():
    with open(location_file, "r") as file:
        location = file.readline()
    file.close()
    ers = Errors()
    settings = Settings(location, ers)
    if write_errors(ers):
        return
    classroom = Classroom(settings.created_students, settings)
    print_testing_report(settings)
    write_results(classroom)
    subprocess.call(['open', '-a', 'TextEdit', results_file])
class TestSettings(object):
    
    def setup(self):
        self.settings = Settings(None,'test_settings.cfg')
    
    def test_set_and_read(self):
        section = 'Test'
        setting = 'TestSetting'
        val = 'TESTsettingISset'
        self.settings.set(setting, val, section)
        self.settings.save()
        self.settings.load()
        assert self.settings.get(setting, section) == val
        assert self.settings.get('NoSection', 'NoSetting') == None
Esempio n. 29
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    ship = Ship(ai_settings, screen)
    bullets = Group()
    alien = Alien(ai_settings, screen)
    while True:
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        gf.update_bullet(bullets)
        gf.update_screen(ai_settings, screen, ship, alien, bullets)
Esempio n. 30
0
def run_game():
    pygame.init()
    game_settings = Settings()
    screen = Screen(game_settings)
    pygame.display.set_caption("BOMBERMAN")
    character = Character(game_settings, screen.screen, (0, 0))
    character2 = Character(game_settings, screen.screen, (1, 1))
    bombs_handler = BombsHandler(Group(), Group())
    obstacles = Group()
    hard_obstacles = Group()
    explosions = Group()
    treasures = Group()
    obstacle_placer = ObstaclePlacer()
    obstacle_placer.create_obstacles(game_settings, screen.screen, obstacles)
    obstacle_placer.create_hard_obstacles(game_settings, screen.screen,
                                          hard_obstacles)
    joystick = Joystick()
    smile_of_fate = SmileOfFate(game_settings)
    latest_choices = (0, 0)
    controller = Controller()
    while True:
        pygame.event.pump()
        controller.check_events(game_settings, screen.screen, character,
                                bombs_handler.bombs[0], character2,
                                bombs_handler.bombs[1])
        character.update(obstacles, hard_obstacles)
        if joystick.is_joystick():
            latest_choices = controller.check_joystick_events(
                character2, joystick.is_joystick(), latest_choices)
        character2.update(obstacles, hard_obstacles)
        bombs_handler.update_bombs(bombs_handler.bombs[0], game_settings,
                                   screen.screen, explosions, obstacles,
                                   treasures, smile_of_fate)
        bombs_handler.update_bombs(bombs_handler.bombs[1], game_settings,
                                   screen.screen, explosions, obstacles,
                                   treasures, smile_of_fate)
        bombs_handler.kill_your_heroes(explosions, character, character2)
        if len(obstacles.sprites()) < 5:
            treasures.empty()
            character.reset_character_status()
            character2.reset_character_status()
            obstacle_placer.create_obstacles(game_settings, screen.screen,
                                             obstacles)
        smile_of_fate.player_collected_treasure(character, treasures)
        smile_of_fate.player_collected_treasure(character2, treasures)
        screen.update_screen(game_settings, character, obstacles,
                             bombs_handler.bombs[0], character2,
                             bombs_handler.bombs[1], hard_obstacles,
                             explosions, treasures)
Esempio n. 31
0
def main():
	"""
	Just the test
	This method is a god resource on how to handle the results
	"""

	filename = sys.argv[1]
	image = highgui.cvLoadImage (filename)

	cutRatios = [0.61]
	settings = Settings(cutRatios)
	image = highgui.cvLoadImage (filename)
	thickness = 4
	settings.setMarginPercentage(0.025)
	cutNo = int(sys.argv[2])
	
	cut = lib.findMeans(cv.cvGetSize(image), settings.cutRatios[0])[cutNo]
	
	# Get the BW edge image
	edgeImage = naiveMethod.getEdgeImage(image, settings)

	(blobImg, comp) = naiveMethod.analyzeCut(image, edgeImage, cut, settings, 'True')
	#liste af liste 
	
	gridPointsList = grid.gridIt(blobImg, comp)
	#print gridPointsList
	points = centerOfMass(gridPointsList)
	#(x,y)
	for point in points:
		cv.cvLine(image, cv.cvPoint(point, 0), cv.cvPoint(point,600), COL_GREEN)
	lib.drawBoundingBoxes(image, comp)
	
	#highgui.cvSaveImage('floodfillbilledet.png', blobImg)
	#highgui.cvSaveImage('boindingboxbilledet.png', boxxImg)
	
	showImage(image, 'name')
Esempio n. 32
0
def load_settings(task_file, arg_duration, arg_seed):
    settings = task_file['settings']
    if arg_seed is None and 'seed' not in settings:
        seed = None
    else:
        seed = int(arg_seed) if arg_seed is not None else settings['seed']

    if arg_duration is None and 'duration' not in settings:
        print('No duration specified, using the default of 30 seconds')
        duration = 30
    else:
        duration = int(arg_duration) if arg_duration is not None else settings['duration']

    breath_pause_length = settings['breath_pause_length']
    return Settings(seed, duration, breath_pause_length)
Esempio n. 33
0
def init_app():
    app = Sanic(__name__, strict_slashes=False)
    env = Env()
    env.read_env()
    app.config.update_config(Settings())
    setup_routes(app)
    setup_middlewares(app)
    app.request_class = AppRequest

    app.run(
        host=app.config.HOST,
        port=app.config.PORT,
        debug=app.config.DEBUG,
        auto_reload=app.config.DEBUG,
    )
    return app
Esempio n. 34
0
 def __init__(self):
     pygame.init()
     self.settings = Settings()
     self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
     self.settings.screen_height = self.screen.get_rect().height
     self.settings.screen_width = self.screen.get_rect().width
     self.bg = pygame.image.load('../images/bg.png').convert()
     pygame.display.set_caption("Battle Tank")
     self.bullets = pygame.sprite.Group()
     self.player = Player(self)
     enemy = Enemy(self)
     self.enemies = pygame.sprite.Group()
     self.enemies.add(enemy)
     self.all_tanks = pygame.sprite.Group()
     self.all_tanks.add(self.player)
     self.all_tanks.add(enemy)
 def __init__(self, d):
     self.d = d
     self.settings = Settings(d)
     self.ncacootv = NCA_Cootv(d)
     self.khmcootv = KHM_Cootv(d)
     self.cooclean = Coo_Clean(d)
     self.ncacoobill = NCA_CooBill(d)
     self.khmcoobill = KHM_CooBill(d)
     self.mi_cootel = Mi_CooTel(d)
     self.camtalk = CamTalk(d)
     self.nictalk = NicTalk(d)
     self.path = os.path.abspath(os.path.join(
         os.getcwd(), "../..")) + "\\enter_resource\\"
     self.NCA_test_report = []
     self.KHM_test_report = []
     self.test_report = []
Esempio n. 36
0
    def __init__(self):

        pygame.init()
        pygame.display.set_caption("Battle Tank")

        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        self.clock = pygame.time.Clock()
        self.fps = self.settings.fps
        self.blocks = pygame.sprite.Group()
        self.all_objects = pygame.sprite.Group()
        self.all_tanks = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        self.bg = None
        self.player = None
Esempio n. 37
0
def main():
	"""
	Just the test
	This method is a good resource on how to handle the results.
	Save images in this method if you have to.
	"""

	filename = sys.argv[1]
	image = highgui.cvLoadImage (filename)

	cutRatios = [lib.PHI]
	#cutRatios = [0.75]
	ratios = (0.51803398874999995, 0.56803398875, 0.61803398875000004, 0.66666000000000003, 0.71803398875000002, 0.76803398874999995, 0.81803398875, 0.86803398875000004 , 0.91803398874999997, 0.96803398875000002)
	settings = Settings(cutRatios)
	image = highgui.cvLoadImage (filename)
	thickness = 4
	settings.setMarginPercentage(0.024)
	cuts = (0,1,2,3)
	cut = int(sys.argv[2])
	winname = sys.argv[3]+".png"
	#settings.setThresholds(100,150)
	# Set the color for the boxes
	#color = lib.COL_BLACK
	#color = lib.COL_WHITE
	#color = lib.COL_RED
	color = lib.COL_GREEN
	#color = lib.COL_BLUE
	tmp = 0
	for r in cuts:
		cut = r
		print str(r), '---------------------------------'
		for i in ratios:
			#settings = Settings(cutRatios)
			print i
			cutd = lib.findMeans(cv.cvGetSize(image), i)[cut]
			edgeImage = naiveMethod.getEdgeImage(image, settings)
			components = naiveMethod.analyzeCut(image, edgeImage, cutd, settings)
			print len(components)		
			tmp = tmp + len(components)
	print tmp
	blobImg = blobResult(image, settings, cut)
	boxxImg = boundingBoxResult(image, settings, cut, thickness, color)
	cutt = lib.findMeans(cv.cvGetSize(image), settings.cutRatios[0])[cut]
	# cuttet verdi, dog skal det vi generaliseres lidt
	oriantesen = cutt.getPoints()[0].x == cutt.getPoints()[1].x
	if oriantesen:
		cutPixel = cutt.getPoints()[1].x
	else:
		cutPixel = cutt.getPoints()[1].y
	
	if oriantesen:
	#	print 'hej'
		cv.cvLine(boxxImg, cv.cvPoint(cutPixel, cutt.getPoints()[0].y), cv.cvPoint(cutPixel, cutt.getPoints()[1].y), lib.COL_RED)
	else:
		cv.cvLine(boxxImg, cv.cvPoint(cutt.getPoints()[0].x, cutPixel), cv.cvPoint(cutt.getPoints()[1].x, cutPixel), lib.COL_RED)
	# Save images
	highgui.cvSaveImage('floodfillbilledet.png', blobImg)
	highgui.cvSaveImage(winname, boxxImg)

	# Show images
	compareImages(blobImg, boxxImg, "blob", winname)
Esempio n. 38
0
def main():
	"""
	Just the test
	This method is a god resource on how to handle the results
	"""

	filename = sys.argv[1]
	image = highgui.cvLoadImage (filename)

	cutRatios = [0.75]
	#cutRatios = [lib.PHI]
	settings = Settings(cutRatios)
	image = highgui.cvLoadImage (filename)
	thickness = 4
	settings.setMarginPercentage(0.025)
	cutNo = int(sys.argv[2])
	
	#udtrak af cut
	cut = lib.findMeans(cv.cvGetSize(image), settings.cutRatios[0])[cutNo]
	
	# cuttet verdi, dog skal det vi generaliseres lidt
	oriantesen = cut.getPoints()[0].x == cut.getPoints()[1].x
	
	if oriantesen:
		cutPixel = cut.getPoints()[1].x
	else:
		cutPixel = cut.getPoints()[1].y
	

	
	#Get the BW edge image
	edgeImage = expandedMethod.getEdgeImage(image, settings)

	(blobImg, comp) = expandedMethod.analyzeCut(image, edgeImage, cut, settings, 'True')
	#Liste af liste 
	
	# Find the margin
	margin = marginCalculator.getPixels(image, cut, settings.marginPercentage)

	lib.drawMargin(image, cut, margin)
	
	#Udregning af gridet
	gridPointsList = grid.gridIt(blobImg, comp)
	#hvor mange pixel der er pa den ende side i forhold til den anden, i procent
	
	pixelRatio = pixelSideCounter(gridPointsList, cutPixel, oriantesen)
	print pixelRatio
	#Udregning af center og mass
	points = centerOfMass(gridPointsList, oriantesen)
	#Draw the cut
	#print cut.getPoints()[0].y
	#print cut.getPoints()[1].y
	#print cut.getPoints()[0].x
	#print cut.getPoints()[1].x
	#print cutPixel
	
	if oriantesen:
	#	print 'hej'
		cv.cvLine(image, cv.cvPoint(cutPixel, cut.getPoints()[0].y), cv.cvPoint(cutPixel, cut.getPoints()[1].y), COL_RED)
	else:
		cv.cvLine(image, cv.cvPoint(cut.getPoints()[0].x, cutPixel), cv.cvPoint(cut.getPoints()[1].x, cutPixel), COL_RED)
	
	#Draw center of mass
	for point in points:
		if oriantesen:
	#		print 'hej'
	#		print point
			cv.cvLine(image, cv.cvPoint(point, cut.getPoints()[0].y), cv.cvPoint(point, cut.getPoints()[1].y), COL_GREEN)
		else:
	#		print point
			cv.cvLine(image, cv.cvPoint(cut.getPoints()[0].x, point), cv.cvPoint(cut.getPoints()[1].x, point), COL_GREEN)
	lib.drawBoundingBoxes(image, comp, 4, COL_GREEN)
	#highgui.cvSaveImage('floodfillbilledet.png', blobImg)
	highgui.cvSaveImage('centerOfMass.png', image)
	
	showImage(image, 'name')
 def setup(self):
     self.settings = Settings(None,'test_settings.cfg')
    def onRun(self):
        # Inputs:
        bam = self.ana.getFile('alignmentRep' + self.replicate + '.bam')
        
        # Outputs:
        strandCorr = self.declareInterimFile('strandCorr'+ self.suffix + '.txt')
        bamSample  = self.declareGarbageFile('alignment' + self.suffix + '_5M.bam')

        # Run the val script
        statsRa  = self.declareGarbageFile('stats.ra')
        if self.ana.type == 'DNase':
            tagLen = 36 # 100? TODO find this info from somewhere
            spotsRa  = self.declareGarbageFile('spots.ra')
            self.eap_dnase_stats(bam,self.ana.genome,tagLen,statsRa,strandCorr,spotsRa)
        else:
            self.eap_eval_bam(bam,bamSample,statsRa,strandCorr)
        
        
        # json summary of stats:
        if not self.ana.dryRun:
            stats = Settings(statsRa)
            for key in stats.keys():   # sorted( stats.keys() )
                if key == 'isPaired':
                    self.json[key] = stats.getBoolean(key) 
                    if stats.getBoolean(key):
                        self.ana.readType = "paired"
                    else:
                        self.ana.readType = "single"
                elif key == 'isSortedByTarget':
                    self.json[key] = stats.getBoolean(key) 
                elif key == 'readCount' or key == 'readBaseCount' or key == 'mappedCount' \
                  or key == 'uniqueMappedCount' or key == 'u4mReadCount' or key == 'u4mUniquePos' \
                  or key == 'targetBaseCount':
                    self.json[key] = long(stats.get(key))
                elif key == 'readSizeMean' or key == 'readSizeStd' or key == 'readSizeMin' \
                  or key == 'readSizeMax' or key == 'targetSeqCount':
                    self.json[key] = int(stats.get(key))
                elif key == 'u4mUniqueRatio':
                    self.json[key] = float(stats.get(key))
                else:
                    self.json[key] = stats.get(key)
        else:
            self.ana.readType = "single"
            self.json['alignedBy'        ] = 'unknown'
            self.json['isPaired'         ] = False
            self.json['isSortedByTarget' ] = True
            self.json['readCount'        ] = 0
            self.json['readBaseCount'    ] = 0
            self.json['mappedCount'      ] = 0
            self.json['uniqueMappedCount'] = 0
            self.json['readSizeMean'     ] = 50
            self.json['readSizeStd'      ] = 0
            self.json['readSizeMin'      ] = 0
            self.json['readSizeMax'      ] = 0
            self.json['u4mReadCount'     ] = 0
            self.json['u4mUniquePos'     ] = 0
            self.json['u4mUniqueRatio'   ] = 0
            self.json['targetSeqCount'   ] = 0
            self.json['targetBaseCount'  ] = 0
        
        self.json['strandCorrelation'] = {}
        if not self.ana.dryRun:
            with open(strandCorr, 'r') as strandFile:
                for line in strandFile:
                    splits = line.split('\t')
                    self.json['strandCorrelation']['Frag'] = splits[2]
                    self.json['strandCorrelation']['RSC'] = splits[8]
                    self.json['strandCorrelation']['NSC'] = splits[9]
        else:
            self.json['strandCorrelation']['Frag'] = 0
            self.json['strandCorrelation']['RSC'] = 0
            self.json['strandCorrelation']['NSC'] = 0
            
        if self.ana.type == 'DNase':
            self.json['hotspots'] = {}
            if not self.ana.dryRun:
                spots = Settings(spotsRa)
                for key in spots.keys():   # sorted( stats.keys() )
                    if key == 'spotRatio' or key == 'enrichment' or key == 'maxEnrichment' \
                    or key == 'sumSignal' or key == 'spotSumSignal':
                        self.json['hotspots'][key] = float(spots.get(key))
                    elif key == 'basesInGenome' or key == 'basesInSpots' \
                      or key == 'basesInSpotsWithSignal':
                        self.json['hotspots'][key] = long(spots.get(key))
                    else:
                        self.json['hotspots'][key] = spots.get(key)
            else:
                self.json['hotspots']['spotRatio'] = 0.1
                self.json['hotspots']['enrichment']   = 0.2
                self.json['hotspots']['maxEnrichment']   = 0.3
                self.json['hotspots']['basesInGenome']     = 4
                self.json['hotspots']['basesInSpots']         = 5
                self.json['hotspots']['basesInSpotsWithSignal']  = 6
                self.json['hotspots']['sumSignal']              = '7.654321e+08'
                self.json['hotspots']['spotSumSignal']         = '8.765432e+08'
            
        self.createAndWriteJsonFile( 'bamEvaluate'+ self.suffix, target=True )