示例#1
0
	def grab(self, id):
		databag = function.dict_object('data.json')
		studentName = databag['students'][id][0]
		studentDept = databag['students'][id][1]
		studentAvi = databag['students'][id][2]
		studentCourses = databag['students'][id][3]
		self.setWindowTitle('Registron - %s' %studentName)
		self.ui.studentName.setText(studentName)
		self.ui.studentID.setText(id)
		self.ui.studentDept.setText(studentDept)
		if len(databag['school']) > 34:
			truncated = databag['school'][:32] + '...'
			self.ui.schoolName.setText(truncated)
			self.ui.schoolName.setToolTip(databag['school'])
		else:
			self.ui.schoolName.setText(databag['school'])
		avatar = self.ui.studentAvatar
		if studentAvi == '':
			avatar.setPixmap(QtGui.QPixmap(function.resource_path('resources/images/128x128/default.jpg')))
		else:
			avatar.setPixmap(QtGui.QPixmap(function.resource_path('resources/images/128x128/%s' % studentAvi)))
		__courses__ = len(databag['departments'][studentDept])
		# Show the student's department courses
		for x, course in enumerate(databag['departments'][studentDept]):
			getattr(self.ui, 'course{}'.format(x + 1)).setText(' %s' %course)
			getattr(self.ui, 'course{}'.format(x + 1)).show()
			getattr(self.ui, 'courseCheck{}'.format(x + 1)).show()
		# check the courses offered by the student
		if studentCourses.split(':') != ['']: # check in cases of students with no registered courses
			for x, registered in enumerate(studentCourses.split(':')):
				getattr(self.ui, 'courseCheck{}'.format(registered)).setCheckState(2)
		self.show()
示例#2
0
    def __init__(self, master, **kwargs):
        super().__init__(**kwargs)
        self.master = master
        self.input_bar = self.ids.SearchFieldID
        self.input_bar.focus = True
        self.downloader_sites = [
            "manganelo", "kissmanga", "rawdevart", "senmanga"
        ]

        # Side menu
        icons = iter([
            resource_path("./DATA/manga_nelo_icon.png"),
            resource_path("./DATA/kissmanga_logo.png"),
            resource_path("./DATA/rawdevart_logo.png"),
            resource_path("./DATA/sen_manga_logo.png")
        ])
        menu_items = [{
            "height": "70dp",
            "right_content_cls": RightContentCls(site),
            "icon": next(icons),
            "text": site
        } for site in self.downloader_sites]
        self.btn = MDRaisedButton(text="Manga sites",
                                  pos_hint={
                                      "center_x": .85,
                                      "center_y": .5
                                  },
                                  on_release=lambda x: self.menu.open())
        self.menu = MDDropdownMenu(caller=self.btn,
                                   items=menu_items,
                                   width_mult=4)
        self.menu.bind(on_release=self.menu_callback)
        self.add_widget(self.btn)
示例#3
0
    def __init__(self, bbclient, config, parent=None):
        super(HistoryWidget, self).__init__(parent)

        self.bbclient = bbclient
        self.config = config

        self.track_list = []

        self.list = QListWidget(self)
        self.list.setUniformItemSizes(True)
        self.list.setSelectionMode(QListWidget.ExtendedSelection)

        self.list.currentRowChanged.connect(self._onRowChanged)


        self.delete_btn = QPushButton(QIcon(resource_path('img/delete.png')), '', self)
        self.save_btn = QPushButton(QIcon(resource_path('img/save.png')), '', self)
        self.upload_btn = QPushButton(QIcon(resource_path('img/upload.png')), '', self)

        for i, w in enumerate((self.delete_btn, self.save_btn, self.upload_btn)):
            w.setIconSize(QSize(22, 22))

            if i < 1:
                w.setMinimumSize(32, 32)
                w.setMaximumSize(32, 32)
            else:
                w.setMinimumSize(58, 32)
                w.setMaximumSize(58, 32)

        save_menu = QMenu('Export tracks', self)
        act = save_menu.addAction('Save as TCX')
        act.triggered.connect(self._onSaveAsTCX)
        act = save_menu.addAction('Save as BDX (Bryton GPX extension)')
        act.triggered.connect(self._onSaveAsBDX)

        self.save_btn.setMenu(save_menu)


        upload_menu = QMenu('Upload tracks', self)
        act = upload_menu.addAction(QIcon(resource_path('img/strava-icon.png')), 'Upload to Strava.com')
        act.triggered.connect(self._onUploadStrava)
        act = upload_menu.addAction(QIcon(resource_path('img/bryton-icon.png')), 'Upload to Brytonsport.com')
        act.triggered.connect(self._onUploadBrytonSport)


        self.upload_btn.setMenu(upload_menu)


        self.delete_btn.clicked.connect(self._onDeleteTracks)


        self._createLayout()


        self.message_overlay = MessageWidget(self)
        self.message_overlay.setLoading('Loading tracklist')


        bbclient.refreshingTrackList.connect(self.message_overlay.show)
