def rest(self, method, uri, data=None, status_codes=None, parse=True, **kwargs): """ Rest helpers """ r = self.pool.request_encode_body(method, uri, fields=data, encode_multipart=False) if not r.status in (status_codes if status_codes else (200, 201)): print cl('\n---------\nURI / REQUEST TYPE : %s %s' % (uri, method), 'red') print cl(data, 'red') print r.headers raise Exception, "Invalid status code: %s" % r.status if not parse: " return raw urllib3 response" return r if not self.debug_loads: " return parsed edn" return loads(r.data) "time edn parse time and return parsed edn" return self.debug(loads, args=(r_data, ), kwargs={}, fmt='<<< parsed edn datastruct in {ms}ms', color='green')
def clear(): clear = input(cl('clear text files (yes or no): ', 'white')) if clear == 'yes': pick = input(cl('valid, notvalid, or both: ', 'white')) if pick == 'valid': file = open("YESvalid.txt", "w+") file.write("") file.close() elif pick == 'notvalid': file = open("NOTvalid.txt", "w+") file.write("") file.close() elif pick == 'both': file = open("YESvalid.txt", "w+") file.write("") file.close() file = open("NOTvalid.txt", "w+") file.write("") file.close() else: print('\033[H\033[J') print(cl('invalid choice', 'red')) t.sleep(3) os.system('python3 main.py') elif clear == 'no': print('files wont be cleared\n') else: print('\033[H\033[J') print(cl('invalid choice', 'red')) t.sleep(3) print('\033[H\033[J') os.system('python3 main.py')
def datoms(self, index='aevt', e='', a='', v='', limit=0, offset=0, chunk=100, start='', end='', since='', as_of='', history='', **kwargs): """ Returns a lazy generator that will only fetch groups of datoms at the chunk size specified. http://docs.datomic.com/clojure/index.html#datomic.api/datoms """ assert index in ['aevt','eavt','avet','vaet'], "non-existant index" data = {'index': index, 'a': ':{0}'.format(a) if a else '', 'v': dump_edn_val(v) if v else '', 'e': int(e) if e else '', 'offset': offset or 0, 'start': start, 'end': end, 'limit': limit, 'history': 'true' if history else '', 'as-of': int(as_of) if as_of else '', 'since': int(since) if since else '', } data['limit'] = offset + chunk rs = True while rs and (data['offset'] < (limit or 1000000000)): ta = datetime.datetime.now() rs = self.rest('GET', self.uri_db + '-/datoms', data=data, parse=True) if not len(rs): rs = False tb = datetime.datetime.now() - ta print cl('<<< fetched %i datoms at offset %i in %sms' % ( len(rs), data['offset'], tb.microseconds/1000.0), 'cyan') for r in rs: yield r data['offset'] += chunk
def look_up(word): url = 'http://dict.youdao.com/search?q=' r = requests.get(url + word) content = r.text try: ps = re.findall(re.compile('"phonetic">(.*?)</span>'), content) pattern = re.compile('"trans-container">(.*?)</div>', re.S) tmp = re.findall(pattern, content) mean = re.findall(re.compile('<li>(.*?)</li>'), tmp[0]) except: print('Can\'t find it') return if len(ps) is 2: print(cl(u'英{0} 美{1}'.format(ps[0], ps[1]), 'cyan')) else: try: print(cl(ps[0], 'cyan')) except: pass for line in mean: words = line.split('.', 1) if len(words) is 2: words[0] += '.' print(u'{0}{1}'.format(cl(words[0], 'green'), cl(words[1], 'blue'))) # word else: print(u'{0}'.format(cl(words[0], 'blue')))
def e(self, eid): """Get an Entity """ ta = datetime.datetime.now() rs = self.rest('GET', self.uri_db + '-/entity', data={'e':int(eid)}, parse=True) tb = datetime.datetime.now() - ta print cl('<<< fetched entity %s in %sms' % (eid, tb.microseconds/1000.0), 'cyan') return rs
def main(): print(cl("~~~~~~~~~~~~~~~Word of the Day~~~~~~~~~~~~~~~~", "grey")) wordADay() print(cl("~~~~~~~~~~~~~~~Quote for the Day~~~~~~~~~~~~~~", "grey")) quoteADay() print(cl("~~~~~~~~~~~~~German Word of the Day~~~~~~~~~~~~~", "grey")) deustchesWort()
def modela_kvalitate(y_test, resultats): # Kvalitate virs 0.6 ir OK print( cl('Explained Variance Score (dispersija): {}'.format( evs(y_test, resultats)), attrs=['bold'])) print( cl('R-Squared (kvadratiska novirze): {}'.format(r2(y_test, resultats)), attrs=['bold']))
def info(datne): print(cl("\n\nInformācija par datni " + datne, 'green', attrs = ['reverse'])) # # importējam datus # # df is saīsinajums no Data Frame, # # Pandas bibliotēkas pamata datu struktūras df = pd.read_csv(datne) # # apskatīt pirmās 5 datu rindiņas print(cl("\nPirmās 5 rindiņas", attrs = ['bold'])) print(df.head(5))
def retract(self, e, a, v): """ redact the value of an attribute """ ta = datetime.datetime.now() ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v)) rs = self.tx(ret) tb = datetime.datetime.now() - ta print cl('<<< retracted %s,%s,%s in %sms' % (e,a,v, tb.microseconds/1000.0), 'cyan') return rs
def targets(name=None): return cl(''' TARGETS:''', 'red') + cl( ''' (-trgt) [ zervit = Zervit 0.4 for Windows ] [ cuppa = CUPPA CMS vb.0..1 for FreeBSD ] [ wbm128 = Webmin 1.28 for Fedora Core 4 ] [ iweb = Ashley Brown iWeb Server for Windows ] ''', 'white')
def retract(self, e, a, v): """ redact the value of an attribute """ ta = datetime.datetime.now() ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v)) rs = self.tx(ret) tb = datetime.datetime.now() - ta print cl( '<<< retracted %s,%s,%s in %sms' % (e, a, v, tb.microseconds / 1000.0), 'cyan') return rs
def fibNum(n): goldenRatio = 1.61803 #https://en.wikipedia.org/wiki/Fibonacci_number #Used the formula concerning golden ratio to create a #comprehension list to hold the Fibonacci sequence and see if #n is part of that sequence seq = [round(((goldenRatio ** i) - (1-goldenRatio)**i)/math.sqrt(5)) for i in range(1001)] if int(n) in seq: print(cl("The number you gave is a part of the Fibonacci sequence!", "blue")) else: print(cl("Sorry! That number is not a part of the Fibonacci sequence!", "red")) del seq
def e(self, eid): """Get an Entity """ ta = datetime.datetime.now() rs = self.rest('GET', self.uri_db + '-/entity', data={'e': int(eid)}, parse=True) tb = datetime.datetime.now() - ta print cl( '<<< fetched entity %s in %sms' % (eid, tb.microseconds / 1000.0), 'cyan') return rs
def debug(self, defn, args, kwargs, fmt=None, color='green'): """ debug timing, colored terminal output """ ta = datetime.datetime.now() rs = defn(*args, **kwargs) tb = datetime.datetime.now() - ta fmt = fmt or "processed {defn} in {ms}ms" logmsg = fmt.format(ms=tb.microseconds / 1000.0, defn=defn) "terminal output" print cl(logmsg, color) "logging output" logging.debug(logmsg) return rs
def debug(self, defn, args, kwargs, fmt=None, color='green'): """ debug timing, colored terminal output """ ta = datetime.datetime.now() rs = defn(*args, **kwargs) tb = datetime.datetime.now() - ta fmt = fmt or "processed {defn} in {ms}ms" logmsg = fmt.format(ms=tb.microseconds/1000.0, defn=defn) "terminal output" print cl(logmsg, color) "logging output" logging.debug(logmsg) return rs
def datoms(self, index='aevt', e='', a='', v='', limit=0, offset=0, chunk=100, start='', end='', since='', as_of='', history='', **kwargs): """ Returns a lazy generator that will only fetch groups of datoms at the chunk size specified. http://docs.datomic.com/clojure/index.html#datomic.api/datoms """ assert index in ['aevt', 'eavt', 'avet', 'vaet'], "non-existant index" data = { 'index': index, 'a': ':{0}'.format(a) if a else '', 'v': dump_edn_val(v) if v else '', 'e': int(e) if e else '', 'offset': offset or 0, 'start': start, 'end': end, 'limit': limit, 'history': 'true' if history else '', 'as-of': int(as_of) if as_of else '', 'since': int(since) if since else '', } data['limit'] = offset + chunk rs = True while rs and (data['offset'] < (limit or 1000000000)): ta = datetime.datetime.now() rs = self.rest('GET', self.uri_db + '-/datoms', data=data, parse=True) if not len(rs): rs = False tb = datetime.datetime.now() - ta print cl( '<<< fetched %i datoms at offset %i in %sms' % (len(rs), data['offset'], tb.microseconds / 1000.0), 'cyan') for r in rs: yield r data['offset'] += chunk
def printBoard(self, s, b, score, x, y, count, bx, by, life, level): print("Your Score is ", score) print("No of lives left ", life) print("You are on level ", level) print("Press q to quit") for i in range(42): for j in range(68): if s[i][j] == 2: print(cl("^", "yellow"), end="") elif b[i][j] == 2: print(cl("E", "red"), end="") elif b[i][j] == 1: print(cl("B", "white"), end="") elif s[i][j] == 0 and b[i][j] == 0: print(" ", end="") elif s[i][j] == 1 and b[i][j] == 0: print(cl("#", "cyan"), end="") elif s[i][j] == 3 and b[i][j] == 0: if j == by: print(cl("[", "yellow"), end="") elif j == by + 1 or j == by + 2: print(cl(count, "yellow"), end="") elif j == by + 3: print(cl("]", "yellow"), end="") elif s[i][j] == 4 and b[i][j] == 0: print(cl("/", "green"), end="") print(" ")
def rest(self, method, uri, data=None, status_codes=None, parse=True, **kwargs): """ Rest helpers """ r = self.pool.request_encode_body(method, uri, fields=data, encode_multipart=False) if not r.status in (status_codes if status_codes else (200,201)): print cl('\n---------\nURI / REQUEST TYPE : %s %s' % (uri, method), 'red') print cl(data, 'red') print r.headers raise Exception, "Invalid status code: %s" % r.status if not parse: " return raw urllib3 response" return r if not self.debug_loads: " return parsed edn" return loads(r.data) "time edn parse time and return parsed edn" return self.debug(loads, args=(r_data, ), kwargs={}, fmt='<<< parsed edn datastruct in {ms}ms', color='green')
def ievade(): turpinam = True modelis = ieladet_modeli("ss-modelis.pickle") print( cl("Auto cenu prognoze. Ievadiet pieprasītos datus, lai saņemtu prognozi.", "green", attrs=["reverse"])) while turpinam: gads = int(input("Auto izlaišanas gads vai 0, lai izietu: ")) if gads == 0: turpinam = False continue tilpums = float(input("Dzinēja tilpums: ")) nobraukums = float(input("Nobraukums, tūkstošos km.: ")) dati = [[gads, tilpums, nobraukums]] prognoze = prognozejam_rezultatu(modelis, dati) print("Prognozētā cena:", cl(round(prognoze[0]), "green", attrs=["bold"])) print()
def quoteADay(): goodReads = "https://www.goodreads.com/quotes" goodClient = req(goodReads) site_parse_quote = soup(goodClient.read(), "lxml") goodClient.close() #Pull from the left container quotesOnly = site_parse_quote.find("div", {"class": "leftContainer"}) #Randomly choose a quote from the front page ranQuote = quotesOnly.find("div", {"class": "quotes"}).findAll("div", {"class": "quote"})[rn.randrange(30)] #Pull info from ranQuote sourceQuote = ranQuote.find("span").text.strip() quote = ranQuote.find("div", {"class": "quoteText"}).text.strip().split('\n')[0] #Give a little background info about the author of the quote authorInfo = wiki.summary(sourceQuote, sentences=1) print(cl(quote, "green")) print(cl('~'+'\033[1m'+sourceQuote+'~', "magenta")) print(cl(authorInfo, "magenta"))
def banner(name=None): return ''' --------------------------------------------------------------- ''' + cl( ''' ██╗ ███████╗██╗████████╗███████╗██████╗ ██████╗ ██████╗ ██║ ██╔════╝██║╚══██╔══╝██╔════╝██╔══██╗ ╚════██╗ ██╔═████╗ ██║ █████╗ ██║ ██║ █████╗ ██████╔╝ █████╔╝ ██║██╔██║ ██║ ██╔══╝ ██║ ██║ ██╔══╝ ██╔══██╗ ██╔═══╝ ████╔╝██║ ███████╗██║ ██║ ██║ ███████╗██║ ██║ ███████╗██╗╚██████╔╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═════╝ ''', 'red' ) + ''' ------------------------------------------------ By 3mrgnc3 ---
def taskSix(): """ Write a program with a variable 'age' assigned to an integer that prints different strings depending on what integer 'age' is """ quote_one = """The timeless in you is aware of life's timelessness. And knows that yesterday is but today's memory and tomorrow is today's dream. ~ Khalil Gibran""" quote_two = "What happens when people open their hearts? They get better. ~ Haruki Murakami" quote_three = "You only live once, but if you do it right, once is enough. ~ Mae West" quote_four = """I've learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel. ~ Maya Angelou""" quote_five = """Non est ad astra mollis e terris via. (There is no easy way from the earth to the stars) ~ Seneca""" age = input("How old are you? ") if int(age) <= 10: print(cl("Life has yet begun for you!", "cyan")) elif int(age) > 10 and int(age) <= 20: print(cl(quote_one + "\n", "magenta")) elif int(age) > 20 and int(age) <= 40: print(cl(quote_two + "\n", "blue")) elif int(age) > 40 and int(age) <= 60: print(cl(quote_three + "\n", "green")) elif int(age) > 60 and int(age) <= 80: print(cl(quote_four + "\n", "magenta")) elif int(age) > 80: print(cl(quote_five + "\n", "cyan"))
def taskOne(): #Print three different strings #I added a bit more to this task by pulling three different #quotes from GoodReads goodReads = "https://www.goodreads.com/quotes" goodClient = req(goodReads) quote_parse = soup(goodClient.read(), "lxml") goodClient.close() #Hold quotes into list from main page hold = quote_parse.find_all("div", {"class": "quoteText"}) #String one prints a random quote with its author strOneRn = rn.randrange(30) strOneQte = hold[strOneRn].text.strip().split("\n")[0] strOneAthr = hold[strOneRn].text.strip().split("\n")[3].strip() string_one = strOneQte + " ~ " + strOneAthr.strip() #String two prints a random quote with its author strTwoRn = rn.randrange(30) strTwoRan = rn.randint(0, 30) if strTwoRn == strOneRn else strTwoRn strTwoQte = hold[strTwoRan].text.strip().split("\n")[0] strTwoAthr = hold[strTwoRan].text.strip().split("\n")[3].strip() string_two = strTwoQte + " ~ " + strTwoAthr.strip() #String three prints a random quote with its author strThreeRn = rn.randrange(30) strThreeRan = rn.randint( 0, 30) if strThreeRn == (strTwoRn or strOneRn) else strThreeRn strThreeQte = hold[strThreeRan].text.strip().split("\n")[0] strThreeAthr = hold[strThreeRan].text.strip().split("\n")[3].strip() string_three = strThreeQte + " ~ " + strThreeAthr.strip() print("This task prints out three strings, or rather three quotes.\n") print(cl(string_one + "\n", "cyan")) print(cl(string_two + "\n", "green")) print(cl(string_three, "blue")) del hold
def fizzBuzz(start, stop): #Create a file to hold the answer file = open('fizzBuzz.txt', "w") for i in range(int(start), int(stop) + 1): if (i % 3 == 0) and (i % 5 != 0): file.write('Fizz\n') print(cl('Fizz', 'red')) elif (i % 5 == 0) and (i % 3 != 0): file.write('Buzz\n') print(cl('Buzz', 'blue')) elif (i % 3 == 0) and (i % 5 == 0): file.write('FizzBuzz\n') print(cl('FizzBuzz', 'magenta')) elif (i % 3 != 0) and (i % 5 != 0): file.write(str(i)) file.write('\n') print(str(i)) file.close()
def taskTwo(): """ Write a program that prints a message if a variable is less than 10, and a different message if a variable is greater than or equal to 10. """ strLess = "Books are a uniquely portable magic. ~ Stephen King" strGrtTen = """\tMemories warm you up from the inside. But they also tear you apart. ~ Haruki Murakami""" pick = input("Please pick a number from 0 to 20 to get a quote: ") checker = [str(i) for i in range(0, 21)] if pick in checker: print( cl(strLess, "cyan") if int(pick) < 10 else cl(strGrtTen, "green")) else: print(cl("Please try again!\n", "red")) taskTwo() del checker
def wordADay(): nary = "https://www.dictionary.com/e/word-of-the-day/" naryClient = req(nary) site_parse_nary = soup(naryClient.read(), "lxml") naryClient.close() #Pull from 'Word of the Day' wrapper wordDayCase = site_parse_nary.find("div", {"class": "wotd-item-wrapper"}) #Pull the word itself wordDay = wordDayCase.find("div", {"class": "wotd-item-headword__word"}).text.strip() #Pull the pronunciation wordSpeak = wordDayCase.find("div", {"class": "wotd-item-headword__pronunciation"}).text.strip() #Pull the definition wordMean = wordDayCase.find("div", {"class": "wotd-item-headword__pos-blocks"}) wordType = wordMean.find("span").text.strip() wordDef = wordMean.findAll("p")[1].text.strip() print(cl(wordDay, "blue")) print(cl(wordSpeak, "red")) print(cl("----------------------", "grey")) print(cl("Word type: " + wordType, "cyan")) print(cl(wordDef, "blue"))
def deustchesWort(): dicttu = "https://dict.tu-chemnitz.de/dings.cgi?o=3020;service=deen;random=en" dictClient = req(dicttu) site_parse_deutsch = soup(dictClient.read(), "lxml") dictClient.close() #Pull a subject in order to find a word subDeutsch = site_parse_deutsch.find("div", {"class": "result"}).find("table", {"id": "result"}) wortAlles = subDeutsch.find("tbody", {"id": "h1"}).find("tr", {"class": "s1"}).text.strip() wort = wortAlles.split('\n')[0] wortDef = wortAlles.split('\n')[1] print(cl("Deutsches Wort: ", "yellow")) print(cl(wort, "blue")) print(cl("auf Englisch: " + wortDef, "red")) #In case a search is incomplete or not found try: wortInfo = wiki.summary(wortDef,sentences=2, auto_suggest=False) except: print("Page not found for English entry") else: print(cl(wortInfo, "green"))
def info(datne): print(cl("\n\nInformācija par datni " + datne, 'green', attrs=['reverse'])) # # importējam datus # # df is saīsinajums no Data Frame, # # Pandas bibliotēkas pamata datu struktūras df = pd.read_csv(datne) # # apskatīt pirmās 5 datu rindiņas print(cl("\nPirmās 5 rindiņas", attrs=['bold'])) print(df.head(5)) # # aplūkojam kolonnu nosaukumus # print(cl("\nKolonnu nosaukumi", attrs = ['bold'])) # print(df.columns) # # aplūkojam statistisku informāciju # print(cl("\nStatistika", attrs = ['bold'])) print(df.describe()) # print(cl("\nDatu tipi", attrs = ['bold'])) # aplūkojam datu tipus # print(cl(df.dtypes, attrs = ['bold'])) # # parāda, kur datos ir tukšas vērtības # print(cl("\nTukšas vērtības datos", attrs = ['bold'])) print(df.isnull().sum())
def main(): #Let the user pick a task which will #return that task's solution print( cl( "Welcome! This program prints out the solutions " + "of the challenges section in Chapter Three " + "of Cory Althoff's The Self-Taught Programmer. ", "blue")) task = input( cl("Please choose a task by typing" + "in a number from 1 to 6: ", "blue")) check = [str(i) for i in range(1, 7)] if task in check: print( cl("Thank you for choosing a task! The solution will now print.", "magenta")) if task == check[0]: taskOne() elif task == check[1]: taskTwo() elif task == check[2]: taskThree() elif task == check[3]: taskFour() elif task == check[4]: taskFive() elif task == check[5]: taskSix() else: print(cl("Please choose a number between 1 to 6!", "red")) main()
def main(): load() while True: sys.stdout.write(cl('>>>', 'blue') + ' ') line = sys.stdin.readline().strip('\n').split() if (len(line) == 0): continue if (line[0] == ':quit'): return try: execute(line) save() except Exception as e: print e
def taskFour(): #Create a program that divides two variables and prints the remainder print( cl( "Choose two numbers and we shall return the " + "remainder from its division.", "magenta")) num_one = input("Choose a dividend: ") num_two = input("Now, choose a divisor: ") remainder = int(num_one) % int(num_two) print("\n") print(num_one + " divided by " + num_two + " returns a remainder of " + str(remainder))
def taskFive(): #Create a program that takes two variables, divides them, and prints #the quotient print( cl( "Choose two numbers and we shall return the " + "quotient from its division.", "magenta")) num_one = input("Choose a dividend: ") num_two = input("Now, choose a divisor: ") quotient = int(num_one) / int(num_two) print("\n") print(num_one + " divided by " + num_two + " returns a quotient of " + str(quotient))
def main(): if len(sys.argv) < 3: ievade() else: parser = argparse.ArgumentParser( prog='autocena', description= """Nosaka auto cenu, izmantojot uz reāliem datiem trenētu modeli""" ) parser.add_argument('gads') parser.add_argument('tilpums') parser.add_argument('nobraukums') args = parser.parse_args() print(args) dati = [[args.gads, args.tilpums, args.nobraukums]] modelis = ieladet_modeli("ss-modelis.pickle") prognoze = prognozejam_rezultatu(modelis, dati) print("Prognozētā cena:", cl(round(prognoze[0]), "green", attrs=["bold"]))
for i in df.columns: df[i] = df[i].astype(int) df.head() df.describe() df.info() # Splitting the data X_var = np.asarray( df[['tenure', 'age', 'income', 'ed', 'employ', 'longmon', 'custcat']]) y_var = np.asarray(df['churn']) print(cl('X_var samples : ', attrs=['bold']), X_var[:5]) print(cl('y_var samples : ', attrs=['bold']), y_var[:5]) X_var = StandardScaler().fit(X_var).transform(X_var) print(cl(X_var[:5], attrs=['bold'])) X_train, X_test, y_train, y_test = train_test_split(X_var, y_var, test_size=0.3, random_state=4) print(cl('X_train samples : ', attrs=['bold']), X_train[:5]) print(cl('X_test samples : ', attrs=['bold']), X_test[:5]) print(cl('y_train samples : ', attrs=['bold']), y_train[:10]) print(cl('y_test samples : ', attrs=['bold']), y_test[:10])
# IMPORTING DATA df = pd.read_csv('Dataset.csv') df.drop('Time', axis = 1, inplace = True) print(df.head()) # Count & percentage cases = len(df) nonfraud_count = len(df[df.Class == 0]) fraud_count = len(df[df.Class == 1]) fraud_percentage = round(fraud_count/nonfraud_count*100, 2) print(cl('CASE COUNT', attrs = ['bold'])) print(cl('--------------------------------------------', attrs = ['bold'])) print(cl('Total number of cases are {}'.format(cases), attrs = ['bold'])) print(cl('Number of Non-fraud cases are {}'.format(nonfraud_count), attrs = ['bold'])) print(cl('Number of Non-fraud cases are {}'.format(fraud_count), attrs = ['bold'])) print(cl('Percentage of fraud cases is {}'.format(fraud_percentage), attrs = ['bold'])) print(cl('--------------------------------------------', attrs = ['bold'])) # Description nonfraud_cases = df[df.Class == 0] fraud_cases = df[df.Class == 1] print(cl('CASE AMOUNT STATISTICS', attrs = ['bold'])) print(cl('--------------------------------------------', attrs = ['bold'])) print(cl('NON-FRAUD CASE AMOUNT STATS', attrs = ['bold']))
def __repr__(self): return "{'db/id': %s}" % cl(self._eid, 'magenta')