Beispiel #1
0
def create_connection():
    host = config.get_config("database-settings", "host")
    if host is False or host is None:
        logger = Logger.get_instance()
        logger.err("Value \"host\" must not be None")
        return False
    
    user = config.get_config("database-settings", "user")
    if user is False or user is None:
        logger = Logger.get_instance()
        logger.err("Value \"user\" must not be None")
        return False
    
    password = config.get_config("database-settings", "password")
    if password is False:
        logger = Logger.get_instance()
        logger.err("Value \"password\" has not been declared in file.config")
        return False
    
    database = config.get_config("database-settings", "database")
    if database is False or database is None:
        logger = Logger.get_instance()
        logger.err("Value \"database\" must not be None")
        return False

    return DBConnection(host, user, password, database)
	def setTitle( self, name ):
		"""
		Fügt den Inhalt des Arguments zum Fenstertitel hinzu.
		"""

		titleStr = "{} {} ({})".format(Config.PROGRAM_NAME, Config.version(change=True), name )
		if not name:
			titleStr = "{} {}".format(Config.PROGRAM_NAME, Config.version(change=True) )
		self.setWindowTitle( titleStr )
Beispiel #3
0
    def setTitle(self, name):
        """
		Fügt den Inhalt des Arguments zum Fenstertitel hinzu.
		"""

        titleStr = "{} {} ({})".format(Config.PROGRAM_NAME,
                                       Config.version(change=True), name)
        if not name:
            titleStr = "{} {}".format(Config.PROGRAM_NAME,
                                      Config.version(change=True))
        self.setWindowTitle(titleStr)
	def checkXmlVersion(self, name, version, filename=None, required=False ):
		"""
		Überprüft die Version der XML-Datei. Damit ist die SoulCreator-Version gemeint.

		\param required Für den Betrieb des Programms erfordelriche Dateien sorgen dafür, daß das Programm einen entsprechend ernsten Fehler ausgibt.
		"""

		Debug.debug( "Version of file \"{name_file}\": {name} {version}".format(
			name_file=filename,
			name=name,
			version=version,
		), level=3 )

		if name == Config.PROGRAM_NAME:
			if version == Config.version():
				return
			else:
				# Unterschiede in der Minor-Version sind ignorierbar, Unterschiede in der Major-Version allerdings nicht.
				version_split = version.split(".")
				version_split = [ int(item) for item in version_split ]

				if filename is not None:
					filename = os.path.basename(filename)
				if version_split[0] < Config.PROGRAM_VERSION["major"]:
					raise Error.ErrXmlVersion(
						"XML-file \"{filename}\" was created with {program_name} {file_version} and is incompatible with {program_name} {program_version}.\nLoading of file aborted.".format(
							filename=filename,
							file_version=version,
							program_name=Config.PROGRAM_NAME,
							program_version=Config.version()
						),
						got=version,
						critical=required
					)
				else:
					raise Error.ErrXmlOldVersion(
						"XML-file \"{filename}\" was created with {program_name} {file_version} and may be compatible with {program_name} {program_version}.".format(
							filename=filename,
							file_version=version,
							program_name=Config.PROGRAM_NAME,
							program_version=Config.version()
						),
						got=version,
						critical=required
					)
		else:
			raise Error.ErrXmlVersion(
				got="{} {}".format(name, version),
				expected="{} {}".format(Config.PROGRAM_NAME, Config.version()),
				critical=required
			)
	def __calcAge(self):
		"""
		Zur Berechnung des Alters werden Geburtstag und Datum im Spiel herangezogen.
		"""

		age = Calc.years(self.dateBirth, self.dateGame)

		if self.__age != age:
			ageCtagoryChanged = False
			if Config.getAge(self.__age) != Config.getAge(age):
				ageCtagoryChanged = True
			self.__age = age
			self.ageChanged.emit(age)
			if ageCtagoryChanged:
				self.ageChanged[str].emit(Config.getAge(age))
Beispiel #6
0
    def __calcAge(self):
        """
		Zur Berechnung des Alters werden Geburtstag und Datum im Spiel herangezogen.
		"""

        age = Calc.years(self.dateBirth, self.dateGame)

        if self.__age != age:
            ageCtagoryChanged = False
            if Config.getAge(self.__age) != Config.getAge(age):
                ageCtagoryChanged = True
            self.__age = age
            self.ageChanged.emit(age)
            if ageCtagoryChanged:
                self.ageChanged[str].emit(Config.getAge(age))
Beispiel #7
0
def test_big_test(max_count_vertexes, regex):
    count_edges = random.randint(1, max_count_vertexes**2)
    I = [random.randint(0, max_count_vertexes - 1) for _ in range(count_edges)]
    J = [random.randint(0, max_count_vertexes - 1) for _ in range(count_edges)]
    V = [random.choice(['a', 'b', 'c']) for _ in range(count_edges)]
    count_vertexes = max(I + J) + 1
    max_count_input_vertexes = random.randint(1, count_vertexes)
    max_count_output_vertexes = random.randint(1, count_vertexes)
    input_vertexes = list({
        random.randint(0, count_vertexes - 1)
        for _ in range(max_count_input_vertexes)
    })
    output_vertexes = list({
        random.randint(0, count_vertexes - 1)
        for _ in range(max_count_output_vertexes)
    })
    config = Config.from_dict({
        'data_base_lists': [I, J, V],
        'regular_query_regex': regex,
        'input_vertexes': input_vertexes,
        'output_vertexes': output_vertexes
    })
    result = rpq(config)
    for V_from, _ in result:
        assert V_from in input_vertexes
    for _, V_to in result:
        assert V_to in output_vertexes
	def updateHeight(self):
		"""
		Werden der Giant-Merit oder der Dwarf-Flaw verändert, muß die Körpergröße angepaßt werden.
		"""

		giantTrait = self.__character.traits["Merit"]["Physical"]["Giant"]
		smallTrait = self.__character.traits["Flaw"]["Physical"]["Dwarf"]
		if self.__character.age < Config.AGE_ADULT:
			giantTrait = self.__character.traits["Merit"]["Physical"]["GiantKid"]
			smallTrait = self.__character.traits["Merit"]["Physical"]["Tiny"]

		ageText = Config.getAge(self.__character.age)
		if giantTrait.value > 0 and self.ui.doubleSpinBox_height.value() < Config.HEIGHT_GIANT_MIN[ageText]:
			self.ui.doubleSpinBox_height.setValue(Config.HEIGHT_GIANT_MIN[ageText])
			self.notificationSent.emit(self.tr("Height changed to {} meters".format(Config.HEIGHT_GIANT_MIN[ageText])))
		elif giantTrait.value < 1 and self.ui.doubleSpinBox_height.value() >= Config.HEIGHT_GIANT_MIN[ageText]:
			newHeight = Config.HEIGHT_GIANT_MIN[ageText] - 0.01
			self.ui.doubleSpinBox_height.setValue(newHeight)
			self.notificationSent.emit(self.tr("Height changed to {} meters".format(newHeight)))
		elif smallTrait.value > 0 and self.ui.doubleSpinBox_height.value() > Config.HEIGHT_DWARF_MAX[ageText]:
			self.ui.doubleSpinBox_height.setValue(Config.HEIGHT_DWARF_MAX[ageText])
			self.notificationSent.emit(self.tr("Height changed to {} meters".format(Config.HEIGHT_DWARF_MAX[ageText])))
		elif smallTrait.value < 1 and self.ui.doubleSpinBox_height.value() <= Config.HEIGHT_DWARF_MAX[ageText]:
			newHeight = Config.HEIGHT_DWARF_MAX[ageText] + 0.01
			self.ui.doubleSpinBox_height.setValue(newHeight)
			self.notificationSent.emit(self.tr("Height changed to {} meters".format(newHeight)))
	def warnHeightChange(self, newHeight):
		"""
		Ändert sich die Körpergröße zu sehr, sollautomatisch der Merit Giant bzw. der Flaw Dwarf vorgeschlagen werden.
		"""

		## Wird der Charkater gerade geladen, werden keine Warnungen gezeigt und automatisch davon ausgegangen, daß der Anwender sie auch akzeptieren würde.
		if self.__character.isLoading:
			return True
		else:
			smallTrait = "Dwarf Flaw"
			if self.__character.age < Config.AGE_ADULT:
				smallTrait = "Tiny Merit"

			title = self.tr("Too big")
			text = self.tr("To be this big, the character needs to purchase the Giant Merit.")
			if newHeight <= Config.HEIGHT_DWARF_MAX[Config.getAge(self.__character.age)]:
				title = self.tr("Too small")
				text = self.tr("To be this small, the character needs to get the {}.".format(smallTrait))
			ret = QMessageBox.warning(
				self,
				title,
				self.tr( "{} Do you want that to happen?".format(text) ),
				QMessageBox.Yes | QMessageBox.No
			)
			if ret == QMessageBox.StandardButton.No:
				return False
			else:
				return True
	def aboutApp(self):
		"""
		Zeigt den Informationsdialog für dieses Programm an.
		"""

		aboutText = self.tr(
			"""
			<h1>{name}</h1>
			<h2>Version: {version}</h2>
			<p>Copyright (C) {author}, 2011, 2012<br>
			EMail: {mail}</p>
			<h2>GNU General Public License</h2>
			<p>This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.</p>
			<p>This program is distributed in the hope that it will be useful, but <i>without any warranty</i>; without even the implied warranty of <i>merchantability</i> or <i>fitness for a particular purpose</i>. See the GNU General Public License for more details.</p>
			<p>You should have received a copy of the GNU General Public License along with self program. If not, see <a>http://www.gnu.org/licenses/</a>.</p>
			<h2>World of Darkness</h2>
			<p>White Wolf and its logo, World of Darkness, Changeling the Lost, Mage the Awakening, Vampire the Requiem, and Werewolf the Forsaken are registered trademarks of White Wolf Publishing, Inc. All rights reserved. All rights reserved. The mention of or reference to any company or product in this program is not a challenge to the trademark or copyright concerned. The developers of SoulCreator are in no way affiliated with or endorsed by White Wolf Publishing, Inc. SoulCreator is intended for personal and non-profit use only.</p>
			<p>The developers make no claim to own White Wolf or any of the names related to it. Some images that are displayed as part of SoulCreator are copyrighted to White Wolf Publishing, Inc or to the creator of the image (for developer-made artwork).</p>
			""".format(
				name=Config.PROGRAM_NAME,
				version=Config.version(),
				author=Config.PROGRAM_AUTHOR,
				mail=Config.PROGRAM_AUTHOR_EMAIL,
			)
		)

		QMessageBox.about(self, self.tr("About {}".format(Config.PROGRAM_NAME)), aboutText)
