コード例 #1
0
    def rebuild_db(self):
        self.write()

        def bad_asset_dialog():
            dialog = QMessageBox()
            dialog.setText("No Starbound assets could be found.")
            dialog.setInformativeText(
                "The Starbound folder option might be set wrong.")
            dialog.setIcon(QMessageBox.Critical)
            dialog.exec()

        try:
            rebuild = build_assets_db(self.dialog)
        except FileNotFoundError:
            bad_asset_dialog()

        assets_db_file = Config().read("assets_db")
        starbound_folder = Config().read("starbound_folder")
        self.db = assets.Assets(assets_db_file, starbound_folder)
        total = str(self.db.total_indexed())

        if not rebuild or total == 0:
            bad_asset_dialog()
        else:
            dialog = QMessageBox()
            dialog.setText("Finished indexing Starbound assets.")
            dialog.setInformativeText("Found %s assets." % total)
            dialog.setIcon(QMessageBox.Information)
            dialog.exec()

        self.ui.total_indexed.setText(total + " indexed")
コード例 #2
0
 def test_add_or_modify_asset(self):
     """
     Test that it can sum a list of integers
     """
     assets = at.Assets()
     result = sum(assets)
     self.assertEqual(result, 6)
コード例 #3
0
    def __init__(self, main_window):
        self.dialog = QDialog(main_window.window)
        self.ui = qt_techs.Ui_Dialog()
        self.ui.setupUi(self.dialog)
        self.main_window = main_window

        starbound_folder = Config().read("starbound_folder")
        self.assets = assets.Assets(Config().read("assets_db"),
                                    starbound_folder)
        self.player = main_window.player

        self.selected_tech = None

        self.ui.tech_list.currentItemChanged.connect(self.update_selection)

        self.techs = [None, None, None, None]
        self.equip = [None, None, None, None]

        # populate equipped techs
        current = 1
        for i in self.player.get_tech_modules():
            try:
                tech_name = os.path.basename(i["modulePath"].replace(
                    ".tech", ""))
                tech = self.assets.techs().get_tech(tech_name)
                icon = QPixmap.fromImage(ImageQt(tech[1]))
                getattr(self.ui,
                        "icon" + str(current)).setPixmap(icon.scaled(32, 32))
                getattr(self.ui, "icon" + str(current)).setToolTip(
                    tech[0]["shortdescription"])
                self.techs[current - 1] = i
                self.equip[current - 1] = tech[0]["itemName"]
            except TypeError:
                logging.exception("Couldn't load tech: %s", i["modulePath"])
                pass

            current += 1

        self.ui.icon1_clear.clicked.connect(lambda: self.clear_tech(0))
        self.ui.icon2_clear.clicked.connect(lambda: self.clear_tech(1))
        self.ui.icon3_clear.clicked.connect(lambda: self.clear_tech(2))
        self.ui.icon4_clear.clicked.connect(lambda: self.clear_tech(3))

        self.ui.icon1_button.clicked.connect(lambda: self.set_tech(0))
        self.ui.icon2_button.clicked.connect(lambda: self.set_tech(1))
        self.ui.icon3_button.clicked.connect(lambda: self.set_tech(2))
        self.ui.icon4_button.clicked.connect(lambda: self.set_tech(3))

        known_recipes = [x["name"] for x in self.player.get_blueprints()]
        self.ui.tech_list.clear()
        for tech in self.assets.techs().all():
            item = QListWidgetItem(tech)
            if tech in known_recipes:
                item.setBackground(QBrush(QColor("lightBlue")))
            self.ui.tech_list.addItem(item)
コード例 #4
0
ファイル: common.py プロジェクト: Tsunder/starcheat
def preview_icon(race, gender):
    """Return an icon image for player race/gender previews."""
    assets_db_file = Config().read("assets_db")
    starbound_folder = Config().read("starbound_folder")
    db = assets.Assets(assets_db_file, starbound_folder)
    icon_file = db.species().get_preview_image(race, gender)
    if icon_file is None:
        return QPixmap.fromImage(QImage.fromData(
            db.missing_icon())).scaledToHeight(48)
    else:
        return QPixmap.fromImage(QImage.fromData(icon_file)).scaledToHeight(48)
コード例 #5
0
    def __init__(self, parent):
        self.dialog = QDialog(parent)
        self.ui = qt_mods.Ui_Dialog()
        self.ui.setupUi(self.dialog)

        starbound_folder = Config().read("starbound_folder")
        self.assets = assets.Assets(Config().read("assets_db"),
                                    starbound_folder)

        mods = self.assets.get_mods()
        self.ui.mods_total.setText(str(len(mods)) + " total")
        for mod in mods:
            self.ui.mods_list.addItem(mod)