示例#4
0
    def __init__(self, master, language, **kwargs):
        super().__init__(**kwargs)
        self.master = master
        self.effect_cls = "ScrollEffect"
        self.bar_width = "10dp"
        self.pos_hint = {"top": .9}
        self.do_scroll_y = True

        self.language_folder = self.master.japanese_manga_dir if language == "Japanese" else self.master.english_manga_dir

        self.manga_folders = [
            resource_path(str(dir))
            for dir in glob(os.path.join(self.language_folder, "*/"))
            if os.path.isdir(dir)
        ]
        self.manga_cover_imgs = [
            resource_path(str(img_path))
            for img_path in glob(os.path.join(self.language_folder, "*/*.jpg"))
            if os.path.isfile(img_path)
        ]
        self.manga_tile_data = list(
            zip(self.manga_folders, self.manga_cover_imgs))

        # This grid acts as a container for the number of manga found and the table with the clickable tiles
        self.outer_gird = MDGridLayout(rows=2,
                                       adaptive_height=True,
                                       padding=("0dp", "20dp", "0dp", "20dp"),
                                       pos_hint={"top": .8})
        self.outer_gird.add_widget(
            MDLabel(text=f"{len(self.manga_folders)} manga were found",
                    halign="center",
                    pos_hint={
                        "center_x": .5,
                        "y": .9
                    }))

        self.grid = MDStackLayout(adaptive_height=True,
                                  orientation="lr-tb",
                                  spacing=("20dp", "20dp"),
                                  padding=("5dp", "30dp", "5dp", "30dp"))

        for i in self.manga_tile_data:
            title, manga_path = os.path.basename(os.path.realpath(
                i[0])), resource_path(i[0])
            print("i: ", i, "title", title, "manga_path: ", manga_path)
            reload_func = lambda title=title, manga_path=manga_path: self.master.create_manga_reader_chapter_selection(
                title, manga_path)
            self.btn = MangaCoverTile(source=i[1],
                                      text=title,
                                      size_hint=(.25, .25),
                                      on_release=partial(
                                          kill_screen,
                                          "Manga Reader Chapter Selection",
                                          reload_func))
            self.grid.add_widget(self.btn)

        self.outer_gird.add_widget(self.grid)
        self.add_widget(self.outer_gird)
示例#5
0
 def __init__(self):
     super().__init__()
     # "In ClassicStyle and ModernStyle, using subtitles is necessary to make the header appear"
     # https://doc.qt.io/qt-5/qwizardpage.html#subTitle-prop
     self.setSubTitle(" ")
     banner = QPixmap(resource_path("wizard/banner.png"))
     self.setPixmap(QWizard.BannerPixmap, banner)
     image = QPixmap(resource_path("logo/logo.png")).scaled(QSize(banner.height() * 0.85, banner.height() * 0.85), transformMode=Qt.SmoothTransformation)
     self.setPixmap(QWizard.LogoPixmap, image)
示例#6
0
    def __init__(self):
        s1 = pygame.image.load(resource_path('data/sprites/bird1.png')).convert_alpha()
        s2 = pygame.image.load(resource_path('data/sprites/bird2.png')).convert_alpha()
        self.sprites.append(s1)
        self.sprites.append(s2)
        # self.shadows.append(make_shadow(s1, 100))
        # self.shadows.append(make_shadow(s2, 100))

        self._i = 0
        self.reset()
示例#7
0
    def __init__(self, app):
        self.sprites.append(pygame.image.load(resource_path('data/sprites/sea1.png')).convert_alpha())
        self.sprites.append(pygame.image.load(resource_path('data/sprites/sea2.png')).convert_alpha())

        self.cur_sprite = None
        self.x = -150
        self.solidsea = pygame.Surface(app.screen.get_size())
        self.solidsea.fill(Sea.c)
        self.sea_alpha = 255
        self.speed = 0
        self._i = 0
        self.state = "PASSIVE"
示例#8
0
    def __init__(self, app):
        self.app = app

        self.hud = pygame.image.load(resource_path('data/sprites/hud.png')).convert_alpha()

        self.heart = pygame.image.load(resource_path('data/sprites/heart_ico.png')).convert_alpha()
        self.heart_dead = pygame.image.load(resource_path('data/sprites/heart_dead_ico.png')).convert_alpha()

        self.bird = pygame.image.load(resource_path('data/sprites/bird_ico.png')).convert_alpha()
        self.bird_dead = pygame.image.load(resource_path('data/sprites/bird_dead_ico.png')).convert_alpha()

        self.init()