Beispiel #11
0
    def aboutApp(self):
        """
		Zeigt den Informationsdialog für dieses Programm an.
		"""

        aboutText = self.tr("""
			<h1>{name}</h1>
			<h2>Version: {version}</h2>
			<p>Copyright (C) {author}, 2011, 2012<br>
			EMail: {mail}</p>
			<h2>GNU General Public License</h2>
			<p>This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.</p>
			<p>This program is distributed in the hope that it will be useful, but <i>without any warranty</i>; without even the implied warranty of <i>merchantability</i> or <i>fitness for a particular purpose</i>. See the GNU General Public License for more details.</p>
			<p>You should have received a copy of the GNU General Public License along with self program. If not, see <a>http://www.gnu.org/licenses/</a>.</p>
			<h2>World of Darkness</h2>
			<p>White Wolf and its logo, World of Darkness, Changeling the Lost, Mage the Awakening, Vampire the Requiem, and Werewolf the Forsaken are registered trademarks of White Wolf Publishing, Inc. All rights reserved. All rights reserved. The mention of or reference to any company or product in this program is not a challenge to the trademark or copyright concerned. The developers of SoulCreator are in no way affiliated with or endorsed by White Wolf Publishing, Inc. SoulCreator is intended for personal and non-profit use only.</p>
			<p>The developers make no claim to own White Wolf or any of the names related to it. Some images that are displayed as part of SoulCreator are copyrighted to White Wolf Publishing, Inc or to the creator of the image (for developer-made artwork).</p>
			""".format(
            name=Config.PROGRAM_NAME,
            version=Config.version(),
            author=Config.PROGRAM_AUTHOR,
            mail=Config.PROGRAM_AUTHOR_EMAIL,
        ))

        QMessageBox.about(self,
                          self.tr("About {}".format(Config.PROGRAM_NAME)),
                          aboutText)
    def warnHeightChange(self, newHeight):
        """
		Ändert sich die Körpergröße zu sehr, sollautomatisch der Merit Giant bzw. der Flaw Dwarf vorgeschlagen werden.
		"""

        ## Wird der Charkater gerade geladen, werden keine Warnungen gezeigt und automatisch davon ausgegangen, daß der Anwender sie auch akzeptieren würde.
        if self.__character.isLoading:
            return True
        else:
            smallTrait = "Dwarf Flaw"
            if self.__character.age < Config.AGE_ADULT:
                smallTrait = "Tiny Merit"

            title = self.tr("Too big")
            text = self.tr(
                "To be this big, the character needs to purchase the Giant Merit."
            )
            if newHeight <= Config.HEIGHT_DWARF_MAX[Config.getAge(
                    self.__character.age)]:
                title = self.tr("Too small")
                text = self.tr(
                    "To be this small, the character needs to get the {}.".
                    format(smallTrait))
            ret = QMessageBox.warning(
                self, title,
                self.tr("{} Do you want that to happen?".format(text)),
                QMessageBox.Yes | QMessageBox.No)
            if ret == QMessageBox.StandardButton.No:
                return False
            else:
                return True
	def emitHideReasonChanged(self):
		#Debug.debug(Config.getAge(self._character.age), self._character.era)
		#ageStr = Config.AGES[0]
		#if self._character.age < Config.AGE_ADULT:
			#ageStr = Config.AGES[1]
		ageStr = Config.getAge(self._character.age)
		eraStr = self._character.era
		self.hideReasonChanged.emit(self._character.species, ageStr, eraStr)
Beispiel #14
0
 def emitHideReasonChanged(self):
     #Debug.debug(Config.getAge(self._character.age), self._character.era)
     #ageStr = Config.AGES[0]
     #if self._character.age < Config.AGE_ADULT:
     #ageStr = Config.AGES[1]
     ageStr = Config.getAge(self._character.age)
     eraStr = self._character.era
     self.hideReasonChanged.emit(self._character.species, ageStr, eraStr)
	def deselctTraitsWithWrongAge(self, age):
		"""
		\todo Man sollte nicht bei jedem Alterswechsel über alle Eigenschaften laufen, sondern zu Beginn des Programms alle Eigenschaften mit "Kid" bzw. "Adult" mit ageChanged verknüpfen.
		"""

		for typ in self.__traits:
			for category in self.__traits[typ]:
				for trait in self.__traits[typ][category].values():
					if type(trait) == StandardTrait and trait.age and trait.age != Config.getAge(self.age) and trait.value > 0:
						trait.value = 0
Beispiel #16
0
    def __init__(self, exp_arguments, results_path):

        self.config = Config()

        self.experiment_type = exp_arguments.experiment_type
        self.phased_training = (self.experiment_type != 'continuously_add_bad')
        self.sample_size = exp_arguments.sample_size
        self.verbose = exp_arguments.verbose
        self.results_path = results_path
        self.method = exp_arguments.method
        self.add_fake_features = exp_arguments.add_fake_features
        self.num_transitions = TRAINING_DATA_SIZE if not exp_arguments.extended_training else TRAINING_DATA_SIZE * 2
        self.baseline = exp_arguments.baseline

        " Feature Function Setup "
        self.config.state_dims = 2                                              # dimensions in mountain car
        self.config.state_lims = np.array(((-1,1), (-1,1)), dtype=np.float64)   # state bounds in mountain car
        # centers for the Radial Basis Functions
        self.config.initial_centers = np.array(((0,0),(.25,.25),(.25,-.25),(-.25,-.25),(-.25,.25)), dtype=np.float64)
        self.config.sigma = 0.5                 # width of each feature
        self.config.init_noise_mean = 0.0       # mean and variance for the
        self.config.init_noise_var = 0.01 if not self.baseline else 0.0     # noise of each feature

        " Environment Setup "
        self.config.norm_state = True       # normalized the state between -1 and 1
        self.num_actions = 3                # number of actions in the mountain car environment
        # number of observable features at the start of training
        self.config.num_obs_features = self.config.initial_centers.shape[0]
        # max_num_features should be at least num_obs_features + num_new_features
        self.config.max_num_features = self.config.num_obs_features + self.get_num_new_features()
        self.epsilon = 0.1                  # reasonable choice in mountain car
        self.gamma = 0.99                   # discount factor

        " Optimizer Setup "
        self.config.parameter_size = self.config.num_obs_features
        if self.method in ['sgd', 'rescaled_sgd']:
            self.config.alpha = BEST_PARAMETER_VALUE[self.method]
            self.config.rescale = (self.method == 'rescaled_sgd')
        elif self.method in ['adam', 'restart_adam', 'slow_adam']:
            self.config.beta1 = 0.9 if self.method in ['adam', 'restart_adam'] else 0.0
            self.config.beta2 = 0.99
            self.config.eps = 1e-08
            self.config.init_alpha = BEST_PARAMETER_VALUE[self.method]
            self.config.restart_ma = (self.method == 'restart_adam')
        elif self.method in ['idbd', 'sidbd']:
            self.config.init_beta = np.log(0.001) if self.method == 'idbd' else -np.log((1/0.001) - 1)
            self.config.theta = BEST_PARAMETER_VALUE[self.method]
        elif self.method == 'autostep':
            self.config.tau = 10000.0
            self.config.init_stepsize = 0.001
            self.config.mu = BEST_PARAMETER_VALUE[self.method]
        else:
            raise ValueError("{0} is not a valid stepsize adaptation method.".format(exp_arguments.method))