コード例 #6
0
ファイル: game.py プロジェクト: ckaraviotis/gacharl
    def __init__(self):
        self.assets = Assets.Assets()
        self.surface = pygame.display.set_mode(
            (constants.MAP_WIDTH * self.assets.sprites.width,
             constants.MAP_HEIGHT * self.assets.sprites.height))

        # Load the sprites - called AFTER the display is initialized
        self.assets.load_sprites()

        self.level = []
        self.log = Messages.Log(self.assets.fonts['log'])
        self.create_level()
        self.clock = pygame.time.Clock()
        self.paused = False
コード例 #7
0
def loadAssets(path):
	# load asset script
	result = assets.Assets(path)
	
	# load tilemap
	tmap = tmx.TileMap(os.path.join(result.dir, 'test.tmx'))
	w,h = tmap.size

	# find collision-mask tiles
	opaque_ids = (0,)
	opaque_coords = set(
		(tile.x, tile.y)
		for layer in tmap.tilelayers 
		for tile in layer.tiles 
		if tile is not None and tile.id in opaque_ids
	)
	def is_opaque(x,y): return (x,y) in opaque_coords
	bits = [ is_opaque(x,y) for y,x in xyrange(h,w) ]
	nbytes = (len(bits)+7) // 8
	bytes = [0] * nbytes
	for i,bit in enumerate(bits):
		x = i % w
		y = i // w
		if is_opaque(x,y):
			byteIdx = i // 8
			localIdx = i - 8 * byteIdx
			bytes[byteIdx] |= (1<<localIdx)


	# find hero position
	heroObj = next( obj for obj in tmap.objects if obj.type == 'hero' )
	hx,hy = heroObj.position
	hw,hh = heroObj.size
	heroPosition = (hx + 0.5 * hw, hy + hh)
	
	# find kitten position
	kittenObj = next( obj for obj in tmap.objects if obj.type == 'kitten' )
	kx,ky = kittenObj.position
	kw,kh = kittenObj.size
	kittenPosition = (kx + 0.5 * kw, ky + kh)

	# construct world data
	result.addUserdata(
		'world',
		'ffffii#',
		heroPosition + kittenPosition + tmap.size + ('world.maskBytes',),
		assets.raw_userdata('world.maskBytes', bytes)
	)

	return result
コード例 #8
0
def build_assets_db(parent):
    assets_db_file = Config().read("assets_db")
    starbound_folder = Config().read("starbound_folder")
    assets_db = assets.Assets(assets_db_file, starbound_folder)

    missing_assets_text = """<html><body>
    <p>starcheat couldn't find any Starbound assets. You should double check:</p>
    <ol>
    <li>You selected the right Starbound folder.</li>
    <li>The assets you want to use have been unpacked. Instructions are
    <a href="https://github.com/wizzomafizzo/starcheat#unpacking-starbound-assets">here</a>
    and this includes vanilla Starbound assets.</li>
    </ol>
    <p>Once that's done, try restart starcheat to run the setup again.</p>
    </body></html>"""

    def bad_asset_dialog():
        dialog = QMessageBox()
        dialog.setText("Unable to index assets.")
        dialog.setInformativeText(missing_assets_text)
        dialog.setIcon(QMessageBox.Critical)
        dialog.exec()
        assets_db.db.close()
        os.remove(assets_db_file)

    assets_db.init_db()
    asset_files = assets_db.find_assets()
    total = 0
    progress = QProgressDialog("Indexing Starbound assets...", "Cancel", 0,
                               len(asset_files), parent)
    progress.setWindowModality(QtCore.Qt.ApplicationModal)
    progress.forceShow()

    for i in assets_db.create_index():
        total += 1
        progress.setValue(total)
        if progress.wasCanceled():
            assets_db.db.close()
            os.remove(assets_db_file)
            return False

    progress.hide()
    if total == 0:
        bad_asset_dialog()
        return False
    else:
        return True