示例#9
0
    def __init__(self, name, ship, x, y, r, max_speed, rotation_speed,
                 acceleration, game_mode):
        # Get init params and load to self
        self.name = name
        self.ship = ship
        self.max_speed = max_speed
        self.rotation_speed = rotation_speed
        self.acceleration = acceleration
        self.health = constants.MAX_HEALTH

        # Player sprite lists created
        self.sprite_list = arcade.SpriteList()

        # Players sprites
        self.sprite = PlayerSprite(ship, self.max_speed)
        self.sprite.center_x = x
        self.sprite.center_y = y
        self.sprite.angle = r
        self.sprite_list.append(self.sprite)

        # is this player an AI
        if game_mode == 1:
            self.isAI = game_mode
        else:
            self.isAI = 0

        # Init emitter used to draw explosions
        self.burst_texture = utils.resource_path(
            os.path.join('data/' + ship, 'burst.png'))
        self.emitters = []

        self.sound_laser = arcade.load_sound(
            utils.resource_path(os.path.join('data/' + ship, 'laser0.wav')))
        self.sound_mine = arcade.load_sound(
            utils.resource_path(os.path.join('data/' + ship, 'mine0.wav')))
        self.sound_boom = arcade.load_sound(
            utils.resource_path(os.path.join('data/' + ship, 'boom0.wav')))

        # Mines
        self.mines = arcade.SpriteList()

        # Bullets
        # Init bullet lists for player 1 and player 2
        self.bullets = arcade.SpriteList()
        self.cooldown = 0  # Cooldown counter
        self.bullet_cooldown = constants.BULLET_COOLDOWN  # Current cooldown setting (adjusted by powerups)

        self.m_cooldown = constants.MINE_COOLDOWN  # Mine cooldown

        # Player to Player collision on flag
        self.collision_on = True
def main():
    # Ensure that all streams are redirected
    subprocess.Popen = ExtendedPopen

    if len(sys.argv) > 0:
        script_name = sys.argv[0]
        if script_name.endswith(".exe"):
            # Stop other instances
            script_name = os.path.basename(script_name)
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            try:
                subprocess.check_call(
                    ('TASKKILL /F /IM ' + script_name + ' /FI').split(" ") +
                    ["PID ne %s" % os.getpid()],
                    startupinfo=startupinfo)
            except Exception:
                pass

    set_model_id = getattr(ctypes.windll.shell32,
                           "SetCurrentProcessExplicitAppUserModelID", None)
    if callable(set_model_id):
        set_model_id('SoundRecordApplication')

    app_icon_file = utils.resource_path("app_icon.ico")
    credentials_file = utils.resource_path("credentials.json")
    if os.path.isfile(credentials_file):
        language_code = 'el-GR'  # a BCP-47 language tag
        credentials = service_account.Credentials.from_service_account_file(
            credentials_file)
        client = speech.SpeechClient(credentials=credentials)
        config = types.RecognitionConfig(
            encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
            sample_rate_hertz=RATE,
            language_code=language_code)
        streaming_config = types.StreamingRecognitionConfig(
            config=config, interim_results=True, single_utterance=False)
        client.custom_streaming_config = streaming_config
    else:
        client = None

    app = wx.App()
    frm = SpeechAssistantFrame(None,
                               title=_("Speech Assistant"),
                               client=client)
    if os.path.isfile(app_icon_file):
        frm.SetIcon(wx.Icon(app_icon_file))

    frm.Show()
    app.MainLoop()
示例#11
0
 def __init__(self, x, y, diffuculty, app):
     self.app = app
     self.sprite = pygame.image.load(resource_path("data/sprites/player.png")).convert_alpha()
     self.sprite2 = pygame.image.load(resource_path("data/sprites/player2.png")).convert_alpha()
     self.x = x
     self.y = y
     self.diffuculty = diffuculty
     self.x_vel = 0
     self.y_vel = 0
     self.angle = 0
     self._i = False
     self.safe = False
     self.reset_color()
     self.sh1 = fill_with_color(self.sprite, (10, 10, 10), 200)
     self.sh2 = fill_with_color(self.sprite2, (10, 10, 10), 200)