Beispiel #17
0
    def deselctTraitsWithWrongAge(self, age):
        """
		\todo Man sollte nicht bei jedem Alterswechsel über alle Eigenschaften laufen, sondern zu Beginn des Programms alle Eigenschaften mit "Kid" bzw. "Adult" mit ageChanged verknüpfen.
		"""

        for typ in self.__traits:
            for category in self.__traits[typ]:
                for trait in self.__traits[typ][category].values():
                    if type(
                            trait
                    ) == StandardTrait and trait.age and trait.age != Config.getAge(
                            self.age) and trait.value > 0:
                        trait.value = 0
Beispiel #18
0
def main(argv):
    files_dir = ''
    emi_dir = ''
    decompiler = ''
    EMI = False
    try:
        opts, args = getopt.getopt(argv, "", ["help", "EMI", "decompiler=", "files_dir=", "emi_dir="])
    except getopt.GetoptError:
        print('reproduce.py \n'
              '--decompiler <decompiler name> \n'
              '--files_dir <directory of C programs> \n'
              '--emi_dir <where to store EMI variants> \n'
              '--EMI generate EMI variants')
        sys.exit(2)
    for opt, arg in opts:
        # print(opt, arg)
        if opt == '--help':
            print('reproduce.py \n'
                  '--decompiler <decompiler name> \n'
                  '--files_dir <directory of C programs> \n'
                  '--emi_dir <where to store EMI variants> \n'
                  '--EMI generate EMI variants')
            sys.exit()
        elif opt == "--EMI":
            EMI = True
        elif opt == "--files_dir":
            files_dir = arg
        elif opt == "--emi_dir":
            emi_dir = arg
        elif opt == "--decompiler":
            decompiler = arg
    Config.set_decompiler(decompiler)
    if EMI:
        pass
        fuzzer.seed_test_AE(files_dir, emi_dir, os.path.join(files_dir, 'config.txt'))
    else:
        pass
        fuzzer.emi_test_AE(files_dir, os.path.join(files_dir, 'config.txt'))
    def __init__(self, exp_arguments, results_path, tunable_parameter_values):

        self.results_path = results_path
        self.verbose = exp_arguments.verbose
        self.tunable_parameter_values = tunable_parameter_values
        self.stepsize_method = exp_arguments.stepsize_method
        self.noisy = exp_arguments.noisy
        self.config = Config()
        """ Environment Setup """
        self.config.num_true_features = exp_arguments.num_true_features
        self.config.num_obs_features = exp_arguments.num_true_features
        self.config.max_num_features = 200  # arbitrary since it's not used
        self.training_data = exp_arguments.training_data_size
        self.checkpoint = 10
        assert self.training_data % self.checkpoint == 0
        """ Experiment Setup """
        self.sample_size = exp_arguments.sample_size
        """ Stepsize adaptation settings"""
        self.config.parameter_size = self.config.num_true_features
        if self.stepsize_method == 'idbd':
            # non-tunable parameters
            self.config.init_beta = np.log(0.001)
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = IDBD
        elif self.stepsize_method == 'sidbd':
            self.config.init_beta = -np.log(
                (1 / 0.001) -
                1)  # equivalent to starting with a stepsize of 0.001
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = SIDBD
        elif self.stepsize_method == 'adam':
            # non-tunable parameters
            self.config.beta1 = 0.9
            self.config.beta2 = 0.99
            self.config.eps = 1e-08
            self.parameter_name = 'initial_stepsize'
            self.stepsize_method_class = Adam
        elif self.stepsize_method == 'autostep':
            # non-tunable parameters
            self.config.tau = 10000.0
            self.config.init_stepsize = 0.001
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = AutoStep
        elif self.stepsize_method in ['sgd', 'rescaled_sgd']:
            # non-tunable parameters
            self.parameter_name = 'stepsize'
            self.stepsize_method_class = SGD
            self.config.rescale = (self.stepsize_method == 'rescaled_sgd')
        else:
            raise ValueError("Unrecognized stepsize adaptation method.")
Beispiel #20
0
def simple_test(test_dir: str,
                test_files: List[Tuple[str, str]],
                algo: Callable[[Config], Any],
                answer_from_json: Callable[[Any], Any]
               ) -> bool:
    args = dict()
    for file_name, arg_name in test_files:
        full_file_name = os.path.join(test_dir, file_name)
        if os.path.exists(full_file_name):
            args[arg_name] = full_file_name
    config = Config.from_args(args)
    result = algo(config)
    with open(os.path.join(test_dir, 'answer.json'), 'r') as answer_file:
        answer = answer_from_json(json.load(answer_file))
    assert result == answer
    def setCharacterHeight(self, height):
        """
		Ändert sich die Körpergröße zu sehr, sollautomatisch der Merit Giant bzw. der Flaw Dwarf vorgeschlagen werden.

		\todo Bei Kindern heißt der Dwarf-Flaw "Tiny"
		"""

        ageText = Config.getAge(self.__character.age)

        giantTrait = self.__character.traits["Merit"]["Physical"]["Giant"]
        smallTrait = self.__character.traits["Flaw"]["Physical"]["Dwarf"]
        smallAddNotification = self.tr("Added the Dwarf Flaw.")
        smallRemoveNotification = self.tr("Removed the Dwarf Flaw.")
        if self.__character.age < Config.AGE_ADULT:
            giantTrait = self.__character.traits["Merit"]["Physical"][
                "GiantKid"]
            smallTrait = self.__character.traits["Merit"]["Physical"]["Tiny"]
            smallAddNotification = self.tr("Added the Tiny Merit.")
            smallRemoveNotification = self.tr("Removed the Tiny Merit.")

        if height >= Config.HEIGHT_GIANT_MIN[ageText]:
            if giantTrait.value > 0:
                pass
            elif self.warnHeightChange(height):
                giantTrait.value = 5
                self.notificationSent.emit(self.tr("Added the Giant Merit."))
            else:
                self.ui.doubleSpinBox_height.setValue(self.__character.height)
        elif height <= Config.HEIGHT_DWARF_MAX[ageText]:
            if smallTrait.value > 0:
                pass
            elif self.warnHeightChange(height):
                smallTrait.value = 2
                self.notificationSent.emit(smallAddNotification)
            else:
                self.ui.doubleSpinBox_height.setValue(self.__character.height)
        elif giantTrait.value:
            giantTrait.value = 0
            self.notificationSent.emit(self.tr("Removed the Giant Merit."))
        elif smallTrait.value:
            smallTrait.value = 0
            self.notificationSent.emit(smallRemoveNotification)

        self.__character.height = height
	def setCharacterHeight(self, height):
		"""
		Ändert sich die Körpergröße zu sehr, sollautomatisch der Merit Giant bzw. der Flaw Dwarf vorgeschlagen werden.

		\todo Bei Kindern heißt der Dwarf-Flaw "Tiny"
		"""

		ageText = Config.getAge(self.__character.age)

		giantTrait = self.__character.traits["Merit"]["Physical"]["Giant"]
		smallTrait = self.__character.traits["Flaw"]["Physical"]["Dwarf"]
		smallAddNotification = self.tr("Added the Dwarf Flaw.")
		smallRemoveNotification = self.tr("Removed the Dwarf Flaw.")
		if self.__character.age < Config.AGE_ADULT:
			giantTrait = self.__character.traits["Merit"]["Physical"]["GiantKid"]
			smallTrait = self.__character.traits["Merit"]["Physical"]["Tiny"]
			smallAddNotification = self.tr("Added the Tiny Merit.")
			smallRemoveNotification = self.tr("Removed the Tiny Merit.")

		if height >= Config.HEIGHT_GIANT_MIN[ageText]:
			if giantTrait.value > 0:
				pass
			elif self.warnHeightChange(height):
				giantTrait.value = 5
				self.notificationSent.emit(self.tr("Added the Giant Merit."))
			else:
				self.ui.doubleSpinBox_height.setValue(self.__character.height)
		elif height <= Config.HEIGHT_DWARF_MAX[ageText]:
			if smallTrait.value > 0:
				pass
			elif self.warnHeightChange(height):
				smallTrait.value = 2
				self.notificationSent.emit(smallAddNotification)
			else:
				self.ui.doubleSpinBox_height.setValue(self.__character.height)
		elif giantTrait.value:
			giantTrait.value = 0
			self.notificationSent.emit(self.tr("Removed the Giant Merit."))
		elif smallTrait.value:
			smallTrait.value = 0
			self.notificationSent.emit(smallRemoveNotification)

		self.__character.height = height
    def updateHeight(self):
        """
		Werden der Giant-Merit oder der Dwarf-Flaw verändert, muß die Körpergröße angepaßt werden.
		"""

        giantTrait = self.__character.traits["Merit"]["Physical"]["Giant"]
        smallTrait = self.__character.traits["Flaw"]["Physical"]["Dwarf"]
        if self.__character.age < Config.AGE_ADULT:
            giantTrait = self.__character.traits["Merit"]["Physical"][
                "GiantKid"]
            smallTrait = self.__character.traits["Merit"]["Physical"]["Tiny"]

        ageText = Config.getAge(self.__character.age)
        if giantTrait.value > 0 and self.ui.doubleSpinBox_height.value(
        ) < Config.HEIGHT_GIANT_MIN[ageText]:
            self.ui.doubleSpinBox_height.setValue(
                Config.HEIGHT_GIANT_MIN[ageText])
            self.notificationSent.emit(
                self.tr("Height changed to {} meters".format(
                    Config.HEIGHT_GIANT_MIN[ageText])))
        elif giantTrait.value < 1 and self.ui.doubleSpinBox_height.value(
        ) >= Config.HEIGHT_GIANT_MIN[ageText]:
            newHeight = Config.HEIGHT_GIANT_MIN[ageText] - 0.01
            self.ui.doubleSpinBox_height.setValue(newHeight)
            self.notificationSent.emit(
                self.tr("Height changed to {} meters".format(newHeight)))
        elif smallTrait.value > 0 and self.ui.doubleSpinBox_height.value(
        ) > Config.HEIGHT_DWARF_MAX[ageText]:
            self.ui.doubleSpinBox_height.setValue(
                Config.HEIGHT_DWARF_MAX[ageText])
            self.notificationSent.emit(
                self.tr("Height changed to {} meters".format(
                    Config.HEIGHT_DWARF_MAX[ageText])))
        elif smallTrait.value < 1 and self.ui.doubleSpinBox_height.value(
        ) <= Config.HEIGHT_DWARF_MAX[ageText]:
            newHeight = Config.HEIGHT_DWARF_MAX[ageText] + 0.01
            self.ui.doubleSpinBox_height.setValue(newHeight)
            self.notificationSent.emit(
                self.tr("Height changed to {} meters".format(newHeight)))
    def __init__(self, exp_arguments, results_path):

        self.config = Config()

        self.experiment_type = exp_arguments.experiment_type
        self.sample_size = exp_arguments.sample_size
        self.verbose = exp_arguments.verbose
        self.results_path = results_path
        self.method = exp_arguments.method
        self.noisy = exp_arguments.noisy
        " Environment Setup "
        self.config.num_true_features = exp_arguments.num_true_features
        self.config.num_obs_features = exp_arguments.num_true_features - 1
        self.config.max_num_features = 250  # as long as it is more than 101

        " Optimizer Setup "
        self.config.parameter_size = self.config.num_obs_features

        if self.method in ['sgd', 'rescaled_sgd']:
            self.config.alpha = BEST_PARAMETER_VALUE[self.method]
            self.config.rescale = (self.method == 'rescaled_sgd')
        elif self.method == 'adam':
            self.config.beta1 = 0.9
            self.config.beta2 = 0.99
            self.config.eps = 1e-08
            self.config.init_alpha = BEST_PARAMETER_VALUE[self.method]
        elif self.method in ['idbd', 'sidbd']:
            self.config.init_beta = np.log(
                0.001) if self.method == 'idbd' else -np.log((1 / 0.001) - 1)
            self.config.theta = BEST_PARAMETER_VALUE[self.method]
        elif self.method == 'autostep':
            self.config.tau = 10000.0
            self.config.init_stepsize = 0.001
            self.config.mu = BEST_PARAMETER_VALUE[self.method]
        else:
            raise ValueError(
                "{0} is not a valid stepsize adaptation method.".format(
                    exp_arguments.method))
