Ejemplo n.º 1
0
def calculate(myarg):
    stack = list()
    for token in myarg.split():
        try:
            token = int(token)
            stack.append(token)
        except ValueError:
            function = operators[token]
            arg2 = stack.pop()
            arg1 = stack.pop()

            text = colored(token, 'blue')
            arg2text = colored(arg2, 'white')
            arg1text = colored(arg1, 'white')
            if arg2 < 0:
                arg2text = colored(arg2, 'red')
            if arg1 < 0:
                arg1text = colored(arg1, 'red')
            result = function(arg1, arg2)
            stack.append(result)
            print(arg2text, text, arg1text, "=")
        print(stack)
    if len(stack) != 1:
        raise TypeError("Too many parameters")
    return stack.pop()
Ejemplo n.º 2
0
def execute_sql():
    print('there are ' + ' ' + str(len(create_all_sql())) + ' ' + 'queries' + ' ' + 'to execute')

    import pandas as pd
    try:
        conn = MySQLdb.connect(passwd="tli00eNND2ROLm:d,cq-", db="dspe", host="proteus.odin.tel-dev.io", port=3306,
                               user="******")
        engine = create_engine('mysql+pymysql://root:tli00eNND2ROLm:d,[email protected]:3306/dspe')
        sqls = create_all_sql()
        for sql in sqls:
            try:
                cur = conn.cursor()
                cur.execute(sql)
                res = (str(cur.fetchall()).strip("[],(),)' datetime.datetime("))
                if int(res) > 0:
                    print(colored("This test Passed::" + " "+ sql + res,'green'))
                else:
                    print(colored("This test failed to collect any data::" + " " + sql + " " + res,'yellow'))



            except MySQLdb.DatabaseError as dataerror:
                print("table does not exist" + str(dataerror))
    except MySQLdb.ProgrammingError as error:
        print("There was an error executing the query, Please check your queries" + error)
Ejemplo n.º 3
0
    def test_fields(self):
        mydict = self.kafka_test()[0]
        mynewdict = (mydict)
        print(mydict)
        #
        # filename ="canonical_message"
        # mydata = pd.DataFrame((mydict),index=[0])
        # mydata.to_csv(filename)
        #
        #
        data_to_test = [
            'Platform Item', 'externalAdvertiserId', 'externalCampaignId',
            'externalPlatformItemId', 'platformItemName', 'active', 'code',
            'timezone', 'vendorTimezone', 'dailyBudget', 'dailyBudget',
            'overallBudget', 'overallBudget', 'dailyBudgetImpressions',
            'overallBudgetImpressions', 'baseBid', 'minBid', 'maxBid',
            'pacingType', 'pacingInterval', 'frequencyCap', 'frequencyInterval'
        ]

        dict = json.dumps(
            mydict)  # k:v for k,v in (x.split(':') for x in mydict) }

        for data in data_to_test:
            if data in dict:
                print("This key is present in data" + " " + data)
            else:
                print(
                    colored(data + " " + "is not present in this report",
                            'red'))

        pass
Ejemplo n.º 4
0
 def play_menu(self):
     self.print_menu_op()
     self.process_op(
         Quiz.valid_negative_op(
             int(
                 input(
                     colored('white', QuizLabel.get_label('pergunta_op'),
                             'background_black', True)))))
Ejemplo n.º 5
0
def main_marquee():
    content = '北京欢迎你,为你开天辟地。。。。。。。。'
    color = [
        'grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
    ]
    i = 0
    while True:
        # 清理屏幕上的输出
        os.system('cls')
        index = i % len(color)
        print(colored(content[i % len(content)], color[index]))
        print(colored(content, color[index]))
        # print(content)
        # 休眠 200 毫秒
        time.sleep(0.1)
        content = content[1:] + content[0]
        i = i + 1