示例#12
0
文件: nparse.py 项目: wckdtrb/nparse
    def __init__(self, *arg: List[str]) -> None:
        super().__init__(*arg)

        # Updates
        self._toggled: bool = False
        self._log_reader: logreader.LogReader
        self._locked: bool = True

        # Load UI
        self._load_parsers()
        self._settings: SettingsWindow = SettingsWindow()

        # Tray Icon
        self._system_tray: QSystemTrayIcon = QSystemTrayIcon()
        self._system_tray.setIcon(QIcon(resource_path("data/ui/icon.png")))
        self._system_tray.setToolTip("nParse")
        self._system_tray.activated.connect(self._menu)
        self._system_tray.show()

        # Turn On
        self._toggle()

        # Version Check
        if is_new_version_available(ONLINE_VERSION, CURRENT_VERSION):
            self._system_tray.showMessage(
                "nParse Update",
                f"New version available!\ncurrent: {CURRENT_VERSION}\nonline: {ONLINE_VERSION}",
                msecs=3000,
            )
示例#13
0
def spoofy(username: str, password: str, bitrate: int, link_code: str):
    """
    Connect your Spotify account to the Spoofy bot through the CLI
    """
    librespot_path = resource_path("libraries/librespot")
    args = [
        librespot_path, "--name", SPOTIFY_CONNECT_NAME, "--username", username,
        "--password", password, "--bitrate",
        str(bitrate), "--disable-discovery", "--device-type", "speaker",
        "--backend", "pipe", "--initial-volume", "100",
        "--enable-volume-normalisation"
    ]
    process = subprocess.Popen(args=args, stdout=subprocess.PIPE)
    res = requests.get(API_BASE_URL + "connect/",
                       params={
                           "user": username,
                           "link_code": link_code
                       })
    data = res.json()
    address, port = data['address'], data['port']
    output_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    stdout_thread = Thread(target=output_worker,
                           args=[address, port, output_socket, process.stdout])
    stdout_thread.start()
    res = requests.get(API_BASE_URL + "start/",
                       params={"link_code": link_code})
示例#14
0
def enable_adb(host='127.0.0.1', port=5037):
    adb = None
    try:
        adb = Adb(host, port)

        version = adb.client.version()

        if version != 41:
            raise RuntimeError(
                'Error: require adb version 41, but version is {}'.format(
                    version))

    except RuntimeError as err:

        adb_path = resource_path(FilePaths.ADB_EXE_PATH.value)

        ret = subprocess.run(build_command(adb_path, '-P', str(port),
                                           'kill-server', host),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             encoding="utf-8")

        ret = subprocess.run(build_command(adb_path, '-P', str(port),
                                           'connect', host),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             encoding="utf-8")

        if ret.returncode != 0:
            raise RuntimeError(
                'Error: fail to start adb server. \n({})'.format(ret))

    return adb
示例#15
0
def build_database():
    import utils

    now = dtime.date2str_dmy(dtime.dtime('now'), '/')

    print("Downloading Database to : ", now)

    dates, rates = get_selic("01/07/2000", now)
    dates = dates[:-1]
    rates = rates[:-1]


    dailyfactor = lambda s: round((1+s/100.0)**(1/252.0), 8)
    factors = list(map(dailyfactor, rates))
    VNA = cumproduct(factors)
    VNA.insert(0, 1.0)
    VNA = VNA[:-1]
    VNA= [x*1000.0 for x in VNA]


    ts = Tserie(dates,
                [ rates, factors, VNA],
                headers=['rate', 'factor', 'VNA'],
                name = "Taxa SELIC")



    ts.datprovider = "Brazil Central Bank (Banco Central do Brasil)"
    ts.description = "Brazilian Daily Interest Rate Since 1/7/2000"
    ts.url = "www3.bcb.gov.br/selic/consulta/taxaSelic.do?method=listarTaxaDiaria"

    thisdir = utils.this_dir()
    datasets = utils.resource_path("datasets")

    ts.to_csv(os.path.join(thisdir, "../datasets", "selic.csv"))
示例#16
0
def main():

    app = QApplication(sys.argv)


    args = app.arguments()

    args = map(str, args)

    if platform.system() == 'Windows' and 'python' in args[0]:
        args = args[1:]

    config = parse_args(args[1:])

    if config['verbose'] > 0:
        logging.basicConfig(level=logging.DEBUG)

    win = MainWindow(config)

    win.setFixedSize(600, 400)
    win.setWindowTitle('BrytonOffline')
    win.setWindowIcon(QIcon(resource_path('img/bryton_logo.jpg')))
    win.show()

    return app.exec_()