コード例 #9
0
    def __init__(self, parent, known_blueprints, new_blueprints):
        """Blueprint library management dialog."""
        self.dialog = QDialog(parent)
        self.ui = qt_blueprints.Ui_Dialog()
        self.ui.setupUi(self.dialog)

        assets_db_file = Config().read("assets_db")
        starbound_folder = Config().read("starbound_folder")
        self.assets = assets.Assets(assets_db_file, starbound_folder)

        self.blueprints = self.assets.blueprints()
        self.known_blueprints = known_blueprints
        self.new_blueprints = new_blueprints

        # populate known list
        self.ui.known_blueprints.clear()
        for blueprint in self.known_blueprints:
            self.ui.known_blueprints.addItem(BlueprintItem(blueprint))
        self.ui.known_blueprints.sortItems(0)

        # populate initial available list
        self.ui.available_blueprints.clear()
        for blueprint in self.blueprints.get_all_blueprints():
            self.ui.available_blueprints.addItem(blueprint[4])

        # populate category combobox
        for cat in self.blueprints.get_categories():
            self.ui.category.addItem(cat)

        if len(self.new_blueprints) == 0:
            self.ui.clear_new_button.setEnabled(False)

        self.ui.add_button.clicked.connect(self.add_blueprint)
        self.ui.remove_button.clicked.connect(self.remove_blueprint)

        self.ui.filter.textChanged.connect(self.update_available_list)
        self.ui.category.currentTextChanged.connect(self.update_available_list)

        self.ui.available_blueprints.itemSelectionChanged.connect(
            self.update_blueprint_info)

        self.ui.clear_new_button.clicked.connect(self.clear_new_blueprints)

        self.ui.available_blueprints.setCurrentRow(0)
        self.ui.filter.setFocus()
        self.update_blueprint_info()
コード例 #10
0
    def __init__(self, parent, item, player, browser_category="<all>"):
        """Takes an item widget and displays an edit dialog for it."""
        self.dialog = QDialog(parent)
        self.ui = qt_itemedit.Ui_Dialog()
        self.ui.setupUi(self.dialog)

        assets_db_file = Config().read("assets_db")
        starbound_folder = Config().read("starbound_folder")
        self.assets = assets.Assets(assets_db_file, starbound_folder)

        self.player = player

        self.item_browser = None
        self.remember_browser = browser_category
        self.item = copy.deepcopy(item)

        if self.item["name"] != "":
            # set name text box
            self.ui.item_type.setText(self.item["name"])
            # set item count spinbox
            self.ui.count.setValue(int(self.item["count"]))
            # set up variant table
            self.populate_options()
            self.update_item_info(self.item["name"], self.item["data"])
        else:
            # empty slot
            self.new_item_browser()
            self.update_item()

        # set up signals
        self.ui.load_button.clicked.connect(self.new_item_browser)
        self.ui.item_type.textChanged.connect(self.update_item)
        self.ui.variant.itemDoubleClicked.connect(
            lambda: self.new_item_edit_options(False))
        self.ui.max_button.clicked.connect(self.max_count)
        self.ui.add_option_button.clicked.connect(
            lambda: self.new_item_edit_options(True))
        self.ui.remove_option_button.clicked.connect(self.remove_option)
        self.ui.edit_option_button.clicked.connect(self.edit_option)
        self.ui.export_button.clicked.connect(self.export_item)
        self.ui.import_button.clicked.connect(self.import_item)

        self.ui.item_type.setFocus()
コード例 #11
0
    def __init__(self, parent):
        self.dialog = QDialog(parent)
        self.ui = qt_options.Ui_Dialog()
        self.ui.setupUi(self.dialog)

        assets_db_file = Config().read("assets_db")
        starbound_folder = Config().read("starbound_folder")
        self.db = assets.Assets(assets_db_file, starbound_folder)

        self.config = Config()

        # read the current config and prefill everything
        self.ui.starbound_folder.setText(self.config.read("starbound_folder"))
        self.ui.total_indexed.setText(
            str(self.db.total_indexed()) + " indexed")

        self.ui.starbound_folder_button.clicked.connect(self.open_starbound)
        self.ui.rebuild_button.clicked.connect(self.rebuild_db)

        self.ui.buttonBox.accepted.connect(self.write)
コード例 #12
0
def inv_icon(item_name):
    """Return a QPixmap object of the inventory icon of a given item (if possible)."""
    assets_db_file = Config().read("assets_db")
    starbound_folder = Config().read("starbound_folder")
    db = assets.Assets(assets_db_file, starbound_folder)
    icon_file = db.items().get_item_icon(item_name)

    if icon_file == None:
        try:
            image_file = db.items().get_item_image(item_name)
            return QPixmap.fromImage(ImageQt(image_file)).scaledToHeight(64)
        except (TypeError, AttributeError):
            return QPixmap.fromImage(QImage.fromData(
                db.items().missing_icon())).scaled(32, 32)

    try:
        return QPixmap.fromImage(ImageQt(icon_file)).scaled(32, 32)
    except AttributeError:
        return QPixmap.fromImage(QImage.fromData(
            db.items().missing_icon())).scaled(32, 32)
