Ejemplo n.º 1
0
    def parseGrouped(self, compoundstr):
        tokens = [
            x if x != '' else '1'
            for x in grouped_pattern.findall(compoundstr)[0]
        ]
        elems = []
        coeff = 1
        sub = 1

        if isInt(tokens[0]):
            coeff = int(tokens[0])
        else:
            elems.extend(self.parseUngrouped(tokens[0]))

        if isInt(tokens[2]):
            sub = int(tokens[2])
        else:
            raise InvalidCompound(
                "Unexpected '{0}' after group '({1})'".format(
                    tokens[2], tokens[1]))

        innerElems = self.parseUngrouped(tokens[1])

        for elem in innerElems:
            elem.quantity = elem.quantity * coeff * sub

        elems.extend(innerElems)

        return elems
Ejemplo n.º 2
0
def extract_number(toks):
    # toks tokenises (, ) as well
    if (len(toks) == 0) or not (utils.isInt(toks[0]) or utils.isFloat(toks[0])
                                or utils.isFrac(toks[0])):
        return [], toks
    if (len(toks) > 1):
        if utils.isInt(toks[0]) and utils.isFrac(toks[1]):
            return toks[:2], toks[2:]
        else:
            return toks[:1], toks[1:]
    if utils.isInt(toks[0]) or utils.isFloat(toks[0]) or utils.isFrac(toks[0]):
        return toks, []
    else:
        return [], toks
Ejemplo n.º 3
0
	def parseUngrouped(self, compoundstr):
		groups = ungrouped_pattern.findall(compoundstr)
		elems = []
		lastCoeff = None
		
		for group in groups:
			group = [x if x != '' else '1' for x in group]
			subelems = []

			for token in group:
				if isInt(token):
					token = int(token)
					if len(subelems) > 0:
						subelems[-1].quantity *= token
					else:
						lastCoeff = token
				elif isElement(token):
					elem = ChemElement(instance=getElement(token))

					if lastCoeff is not None:
						elem.quantity *= lastCoeff
						lastCoeff = None
					subelems.append(elem)
				else:
					raise InvalidCompound("Unknown element {0} found".format(token))
			elems.extend(subelems)
		return elems
Ejemplo n.º 4
0
    def parseUngrouped(self, compoundstr):
        groups = ungrouped_pattern.findall(compoundstr)
        elems = []
        lastCoeff = None

        for group in groups:
            group = [x if x != '' else '1' for x in group]
            subelems = []

            for token in group:
                if isInt(token):
                    token = int(token)
                    if len(subelems) > 0:
                        subelems[-1].quantity *= token
                    else:
                        lastCoeff = token
                elif isElement(token):
                    elem = ChemElement(instance=getElement(token))

                    if lastCoeff is not None:
                        elem.quantity *= lastCoeff
                        lastCoeff = None
                    subelems.append(elem)
                else:
                    raise InvalidCompound(
                        "Unknown element {0} found".format(token))
            elems.extend(subelems)
        return elems
Ejemplo n.º 5
0
	def parseGrouped(self, compoundstr):
		tokens = [x if x != '' else '1' for x in grouped_pattern.findall(compoundstr)[0]]
		elems = []
		coeff = 1
		sub = 1

		if isInt(tokens[0]):
			coeff = int(tokens[0])
		else:
			elems.extend(self.parseUngrouped(tokens[0]))

		if isInt(tokens[2]):
			sub = int(tokens[2])
		else:
			raise InvalidCompound("Unexpected '{0}' after group '({1})'".format(tokens[2], tokens[1]))

		innerElems = self.parseUngrouped(tokens[1])

		for elem in innerElems:
			elem.quantity = elem.quantity * coeff * sub

		elems.extend(innerElems)

		return elems