# pylint: disable-msg=C0103




if __name__ == "__main__":
	"""
	Creates the resource files for the program.
	"""

	parser = argparse.ArgumentParser(description="Creates resource and ui-files needed to run {}.".format(Config.PROGRAM_NAME))

	parser.add_argument("-v", "--verbose", action="store_true", help="Output useful information.")
	parser.add_argument("-V", "--version", action="version", version="{name}: {version}".format(
		name=sys.argv[0],
		version=Config.version(change=True)
	))

	args = parser.parse_args()

	cmd_path = Config.PATH_RESOURCE_BUILDER
	conversion_targets = {
		"qrc": {
			"dir": Config.PATH_RESOURCE,
			"ext": Config.FILEXT_RESOURCE,
		},
		"ui": {
			"dir": Config.PATH_UI,
			"ext": Config.FILEXT_UI,
		},
	}
	def buildXmlTree(self):
		"""
		Erzeugt den Element-Baum, der später in eine XML-Datei geschrieben werden kann.
		"""

		root = etree.Element(Config.PROGRAM_NAME, version=Config.version())

		etree.SubElement(root, "species").text = self.__character.species

		etree.SubElement(root, "era").text = self.__character.era

		## Identität
		identities = etree.SubElement(root, "identities")
		forenames = " ".join(self.__character.identity.forenames)
		etree.SubElement(identities, "identity",
			forenames=forenames,
			surname=self.__character.identity.surname,
			honorname=self.__character.identity.honorname,
			nickname=self.__character.identity.nickname,
			supername=self.__character.identity.supername,
			gender=self.__character.identity.gender,
		)

		## Daten
		etree.SubElement(root, "dates",
			birth=self.__character.dateBirth.toString(Config.DATE_FORMAT),
			becoming=self.__character.dateBecoming.toString(Config.DATE_FORMAT),
			game=self.__character.dateGame.toString(Config.DATE_FORMAT),
		)

		etree.SubElement(root, "virtue").text = self.__character.virtue

		etree.SubElement(root, "vice").text = self.__character.vice

		breedElement = etree.SubElement(root, "breed")
		breedElement.text = self.__character.breed
		if self.__character.bonus:
			breedElement.attrib["bonusType"] = self.__character.bonus["type"]
			breedElement.attrib["bonusName"] = self.__character.bonus["name"]
			if "specialty" in self.__character.bonus:
				breedElement.attrib["bonusSpecialty"] = self.__character.bonus["specialty"]
		if self.__character.species == "Changeling":
			breedElement.attrib["kith"] = self.__character.kith

		etree.SubElement(root, "faction").text = self.__character.faction

		etree.SubElement(root, "organisation").text = self.__character.organisation

		etree.SubElement(root, "party").text = self.__character.party

		etree.SubElement(root, "height").text = str(self.__character.height)

		etree.SubElement(root, "weight").text = str(self.__character.weight)

		etree.SubElement(root, "eyes").text = self.__character.eyes

		etree.SubElement(root, "hair").text = self.__character.hair

		etree.SubElement(root, "nationality").text = self.__character.nationality

		etree.SubElement(root, "description").text = self.__character.description

		etree.SubElement(root, "powerstat").text = str(self.__character.powerstat)

		etree.SubElement(root, "morality").text = str(self.__character.morality)

		## Geistesstörungen
		derangements = etree.SubElement(root, "derangements")
		for item in self.__character.derangements.items():
			if item[1]:
				etree.SubElement(derangements, "derangement", morality=str(item[0])).text = item[1]

		## Eigenschaften
		traits = etree.SubElement(root, "Traits")
		for item in self.__character.traits:
			traitTypeExists = False
			traitType = None
			for subitem in self.__character.traits[item]:
				traitCategoryExists = False
				traitCategory = None
				for subsubitem in self.__character.traits[item][subitem].values():
					## Eigenschaften müssen nur dann gespeichert werden, wenn ihr Wert != 0 ist und sie für die aktuell gewählte Spezies zur Verfügung stehen.
					if ( subsubitem.value != 0 and (not subsubitem.species or subsubitem.species == self.__character.species) ):
						if not traitTypeExists:
							traitType = etree.SubElement(traits, "Type", name=item)
							traitTypeExists = True
						if not traitCategoryExists:
							traitCategory = etree.SubElement(traitType, "Category", name=subitem)
							traitCategoryExists = True
						trait = etree.SubElement(traitCategory, "trait",
							name=subsubitem.name,
							value=str(subsubitem.value),
						)
						# Zusatztext
						if item != "Subpower" and subsubitem.custom:
							trait.attrib["customText"] =  str( subsubitem.customText )
						# Spezialisierungen
						if subsubitem.specialties:
							etree.SubElement(trait, "specialties").text = Config.XML_SEPARATION_SYMBOL.join( str(n) for n in subsubitem.specialties )

		## Gegenstände
		items = etree.SubElement(root, "Items")
		if self.__character.weapons:
			weapons = etree.SubElement(items, "Weapons")
			for category in self.__character.weapons:
				weaponCategory = etree.SubElement(weapons, "Category", name=category)
				for weapon in self.__character.weapons[category]:
					etree.SubElement(weaponCategory, "weapon").text = weapon
		if self.__character.armor:
			etree.SubElement(items, "armor", dedicated=str(self.__character.armor["dedicated"])).text = self.__character.armor["name"]
		if self.__character.equipment or self.__character.magicalTool:
			equipment = etree.SubElement(items, "Equipment")
			for item in self.__character.equipment:
				etree.SubElement(equipment, "equipment").text = item
			if self.__character.magicalTool:
				etree.SubElement(equipment, "magicalTool").text = self.__character.magicalTool
		if self.__character.automobiles:
			automobiles = etree.SubElement(items, "Automobiles")
			for typ in self.__character.automobiles:
				itemType = etree.SubElement(automobiles, "Type", name=typ)
				for automobile in self.__character.automobiles[typ]:
					etree.SubElement(itemType, "item").text = automobile
		if self.__character.extraordinaryItems:
			extraordinaries = etree.SubElement(items, "ExtraordinaryItems")
			for typ in self.__character.extraordinaryItems:
				itemType = etree.SubElement(extraordinaries, "Type", name=typ)
				for extraordinaryItem in self.__character.extraordinaryItems[typ]:
					etree.SubElement(itemType, "item").text = extraordinaryItem

		## Spezialseigenschaften der Spezies
		if self.__character.nimbus:
			etree.SubElement(root, "nimbus").text = self.__character.nimbus
		if self.__character.paradoxMarks:
			etree.SubElement(root, "paradoxMarks").text = self.__character.paradoxMarks
		if any((x.name and x.value > 0) for x in self.__character.vinculi):
			vinculi = etree.SubElement(root, "vinculi")
			for item in self.__character.vinculi:
				if item.name and item.value > 0:
					etree.SubElement(vinculi, "vinculum", value=str(item.value)).text = item.name
		companion = etree.SubElement(
			root,
			"companion",
			name = self.__character.companionName,
			power = str(self.__character.companionPower),
			finesse = str(self.__character.companionFinesse),
			resistance = str(self.__character.companionResistance),
			size = str(self.__character.companionSize),
			speedFactor = str(self.__character.companionSpeedFactor),
		)
		for item in self.__character.companionNumina:
			etree.SubElement(companion, "numen").text = item
		for item in self.__character.companionInfluences:
			if item.name and item.value > 0:
				etree.SubElement(companion, "influence", value=str(item.value)).text = item.name
		if self.__character.companionBan:
			etree.SubElement(companion, "ban").text = self.__character.companionBan
		

		if self.__character.picture:
			imageData = QByteArray()
			imageBuffer = QBuffer(imageData)
			imageBuffer.open(QIODevice.WriteOnly)
			self.__character.picture.save(imageBuffer, Config.CHARACTER_PIC_FORMAT)	# Schreibt das Bild in ein QByteArray im angegebenen Bildformat.
			imageData = imageData.toBase64().data()
			etree.SubElement(root, "picture").text = imageData.decode("UTF-8")

		return root