コード例 #13
0
def build_assets_db(parent):
    assets_db_file = Config().read("assets_db")
    starbound_folder = Config().read("starbound_folder")
    assets_db = assets.Assets(assets_db_file, starbound_folder)

    def bad_asset_dialog():
        dialog = QMessageBox(parent)
        dialog.setWindowTitle("No Assets Found")
        dialog.setText("Unable to index Starbound assets.")
        dialog.setInformativeText(
            "Check that the Starbound folder was set correctly.")
        dialog.setIcon(QMessageBox.Critical)
        dialog.exec()
        assets_db.db.close()

    assets_db.init_db()
    asset_files = assets_db.find_assets()
    total = 0
    progress = QProgressDialog("Indexing Starbound assets...", "Abort", 0,
                               len(asset_files), parent)
    progress.setWindowTitle("Indexing...")
    progress.setWindowModality(QtCore.Qt.ApplicationModal)
    progress.forceShow()
    progress.setValue(total)

    for i in assets_db.create_index():
        total += 1
        progress.setValue(total)
        if progress.wasCanceled():
            assets_db.db.close()
            return False

    progress.hide()
    if total == 0:
        bad_asset_dialog()
        return False
    else:
        Config().set("pak_hash", make_pak_hash())
        return True
コード例 #14
0
    def view_note(s, column, past=0):
        """ View notes. TEMPORARY FUNCTION for very specific display. """
        title = "Last week." if past == 1 else "{} weeks ago.".format(
            past) if past else "Current week."

        current_stamps = collections.OrderedDict(
            (k, (v[0] - timestamp.WEEK * past, v[1] - timestamp.WEEK * past))
            for k, v in timestamp.week("sunday").items())

        ord_current_stamps = collections.OrderedDict(
            (k, s.rearrange(column, s.query(*v)))
            for k, v in current_stamps.items())

        curr_data = assets.Plotly(ord_current_stamps)
        curr_table = assets.Table(ord_current_stamps)

        ass = assets.Assets()
        ass.view(title=title,
                 plot1=curr_data,
                 table=curr_table,
                 comp=timestamp.datetime.datetime.now().strftime(
                     "Created on %a %m %Y %M:%S"))
コード例 #15
0
    def __init__(self, parent, known_blueprints):
        """Blueprint library management dialog."""
        # BUG: some of the tier weapons are not importing correctly and showing
        # as duplicates in the available list
        # UPDATE: okay i think that's just caused by stripping the data?
        self.dialog = QDialog(parent)
        self.ui = qt_blueprints.Ui_Dialog()
        self.ui.setupUi(self.dialog)

        assets_db_file = Config().read("assets_db")
        starbound_folder = Config().read("starbound_folder")
        self.assets = assets.Assets(assets_db_file, starbound_folder)

        self.blueprints = self.assets.blueprints()
        self.known_blueprints = known_blueprints

        # populate known list
        self.ui.known_blueprints.clear()
        for blueprint in self.known_blueprints:
            self.ui.known_blueprints.addItem(BlueprintItem(blueprint))
        self.ui.known_blueprints.sortItems(0)

        # populate initial available list
        self.ui.available_blueprints.clear()
        for blueprint in self.blueprints.get_all_blueprints():
            self.ui.available_blueprints.addItem(blueprint[4])

        # populate category combobox
        for cat in self.blueprints.get_categories():
            self.ui.category.addItem(cat)

        self.ui.add_button.clicked.connect(self.add_blueprint)
        self.ui.remove_button.clicked.connect(self.remove_blueprint)

        self.ui.filter.textChanged.connect(self.update_available_list)
        self.ui.category.currentTextChanged.connect(self.update_available_list)

        self.ui.filter.setFocus()
コード例 #16
0
def main():
    """Główna funkcja projektu. Inicjalizuje zewnętrzne biblioteki.

    Mieści się w niej główna pętla gry odpowiadająca za jej prawidłowe działanie.
    """
    # pylint: disable=no-member

    # Inicjalizacja bibliotek
    pg.init()

    # Wczytanie zasobów z dysku
    assts = assets.Assets()
    assts.load()

    # Utworzenie obiektu klasy 'Game'
    game = Game(assts)
    pg.display.set_caption(TITLE)
    pg.display.set_icon(assts.icon)
    pg.mixer.music.play(loops=-1)

    # Główna pętla gry
    while game.running:
        if game.game_over:
            game.game_start()

        # Określenie ilości klatek na sekundę
        game.CLOCK.tick(FPS)
        # Obsługa zdarzeń
        game.events()
        # Aktualizacja stanu obiektów w grze
        game.all_entities.update()
        # Obsługa kolizji obiektów
        game.collision()
        # Funkcja rysująca obiekty na ekranie
        game.draw()

    pg.quit()