Ejemplo n.º 6
0
    def print_header(self):
        """
            Função que implemanta o cabeçalho do formulário

            Titulo:::::<nome>
            Status:::::self.is_status_finished
        """
        text_finished = colored('red', QuizLabel.get_label('nao_finalizado'))
        print('self.is_status_finished', self.is_status_finished)
        if self.is_status_finished:
            text_finished = colored('green', QuizLabel.get_label('finalizado'))

        # Cabeçalho do questionario
        Helper.clear()
        print("{}::::::::{}".format(QuizLabel.get_label('titulo'), self.name))
        print("{}:::::::{}".format(QuizLabel.get_label('status'),
                                   text_finished))
        Helper.new_line()
Ejemplo n.º 7
0
    def answer_question(self, id_question):
        question = self.get_question(id_question)
        self.print_header_question(question)
        self.print_possible_answers(question)

        index_answer = int(
            input(
                colored('white', QuizLabel.get_label('pergunta_op'),
                        'background_black', True)))

        self.set_answer(id_question, index_answer)
Ejemplo n.º 8
0
	def lap(self):
		
		self.__end = time.time()
		if self.__mode is 'fixed':
			self.__runLapSequence()
		elif self.__mode is 'indeterminate':
			pass
		else:
			raise InvalidArgumentError(colored('You provided an invalid input ' + \
				'for the mode argument, "' + self.mode + '". Your only options ' + \
				'are "fixed" or "indeterminate".','red'))
		self.__currentLap = self.__currentLap + 1
Ejemplo n.º 9
0
	def start(self):

		self.__elapsedTime = time.time()
		if self.__mode is 'fixed':
			self.__start = time.time()
			self.__timings = deque([])
		elif self.__mode is 'indeterminate':
			#self.__analyizeIndeterminateCodeInit()
		else:
			raise InvalidArgumentError(colored('You provided an invalid input ' + \
				'for the mode argument, "' + self.mode + '". Your only options ' + \
				'are "fixed" or "indeterminate".','red'))
Ejemplo n.º 10
0
def startchat(name, age, rating):
    showmenu = True  #to display menu
    while showmenu:
        menuchoices = "What do you want to do?\n1) Add a status update\n" \
                      "2) Add a friend\n" \
                      "3) Send a secret message\n" \
                      "4) Read a secret message\n" \
                      "5) Read chats from a user\n" \
                      "6) Close the application\n"
        result = int(raw_input(menuchoices))

        #validating the menuchoice
        if result == 1:
            statusmsg = addstatus()
            print colored("Your Current status is: " + statusmsg, 'green')
        elif result == 2:
            # action
            no_of_friends = add_friend()
            print colored("You have %d friends " % (no_of_friends), 'green')
        elif (result == 3):
            send_message()
        elif (result == 4):
            read_message()
        elif result == 5:
            read_chat()
        elif result == 6:
            showmenu = False
        else:
            print colored("Sorry invalid option ", 'red')
Ejemplo n.º 11
0
 def _aligner(self, target, nontarget, evalue):
     blastn = NcbiblastnCommandline(query=target,
                                    db=nontarget,
                                    evalue=evalue,
                                    outfmt=6,
                                    perc_identity=100,
                                    # word_size=word,
                                    ungapped=True,
                                    penalty=-20,
                                    reward=1,
                                    )
     stdout, stderr = blastn()
     sys.stdout.write('[%s] [%s/%s] ' % (time.strftime("%H:%M:%S"), self.counter, t))
     if not stdout:
         print colored("%s has no significant similarity to \"%s\"(%i) with an elimination E-value: %g"
                       % (tname, ntname, allele, evalue), 'red')
     else:
         # music.load('/run/media/blais/blastdrive/coin.wav')
         # music.play()
         print colored("Now eliminating %s sequences with significant similarity to \"%s\"(%i) with an "
                       "elimination E-value: %g" % (tname, ntname, allele, evalue), 'blue', attrs=['blink'])
         blastparse(stdout, target, tname, ntname)