示例#17
0
    def __init__(self):
        super(MyProgressDialog, self).__init__()

        self.__max_length = None  # 进度条最大长度
        self.__main_layout = QVBoxLayout()  # 主界面

        # 文本显示框
        self.__label = QLabel("处理中,请稍等...")
        self.__label.setAlignment(Qt.AlignCenter)

        # 进度条框
        self.__progress_bar = QProgressBar()

        """
        会话框全局设置
        """
        # 组件
        self.__main_layout.addWidget(self.__label)
        self.__main_layout.addWidget(self.__progress_bar)
        self.setLayout(self.__main_layout)

        # 背景
        palette = QPalette()
        palette.setColor(self.backgroundRole(), QColor(255, 255, 255))
        self.setPalette(palette)
        self.setAutoFillBackground(True)

        # 大小
        self.setMinimumSize(250, 50)
        self.setWindowIcon(QIcon(resource_path("icons/choice.png")))
        self.setWindowFlags(Qt.CustomizeWindowHint)
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          style=wx.BORDER_NONE & (~wx.CLOSE_BOX) &
                          (~wx.MAXIMIZE_BOX) & (~wx.RESIZE_BORDER))
        self.parent = parent
        self.cascadeClose = True
        self.ToggleWindowStyle(wx.STAY_ON_TOP)
        self.SetBackgroundColour(wx.Colour(0x000000))
        self.SetTransparent(self.ALPHA)

        app_icon_file = utils.resource_path("app_icon.ico")
        if os.path.isfile(app_icon_file):
            self.SetIcon(wx.Icon(app_icon_file))

        font = wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD)
        self.messageLabel = wx.StaticText(self,
                                          style=wx.ALIGN_CENTRE_HORIZONTAL)
        self.messageLabel.SetFont(font)
        self.messageLabel.SetForegroundColour(wx.Colour(0xFFFFFF))

        dw, dh = wx.DisplaySize()
        self.SetSize(dw / 2, 150)

        w, h = self.GetSize()
        self.SetPosition(((dw - w) / 2, (dh - h) - 50))

        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)
        self.Layout()
        self.Bind(wx.EVT_CLOSE, self.OnClose)
示例#19
0
    def __init__(self):
        super().__init__()
        self.icon = QtGui.QIcon(resource_path(resources['url_logo']))

        self.setWindowTitle('FlanaSounds')
        self.setWindowIcon(self.icon)
        self.show()
示例#20
0
 def __init__(self, beatmap_info, replays=[], events=[], library=None):
     speeds = get_setting("speed_options")
     start_speed = get_setting("default_speed")
     paint_info = get_setting("visualizer_info")
     super().__init__(beatmap_info, replays, events, library, speeds,
                      start_speed, paint_info)
     self.setWindowIcon(QIcon(resource_path("logo/logo.ico")))
示例#21
0
 def __init__(self, main_window):
     super().__init__()
     QThread.currentThread().setObjectName('tab_downloader')
     loadUi(resource_path('qt_assets/tabs/tab_download.ui'), self)
     self.main_window = main_window
     self.init_ui()
     self.show()
示例#22
0
    def __init__(self):
        super().__init__()
        self.setTitle("Tutorial (Loadables - Map)")
        label = WizardLabel(
            "<p>A Map represents one or more replays on a map's leaderboard.</p>"
        )
        image = QLabel()
        image.setPixmap(
            QPixmap(resource_path("wizard/map_empty.png")).scaledToWidth(
                500, Qt.SmoothTransformation))
        label2 = WizardLabel(
            "<p>If you wanted the top 50 replays on <a href=\"https://osu.ppy.sh/beatmapsets/79498#osu/221777\">"
            "https://osu.ppy.sh/beatmapsets/79498#osu/221777</a>, you would enter 221777 as the Map id and 1-50 "
            "as the Span (which happens to be the default).</p>"
            "<p>The \"Span\" field lets you specify which replays on the map's leaderboard to represent. For instance, if "
            "you wanted the first, tenth, 12th, and 14th through 20th replays on the leaderboard (for whatever reason), your span would "
            "be \"1,10,12,14-20\".</p>"
            "<p>As another example, if you've already checked 25 replays of a map, you may only want to represent the "
            "26-50th replays to avoid loading the first 25 replays again. In this case, your span would be 26-50.</p>"
            "<p>Note that although the default span for a Map is 1-50, the osu! api supports loading the top 100 replays of "
            "any map, so you can input a span of 1-100 if you want to check the top 100 replays of a map.</p>"
            "Mods work similarly to a Map Replay. By default (if left empty), a Map will represent the top replays based on score. "
            "If passed, the Map will represent the top replays of the mod. A Span of 1-25 and a Mods of HDDT represents the top 25 "
            "HDDT scores on the map.")

        layout = QVBoxLayout()
        layout.addWidget(label)
        layout.addWidget(image)
        layout.addWidget(label2)
        self.setLayout(layout)