コード例 #17
0
    def __init__(self, parent, just_browse=False, category="<all>"):
        """Dialog for viewing/searching indexed items and returning selection."""
        self.dialog = QDialog(parent)
        self.ui = qt_itembrowser.Ui_Dialog()
        self.ui.setupUi(self.dialog)

        assets_db_file = Config().read("assets_db")
        starbound_folder = Config().read("starbound_folder")
        self.assets = assets.Assets(assets_db_file, starbound_folder)

        self.remember_category = category

        if just_browse:
            self.ui.buttonBox.setStandardButtons(QDialogButtonBox.Close)

        self.item_browse_select = None
        self.items = self.assets.items()

        # populate category combobox
        for cat in self.items.get_categories():
            self.ui.category.addItem(cat[0])
        self.ui.category.setCurrentText(self.remember_category)

        # populate initial items list
        self.ui.items.clear()
        self.update_item_list()
        self.update_item_view()

        self.ui.items.itemSelectionChanged.connect(self.update_item_view)
        if not just_browse:
            self.ui.items.itemDoubleClicked.connect(self.dialog.accept)
        self.ui.filter.textChanged.connect(self.update_item_list)
        self.ui.category.currentTextChanged.connect(self.update_item_list)

        self.ui.items.setCurrentRow(0)
        self.ui.filter.setFocus()
コード例 #18
0
ファイル: mainwindow.py プロジェクト: Tsunder/starcheat
    def __init__(self):
        # check for new starcheat version online in seperate thread
        update_result = [None]
        update_thread = Thread(target=update_check_worker,
                               args=[update_result],
                               daemon=True)
        update_thread.start()
        """Display the main starcheat window."""
        self.app = QApplication(sys.argv)
        self.window = StarcheatMainWindow(self)
        self.ui = qt_mainwindow.Ui_MainWindow()
        self.ui.setupUi(self.window)

        logging.info("Main window init")

        self.players = None
        self.filename = None

        self.item_browser = None
        # remember the last selected item browser category
        self.remember_browser = "<all>"
        self.options_dialog = None

        # connect action menu
        self.ui.actionSave.triggered.connect(self.save)
        self.ui.actionReload.triggered.connect(self.reload)
        self.ui.actionOpen.triggered.connect(self.open_file)
        self.ui.actionQuit.triggered.connect(self.app.closeAllWindows)
        self.ui.actionOptions.triggered.connect(self.new_options_dialog)
        self.ui.actionItemBrowser.triggered.connect(self.new_item_browser)
        self.ui.actionAbout.triggered.connect(self.new_about_dialog)
        self.ui.actionExport.triggered.connect(self.export_save)
        self.ui.actionExportJSON.triggered.connect(self.export_json)
        self.ui.actionImportJSON.triggered.connect(self.import_json)
        self.ui.actionMods.triggered.connect(self.new_mods_dialog)
        self.ui.actionImageBrowser.triggered.connect(
            self.new_image_browser_dialog)

        # set up bag tables
        bags = ("wieldable", "head", "chest", "legs", "back", "main_bag",
                "action_bar", "tile_bag", "essentials", "mouse")
        for bag in bags:
            logging.debug("Setting up %s bag", bag)
            self.bag_setup(getattr(self.ui, bag), bag)

        # signals
        self.ui.blueprints_button.clicked.connect(self.new_blueprint_edit)
        self.ui.appearance_button.clicked.connect(self.new_appearance_dialog)
        self.ui.techs_button.clicked.connect(self.new_techs_dialog)

        self.ui.name.textChanged.connect(self.set_name)
        self.ui.male.clicked.connect(self.set_gender)
        self.ui.female.clicked.connect(self.set_gender)
        self.ui.description.textChanged.connect(self.set_description)
        self.ui.pixels.valueChanged.connect(self.set_pixels)

        self.ui.health.valueChanged.connect(
            lambda: self.set_stat_slider("health"))
        self.ui.energy.valueChanged.connect(
            lambda: self.set_stat_slider("energy"))
        self.ui.health_button.clicked.connect(lambda: self.max_stat("health"))
        self.ui.energy_button.clicked.connect(lambda: self.max_stat("energy"))

        self.ui.name_button.clicked.connect(self.random_name)
        self.ui.copy_uuid_button.clicked.connect(self.copy_uuid)

        self.window.setWindowModified(False)

        logging.debug("Showing main window")
        self.window.show()

        # launch first setup if we need to
        if not new_setup_dialog(self.window):
            logging.error("Config/index creation failed")
            return
        logging.info("Starbound folder: %s", Config().read("starbound_folder"))

        logging.info("Checking assets hash")
        if not check_index_valid(self.window):
            logging.error("Index creation failed")
            return

        logging.info("Loading assets database")
        self.assets = assets.Assets(Config().read("assets_db"),
                                    Config().read("starbound_folder"))
        self.items = self.assets.items()

        # populate species combobox
        for species in self.assets.species().get_species_list():
            self.ui.race.addItem(species)
        self.ui.race.currentTextChanged.connect(self.update_species)

        # populate game mode combobox
        for mode in sorted(self.assets.player().mode_types.values()):
            self.ui.game_mode.addItem(mode)
        self.ui.game_mode.currentTextChanged.connect(self.set_game_mode)

        # launch open file dialog
        self.player = None
        logging.debug("Open file dialog")
        open_player = self.open_file()
        # we *need* at least an initial save file
        if not open_player:
            logging.warning("No player file selected")
            return

        self.ui.name.setFocus()

        # block for update check result (should be ready now)
        update_thread.join()
        if update_result[0]:
            update_check_dialog(self.window, update_result[0])

        sys.exit(self.app.exec_())