Ejemplo n.º 6
0
	def do_POST(self):
		""" Handles the HTTP POST request.

		The POST endpoints are:
		* /login
		When a post is made to login the server check if the hashes of the login data matchs the hashes of the user and password stored in the server.
		If the data match the server create a session with a cookie which still alive for 1200 seconds. Else the server will redirect to a error page.
		* /configuration
		First the server will check if the data type is correct, then it will check if the values are in the permited ranges and after that it will change the configuration.
		This endpoint change the number of samples shown in the home page, the frequency of the temperature sensor and the size of the dara files stored in the device.
		* /scp
		After check the session and the data type the server will set the scp target address and start the scp daemon. If the checkbox is mark, the server will store the configuration of the scp.
		* /pmnormal handles post to set power saving mode normal
		First the server will check if the session is ok, then it will set up the normal power saving mode.
		* /pm1 handles post to set power saving mode 1
		First the server will check if the session is ok, then it will set up the first power saving mode.
		* /pm2_multiple handles post to set power saving mode 2 in the advanced formulary.
		After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user.
		* /pm2_one handles post to set power saving mode 2 with one interval for all days.
		After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user.
		* /pm2_eachday handles post to set power saving mode 2 with one different every day.
		After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user.
		* /pm3_multiple handles post to set power saving mode 3 in the advanced formulary.
		After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user.
		* /pm3_one post to set power saving mode 3 with one interval for all days.
		After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user.
		* /pm3_eachday handles post to set power saving mode 3 with one different every day.
		After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user.


		"""
		global configuration_path

		if(self.path == '/login'):
			print "[Login Post]"
			form = cgi.FieldStorage(
				fp=self.rfile,
				headers=self.headers,
				environ={'REQUEST_METHOD':'POST',
						'CONTENT_TYPE':self.headers['Content-Type'],
						})
			
			login = form["login"].value.strip()
			password = form["password"].value.strip()

			if(utils.check_login(login, password)):
				#Cookie creation
				c = Cookie.SimpleCookie()
				hash_object = hashlib.md5(str(datetime.now()).encode())
				c['cookietemp'] = str(hash_object.hexdigest())
				c['cookietemp']['domain'] = utils.getConfiguration("domain")
				c['cookietemp']['expires'] = 1200
				c['cookietemp']['path'] = "/"
				c['cookietemp']['httponly'] = "true"
				cookie_storage.store_cookie(c)

				self.send_response(200)
				self.send_header('Content-type','text/html')
				self.send_header('Set-Cookie', c.output(attrs=['path', 'expires'], header="Cookie:"))
				
				self.end_headers()
				f = open(curdir + sep + "web/html/configuration.html")
				self.wfile.write(f.read())
				f.close()
			else:
				self.answerPost(curdir + sep + "web/html/login-fail.html", 200)

		if(self.path == '/configuration'):
			global samples_show
			isDataCorrect = True

			print "[Configuration Post]"
			form = cgi.FieldStorage(
				fp=self.rfile,
				headers=self.headers,
				environ={'REQUEST_METHOD':'POST',
						'CONTENT_TYPE':self.headers['Content-Type'],
						})

			#Session check
			if (cookie_storage.check_session(self.headers)):
				#Data validation
				if not re.match("^[0-9]+$", form["samples"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				elif not re.match("^[0-9]+$", form["frequency"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				elif not re.match("^[0-9]+$", form["websamples"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				elif not re.match("^([0-9]+|-[0-9]+)$", form["error"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				else:
					if( utils.isInt( form["websamples"].value ) and int( form["websamples"].value ) > 0 ):
						samples_show = int(form["websamples"].value)
						utils.setConfiguration("samples_show" , samples_show)
					else:
						isDataCorrect = False

					if( utils.isInt( form["error"].value )):
						utils.setConfiguration("sensor_error" , int(form["error"].value))
					else:
						isDataCorrect = False

					if( utils.isInt( form["samples"].value ) and int( form["samples"].value ) > 0 ):
						utils.setConfiguration("file_size" , int(form["samples"].value))
					else:
						isDataCorrect = False

					if( utils.isInt( form["frequency"].value ) and int( form["frequency"].value ) > 0 ):
						frequency = int(form["frequency"].value)
						utils.setConfiguration("frequency_temp" , frequency)
					else:
						isDataCorrect = False

					if( isDataCorrect ):
						self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
					else:
						self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)


		if(self.path == '/scp'):
			#Session check
			if (cookie_storage.check_session(self.headers)):
				global store_data
				isDataCorrect = False

				print "[SCP Post]"
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})

				if 'check' in form:
					store_data = True
				else:
					store_data = False

				#Data validation
				if utils.isInt(form["scpfrequency"].value) and utils.isInt(form["port"].value) and form["scp"].value and form["user"].value and form["directory"].value and form["password"].value:
					isDataCorrect = True

				utils.setConfiguration("frequency_scp", form["scpfrequency"].value)

				#Store data if user wants.
				if store_data:
					with file("./config/scp",'w+') as scpfile:
						scpfile.write(form["user"].value+"\n")
						scpfile.write(form["scp"].value+"\n")
						scpfile.write(form["directory"].value+"\n")
						scpfile.write(form["port"].value+"\n")
						scpfile.write(form["password"].value+"\n")
					scpfile.close()
				else:
					system("sudo rm ./config/scp")

				#Create scp task.
				#TODO encriptar datos que se pasan al script (?)
				p = subprocess.Popen(["python", "scpdaemon.py", "start", form["scp"].value, form["user"].value, form["port"].value, form["directory"].value], stdin=PIPE, stdout=PIPE)
				print p.communicate(form["password"].value)
				#TODO check that is correct, subprocess.check~

				#Redirect to configuration.
				if( isDataCorrect ):
					self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pmnormal'):
			#Session check
			if (cookie_storage.check_session(self.headers)):
				#TODO eliminar datos de otros modos, overclock etc.
				print "[Power mode normal Post]"
				self.setPowerSavingModeNormal()
				utils.setConfiguration("powermode", "0")
				self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)
			
		if(self.path == '/pm1'):
			#Session check
			if (cookie_storage.check_session(self.headers)):
				#TODO pmnormal.sh -> wifi activado, con underclock, eliminar datos que generen los otros modos etc
				print "[Power mode 1 Post]"
				self.setPowerSavingMode1()
				utils.setConfiguration("powermode", "1")
				self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm2_multiple'):
			if (cookie_storage.check_session(self.headers)):
				configuration_path = './web/html/configuration_mode2.html'
				#TODO elimnar datos de los otros modos
				print "[Power mode 2 Post: Multiple intervals]"

				#Post form recover
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})
				if(utils.validateInterval_multiple(form)):
					utils.create_crontab(form, True)
					utils.setConfiguration("powermode", "2")
					self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm2_one'):
			if(cookie_storage.check_session(self.headers)):
				configuration_path = './web/html/configuration_mode2.html'
				print "[Power mode 2 Post: One interval]"

				#Post form recover
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})

				#validation
				if(utils.validateInterval(form["start"].value, form["end"].value)):
					monday = tuesday = wednesday = thursday = friday = saturday = sunday = (int(form["start"].value),int(form["end"].value))
					utils.write_crontab([monday, tuesday, wednesday, thursday, friday, saturday, sunday], False)
					utils.setConfiguration("powermode", "2")
					self.answerPost(curdir + sep + "web/html/configuration-changed.html",200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm2_eachday'):
			if (cookie_storage.check_session(self.headers)):
				configuration_path = './web/html/configuration_mode2.html'
				print "[Power mode 2 Post: Multiple intervals]"

				#Post form recover
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})

				if(utils.validateInterval_eachDay(form)):
					utils.create_crontab(form, False)
					utils.setConfiguration("powermode", "2")
					self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm3'):
			configuration_path = './web/html/configuration_mode3.html'
			print "[Power mode 3 Post]"
			utils.setConfiguration("powermode", "3")