示例#23
0
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Introduction")
        self.setWindowIcon(QIcon(resource_path("logo/logo.ico")))
        self.addPage(IntroPage())
        self.addPage(ApiKeyPage())
        self.addPage(TutorialPageIds())
        self.addPage(TutorialPageScreens())
        self.addPage(TutorialPageLoadables())
        self.addPage(TutorialPageLoadableLocal())
        self.addPage(TutorialPageLoadableMap())
        self.addPage(TutorialPageLoadableUser())
        self.addPage(TutorialPageLoadableUsersAll())
        self.addPage(TutorialPageChecks())
        self.addPage(TipsPage())
        self.addPage(ConclusionPage())

        # disable help button
        self.setWindowFlags(self.windowFlags() | Qt.CustomizeWindowHint)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setButtonText(QWizard.CancelButton, "Skip")
        self.setWizardStyle(QWizard.ModernStyle)

        self.setFixedSize(750, 625)  # 1.2 aspect ratio, same as gui
示例#24
0
def load_device_config():
    try:
        with open(resource_path('devices_config.json')) as f:
            config = json.load(f)
    except Exception as e:
        config = []
    return config
示例#25
0
    def __init__(self):
        super().__init__()
        self.setTitle("Loadables")
        label = WizardLabel(
            "<p>Circleguard uses five different objects (called Loadables) to represent replays. "
            "They are Map Replay, Local Replay, Map, User, and All User Replays on Map.</p>"
            "<p>A Map Replay represents a replay by a single User on a Map.</p>"
        )
        image = QLabel()
        # SmoothTransformation necessary for half decent image quality
        image.setPixmap(
            QPixmap(
                resource_path("wizard/map_replay_empty.png")).scaledToWidth(
                    500, Qt.SmoothTransformation))
        label2 = WizardLabel(
            "<p>If you wanted cookiezi's replay on Freedom Dive, you would enter 129891 "
            "as the Map id and 124493 as the User id.</p>"
            "<p>By default (when Mods is left empty), the highest scoring replay by that user will be used in a Map Replay. "
            "However, if you specify Mods, the replay with that mod combination will be used instead.</p>"
            "<p>Mods are specified using a string made up of two letter combinations — enter HDHR for Hidden Hardrock, "
            "EZ for Easy, NFDT for Nofail Doubletime, etc. The order of the mods does not matter when entering (HDHR is the same as HRHD).</p>"
        )

        layout = QVBoxLayout()
        layout.addWidget(label)
        layout.addWidget(image)
        layout.addWidget(label2)
        self.setLayout(layout)
    def get_windows_name(self):
        path, size, box, threshold, least_diff, gui = ImagePathAndProps.WINDOW_TITLE_MARK_IMG_PATH.value

        imsch = cv2.resize(
            cv2.imdecode(np.asarray(self.get_curr_device_screen_img_byte_array(), dtype=np.uint8), cv2.IMREAD_COLOR),
            size
        )
        imsrc = cv2.imread(resource_path(path))

        # find 2 window title mark location
        result = aircv.find_all_template(imsrc, imsch, threshold)

        # get box position from result
        x0, x1, y0, y1 = 0, 0, 0, 0
        if result is not None and len(result) == 2:
            x0 = result[0]['rectangle'][2][0] + 50
            x1 = result[1]['rectangle'][0][0] - 50
            y0 = result[0]['rectangle'][0][1]
            y1 = result[0]['rectangle'][1][1]
        else:
            return None
        # crop image for ocr
        title_image = imsch[y0:y1, x0:x1]
        title_image = img_remove_background_and_enhance_word(title_image, np.array([0, 0, 160]),
                                                             np.array([255, 255, 255]))
        title_image = Image.fromarray(title_image)
        return img_to_string(title_image)
示例#27
0
def get_levels():
    f = open(resource_path('levels.txt'))
    le = []
    for line in f.readlines():
        le.append(Level(*eval(line)))
    f.close()
    return le
 def find_all_image_props(self, props):
     path, size, box, threshold, least_diff, gui = props
     imsch = cv2.imdecode(np.asarray(self.get_curr_device_screen_img_byte_array(), dtype=np.uint8),
                          cv2.IMREAD_COLOR)
     imsrc = cv2.imread(resource_path(path))
     result = aircv.find_all_template(imsrc, imsch, threshold, 3, True)
     return result