コード例 #19
0
ファイル: spacerun_test.py プロジェクト: bknvpik/JS_projekt
        self.game = spacerun.Game(assts)
        self.bullet = spacerun.Bullet(assts, self.player.rect.centerx,
                                      self.player.rect.top)
        self.game.bullets.add(self.bullet)
        self.bullet.rect.bottom = -100

    def test_update(self):
        self.bullet.update()
        self.assertEqual(len(self.game.bullets), 0)


class PowerUpTest(unittest.TestCase):
    def setUp(self):
        self.game = spacerun.Game(assts)
        self.power_up = spacerun.PowerUp(assts, (400, 50))
        self.game.powerups.add(self.power_up)
        self.power_up.rect.top = 700

    def test_update(self):
        self.power_up.update()
        self.assertEqual(len(self.game.powerups), 0)


if __name__ == '__main__':
    pg.init()

    assts = assets.Assets()
    assts.load()

    unittest.main()
コード例 #20
0
print("Number of time samples: " +
      str(len(ek_data_processed[target_assets[0]])))
"""## Assets
Vengono qui caricati il RIC dell'asset e la relativa serie temporale di ritorni menili %.
```
assets.add_or_modify_asset(asset_name, ek_data_processed[asset_name])
```
Una volta caricati tutti gli asset viene calcolata la matrice di covarianza.
```
assets.compute_and_set_covariance_matrix()
```
Ogni portafoglio farà riferimento a questa entità per disporre della matrice di correlazione, che viene così calcolata una sola volta.
"""

# load data into Assets, and compute covariance matrix
assets = at.Assets()
for asset_name in target_assets:
    assets.add_or_modify_asset(asset_name, ek_data_processed[asset_name])
assets.compute_and_set_covariance_matrix()
print('Covariance Matrix')
print(assets.get_covariance_matrix())
print('Covariance Matrix shape')
print(assets.get_covariance_matrix().shape)
"""## Simulazione di N portafogli
Si creano qui 50000 portafolgi costruiti randomizzando e normalizzando i pesi del vettore `weights`. Si costruisce lo scatter plot volatilità vs rendimento atteso. Si osserva che più ampio è l'insieme degli strumenti analizzati, maggiore tende ad essere la distanza tra la frontiera efficiente ed il pool di portafogli simulati. Questo si può spiegare osservando che il vettore dei pesi viene randomizzato intorno ad un vettore medio in cui ogni componente è centrata intorno a 0.5. Il vettore efficiente, nei vari casi, presenta invece pochi valori estremi (e più specificamente: ha la maggior parte delle componenti ''piccole'' e poche componenti a valori ''grandi'').
"""

# generate 50000 random portfolios
n_weights = len(target_assets)
portfolios = list()
# np.random.seed(0) # let's make it always the same
コード例 #21
0
import assets
import torch
import pandas

print("first commit - attempt 1")

a = assets.Assets()
print(a.name, a.quantity, a.price)

boo = torch.nn()

# aa = pandas.open_csv()

x = 2 * 2 + 5
コード例 #22
0
 def __init__(self):
     pygame.mixer.init()
     self.assets = assets.Assets("./assets")
     self.sounds = dict()
     self._prepare_sounds()