Beispiel #27
0
#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# import sys, getopt

from src import fuzzer
from src import Config

Config.set_decompiler("retdec")
# fuzzer.seed_test_AE('./seed_for_retdec/', './seed_for_retdec/emi/', './seed_for_retdec/config.txt')
# fuzzer.emi_test_AE('./seed_for_retdec/emi/', './seed_for_retdec/emi/config.txt')

Config.set_decompiler("r2")
fuzzer.seed_test_AE('./seed_for_r2/', './seed_for_r2/emi/',
                    './seed_for_r2/config.txt')
fuzzer.emi_test_AE('./seed_for_r2/emi/', './seed_for_r2/emi/config.txt')
Beispiel #28
0
        if self.is_static_image:
            success, self.static_image = self.webcam_videocapture.read()
            # BGR to RGB
            self.static_image = self.static_image[..., ::-1]
            self.static_image = self.static_image.astype(np.float)

            if not success:
                raise ValueError(f"Static image {self.video_device_path} could not be loaded!")

    def get_frame(self):
        if self.is_static_image and self.static_image:
            return self.static_image
        success, frame = self.webcam_videocapture.read()
        if not success:
            raise ValueError("Webcam failed to read image!")
        frame = frame[..., ::-1]
        frame = frame.astype(np.float)
        return frame.astype(np.uint8)

    def close(self):
        self.webcam_videocapture.release()


class WebcamOutput(Webcam):
    NotImplemented

conf = Config(config_path="config.yaml")
webcam_inp = WebcamInput(640, 480, 30, '/dev/video0', conf)
webcam_out = FakeWebcam('/dev/video2', 640, 480)
while True:
    webcam_out.schedule_frame(webcam_inp.get_frame())
Beispiel #29
0
 def __emitTraitVisibleReasonChanged(self):
     ageText = Config.getAge(self.age)
     self.traitVisibleReasonChanged.emit(self.species, ageText, self.era,
                                         self.breed, self.faction)
Beispiel #30
0
    sys.exit(0)

log_level = args.log_level
if not log_level:
    log_level = "debug" if args.verbose else "info"

log = Logging.Log(not args.no_logging, log_level, args.log_dir)
database = Database.Database(log, args.database)

if args.add_server:
    print("Adding a new server")
    utils.cli.add_server(database)
    sys.exit(0)

cache = Cache.Cache()
config = Config.Config(args.config)
events = events = EventManager.EventHook(log)
exports = exports = Exports.Exports()
timers = Timers.Timers(database, events, log)
modules = modules = ModuleManager.ModuleManager(
    events, exports, timers, config, log, os.path.join(directory, "modules"))

bot = IRCBot.Bot(directory, args, cache, config, database, events, exports,
                 log, modules, timers)

if args.module:
    module = modules.load_module(bot, args.module)
    module.module.command_line(args.module_args)
    sys.exit(0)

server_configs = bot.database.servers.get_all()
	def __emitTraitVisibleReasonChanged(self):
		ageText = Config.getAge(self.age)
		self.traitVisibleReasonChanged.emit(self.species, ageText, self.era, self.breed, self.faction)
    def __init__(self, exp_arguments, results_path, tunable_parameter_values):

        self.results_path = results_path
        self.verbose = exp_arguments.verbose
        self.tunable_parameter_values = tunable_parameter_values
        self.stepsize_method = exp_arguments.stepsize_method
        self.config = Config()
        """ Feature Function Setup """
        self.config.state_dims = 2  # number of dimension in mountain car
        self.config.state_lims = np.array(
            ((-1, 1), (-1, 1)),
            dtype=np.float64)  # state bounds in mountain car
        self.config.initial_centers = np.array(
            ((0, 0), (.25, .25), (.25, -.25), (-.25, -.25), (-.25, .25)),
            dtype=np.float64)
        self.config.sigma = 0.5
        self.config.init_noise_mean = 0.0
        self.config.init_noise_var = 0.01
        self.feature_function = RadialBasisFunction(
            self.config)  # stays constant regardless of the parameter value
        """ Environment and Policy Setup """
        self.num_actions = 3  # number of actions in mountain car
        self.config.norm_state = True
        self.config.num_obs_features = self.config.initial_centers.shape[
            0]  # number of initial centers
        self.config.max_num_features = self.config.initial_centers.shape[
            0] + 1  # arbitrary since features are fixed
        self.training_data = exp_arguments.training_data_size
        self.epsilon = 0.1  # reasonable choice in mountain car environment
        self.gamma = 0.99  # discount factor
        self.checkpoint = 5000
        assert self.training_data % self.checkpoint == 0
        """ Experiment Setup """
        self.sample_size = exp_arguments.sample_size
        """ Stepsize adaptation settings"""
        self.config.parameter_size = self.config.num_obs_features
        if self.stepsize_method == 'idbd':
            # non-tunable parameters
            self.config.init_beta = np.log(0.001)
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = IDBD
        elif self.stepsize_method == 'sidbd':
            # non-tunable parameters
            self.config.init_beta = -np.log(
                (1 / 0.001) -
                1)  # equivalent to starting with a stepsize of 0.001
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = SIDBD
        elif self.stepsize_method in ['adam', 'slow_adam']:
            # non-tunable parameters
            self.config.beta1 = 0.9 if self.stepsize_method == 'adam' else 0.0
            self.config.beta2 = 0.99
            self.config.eps = 1e-08
            self.parameter_name = 'initial_stepsize'
            self.stepsize_method_class = Adam
            self.config.restart_ma = False
        elif self.stepsize_method == 'autostep':
            # non-tunable parameters
            self.config.tau = 10000.0
            self.config.init_stepsize = 0.001
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = AutoStep
        elif self.stepsize_method in ['sgd', 'rescaled_sgd']:
            # non-tunable parameters
            self.parameter_name = 'stepsize'
            self.stepsize_method_class = SGD
            self.config.rescale = (self.stepsize_method == 'rescaled_sgd')
        else:
            raise ValueError("Unrecognized stepsize adaptation method.")
	def setHeightMinMax(self, age):
		self.ui.doubleSpinBox_height.setMinimum(Config.HEIGHT_MIN[Config.getAge(age)])
		self.ui.doubleSpinBox_height.setMaximum(Config.HEIGHT_MAX[Config.getAge(age)])