示例#29
0
 def log_file(self):
     file_name = QFileDialog.getSaveFileName(self, "Save", "C:/Test Trailer Log.csv", "CSV (Comma delimited) (*.csv)")
     if file_name:
         self.ui.label_log_file.setText(file_name[0])
         self.settings["log_file"] = file_name[0]
         with open(resource_path("config/settings.json"), 'w') as f:
             json.dump(self.settings, f, indent=4)
示例#30
0
 def __init__(self, frame):
     wx.adv.TaskBarIcon.__init__(self)
     self.frame = frame
     self.icon = wx.Icon(resource_path("res/spoofy_small.png"),
                         type=wx.BITMAP_TYPE_PNG)
     self.SetIcon(self.icon, "Restore")
     self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.OnTaskBarLeftClick)
示例#31
0
    def __init__(self, replay):
        super().__init__()
        self.setWindowTitle("Raw Replay Data")
        self.setWindowIcon(QIcon(resource_path("logo/logo.ico")))

        replay_data_table = ReplayDataTable(replay)
        self.setCentralWidget(replay_data_table)
        self.resize(500, 700)
示例#32
0
    def __init__(self, result, replay):
        super().__init__()
        self.setWindowTitle("Replay Frametime")
        self.setWindowIcon(QIcon(resource_path("logo/logo.ico")))

        frametime_graph = FrametimeGraph(result, replay)
        self.setCentralWidget(frametime_graph)
        self.resize(600, 500)
示例#33
0
 def connect_to_device(self, host='127.0.0.1', port=5555):
     adb_path = resource_path(FilePaths.ADB_EXE_PATH.value)
     cmd = build_command(adb_path, 'connect', "{}:{}".format(host, port))
     ret = subprocess.check_output(cmd,
                                   shell=True,
                                   stderr=subprocess.PIPE,
                                   encoding="utf-8",
                                   timeout=2)
     return self.get_device(host, port)
示例#34
0
def load_building_pos(prefix):
    try:
        with open(resource_path(FilePaths.SAVE_FOLDER_PATH.value + "{}_building_pos.json".format(prefix)
                                )) as f:
            building_pos = json.load(f)
    except Exception as e:
        traceback.print_exc()
        building_pos = None
    return building_pos
 def __init__(self, parent=None):
     super(MainWindow, self).__init__(parent)
     self.resize(1000, 600)
     self.center()
     self.main_widget = MainWidgets()
     self.setCentralWidget(self.main_widget)
     self.create_menu_bar()
     self.setWindowTitle('Optimisateur de Galeries')
     self.setWindowIcon(QIcon(resource_path('icons/main-icon.png')))
示例#36
0
def load_bot_config(prefix):
    try:
        with open(resource_path(FilePaths.SAVE_FOLDER_PATH.value + '{}_config.json'.format(prefix))) as f:
            config_dict = json.load(f)
            config = BotConfig(config_dict)
    except Exception as e:
        traceback.print_exc()
        config = BotConfig()
    return config
示例#37
0
 def initStatusBarItem(self):
     iconPath = utils.resource_path("qsx", "png")
     self.statusMenuItemIcon = NSImage.alloc().\
         initWithContentsOfFile_(iconPath)
     self.statusItem = NSStatusBar.\
         systemStatusBar().statusItemWithLength_(20)
     self.statusItem.setMenu_(self.status_menu)
     self.statusItem.setTitle_("QSX")
     self.statusItem.setImage_(self.statusMenuItemIcon)
示例#38
0
 def get_building_name(self, box):
     x0, y0, x1, y1 = box
     title_image = self.get_curr_device_screen_img().crop(box)
     s = img_to_string(title_image)
     title_image.save(
         resource_path('{}title_x_{}_y_{}.png'.format(
             FilePaths.TEST_SRC_FOLDER_PATH.value, x0, y0)))
     bot_print("Building <{}> on position [({}, {}), ({}, {})] ".format(
         s, x0, y0, x1, y1))