Ejemplo n.º 12
0
    def __init__(self, arm_vals, estimates, arm_vals_var=1):
        # If arm values not provided generate random values between [0,1] of length 10
        if arm_vals == []:
            self.arm_values = np.random.normal(
                0, 1, 10)  # actual mean value of actions # mean reward
        else:
            self.arm_values = arm_vals

        self.k = len(self.arm_values)
        self.K = np.zeros(self.k)  # number of actions
        self.arm_values_var = arm_vals_var

        if estimates == []:
            self.est_values = np.zeros(
                self.k)  # estimated value of value of actions
        elif len(estimates) != self.k:
            print(
                colored(
                    'Size of estimates should be  equal to size of arm values provided',
                    'red'))
Ejemplo n.º 13
0
zero_schools= []

for urn,trustname in zip(new_list,new_list2):

    inputElement = driver.find_element_by_id("SchoolOrCollegeNameId").click()
    inputElement = driver.find_element_by_id("FindByNameId").send_keys(urn)
    driver.find_element_by_name("searchtype").click()
    driver.implicitly_wait(0)
    try:
        nameOnPage = driver.find_element_by_xpath("/html/body/div/main/h1").text
        assert nameOnPage == str(trustname)
        number_of_pupils = driver.find_element_by_xpath("/html/body/div/main/div[2]/div[1]/div/dl/dd[5]").text
        try:
            if int(number_of_pupils) == 0: zero_schools.append((urn, nameOnPage))
            print(number_of_pupils + " " + "Number of Pupils")
            print(colored(nameOnPage + " " + " On website Matches" + " " + str(trustname), ("green")))
            number_or_urns -= 1
            print(str(number_or_urns) + " " + "Schools Remaining")
        except ValueError:
            print("This is not a Valid Value")
    except AssertionError:
        did_not_match.append(urn)
        print(did_not_match)
        print(colored(nameOnPage + " " + " On website  Does Not Match" + " " + str(trustname), ("red")))
        # driver.find_element_by_class_name("home-link").click()
    except NoSuchElementException:
        unable_to_test.append(urn)
        print(colored("Unable to test LAESTAT number " + " " + str(urn) + " " + "Please do this manually",("red")))
        pass
    driver.refresh()
    driver.find_element_by_class_name("home-link").click()
Ejemplo n.º 14
0
def yellow(string):
    string = colored(string, 'yellow', attrs=['bold'])

    return string
    global population, population_male, population_female, y, n, spiders, lim, pf, bounds
    rand = random.random()  # random [0,1]
    population = 30
    population_female = int((0.9 - rand * 0.25) * population)
    population_male = population - population_female
    y = "-100*(z[1]-z[0]**2)**2 - (1 - z[0]**2)**2"
    n = 2
    bounds = np.array([[-10, 10], [-10, 10]])
    lim = 200
    pf = 0.7


for test in range(10):
    test_3()
    best_fitness, best_s = social_spider_optimization()
    print('\n' + colored("Τest " + str(test + 1), 'blue') + '\n' +
          "f(max) = " + str(best_fitness) + " max = " + str(best_s))

# # Bukin function N.6 4 minimum = 0 (-10,1)
# def test_():
#     global population, population_male, population_female, y, n, spiders, lim, pf, bounds
#     rand = random.random()  # random [0,1]
#     population = 100
#     population_female = int((0.9 - rand * 0.25) * population)
#     population_male = population - population_female
#     y = "-100 * math.sqrt(abs(z[1]-0.01*z[0]**2)) - 0.01* abs(z[0]+10)"
#     n = 2
#     bounds = np.array([[-1.5, -5],
#                        [-3, 3]])
#     lim = 200
#     pf = 0.7
Ejemplo n.º 16
0
def cyan(string):
    string = colored(string, 'cyan', attrs=['bold'])

    return string
Ejemplo n.º 17
0
def setColor(message, bold=False, color=None, onColor=None):
    from termcolor import colored, cprint
    retVal = colored(message, color=color, on_color=onColor, attrs=("bold", ))
    return retVal
Ejemplo n.º 18
0
def red(string):
    string = colored(string, 'red', attrs=['bold'])

    return string
Ejemplo n.º 19
0
def green(string):
    string = colored(string, 'green', attrs=['bold'])

    return string