def GenerateTrajectories(seed=0, num_evaluations=1000, verbose=False):

    data_dir = os.path.join(
        os.getcwd(),
        'mountain_car_prediction_data_{0}evaluations'.format(num_evaluations))
    os.makedirs(data_dir, exist_ok=True)
    data_path = os.path.join(data_dir, 'seed' + str(seed) + '.p')

    config = Config()
    config.norm_state = True
    epsilon = 0.1
    gamma = 0.99
    num_states = 2

    print("Currently working on seed {0}...".format(seed))
    np.random.seed(seed)
    # initialize environment
    env = MountainCar(config)
    states = np.zeros((NUM_TRANSITIONS, num_states), dtype=np.float64)
    actions = np.zeros(NUM_TRANSITIONS, dtype=np.int32)
    rewards = np.zeros(NUM_TRANSITIONS, dtype=np.int8)
    terminations = np.zeros(NUM_TRANSITIONS, dtype=np.int8)

    # generate trajectory
    states[0] = env.get_current_state()
    curr_a = pumping_action(states[0])
    actions[0] = np.int32(curr_a)
    rewards[0] = np.int8(0)
    terminations[0] = np.int8(0)
    i = 1
    while i < NUM_TRANSITIONS:
        next_s, next_reward, next_term = env.step(curr_a)
        next_a = pumping_action(next_s, rprob=epsilon)

        states[i] += next_s
        actions[i] += np.int32(next_a)
        rewards[i] += np.int8(next_reward)
        terminations[i] += np.int8(next_term)

        curr_a = next_a
        i += 1

        if next_term and i < NUM_TRANSITIONS:
            env.reset()
            states[i] = env.get_current_state()
            curr_a = pumping_action(states[i])
            actions[i] = np.int32(curr_a)
            rewards[i] = np.int8(0)
            terminations[i] = np.int8(0)
            i += 1

    # compute estimated discounted returns for each state in the trajectory using monte carlo rollouts
    avg_discounted_returns = np.zeros(NUM_TRANSITIONS, dtype=np.float64)
    ste_discounted_returns = np.zeros(NUM_TRANSITIONS, dtype=np.float64)
    for j in range(NUM_TRANSITIONS):
        if terminations[j] != 1:
            avg, ste = estimate_expected_discounted_return(
                env=env,
                init_s=states[j],
                init_a=actions[j],
                epsilon=epsilon,
                gamma=gamma,
                samples=num_evaluations)
            avg_discounted_returns[j] += avg
            ste_discounted_returns[j] += ste

    if verbose:
        for j in range(NUM_TRANSITIONS):
            print(
                "Step: {0}\tState: {1}\tEstimated Return: {2}\tStandard Error {3}"
                .format(j + 1, states[j], avg_discounted_returns[j],
                        ste_discounted_returns[j]))

    trajectory_dict = {
        'states': states,
        'actions': actions,
        'rewards': rewards,
        'terminations': terminations,
        'avg_discounted_return': avg_discounted_returns,
        'ste_discounted_returns': ste_discounted_returns
    }

    with open(data_path, mode='wb') as trajectories_file:
        pickle.dump(trajectory_dict, trajectories_file)
Beispiel #35
0
	exe = [
		Executable(
			script="SoulCreator.py",
			base = _base,
			#targetDir = r"build/test",	# Verursacht Schwierigkeiten, denn die Module werden in ein anderes Verzeichnis geschoben.
			compress = True,
			#copyDependentFiles = True,
			#appendScriptToExe = False,
			#appendScriptToLibrary = False,
			icon = None,
		)
	]

	setup(
		name = Config.PROGRAM_NAME,
		version = Config.version(),
		description = Config.PROGRAM_DESCRIPTION,
		author = Config.PROGRAM_AUTHOR,
		author_email = Config.PROGRAM_AUTHOR_EMAIL,
		options = {
			"build_exe": {
				"includes": includes,
				"excludes": excludes,
				"packages": packages,
				"path": path,
				"include_files": includefiles,
			},
		},
		executables = exe
	)
Beispiel #36
0
import pickle as p
import sys
import time

import numpy as np
import tensorflow as tf

from src import Config, Model

config = Config.Configs()

config_tf = tf.ConfigProto()
config_tf.gpu_options.allow_growth = True
config_tf.inter_op_parallelism_threads = 1
config_tf.intra_op_parallelism_threads = 1

# file = sys.argv[1]
file = config.data_dir
data = open(file, 'r').read()
# data = data.decode('utf-8')
chars = list(set(data))  # char vocabulary

data_size, _vocab_size = len(data), len(chars)
print('Data has %d password strings, %d unique characters.' %
      (data_size, _vocab_size))
char_to_idx = {ch: i for i, ch in enumerate(chars)}
idx_to_char = {i: ch for i, ch in enumerate(chars)}