示例#39
0
    def __init__(self):
        os.environ['SDL_VIDEO_CENTERED'] = '1'

        pygame.init()
        pygame.display.set_mode((App.screen_w, App.screen_h))  # , FULLSCREEN)
        pygame.display.set_caption('Camouflage')
        self.screen = pygame.display.get_surface()
        self.is_running = True  # used to trigger exit by ESC

        self.clock = pygame.time.Clock()

        self.font = pygame.font.Font(resource_path(os.path.join('data', 'fonts', 'visitor2.ttf')), 20)  # or 25?
        self.font_med = pygame.font.Font(resource_path(os.path.join('data', 'fonts', 'visitor2.ttf')), 36)
        self.font_big = pygame.font.Font(resource_path(os.path.join('data', 'fonts', 'visitor2.ttf')), 64)

        self._appstates = []
        self._appstates.append(MenuMain(self))
        self._appstates.append(MenuHelp(self))
        self._appstates.append(MenuPaused(self))
        self._appstates.append(MenuDifficulty(self))
        self._appstates.append(InGame(self))
        self._appstates.append(DeathBySea(self))
        self._appstates.append(Victory(self))
        self._appstates.append(Defeat(self))

        self.resman = ResourceManager(self)
        self.audman = AudioManager(self)

        #self.appstate = self._get_appstate("InGame")
        #self.appstate.reset()

        self.appstate = self._get_appstate("MenuMain")

        ## Main Loop
        while self.is_running:
            self.process()
        pygame.quit()  # cleanup finally
示例#40
0
import pandas as pd
import numpy as np
import utils

# row format:
# Ele.  A   Trans.  Theory (eV) Unc. (eV)   Direct (eV) Unc. (eV)   Blend  Ef
# Data source: http://physics.nist.gov/PhysRefData/XrayTrans/Html/search.html
with open(utils.resource_path('data/fluorescence.txt'), 'rb') as f:
    data = pd.read_csv(f, sep = '\t')

def emission_dict():
    """
    Returns a dict of dicts mapping element name and emission line label
    to photon energy in eV.

    The line label keys are: 'ka1', 'ka2', 'kb', and 'Ef' (Fermi energy)
    The element keys are 'Ne' through 'Fm'

    The energies used are from column 5 in fluorescence.txt. This data file
    currently contains complete data only for ka1, ka2, and kb. Ef energies
    for a few elements have been manually added.
    """
    line_dict = {}
    line_lookup = {'KL2': 'ka2', 'KL3': 'ka1', 'KM3': 'kb', 'Ef': 'Ef'}
    def process_one_row(row):
        name, line, energy = row[0], line_lookup[row[2]], row[5]
        elt_dict = line_dict.setdefault(name, {})
        elt_dict[line] = energy
    for i, row in data.iterrows():
        process_one_row(row)
    return line_dict
示例#41
0
 def setDisconnected(self, msg):
     self.spinner.hide()
     self._setIcon(resource_path('img/connect.png'))
     self.icon.show()
     self.setMessage(msg)
示例#42
0
 def setError(self, msg):
     self.spinner.hide()
     self._setIcon(resource_path('img/error.png'))
     self.icon.show()
     self.setMessage('<font color="red">'+msg+'</font>')
示例#43
0
event_snapshot = 4
event_lock = 5
event_cancel_frame = 6
event_save = 7
event_manual_id = 8
event_next_id = 9
event_previous_id = 10
event_id_digit = 11
event_click = 12
event_manual_detection = 13

statusbar_event_id = pygame.USEREVENT + 1
statusbar_display_time = 10000
statusbar_tooltip_delay = 1000

eyegrade_icon = pygame.image.load(utils.resource_path('icon.png'))
eyegrade_icon_small = pygame.image.load(utils.resource_path('icon-32x32.png'))
save_icon_normal = pygame.image.load(utils.resource_path('save.png'))
save_icon_high = pygame.image.load(utils.resource_path('save_high.png'))
next_id_icon_normal = pygame.image.load(utils.resource_path('next_id.png'))
next_id_icon_high = pygame.image.load(utils.resource_path('next_id_high.png'))
edit_id_icon_normal = pygame.image.load(utils.resource_path('edit_id.png'))
edit_id_icon_high = pygame.image.load(utils.resource_path('edit_id_high.png'))
discard_icon_normal = pygame.image.load(utils.resource_path('discard.png'))
discard_icon_high = pygame.image.load(utils.resource_path('discard_high.png'))
snapshot_icon_normal = pygame.image.load(utils.resource_path('snapshot.png'))
snapshot_icon_high = pygame.image.load(utils.resource_path('snapshot_high.png'))
manual_detect_icon_normal = \
    pygame.image.load(utils.resource_path('manual_detect.png'))
manual_detect_icon_high = \
    pygame.image.load(utils.resource_path('manual_detect_high.png'))
示例#44
0
 def __init__(self, x, y, diffuculty):
     self.r = pygame.Rect(x, y, Safehouse.a, Safehouse.a)
     self.lock = pygame.image.load(resource_path('data/sprites/lock.png')).convert_alpha()
     self.invis = pygame.image.load(resource_path('data/sprites/invisibility.png')).convert_alpha()
     self.orig_sprite = pygame.image.load(resource_path('data/sprites/safehouse.png')).convert_alpha()
     self.diffuculty = diffuculty