def buyOrSell(): print("\nAre you monitoring to BUY or SELL: ") for idx, element in enumerate([chalk.green('BUY'), chalk.green('SELL')]): print('{}) {}'.format(idx + 1, element)) i = input('Enter Number: ') try: if i == '1': return 'BUY' elif i == '2': return 'SELL' else: return 'ERROR' except: print('Error: Invalid Option') return None
def start_quiz(questions): score = 0 for i in range(0, len(questions)): print(questions[i]["question"] + "\n") for j in range(1, 5): print(str(j) + " " + questions[i]["option" + str(j)]) print() try: answer = int(input()) except ValueError: print(chalk.cyan('Please enter a choice between 1 and 4\n')) continue print() if 0 < answer < 5: if (questions[i]["correct_answer"] == "option" + str(answer)): print(chalk.green("Correct Answer!!!\n")) score = score + 1 else: correct_answer = questions[i]["correct_answer"] print( chalk.red("Wrong!! The Correct Answer is {}".format( questions[i][correct_answer]))) print() else: print(chalk.yellow("Invalid Choice\n")) print(chalk.yellow("Your Score is {}/{}".format(score, len(questions))))
def postMaker(): url = "https://api.telegram.org/<bot-key>/sendMessage" tags = input("\nTags: ") if tags.find('-') >= 0: return chalk.red("\nText has a hyphen!\n") else: description = input("Description: ") # TODO - add conditional check for if the URL is working link = input("Link: ") data = { "chat_id": "<Chat-id>", "text": f"<b>Tags:</b> {tags}\n\n<b>Description:</b> {description}\n\n<b>Link:</b> {link}", "parse_mode": "html" } # Send a post request to the bot's API response = requests.post(url, data) # Check if there's an error if response.status_code == 200: return chalk.green("\nThe post has been sent successfully!\n") else: return chalk.red("\nSomething wrong has happened\n")
def standardDeviation(): print(chalk.blue("<------------- Standard Deviation ------------->\n")) print(chalk.green("<------------- Giga IOPS ------------->\n")) for i in threadedIOPSResults: # For all the thread numbers std = [] for j in threadedIOPSResults[i]: try: std.append((j[0] / j[1]) / 1e9) except ZeroDivisionError: std.append(0) print(chalk.yellow(str(i) + " threads: " + str(np.std(std)))) print(chalk.green("\n<------------- Giga IOPS ------------->\n")) for i in threadedFLOPSResults: # For all the thread numbers std = [] for j in threadedFLOPSResults[i]: try: std.append((j[0] / j[1]) / 1e9) except ZeroDivisionError: std.append(0) print(chalk.yellow(str(i) + " threads: " + str(np.std(std))))
def changeTicker(): print("If you wish to change the ticker symbol to watch, type it below") print("Otherwise, press " + chalk.green.bold("ENTER")) i = input(chalk.green('Enter Ticker Symbol: ')) if i == '': pass else: global tickerSymbol tickerSymbol = i os.remove('twilioInfo.txt') infoFile = open('twilioInfo.txt', 'a') writeInfo = ( 'Account Number: {}Account Token: {}Twilio Number: {}My Number: {}Ticker Symbol: {}' .format(userID, authToken, twilioNumber, myNumber, tickerSymbol)) infoFile.write(writeInfo) infoFile.close()
def report(self, msg: str, options: MessageOptions = MessageOptions()) -> None: if not self.flags.silent: if options.title: msg = "\n" + chalk.green(msg) elif options.subtitle: msg = "\n" + chalk.blue(msg) elif options.block: msg = "\n" + msg elif self.flags.dry_run and options.action: msg = indent_lines(msg, " (Dry run) ") else: msg = indent_lines(msg, " ") if self.flags.verbosity < 2: msg = truncate_lines(msg, 100) print(msg)
def scrab_hn(): titleMod = [] for i, title in enumerate(titles): titleMod.append({ 'title': chalk.blue(title.get_text()), 'score_sort': int(scores[i - 1].get_text().replace(' points', '')), 'score': chalk.green('- ' + scores[i - 1].get_text()), 'link': f"\n{chalk.yellowBright(title.get('href'))}" }) # Loop through a sorted array by score value for i, title in enumerate(sorted(titleMod, key=lambda k: k['score_sort'])): print(f'\n{i + 1} -', title['title'], title['score'], title['link'], '\n\n') return ''
def my_hook(self, d): filename = d['filename'] #type: str if d['status'] == 'finished': self.bars[filename].close() file_tuple = os.path.split(os.path.abspath(d['filename'])) #print("Done downloading {}".format(file_tuple[1])) print(chalk.green('converting to mp3... ')) if d['status'] == 'downloading': if filename not in self.bars: self.bars[filename] = tqdm( total=100, unit='mb', desc=filename[filename.rindex('/') + 1:filename.rindex('.')], bar_format=chalk.white("{l_bar}") + chalk.cyan("{bar}") + chalk.white("{r_bar}")) p = d['_percent_str'] p = p.replace('%', '') self.bars[filename].n = float(p) # check this self.bars[filename].refresh()
def start_quiz(questions): score = 0 for i in range(0, len(questions)): print('--------------------------------------------------------') print(f'Q{i+1}) {questions[i]["question"]}\n') sleep(0.3) for j in range(1, 5): print(f"({j}) {questions[i]['option'+str(j)]:30}", end='\t') sleep(0.2) if not j % 2: print() try: answer = int(input("\nEnter your option number: ")) sleep(0.3) if not 0 < answer < 5: print(chalk.yellow("Please enter a choice between 1 and 4\n")) sleep(0.4) continue except ValueError: print(chalk.cyan('Invalid Choice\n')) sleep(0.4) continue print() if (questions[i]["correct_answer"] == "option" + str(answer)): print(chalk.green("Correct Answer!!!\n")) sleep(0.4) score = score + 1 else: correct_answer = questions[i]["correct_answer"] print( chalk.red( f"Wrong!! The Correct Answer is {questions[i][correct_answer]}" )) sleep(0.4) print() print('--------------------------------------------------------\n\n') print(chalk.yellow(f"Your Score is {score}/{len(questions)}"))
Flower = '' Attracts = '' Fruit = '' Leaf = '' Other = '' Tolerate = '' Culture = '' NoteworthyCharacteristics = '' Problems = '' GardenUses = '' common_not_found = 0 common_found = 0 # Requst the plantFinder for plant based on common name common_name_req = {'basic': commonNameOriginal} print(chalk.green(commonNameOriginal)) time.sleep(1) r = requests.get( 'http://www.missouribotanicalgarden.org/PlantFinder/PlantFinderProfileResults.aspx', params=common_name_req) # print(chalk.yellow.bold('common name search url'),r.url) soup = BeautifulSoup(r.text, 'html.parser') span = soup.find(id="dnn_ctr4158_SearchResults_lblNoResults") if span: # print(chalk.red(span.text)) if span.text == "We're sorry, but no results were found matching your criteria. Please revise your search criteria.": print(chalk.red.bold('plant not found with common name'), commonNameOriginal) common_not_found = 1 with open('MBGCommonNames.csv', 'a') as writeFile: writer = csv.writer(writeFile)
infoFile.close() else: infoFile = open('twilioInfo.txt', 'a') userID = input('Enter Twilio user ID: ') authToken = input('Enter Twilio authentication token: ') twilioNumber = input('Enter Twilio Phone number: ') myNumber = input('Enter your phone number: ') tickerSymbol = input('Enter Ticker Symbol to watch: ') writeInfo = ( 'Account Number: {}\nAccount Token: {}\nTwilio Number: {}\nMy Number: {}\nTicker Symbol: {}' .format(userID, authToken, twilioNumber, myNumber, tickerSymbol)) infoFile.write(writeInfo) infoFile.close() # Change stock to watch? print('\nCurrently watching prices of {}...'.format(chalk.green(tickerSymbol))) changeTicker() # Choose if waiting to buy or sell buyingOrSelling = buyOrSell() # Set price to watch for lowPrice = float(input(chalk.red('\nLow price to watch for?: '))) highPrice = float(input(chalk.green('High price to watch for?: '))) # Initialize Twilio Client client = Client(userID, authToken) # Initialize selenium settings DRIVER_PATH = 'C:/webdrivers/chromedriver.exe' options = Options() options.headless = True
def main(): # # Specify tests for various numbers of threads # testThreads = [i for i in range(1,200)] testThreads = [1, 2, 4, 8] # Specify tests for various numbers of operations # KEEP THE RANGE (1,2) FOR SINGLE VALUE # testInputs = [int(i * 1e4) for i in range(1,10)] testInputs = [int(i * 1e4) for i in range(1, 100)] totalOps = sum(testInputs) * 4 # Compile all FLOPS and IOPS functions into list and associated descriptions list testFunctions = [ intOpsAdd, intOpsSub, intOpsMul, intOpsDiv, fpOpsAdd, fpOpsSub, fpOpsMul, fpOpsDiv ] testFunctionDescriptions = [ "IOPS Add", "IOPS Subtract", "IOPS Multiply", "IOPS Divide", "FLOPS Add", "FLOPS Subtract", "FLOPS Multiply", "FLOPS Divide" ] # RUN ALL TESTS unthreadedResults, threadedResults = runAllTests(testInputs, testThreads, testFunctions) iopsUnthreadedAverage = 0 flopsUnthreadedAverage = 0 iopsThreadedAverage = {} for i in testThreads: iopsThreadedAverage[i] = 0 flopsThreadedAverage = {} for i in testThreads: flopsThreadedAverage[i] = 0 # Print unthreaded results to console print(chalk.blue.bold("Unthreaded Results:")) print(chalk.blue.bold("-------------------------------")) for i in range(len(testFunctions)): print(chalk.yellow.bold(testFunctionDescriptions[i] + " : ")) for j in range(len(unthreadedResults[i])): if i < 4: iopsUnthreadedAverage += (testInputs[j] / unthreadedResults[i][j]) else: flopsUnthreadedAverage += (testInputs[j] / unthreadedResults[i][j]) print( chalk.yellow( str(testInputs[j]) + " operations took " + str(unthreadedResults[i][j]) + " seconds")) print(chalk.blue("-------------------------------")) print("\n\n") # Print threaded results to the console print(chalk.blue.bold("Threaded Results:")) print(chalk.blue.bold("-------------------------------")) for i in testThreads: print(chalk.green.bold(str(i) + " threads: ")) for j in range(len(testFunctions)): print(chalk.yellow.bold(testFunctionDescriptions[j]) + " : ") for k in range(len(testInputs)): if j < 4: iopsThreadedAverage[i] += sum( threadedResults[i][j][testInputs[k]]) else: flopsThreadedAverage[i] += (sum( threadedResults[i][j][testInputs[k]])) print( chalk.yellow( str(testInputs[k]) + " operations took " + str(sum(threadedResults[i][j][testInputs[k]])) + " seconds")) print() print(chalk.blue("-------------------------------")) for i in iopsThreadedAverage: iopsThreadedAverage[i] = totalOps / iopsThreadedAverage[i] flopsThreadedAverage[i] = totalOps / flopsThreadedAverage[i] print("\n\n") # Print summary of results print(chalk.blue.bold("Summary of Results:")) print(chalk.blue.bold("-------------------------------")) print(chalk.yellow.bold("Unthreaded IOPS: ") + str(iopsUnthreadedAverage)) print( chalk.yellow.bold("Unthreaded FLOPS: ") + str(flopsUnthreadedAverage)) print( chalk.yellow.bold("Unthreaded Giga IOPS: ") + str(iopsUnthreadedAverage / 1e9)) print( chalk.yellow.bold("Unthreaded Giga FLOPS: ") + str(flopsUnthreadedAverage / 1e9)) print(chalk.blue("-------------------------------")) print(chalk.yellow.bold("Threaded IOPS: ")) for i in testThreads: print(chalk.green(str(i) + " threads: ") + str(iopsThreadedAverage[i])) print(chalk.yellow.bold("Threaded FLOPS: ")) for i in testThreads: print( chalk.green(str(i) + " threads: ") + str(flopsThreadedAverage[i])) print(chalk.yellow.bold("Threaded Giga IOPS: ")) for i in testThreads: print( chalk.green(str(i) + " threads: ") + str(iopsThreadedAverage[i] / 1e9)) print(chalk.yellow.bold("Threaded Giga FLOPS: ")) for i in testThreads: print( chalk.green(str(i) + " threads: ") + str(flopsThreadedAverage[i] / 1e9)) print(chalk.blue("-------------------------------")) # Convert results to JSON for formatting f = open("threadedResults.py", "w") f.write("threadedResults = ") f.write(json.dumps(threadedResults, indent=4)) f.write("\niops = ") f.write(json.dumps(iopsThreadedAverage, indent=4)) f.write("\nflops = ") f.write(json.dumps(flopsThreadedAverage, indent=4)) f.close()
r = requests.get(url) t = filter(lambda x: x['Country'].lower() == self.name.lower(), r.json()['Countries']) countries = list(t) if len(countries) == 0: return [] # This is how you delete multiple keys in an dict object. final = {(k, v) for k, v in countries[0].items() if k not in ['Country', 'Slug', 'Premium']} return final if __name__ == "__main__": print("------------------------------------------------") print(chalk.red.bold("COVID SCAPE!")) print("------------------------------------------------") print("\n") print("Please enter the country name.") country_input = input() print(f"Finding covid details for {country_input} ...") print("\n") c = country(country_input) output = c.get_covid_details() if len(output) > 0: # print(output) # print(tuple(output)) print(chalk.green(tabulate(output))) else: print(chalk.red.bold(f"Country {country_input} details not found."))
def create_output(self) -> str: fileMessageMap = defaultdict(list) for message in self.messages: fileMessageMap[os.path.relpath(message.abspath)].append(message) totalErrorCount = 0 totalWarningCount = 0 outputs = [] for (filePath, messages) in fileMessageMap.items(): fileOutputs = [] for message in messages: location = chalk.grey(f'{filePath}:{message.line}:{message.column + 1}') color = chalk.yellow if message.category == 'warning' else chalk.red fileOutputs.append(f'{location} [{color(message.symbol)}] {message.msg}') errorCount = sum(1 for message in messages if message.category != 'warning') totalErrorCount += errorCount warningCount = sum(1 for message in messages if message.category == 'warning') totalWarningCount += warningCount fileOutputString = '\n'.join(fileOutputs) outputs.append(f'{self.get_summary(errorCount, warningCount)} in {filePath}\n{fileOutputString}\n') output = '\n'.join(outputs) output += f'\nFailed due to {self.get_summary(totalErrorCount, totalWarningCount)}.' if (totalErrorCount or totalWarningCount) else chalk.green('Passed.') return output
cleanRow_02 = re.sub('\º', '', cleanRow_01) cleanRow_03 = re.sub('\,', '.', cleanRow_02) cleanRow_array = cleanRow_03.split(' ') for i, cell in enumerate(cleanRow_array): cleanRow_array[i] = float(cell) return cleanRow_array # # Get dataset datasetBuffer = open('data/raw/dataset.txt', 'r') dataset = datasetBuffer.read() datasetBuffer.close() print(chalk.green('dataset getted from \'data/raw/dataset.txt\'')) # # Get header header = dataset.split('\n')[0] headerSafe = re.split('\s', header) headerSafe = list(filter(lambda h: h, headerSafe)) # # Get rows rows = dataset.split('\n')[1:] rowsSafe = [] for row in rows: rowsSafe.append(cleanRow(row)) # from cleanRow() #
def findHeightWordInSentences(lemmatizedSentences, plantName, category, wikiLink): foundHeight = False with open('plantHeightData.csv', 'a', newline='') as csvfile: writer = csv.writer(csvfile) for sentence in lemmatizedSentences: for word in sentence: if (word == 'height' or word == 'tall'): print(chalk.green.bold('height found for'), plantName) foundHeight = True sentenceThatContainHeightKeyword = " ".join( str(x) for x in sentence) # print(sentenceThatContainHeightKeyword,'\n') # filterdSentence = tokenizer.tokenize(sentenceThatContainHeightKeyword) # sentenceThatContainHeightKeyword = " ".join(str(x) for x in filterdSentence) # print("plant Name is :" ,plantName, sentenceThatContainHeightKeyword); doc = nlp(sentenceThatContainHeightKeyword) count = 0 plant_height_data = [] for token in doc: t = token.text if t == 'm' or t == 'meter' or t == 'metre' or t == 'ft' or t == 'foot' or t == 'cm' or t == 'centimetre' or t == 'in': # if len(doc) > (token.i+1): # next_token = doc[token.i + 1] prev_token = doc[token.i - 1] if prev_token.like_num: count += 1 # print("token",token," token.i",token.i," len(doc)",len(doc)) token_sentence = doc[prev_token.i:token.i + 1] print("case#1", chalk.yellow.bold(token_sentence)) plant_height_data.append(token_sentence) if doc[prev_token.i - 2].like_num: # 1 to 2 unit count += 1 token_sentence = doc[prev_token.i - 2:token.i + 1] print("case#2", chalk.blue.bold(token_sentence)) plant_height_data.append(token_sentence) else: pass else: #get data for case#3 x-x unit if prev_token.is_punct == False: token_sentence = doc[prev_token.i:token.i + 1] print("case#3", chalk.magenta( token_sentence)) #x-x uni plant_height_data.append(token_sentence) else: pass # do nothing if theres a punct mark # if next_token.lower_ == "m" or next_token.lower_ == 'ft' or next_token.lower_ == 'meter' or next_token.lower_ == 'metre' or next_token.lower_ == 'cm' or next_token.lower_ == 'in' or next_token.lower_ == 'foot': # count += 1 # token_sentence = doc[prev_token.i:next_token.i + 1] # print('Height sentence',token_sentence) # unit = token_sentence[len(token_sentence) - 1:len(token_sentence)] # print(unit) # writer.writerow([plantName,category,unit,'',token_sentence,'',wikiLink,sentenceThatContainHeightKeyword,'']) # unit cleanup plant_height_data_str = [] plant_height_data_str_ft = '' plant_height_data_str_cm = '' plant_height_data_str_m = '' plant_height_data_str_in = '' for valueWithUnit in plant_height_data: stringData = valueWithUnit.text stringData = stringData.replace("-", " ") stringData = stringData.replace("centimetre", "cm") stringData = stringData.replace("foot", "ft") stringData = stringData.replace("meter", "m") stringData = stringData.replace("inch", "in") stringData = stringData.replace('–', ' ') stringData = stringData.replace('to', ' ') stringData = stringData.replace(',', '') stringData = stringData.replace('1/2', '0.5') if stringData.find('in') > 0: plant_height_data_str_in = plant_height_data_str_in + stringData plant_height_data_str_in = plant_height_data_str_in.replace( 'in', '') if stringData.find('ft') > 0: plant_height_data_str_ft = plant_height_data_str_ft + stringData plant_height_data_str_ft = plant_height_data_str_ft.replace( 'ft', '') if stringData.find(' m') > 0: plant_height_data_str_m = plant_height_data_str_m + stringData plant_height_data_str_m = plant_height_data_str_m.replace( 'm', '') if stringData.find(' cm') > 0: plant_height_data_str_cm = plant_height_data_str_cm + stringData plant_height_data_str_cm = plant_height_data_str_cm.replace( 'cm', '') plant_height_data_str.append(stringData) print(chalk.red(plantName), plant_height_data) print(chalk.green(plantName), plant_height_data_str) # inch # remove all characters plant_height_data_str_in = removeAlphabets( plant_height_data_str_in) print(chalk.yellow(plantName), 'inch values', plant_height_data_str_in) plant_height_data_str_in = plant_height_data_str_in.split() try: plant_height_data_str_in = list( map(float, plant_height_data_str_in)) plant_height_data_str_in = sorted( plant_height_data_str_in) print(chalk.cyan.bold(plantName), 'inch values', plant_height_data_str_in) except ValueError: pass # ft plant_height_data_str_ft = removeAlphabets( plant_height_data_str_ft) print(chalk.yellow(plantName), 'ft values', plant_height_data_str_ft) plant_height_data_str_ft = plant_height_data_str_ft.split() try: plant_height_data_str_ft = list( map(float, plant_height_data_str_ft)) plant_height_data_str_ft = sorted( plant_height_data_str_ft) print(chalk.cyan.bold(plantName), 'ft values', plant_height_data_str_ft) except ValueError: pass # m plant_height_data_str_m = removeAlphabets( plant_height_data_str_m) print(chalk.yellow(plantName), 'm values', plant_height_data_str_m) plant_height_data_str_m = plant_height_data_str_m.split() try: plant_height_data_str_m = list( map(float, plant_height_data_str_m)) plant_height_data_str_m = sorted( plant_height_data_str_m) print(chalk.cyan.bold(plantName), 'm values', plant_height_data_str_m) except ValueError: pass # cm plant_height_data_str_cm = removeAlphabets( plant_height_data_str_cm) print(chalk.yellow(plantName), 'cm values', plant_height_data_str_cm) plant_height_data_str_cm = plant_height_data_str_cm.split() try: plant_height_data_str_cm = list( map(float, plant_height_data_str_cm)) plant_height_data_str_cm = sorted( plant_height_data_str_cm) print(chalk.cyan.bold(plantName), 'cm values', plant_height_data_str_cm) except ValueError: pass if (len(plant_height_data_str_in) > 0): temp = ['x'] * 10 for index, value in enumerate( plant_height_data_str_in): temp[index] = value writer.writerow([ plantName, category, 'in', temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8], temp[9], wikiLink, sentenceThatContainHeightKeyword ]) if (len(plant_height_data_str_cm) > 0): temp = ['x'] * 10 for index, value in enumerate( plant_height_data_str_cm): temp[index] = value writer.writerow([ plantName, category, 'cm', temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8], temp[9], wikiLink, sentenceThatContainHeightKeyword ]) if (len(plant_height_data_str_ft) > 0): temp = ['x'] * 10 for index, value in enumerate( plant_height_data_str_ft): temp[index] = value writer.writerow([ plantName, category, 'ft', temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8], temp[9], wikiLink, sentenceThatContainHeightKeyword ]) if (len(plant_height_data_str_m) > 0): temp = ['x'] * 10 for index, value in enumerate(plant_height_data_str_m): temp[index] = value writer.writerow([ plantName, category, 'm', temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8], temp[9], wikiLink, sentenceThatContainHeightKeyword ]) # if (count > 0): # print(count,chalk.red.bold('tokens found in'),plantName,'\n') # else: # writer.writerow([plantName,category,'not found','','not found','',wikiLink,sentenceThatContainHeightKeyword,'']) # print(count,chalk.red('tokens matched in'),plantName,'\n') if (foundHeight == False): print(chalk.red("No Height for "), plantName) with open('plantHeightData.csv', 'a', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow([ plantName, category, 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', wikiLink, 'x' ])