Ejemplo n.º 20
0
	def __paintBar(self):

		if self.progressionInfo:
			self.__initPBTimer()
		
		formatting = '%0'+str(len(str(self.numberOfRuns)))+'.f'
		progress = '['+str(formatting % self.currentRunIndex)+' of '+str(formatting % self.numberOfRuns)+']'
		progLength = len(progress)
		if self.lengthOfPB < progLength and self.progressionInfo:
			raise InsufficientPrintBarSizeError(colored('The progress bar is of insufficient length to render properly. ' + \
				'Try setting the pregressionInfo argument for PB.repaintBar(), e.g. ProgressBar.repaintBar(progressionInfo=False), or '+\
				'increase the length of the ProgressBar to at least '+str(progLength)+', the minimum length for a the terminal value '+\
				'that your provided as an argument, i.e. numberOfRuns = '+str(numberOfRuns)+',  by either instantiating a new instance '+\
				'of the ProgressBar with a sufficient length argument or modify your current ProgressBar instance, e.g. newPB = '+\
				'ProgressBar(length >= '+str(progLength)+') or currentPB.lengthOFPB = '+str(progLength)+' or greater.','red'))
			print('\n')

		if len(self.timings) <= 1:
			self.__initStatement()

		if self.numberOfRuns <= 0:
			self.barPercent  = "Percentage Unknown..."
			self.percentageColor = 'red'
		else:
			self.barPercent  = ((self.currentRunIndex/self.numberOfRuns)*100)
			self.percentageColor = 'white'
			if self.barPercent  <= 30:
			    self.percentageColor = 'red'
			elif self.barPercent  > 30 and percentage < 80:
			    self.percentageColor = 'yellow'
			else:
			    self.percentageColor = 'green'

		cprint('\r%s' % '|', end='')

		startIndex = (self.lengthOfPB//2)-progLength//2
		
		for x in range(1,self.lengthOfPB+1):
			character = ' '
			if x >= startIndex and x < progLength+startIndex:
				character = str(progress[x-startIndex])
			if ((x/self.lengthOfPB)*100) <= self.barPercent:
				cprint(character, attrs=['reverse'], end='')
			else:
				cprint(character,end='')

		cprint('|', end='')

		progress = ' '+str(round(self.barPercent))+'%'
		cprint(progress, self.percentageColor, end='')
		
		if self.progressionInfo and self.seconds() > 0:
			totalestimate = ' Total Time - ' + str('%02.i' % self.hours()) + ':' + str('%02.i' % self.minutes()) + \
			':' + str('%02.i' % self.seconds() ) + ':' + str('%03.i' % int(self.milliseconds() ))
			cprint(totalestimate,'green',end='')

			programEstimate = ' Program Time - ' + str('%04i' % (self.seconds()-self.secondsRemainingPB)) + ' ' + str(round(2,(self.seconds()-self.secondsRemainingPB)/self.seconds())) + '%'
			cprint(programEstimate,'cyan',end='')

			if ((self.secondsRemainingPB)/self.seconds()) > 0.30:
				color = 'red'
			elif ((self.secondsRemainingPB)/self.seconds()) <= 0.30:
				color = 'yellow'
			elif ((self.secondsRemainingPB)/self.seconds()) <= 0.10:
				color = 'green'
			else:
				color = 'magenta'

			PBEstimate = ' PB Time - ' + str('%04i' % (self.secondsRemainingPB)) + ' ' + str(round(2,((self.secondsRemainingPB)/self.seconds()))) + '%'
			cprint(PBEstimate,color,end='')


		else:
			estimateText = ' Program Time - ' + str('%02.i' % self.hours()) + ':' + str('%02.i' % self.minutes()) + \
			':' + str('%02.i' % self.seconds() ) + ':' + str('%03.i' % int(self.milliseconds() ))
			cprint(estimateText,self.percentageColor,end='')
		
		sys.stdout.flush()

		if self.currentRunIndex == self.numberOfRuns:
			self.__closingStatement()

		if self.progressionInfo:
			self.__terminatePBTimer()