コード例 #23
0
ファイル: networking.py プロジェクト: nguyenmthien/pong
if __name__ == "__main__":
    # all of these is only used for testing only.
    import time
    import pygame

    def ui_thread():
        """Thread for threading"""
        while NET.flag["is_scanning"]:
            UI.wait_for_search(ASSETS)
            pygame.event.get()

    def net_thread():
        """Thread for threading"""
        NET.scan_for_server(UI)

    ASSETS = assets.Assets()
    UI = assets.UserInterface()
    NET = Networking()
    UI_THR = threading.Thread(target=ui_thread, args=[])
    NET_THR = threading.Thread(target=net_thread, args=[])
    print(f"created threads successfully!")
    T1 = time.time()
    UI_THR.start()
    NET_THR.start()
    NET_THR.join()
    UI_THR.join()
    T2 = time.time()
    UI.choose_server(ASSETS, NET.ip_result['found'])
    print(f"Scanning time: {T2-T1} s")
    time.sleep(5)
コード例 #24
0
#!/usr/bin/python

from lputil import *
import tmx, assets, export_asset_bin, bintools

if __name__ == '__main__':
    assert len(sys.argv) >= 2
    input = sys.argv[1]
    output = 'assets.bin' if len(sys.argv) <= 2 else sys.argv[2]
    bpp = 32 if len(sys.argv) <= 3 else int(sys.argv[3])
    export_asset_bin.export_native_assets(assets.Assets(input), output, bpp)
コード例 #25
0
    def __init__(self, main_window):
        self.dialog = QDialog(main_window.window)
        self.ui = qt_appearance.Ui_Dialog()
        self.ui.setupUi(self.dialog)
        self.main_window = main_window

        assets_db_file = Config().read("assets_db")
        starbound_folder = Config().read("starbound_folder")
        self.assets = assets.Assets(assets_db_file, starbound_folder)
        self.species = self.assets.species()
        # need to think of a new approach here. player rendering on the fly
        # will not work if we also want to maintain the save/cancel functions
        # it will probably be easier to ditch that entirely across all dialogs
        self.player = main_window.player

        race = main_window.ui.race.currentText()
        self.player.set_race(race)
        self.player.set_gender(main_window.get_gender())

        # Current player stats
        race = self.player.get_race()
        gender = self.player.get_gender()
        personality = self.player.get_personality()

        self.colors = {
            "body":
            assets.read_color_directives(self.player.get_body_directives()),
            "emote":
            assets.read_color_directives(self.player.get_emote_directives()),
            "hair":
            assets.read_color_directives(self.player.get_hair_directives()),
            "facial_hair":
            assets.read_color_directives(
                self.player.get_facial_hair_directives()),
            "facial_mask":
            assets.read_color_directives(
                self.player.get_facial_mask_directives()),
            "undy":
            self.player.get_undy_color()
        }
        color_values = ("body", "emote", "hair", "facial_hair", "facial_mask")

        current_appearance = {
            "hair": self.player.get_hair(),
            "facial_hair": self.player.get_facial_hair(),
            "facial_mask": self.player.get_facial_mask()
        }
        appearance_values = ("hair", "facial_hair", "facial_mask")

        # appearance groups/types
        for value in appearance_values:
            group_data = getattr(self.species, "get_%s_groups" % value)(race,
                                                                        gender)
            type_data = getattr(self.species, "get_%s_types" % value)(
                race, gender, current_appearance[value][0])
            group_widget = getattr(self.ui, value + "_group")
            for option in group_data:
                group_widget.addItem(option)
            group_widget.setCurrentText(current_appearance[value][0])
            if len(group_data) < 2: group_widget.setEnabled(False)

            type_widget = getattr(self.ui, value + "_type")
            for option in type_data:
                type_widget.addItem(option)
            type_widget.setCurrentText(current_appearance[value][1])
            if len(type_data) < 2: type_widget.setEnabled(False)

            group_widget.currentTextChanged.connect(
                self.write_appearance_values)
            type_widget.currentTextChanged.connect(
                self.write_appearance_values)

        # personality
        for option in self.species.get_personality():
            self.ui.personality.addItem(option[0])
        self.ui.personality.setCurrentText(personality)
        self.ui.personality.currentTextChanged.connect(
            self.write_appearance_values)

        # set up color picker buttons
        for value in color_values:
            getattr(self.ui, value + "_color").clicked.connect(
                getattr(self, "new_%s_color_edit" % value))
            if len(self.colors[value]) == 0:
                getattr(self.ui, value + "_color").setEnabled(False)
            else:
                getattr(self.ui, value + "_color").setEnabled(True)

        self.ui.favorite_color.clicked.connect(self.new_undy_edit)

        # player image
        image = self.assets.species().render_player(self.player)
        pixmap = QPixmap.fromImage(ImageQt(image))
        self.ui.player_preview.setPixmap(pixmap)