Ejemplo n.º 7
0
	def parseFormula(self, formula, sets, operators):

		if not len(formula):
			return None

		formula = formula.strip()

		if formula[0] == "f" and utils.isInt(formula[1:]):
			if formula in sets:
				return sets[formula]
			else:
				return None


		depth = 0
		tree = None
		for i in reversed(xrange(len(formula))):

			if formula[i] == ")":
				depth += 1
			elif formula[i] == "(":
				depth -= 1
			elif depth == 0:

				for operator in ["*", "+", "->"]:

					start = i - len(operator) + 1
					if formula[start:].startswith(operator):

						if tree is not None:
							return None
						
						definition = operators[operator]
						
						left_set = self.parseFormula(formula[0:start], sets, operators)
						right_set = self.parseFormula(formula[i + 1:], sets, operators)

						if left_set == None or right_set == None:
							return None

						s = ""

						if operator == "*":

							if not left_set.getDomain().getName() == right_set.getDomain().getName():
								print ("ERROR: Sets " + left_set.getName() + " and " + right_set.getName() + " dont have same domains.")
								return None

							if definition[0] == "ZadehT":
								s = FuzzySetTimesZadeh("temp", left_set, right_set)
							elif definition[0] == "HammacherT":
								param = definition[1]
								s = FuzzySetTimesHammacher("temp", left_set, right_set, param)

						elif operator == "+":

							if not left_set.getDomain().getName() == right_set.getDomain().getName():
								print ("ERROR: Sets " + left_set.getName() + " and " + right_set.getName() + " dont have same domains.")
								return None

							if definition[0] == "ZadehS":
								s = FuzzySetPlusZadeh("temp", left_set, right_set)
							elif definition[0] == "HammacherS":
								param = definition[1]
								s = FuzzySetPlusHammacher("temp", left_set, right_set, param)							

						elif operator == "->":
							# print definition
							if definition[0] == "'max-min'":
								# print "here"
								s = FuzzySetMamdaniMin("temp", left_set, right_set)
							elif definition[0] == "'max-product'":
								param = definition[1]
								s = FuzzySetMamdaniProduct("temp", left_set, right_set)							

						tree = s
						break

		if tree is not None:
			return tree

		if formula[0] == "!":
			definition = operators[formula[0]]

			s = ""
			if definition[0] == "ZadehNot":
				source = self.parseFormula(formula[1:], sets, operators)
				if source == None:
					return None

				s = FuzzySetComplementZadeh("temp", source)
				return s

		if formula[0] == "(" and formula[-1] == ")":
			return self.parseFormula(formula[1:-1], sets, operators)

		return None