print(char_to_idx)
print(idx_to_char)
Beispiel #37
0
    def __init__(self, fileName=None, exportPath=None, parent=None):
        debug_timing_start = Debug.timehook()

        super(MainWindow, self).__init__(parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        QCoreApplication.setOrganizationName(Config.ORGANIZATION)
        QCoreApplication.setApplicationName(Config.PROGRAM_NAME)
        QCoreApplication.setApplicationVersion(Config.version())

        #Debug.debug(QApplication.style())

        self.setWindowTitle("")
        self.setWindowIcon(QIcon(":/icons/images/WoD.png"))

        self.__storage = StorageTemplate(self)
        self.storeTemplateData()
        self.__character = StorageCharacter(self.__storage)
        ## Später sollte ich mich für einen entscheiden!!
        self.__readCharacter = ReadXmlCharacter(self.__character)
        self.__writeCharacter = WriteXmlCharacter(self.__character)

        self.ui.pushButton_next.clicked.connect(
            self.ui.selectWidget_select.selectNext)
        self.ui.pushButton_previous.clicked.connect(
            self.ui.selectWidget_select.selectPrevious)
        self.ui.selectWidget_select.currentRowChanged.connect(
            self.ui.stackedWidget_traits.setCurrentIndex)
        self.ui.selectWidget_select.currentRowChanged.connect(
            self.setTabButtonState)
        #self.ui.selectWidget_select.currentRowChanged.connect(self.pageChanged.emit)
        self.__character.speciesChanged.connect(
            self.ui.selectWidget_select.changeIcons)

        self.__readCharacter.exception_raised.connect(
            self.showExceptionMessage)

        # Laden der Konfiguration
        self.readSettings()

        self.populateUi()

        Debug.timesince(debug_timing_start,
                        "Time neccessary to populate the UI.")

        debug_timing_between_start = Debug.timehook()

        self.activate()

        Debug.timesince(debug_timing_between_start,
                        "Time neccessary to activate the UI.")

        debug_timing_between_start = Debug.timehook()

        self.ui.selectWidget_select.currentRowChanged.connect(
            self.showCreationPoints)

        self.ui.actionSettings.triggered.connect(self.showSettingsDialog)
        self.ui.actionNew.triggered.connect(self.newCharacter)
        self.ui.actionOpen.triggered.connect(self.openCharacter)
        self.ui.actionSave.triggered.connect(self.saveCharacter)
        self.ui.actionExport.triggered.connect(self.exportCharacter)
        self.ui.actionPrint.triggered.connect(self.printCharacter)
        self.ui.actionAbout.triggered.connect(self.aboutApp)

        self.reset()
        Debug.timesince(debug_timing_between_start,
                        "Time neccessary to set all initial values.")

        debug_timing_between_start = Debug.timehook()

        ## Wird ein Dateiname angegeben, soll dieser sofort geladen werden.
        if fileName:
            if os.path.exists(fileName):
                if GlobalState.is_verbose:
                    print("Opening file {}.".format(fileName))
                self.openCharacter(fileName)
            elif fileName.lower() in [
                    species.lower()
                    for species in self.__storage.species.keys()
            ]:
                if GlobalState.is_verbose:
                    print(
                        "Empty Charactersheet of species {} will be created.".
                        format(fileName.lower()))
                self.__character.species = fileName[0].upper(
                ) + fileName[1:].lower()
                self.__character.setModified(False)
            else:
                Shell.print_warning(
                    "A file named \"{}\" does not exist.".format(fileName))

            Debug.timesince(debug_timing_between_start,
                            "Time neccessary to load a file at startup.")

        if exportPath:
            if GlobalState.is_verbose:
                print("Creating PDF {}".format(exportPath[0]))
            # exportPath ist eine Liste mit einem einzigen Element als Inhalt (argparse)
            self.__createPdf(exportPath[0])
            # Damit das Programm ordentlich geschlossen werden kann, muß auf das Starten der Event-Loop gewartet werden. dies geht am einfachsten mit einem QTimer.
            QTimer.singleShot(0, self.close)

        Debug.timesince(
            debug_timing_start,
            "The full time span neccessary to prepare the application for user input."
        )
Beispiel #38
0
class Start:
    cronjob_minute = config.get_config("settings", "cronjob-minute")
    cronjob_hour = config.get_config("settings", "cronjob-hour")
    cronjob_day = config.get_config("settings", "cronjob-day")
    subprocess.call(
        ['bash', 'cronjob.sh', cronjob_minute, cronjob_hour, cronjob_day])
Beispiel #39
0
    exe = [
        Executable(
            script="SoulCreator.py",
            base=_base,
            #targetDir = r"build/test",	# Verursacht Schwierigkeiten, denn die Module werden in ein anderes Verzeichnis geschoben.
            compress=True,
            #copyDependentFiles = True,
            #appendScriptToExe = False,
            #appendScriptToLibrary = False,
            icon=None,
        )
    ]

    setup(name=Config.PROGRAM_NAME,
          version=Config.version(),
          description=Config.PROGRAM_DESCRIPTION,
          author=Config.PROGRAM_AUTHOR,
          author_email=Config.PROGRAM_AUTHOR_EMAIL,
          options={
              "build_exe": {
                  "includes": includes,
                  "excludes": excludes,
                  "packages": packages,
                  "path": path,
                  "include_files": includefiles,
              },
          },
          executables=exe)

    sys.exit(0)
	def __init__(self, fileName=None, exportPath=None, parent=None):
		debug_timing_start = Debug.timehook()

		super(MainWindow, self).__init__(parent)

		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		QCoreApplication.setOrganizationName( Config.ORGANIZATION )
		QCoreApplication.setApplicationName( Config.PROGRAM_NAME )
		QCoreApplication.setApplicationVersion( Config.version() )

		#Debug.debug(QApplication.style())

		self.setWindowTitle( "" )
		self.setWindowIcon( QIcon( ":/icons/images/WoD.png" ) )

		self.__storage = StorageTemplate( self )
		self.storeTemplateData()
		self.__character = StorageCharacter(self.__storage)
		## Später sollte ich mich für einen entscheiden!!
		self.__readCharacter = ReadXmlCharacter(self.__character)
		self.__writeCharacter = WriteXmlCharacter(self.__character)

		self.ui.pushButton_next.clicked.connect(self.ui.selectWidget_select.selectNext)
		self.ui.pushButton_previous.clicked.connect(self.ui.selectWidget_select.selectPrevious)
		self.ui.selectWidget_select.currentRowChanged.connect(self.ui.stackedWidget_traits.setCurrentIndex)
		self.ui.selectWidget_select.currentRowChanged.connect(self.setTabButtonState)
		#self.ui.selectWidget_select.currentRowChanged.connect(self.pageChanged.emit)
		self.__character.speciesChanged.connect(self.ui.selectWidget_select.changeIcons)

		self.__readCharacter.exception_raised.connect(self.showExceptionMessage)

		# Laden der Konfiguration
		self.readSettings()

		self.populateUi()

		Debug.timesince( debug_timing_start, "Time neccessary to populate the UI." )

		debug_timing_between_start = Debug.timehook()

		self.activate()

		Debug.timesince( debug_timing_between_start, "Time neccessary to activate the UI." )

		debug_timing_between_start = Debug.timehook()

		self.ui.selectWidget_select.currentRowChanged.connect(self.showCreationPoints)

		self.ui.actionSettings.triggered.connect(self.showSettingsDialog)
		self.ui.actionNew.triggered.connect(self.newCharacter)
		self.ui.actionOpen.triggered.connect(self.openCharacter)
		self.ui.actionSave.triggered.connect(self.saveCharacter)
		self.ui.actionExport.triggered.connect(self.exportCharacter)
		self.ui.actionPrint.triggered.connect(self.printCharacter)
		self.ui.actionAbout.triggered.connect(self.aboutApp)

		self.reset()
		Debug.timesince( debug_timing_between_start, "Time neccessary to set all initial values." )

		debug_timing_between_start = Debug.timehook()

		## Wird ein Dateiname angegeben, soll dieser sofort geladen werden.
		if fileName:
			if os.path.exists(fileName):
				if GlobalState.is_verbose:
					print("Opening file {}.".format(fileName))
				self.openCharacter(fileName)
			elif fileName.lower() in [ species.lower() for species in self.__storage.species.keys() ]:
				if GlobalState.is_verbose:
					print("Empty Charactersheet of species {} will be created.".format(fileName.lower()))
				self.__character.species = fileName[0].upper() + fileName[1:].lower()
				self.__character.setModified(False)
			else:
				Shell.print_warning("A file named \"{}\" does not exist.".format(fileName))

			Debug.timesince( debug_timing_between_start, "Time neccessary to load a file at startup." )

		if exportPath:
			if GlobalState.is_verbose:
				print("Creating PDF {}".format(exportPath[0]))
			# exportPath ist eine Liste mit einem einzigen Element als Inhalt (argparse)
			self.__createPdf(exportPath[0])
			# Damit das Programm ordentlich geschlossen werden kann, muß auf das Starten der Event-Loop gewartet werden. dies geht am einfachsten mit einem QTimer.
			QTimer.singleShot(0, self.close)

		Debug.timesince( debug_timing_start, "The full time span neccessary to prepare the application for user input." )
Beispiel #41
0
    def __init__(self, exp_arguments, results_path):

        self.config = Config()

        self.experiment_type = exp_arguments.experiment_type
        self.phased_training = (self.experiment_type != 'continuously_add_bad')
        self.sample_size = exp_arguments.sample_size
        self.verbose = exp_arguments.verbose
        self.results_path = results_path
        self.method = exp_arguments.method
        self.add_fake_features = exp_arguments.add_fake_features
        self.num_transitions = TRAINING_DATA_SIZE
        self.baseline = exp_arguments.baseline

        self.data_path = os.path.join(
            os.getcwd(), 'mountain_car_prediction_data_30evaluations')
        self.init_seed = 30  # the first 30 seeds were used for parameter tuning
        # checks if there are enough data files
        assert len(os.listdir(
            self.data_path)) - self.init_seed >= self.sample_size

        " Feature Function Setup "
        self.config.state_dims = 2  # dimensions in mountain car
        self.config.state_lims = np.array(
            ((-1, 1), (-1, 1)),
            dtype=np.float64)  # state bounds in mountain car

        # centers for the Radial Basis Functions
        if self.method == 'dense_baseline':
            # 121 centers distributed evenly across the state space
            x = np.arange(-1, 1.2, 2 / 10)
            self.config.initial_centers = np.transpose(
                [np.tile(x, len(x)), np.repeat(x, len(x))])
        else:
            # 5 centers distributed evenly around (0,0)
            self.config.initial_centers = np.array(
                ((0, 0), (.25, .25), (.25, -.25), (-.25, -.25), (-.25, .25)),
                dtype=np.float64)

        self.config.sigma = 0.5  # width of each feature
        self.config.init_noise_mean = 0.0  # mean of the noise of each features
        if self.baseline or (self.method == 'dense_baseline'
                             ):  # variance of the noise of each feature
            self.config.init_noise_var = 0.0
        else:
            self.config.init_noise_var = 0.01

        " Environment Setup "
        self.num_actions = 3  # number of actions in the mountain car environment
        # number of observable features at the start of training
        self.config.num_obs_features = self.config.initial_centers.shape[0]
        # max_num_features should be at least num_obs_features + num_new_features
        self.config.max_num_features = self.config.num_obs_features + self.get_num_new_features(
        )
        self.gamma = 0.99  # discount factor

        " Optimizer Setup "
        self.config.parameter_size = self.config.num_obs_features
        if self.method in ['sgd', 'rescaled_sgd', 'dense_baseline']:
            self.config.alpha = BEST_PARAMETER_VALUE[self.method]
            self.config.rescale = (self.method == 'rescaled_sgd')
        elif self.method in [
                'keep_adam', 'reset_adam', 'keep_slow_adam', 'reset_slow_adam'
        ]:
            self.config.beta1 = 0.9 if self.method in [
                'keep_adam',
                'reset_adam',
            ] else 0.0
            self.config.beta2 = 0.99
            self.config.eps = 1e-08
            self.config.init_alpha = BEST_PARAMETER_VALUE[self.method]
            self.config.increase_setting = self.method.split('_')[0]
        elif self.method in [
                'keep_idbd', 'reset_idbd', 'max_idbd', 'keep_sidbd',
                'reset_sidbd', 'max_sidbd'
        ]:
            self.config.init_beta = np.log(
                0.001) if self.method == 'idbd' else -np.log((1 / 0.001) - 1)
            self.config.theta = BEST_PARAMETER_VALUE[self.method]
            self.config.increase_setting = self.method.split('_')[0]
        elif self.method in [
                'keep_autostep', 'reset_autostep', 'max_autostep'
        ]:
            self.config.tau = 10000.0
            self.config.init_stepsize = 0.001
            self.config.mu = BEST_PARAMETER_VALUE[self.method]
            self.config.increase_setting = self.method.split('_')[0]
        else:
            raise ValueError(
                "{0} is not a valid stepsize adaptation method.".format(
                    exp_arguments.method))
    ## Development. Some tasks are automatic, that normally the user would have to undertake, like choosing a file name for saving characters and other stuff. Very dangerous for normal work.
    parser.add_argument("--develop",
                        action="store_true",
                        help=argparse.SUPPRESS)
    parser.add_argument("--fallback",
                        action="store_true",
                        help=argparse.SUPPRESS)
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="Output useful information.")
    parser.add_argument("-V",
                        "--version",
                        action="version",
                        version="{name}: {version}".format(
                            name=sys.argv[0], version=Config.version()))
    parser.add_argument(
        dest="file",
        metavar="File/Species",
        nargs="?",
        help=
        "Opens the character from this file at start. Instead of a file, the name of a supported species (human, changeling, mage, vampire, werewolf) may be entered, to create an empty character of the specified species, if no file of that specific name exists. This is most useful in combination with the -p option."
    )

    args = parser.parse_args()

    ## Hauptprogramm starten
    main(sys.argv,
         file=args.file,
         pdf=args.pdf,
         verbose=args.verbose,
Beispiel #43
0
    def __init__(self, exp_arguments, results_path, tunable_parameter_values):

        self.results_path = results_path
        self.verbose = exp_arguments.verbose
        self.tunable_parameter_values = tunable_parameter_values
        self.stepsize_method = exp_arguments.stepsize_method
        self.sample_size = exp_arguments.sample_size
        self.num_transitions = 200000
        self.checkpoint = 1000
        self.dense = exp_arguments.dense
        self.config = Config()

        self.data_path = os.path.join(
            os.getcwd(), 'mountain_car_prediction_data_30evaluations')
        assert len(os.listdir(self.data_path)) >= self.sample_size
        """ Feature Function Setup """
        self.config.state_dims = 2  # number of dimension in mountain car
        self.config.state_lims = np.array(
            ((-1, 1), (-1, 1)),
            dtype=np.float64)  # state bounds in mountain car
        if self.dense:
            x = np.arange(-1, 1.2, 2 / 10)
            self.config.initial_centers = np.transpose(
                [np.tile(x, len(x)), np.repeat(x, len(x))])
        else:
            self.config.initial_centers = np.array(
                ((0, 0), (.25, .25), (.25, -.25), (-.25, -.25), (-.25, .25)),
                dtype=np.float64)
        self.config.sigma = 0.5
        self.config.init_noise_mean = 0.0
        self.config.init_noise_var = 0.01 if not self.dense else 0.0
        self.feature_function = RadialBasisFunction(
            self.config)  # stays constant regardless of the parameter value
        """ Environment and Policy Setup """
        self.num_actions = 3  # number of actions in mountain car
        self.config.num_obs_features = self.config.initial_centers.shape[
            0]  # number of initial centers
        self.config.max_num_features = self.config.initial_centers.shape[
            0] + 1  # arbitrary since features are fixed
        self.gamma = 0.99  # discount factor
        """ Stepsize adaptation settings"""
        self.config.parameter_size = self.config.num_obs_features
        if self.stepsize_method == 'idbd':
            # non-tunable parameters
            self.config.init_beta = np.log(0.001)
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = IDBD
        elif self.stepsize_method == 'sidbd':
            # non-tunable parameters
            self.config.init_beta = -np.log(
                (1 / 0.001) -
                1)  # equivalent to starting with a stepsize of 0.001
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = SIDBD
            self.increase_setting = 'reset'  # not used since no new features are added during tuning
        elif self.stepsize_method in ['adam', 'slow_adam']:
            # non-tunable parameters
            self.config.beta1 = 0.9 if self.stepsize_method == 'adam' else 0.0
            self.config.beta2 = 0.99
            self.config.eps = 1e-08
            self.parameter_name = 'initial_stepsize'
            self.stepsize_method_class = Adam
            self.config.restart_ma = False
        elif self.stepsize_method == 'autostep':
            # non-tunable parameters
            self.config.tau = 10000.0
            self.config.init_stepsize = 0.001
            self.parameter_name = 'meta_stepsize'
            self.stepsize_method_class = AutoStep
        elif self.stepsize_method in ['sgd', 'rescaled_sgd']:
            # non-tunable parameters
            self.parameter_name = 'stepsize'
            self.stepsize_method_class = SGD
            self.config.rescale = (self.stepsize_method == 'rescaled_sgd')
        else:
            raise ValueError("Unrecognized stepsize adaptation method.")
 def setHeightMinMax(self, age):
     self.ui.doubleSpinBox_height.setMinimum(
         Config.HEIGHT_MIN[Config.getAge(age)])
     self.ui.doubleSpinBox_height.setMaximum(
         Config.HEIGHT_MAX[Config.getAge(age)])
	signal.signal(signal.SIGINT, signal.SIG_DFL)

	parser = argparse.ArgumentParser(description=Config.PROGRAM_DESCRIPTION)

	#parser.add_argument("-o", "--onepage", action="store_true", help="Charactersheets will consist of one page only. (Momentan noch ohne Funktion.)")
	parser.add_argument("-p", "--pdf", metavar="Name", nargs=1, help="Directly creates a pdf file of the specified name out of the loaded character and closes immediatly. If no character file is passed as an argument to this program, an empty character sheet will be created.")
	# Als Argument kann der Name oder die Nummer des Debug-levels eingegeben werden. Bei der Liste der erlaubten Möglichkeiten wird der Name immer nach der zugehörigen Nummer eingefügt.
	__choices_debug_level = []
	for item in range( len( Config.DEBUG_LEVELS ) ):
		__choices_debug_level.append( str(item) )
		__choices_debug_level.append( Config.DEBUG_LEVELS[item] )
	parser.add_argument("--debug", nargs="?", choices=__choices_debug_level, const=Config.DEBUG_LEVELS[Config.DEBUG_LEVEL_STD], default="0", help="Give debug information. {level_index_none} ({level_name_none}) means, that no debug information will be printed (standard behaviour). {level_index_normal} ({level_name_normal}) is the normal behaviour, if the option string is present, but no argument given. Debug from {level_index_mod} ({level_name_mod}) and above are not recommended for printing and/or exporting character sheets.".format(
		level_index_none=Config.DEBUG_LEVEL_NONE,
		level_name_none=Config.DEBUG_LEVELS[Config.DEBUG_LEVEL_NONE],
		level_index_normal=Config.DEBUG_LEVEL_STD,
		level_name_normal=Config.DEBUG_LEVELS[Config.DEBUG_LEVEL_STD],
		level_index_mod=Config.DEBUG_LEVEL_MODIFIES_EXPORTS,
		level_name_mod=Config.DEBUG_LEVELS[Config.DEBUG_LEVEL_MODIFIES_EXPORTS],
	) )
	## Development. Some tasks are automatic, that normally the user would have to undertake, like choosing a file name for saving characters and other stuff. Very dangerous for normal work.
	parser.add_argument("--develop", action="store_true", help=argparse.SUPPRESS)
	parser.add_argument("--fallback", action="store_true", help=argparse.SUPPRESS)
	parser.add_argument("-v", "--verbose", action="store_true", help="Output useful information.")
	parser.add_argument("-V", "--version", action="version", version="{name}: {version}".format( name=sys.argv[0], version=Config.version()) )
	parser.add_argument(dest="file", metavar="File/Species", nargs="?", help="Opens the character from this file at start. Instead of a file, the name of a supported species (human, changeling, mage, vampire, werewolf) may be entered, to create an empty character of the specified species, if no file of that specific name exists. This is most useful in combination with the -p option.")

	args = parser.parse_args()

	## Hauptprogramm starten
	main( sys.argv, file=args.file, pdf=args.pdf, verbose=args.verbose, debug=args.debug, develop=args.develop, fallback=args.fallback )