コード例 #26
0
 def __init__(s, db_path):
     s.db = db.DB(db_path)
     s.assets = assets.Assets()
コード例 #27
0
    def __init__(self):
        """Display the main starcheat window."""
        self.app = QApplication(sys.argv)
        self.window = StarcheatMainWindow(self)
        self.ui = qt_mainwindow.Ui_MainWindow()
        self.ui.setupUi(self.window)

        logging.info("Main window init")

        # launch first setup if we need to
        if not new_setup_dialog(self.window):
            logging.warning("Config/index creation failed")
            return
        logging.info("Starbound folder: %s", Config().read("starbound_folder"))

        self.filename = None

        logging.debug("Loading assets database")
        self.assets = assets.Assets(Config().read("assets_db"),
                                    Config().read("starbound_folder"))

        self.items = self.assets.items()

        self.item_browser = None
        # remember the last selected item browser category
        self.remember_browser = "<all>"
        self.options_dialog = None

        # connect action menu
        self.ui.actionSave.triggered.connect(self.save)
        self.ui.actionReload.triggered.connect(self.reload)
        self.ui.actionOpen.triggered.connect(self.open_file)
        self.ui.actionQuit.triggered.connect(self.app.closeAllWindows)
        self.ui.actionOptions.triggered.connect(self.new_options_dialog)
        self.ui.actionItemBrowser.triggered.connect(self.new_item_browser)
        self.ui.actionAbout.triggered.connect(self.new_about_dialog)
        self.ui.actionExport.triggered.connect(self.export_save)
        self.ui.actionExportJSON.triggered.connect(self.export_json)
        self.ui.actionImportJSON.triggered.connect(self.import_json)
        self.ui.actionMods.triggered.connect(self.new_mods_dialog)

        # populate species combobox
        for species in self.assets.species().get_species_list():
            self.ui.race.addItem(species)

        # populate game mode combobox
        for mode in self.assets.player().mode_types.values():
            self.ui.game_mode.addItem(mode)

        # set up bag tables
        bags = "wieldable", "head", "chest", "legs", "back", "main_bag", "action_bar", "tile_bag"
        for b in bags:
            logging.debug("Setting up %s bag", b)
            item_edit = getattr(self, "new_" + b + "_item_edit")
            getattr(self.ui, b).cellDoubleClicked.connect(item_edit)
            # TODO: still issues with drag drop between tables
            getattr(self.ui, b).setDragDropMode(
                QtWidgets.QAbstractItemView.InternalMove)

        self.ui.blueprints_button.clicked.connect(self.new_blueprint_edit)
        self.ui.appearance_button.clicked.connect(self.new_appearance_dialog)
        self.ui.techs_button.clicked.connect(self.new_techs_dialog)

        self.ui.name.textChanged.connect(self.set_name)
        self.ui.race.currentTextChanged.connect(self.update_species)
        self.ui.male.clicked.connect(self.set_gender)
        self.ui.female.clicked.connect(self.set_gender)
        self.ui.description.textChanged.connect(self.set_description)
        self.ui.pixels.valueChanged.connect(self.set_pixels)
        self.ui.game_mode.currentTextChanged.connect(self.set_game_mode)
        self.ui.energy_regen.valueChanged.connect(self.set_energy_regen)

        # set up stat signals
        self.ui.health.valueChanged.connect(
            lambda: self.set_stat_slider("health"))
        self.ui.max_health.valueChanged.connect(
            lambda: self.set_stat("health"))
        self.ui.energy.valueChanged.connect(
            lambda: self.set_stat_slider("energy"))
        self.ui.max_energy.valueChanged.connect(
            lambda: self.set_stat("energy"))
        self.ui.max_food.valueChanged.connect(lambda: self.set_stat("food"))
        self.ui.max_breath.valueChanged.connect(
            lambda: self.set_stat("breath"))
        self.ui.max_warmth.valueChanged.connect(
            lambda: self.set_stat("warmth"))

        self.ui.health_button.clicked.connect(lambda: self.max_stat("health"))
        self.ui.energy_button.clicked.connect(lambda: self.max_stat("energy"))
        self.ui.food_button.clicked.connect(lambda: self.max_stat("food"))
        self.ui.breath_button.clicked.connect(lambda: self.max_stat("breath"))

        # launch open file dialog
        self.player = None
        logging.debug("Open file dialog")
        open_player = self.open_file()
        # we *need* at least an initial save file
        if not open_player:
            logging.warning("No player file selected")
            return

        self.ui.name.setFocus()
        self.window.setWindowModified(False)

        logging.debug("Showing main window")
        self.window.show()
        sys.exit(self.app.exec_())