Ejemplo n.º 8
0
 def set_counter(self, val):
     self.__count = val
     s = f'({val})' if isInt(val) else ''
     self._w_count.set_text(s)
Ejemplo n.º 9
0
Archivo: main.py Proyecto: amoulis/YATA
		if player.isEnergyEmpty():
			log.failure("You have no more energy. You will die alone, drifting in space")
			event.gameOver()
			break;
		else:
			player._energy = player._energy-1
			rand_event = random.randint(1,3)
			if rand_event == 1:
				success = event.eventNothing()
			elif rand_event == 2:
				success = event.eventBattle(player)
			else:
				success = event.eventSpaceStation(player)
	elif order == "repare":
		choice = input("How much energy to you want to consumme for charging shield ? \n >>> ")
		if utils.isInt(choice):
			if player._energy - int(choice) >= 0:
				player._energy = player._energy - int(choice)
				player._shield = player._shield + int(choice)
				if player._shield > player._shieldMax:
					player._shield = player._shieldMax
				log.information("Shield repared !")
			else:
				log.warning("You don't have enough energy to do that")
		else:
			log.debug("Not a good option. Try again please")

	elif order == "save":
		save.saveGame(player)
	elif order == "load":
		save.loadGame(player)
Ejemplo n.º 10
0
def select_model(args):
    '''

    Args:
        model_name: pixelvae_with_1_kl_10_mmd

    Returns: A model selected from the parameters provided

    '''
    model_name = args.model
    splits = model_name.split("_")
    '''
        Assertions for model name i.e a string
    '''
    # It is only pixelcnn
    if len(splits) == 2:
        assert (splits[0] == "pixelcnn"), "It has to be only pixelcnn_2/4/7"
        assert (isInt(splits[1])), "The number of layers has to be an int"
        only_pixelcnn = True
        use_pixelcnn = True
        args.num_pixelcnn_layers = int(splits[1])
        model_params = {
            'model_name': "PixelCNN",
            'is_decoder_out_normal': False,
            'only_pixelcnn': only_pixelcnn,
            'use_pixelcnn': use_pixelcnn,
            "coeff_kl": 0.,
            "coeff_mmd": 0.
        }

    # It is either pixelvae or vae
    else:
        only_pixelcnn = False
        # normal_vae_0_kl_0_mmd
        assert (
            len(splits) == 6 and "vae" in splits[1]
        ), "model name should be of the format normal_pixelvae_1_kl_10_mmd"
        assert (splits[1] == "pixelvae"
                or splits[1] == "vae"), "model should be vae or pixelvae"
        assert (isFloat(splits[2])
                and isFloat(splits[4])), "coefficients should be numeric"
        use_pixelcnn = splits[1] == "pixelvae"
        is_normal = splits[0] == "normal"
        # If we are using normal distribution for P(x_hat/z) in decoder-output, then
        model_params = {
            'is_decoder_out_normal': is_normal,
            'only_pixelcnn': False,
            'use_pixelcnn': use_pixelcnn,
            "coeff_kl": float(splits[2]),
            "coeff_mmd": float(splits[4])
        }
        if use_pixelcnn:
            model_params['model_name'] = "PixelVAE"
            # If it is PixelVAE and it is not normal then out_channels should be > in_channels
            if not model_params['is_decoder_out_normal']:
                assert args.decoder_out_channels > args.input_channels, "decoder_out_channels should be > input_channels when categorical_pixelvae else simply use normal_pixelvae"
        else:
            model_params['model_name'] = "VAE"

    # assert (
    #     model_params['use_pixelcnn'] == (
    #         args.sigma_decoder == 0)), "sigma_decoder should be 0 when using vae and non-zero when using pixelvae/pixelcnn"
    assert not (
        model_params['is_decoder_out_normal']
        and not use_pixelcnn == (args.sigma_decoder == 0)
    ), "sigma_decoder should be 0 when using vae and non-zero when using pixelvae/pixelcnn"

    if model_params['use_pixelcnn']:
        assert (
            args.num_pixelcnn_layers >= 2
        ), "num of pixelcnn layers should be greater than 2 when using pixelvae/pixelcnn"
    if model_params['use_pixelcnn']:
        assert (model_params['use_pixelcnn'] and
                (args.pixelcnn_activation == "ReLu" or args.pixelcnn_activation
                 == "ELU")), "Choose either Relu or ELU"

    model_params['input_channels'] = args.input_channels
    model_params['input_image_size'] = args.input_image_size
    model_params['intermediate_channels'] = args.intermediate_channels
    model_params['z_dimension'] = args.z_dimension
    model_params['sigma_decoder'] = args.sigma_decoder
    model_params['require_rsample'] = args.require_rsample
    model_params['input_image_size'] = args.input_image_size
    model_params['num_pixelcnn_layers'] = args.num_pixelcnn_layers
    model_params['pixelcnn_activation'] = args.pixelcnn_activation
    model_params['coeff_nll'] = args.nll

    # Could be PixelCNN or PixelVAE
    if use_pixelcnn:
        model_params['pixelcnn_out_channels'] = int(args.quantization)
        # If PixelVAE
        if not only_pixelcnn:
            if model_params['is_decoder_out_normal']:
                model_params['decoder_out_channels'] = args.input_channels
            else:
                model_params[
                    'decoder_out_channels'] = args.decoder_out_channels
        else:
            model_params['decoder_out_channels'] = 0

    # If VAE
    else:
        model_params['pixelcnn_out_channels'] = 0
        # Decoder output follows normal distribution then output channels will be same as input channels
        if model_params['is_decoder_out_normal']:
            model_params['decoder_out_channels'] = model_params[
                'input_channels']
        # Decoder output follows categoriacal distribution then output channels will be same as quantization
        else:
            model_params['decoder_out_channels'] = int(args.quantization)

    model = VAE(in_channels=model_params['input_channels'],
                intermediate_channels=model_params['intermediate_channels'],
                decoder_out_channels=model_params['decoder_out_channels'],
                pixelcnn_out_channels=model_params['pixelcnn_out_channels'],
                z_dimension=model_params['z_dimension'],
                pixelcnn=model_params['use_pixelcnn'],
                only_pixelcnn=model_params['only_pixelcnn'],
                pixelcnn_layers=model_params['num_pixelcnn_layers'],
                pixelcnn_activation=model_params['pixelcnn_activation'],
                nll=model_params['coeff_nll'],
                kl=model_params['coeff_kl'],
                mmd=model_params['coeff_mmd'],
                require_rsample=model_params['require_rsample'],
                sigma_decoder=model_params['sigma_decoder'],
                input_image_size=model_params['input_image_size'])
    print(model)
    return model, model_params