def main(): print figlet_format("sql-bool") parser = OptionParser(usage='Usage: python %prog [options]',version='%prog 1.2') parser.add_option("-u","--URL",action="store", type="string",dest="url", help="target url") parser.add_option("-D","--DB",action="store", type="string",dest="db_name", help="get database name") parser.add_option("-T","--TBL",action="store", type="string",dest="table_name", help="get table name") parser.add_option("-C","--COL",action="store", type="string",dest="column_name", help="get column name") parser.add_option("--dbs",action="store_true", dest="dbs",help="get all database name") (options,args) = parser.parse_args() if options == None or options.url == None: parser.print_help() elif options.column_name and options.table_name and options.db_name: getAllcontent(options.url,options.column_name,options.table_name,options.db_name) elif options.table_name and options.db_name: getAllColumnsByTable(options.url,options.table_name,options.db_name) elif options.db_name: getAllTablesByDb(options.url,options.db_name) elif options.dbs: getAllDatabases(options.url) elif options.url: parser.print_help()
def main(): print figlet_format('Stats!', font=fonts[random.randrange(len(fonts))]) if geo or everything: getCountryStats() if address or everything: getAddresses() if ports or everything: getPorts() if usernames or credentials or everything: getUsernames() if passwords or credentials or everything: getPasswords() if honeypots or everything: getHoneypots() if malware or everything: getMalware() print "Total attacks: " + str(totalAttacks)
def getPorts(): print "Distinct ports attacked: " + executeQuery("db.session.distinct('destination_port').length") if verbose or veryVerbose: portList = executeQuery("db.session.aggregate({\$group:{_id:'\$destination_port','count':{\$sum:1}}},{\$sort:{count:-1}}).forEach(function(x){printjson(x)})").split('\n') for pair in portList: match = re.search(r'"_id" : (\d+), "count" : (\d+) }',pair) if match: countByPort[match.group(1)] = int(match.group(2)) print figlet_format('Ports', font='small') graph = Pyasciigraph() for line in graph.graph('', sorted(countByPort.items(), key=operator.itemgetter(1), reverse=True)): print(line) print else: portList = executeQuery("db.session.aggregate({\$group:{_id:'\$destination_port','count':{\$sum:1}}},{\$sort:{count:-1}},{\$limit:10}).forEach(function(x){printjson(x)})").split('\n') for pair in portList: match = re.search(r'"_id" : (\d+), "count" : (\d+) }',pair) if match: countByPort[match.group(1)] = int(match.group(2)) print figlet_format('Ports ( Top 10 )', font='small') graph = Pyasciigraph() for line in graph.graph('', sorted(countByPort.items(), key=operator.itemgetter(1), reverse=True)): print(line) print
def winner(name=None): history.store_winner(name) if name is "draw": print(figlet_format("A {0}!!!".format(name), font="big")) else: print(figlet_format("{0} wins!!!".format(name), font="big"))
def handle(self, *args, **options): print "Opening pokedex..." if options['pk']: pk = int(options['pk']) else: pk = randint(0,400) print pk response = requests.get("https://phalt-pokeapi.p.mashape.com/pokemon/%s/" % pk, headers={ "X-Mashape-Key": "qEgnkvwWh4mshIfmA0n6zAbMPOjjp1Tlf7VjsntSR4MBqEosIl", "Accept": "application/json" } ) pokemon = json.loads(response.content) urban = self.get_urban_dictionary_word(pokemon["name"]) print "" print figlet_format(pokemon["name"], font="big") if urban["definition"]: print "--------------------------------------------------------------------------------" print urban["definition"] print "" print "%s" % urban["url"] if urban["photo"]: print urban["photo"] photo = StringIO(urllib.urlopen(urban["photo"]).read()) print photo response = twitter_conn.upload_media(media=photo) twitter_conn.update_status(status=pokemon["name"], media_ids=[response['media_id']])
def print_welcome(): from pyfiglet import figlet_format import time # big, doom, larry3d,starwars,slant, small,speed,mini, standard; script font = "straight" print figlet_format(' MORSE CODE ', font=font) print figlet_format('* KARAOKE *', font=font) time.sleep(4)
def getMalware(): print "Malware samples: " + executeQuery("db.session.distinct('attachments.hashes.md5').length") print figlet_format('md5 hashes', font='small') md5List = executeQuery("db.session.distinct('attachments.hashes.md5')").split(',') i = 1 for malware in md5List: print " "+str(i)+": "+malware i = i + 1
def intro(): init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected cprint(figlet_format('kitty', font='starwars'), 'white', 'on_red', attrs=['bold']) cprint(figlet_format('the', font='starwars'), 'white', 'on_red', attrs=['bold']) cprint(figlet_format('game', font='starwars'), 'white', 'on_red', attrs=['bold'])
async def _ascii(self, *, text): msg = str(figlet_format(text, font='cybermedium')) if msg[0] == " ": msg = "." + msg[1:] error = figlet_format('LOL, that\'s a bit too long.', font='cybermedium') if len(msg) > 2000: await self.bot.say(box(error)) else: await self.bot.say(box(msg))
def getHoneypots(): honeypotList = executeQuery("db.session.aggregate({\$group:{_id:'\$honeypot','count':{\$sum:1}}},{\$sort:{count:-1}}).forEach(function(x){printjson(x)})").split('\n') for pair in honeypotList: match = re.search(r'"_id" : "(.*)", "count" : (\d+) }',pair) if match: attacksByHoneypot[match.group(1)] = int(match.group(2)) print figlet_format('Honeypots', font='small') graph = Pyasciigraph() for line in graph.graph('', sorted(attacksByHoneypot.items(), key=operator.itemgetter(1), reverse=True)): print(line) print
def __init__(self): self.last_epoch = self.get_last_epoch() if not self.last_epoch: cprint(figlet_format("No document exists in mongodb, STARTING FRESH :) ", font='mini'), attrs=['bold']) self.articles = self.fetch_articles_mongo() if not self.articles: cprint(figlet_format("No new documents beeds to updated to elastic search", font='mini'), attrs=['bold']) else: self.feed_elasticsearch() return
def main(): print figlet_format("sqli-error") parser = OptionParser() parser.add_option("-u","--URL",action="store", type="string",dest="url", help="get url") parser.add_option("-D","--DB",action="store", type="string",dest="db_name", help="get database name") parser.add_option("-T","--TBL",action="store", type="string",dest="table_name", help="get table name") parser.add_option("-C","--COL",action="store", type="string",dest="column_name", help="get column name") parser.add_option("--dbs",action="store_true", dest="dbs",help="get all database name") parser.add_option("--current-db",action="store_true", dest="current_db",help="get current database name") parser.add_option("--current-user",action="store_true", dest="current_user",help="get current user name") parser.add_option("--tables",action="store_true", dest="tables",help="get tables from databases") parser.add_option("--columns",action="store_true", dest="columns",help="get columns from tables") parser.add_option("--dump",action="store_true", dest="dump",help="get value") (options,args) = parser.parse_args() # parser.print_help() # print options # print args if options == None or options.url == None: parser.print_help() elif options.dump and options.column_name and options.table_name and options.db_name: getAllcontent(options.url,options.column_name,options.table_name,options.db_name) elif options.table_name and options.db_name: getAllColumnsByTable(options.url,options.table_name,options.db_name) elif options.db_name: getAllTablesByDb(options.url,options.db_name) elif options.dbs: getAllDatabases(options.url) elif options.current_db: getCurrentDb(options.url) elif options.current_user: getCurrentUser(options.url) elif options.url: print "you input: sqli-error.py -u www.xxx.com/?id=xx"
def startupmessage(): print("Welcome. This is the rule booklet for the DPS East c0def3st") time.sleep (3) cleardeadbodies() print("Prepare well young 'un.") time.sleep(3) cleardeadbodies() time.sleep(4) cprint(figlet_format(' DPS EAST ', font='starwars'), 'yellow', 'on_red', attrs=['bold']) print("PRESENTS:") time.sleep(4) cleardeadbodies() cprint(figlet_format(' c0de f3st', font='starwars'), 'cyan', 'on_grey', attrs=['bold'])
def cli(recursive, path): if not path: path = '.' click.clear() cprint(figlet_format('lsBranch', width=120), 'red') click.secho(' '*25 + 'by Ivan Arar', fg='red') lsbranch = lsBranch(path=path) click.echo() click.echo('-'*lsbranch.terminal_size) click.echo() lsbranch.search(recursive=recursive) click.echo('-'*lsbranch.terminal_size) click.echo() click.secho('Went through ' + str(lsbranch.counter_all()) + ' directories and found ' + str(lsbranch.counter_git()) + ' git repositories!', fg='blue', bold=True, blink=True) click.echo() click.echo('-'*lsbranch.terminal_size) click.echo()
def instructions(stdscr): # Title myscreen.clear() myscreen.addstr(1, 1, figlet_format('Code Breaker', font='big', justify = 'center'), curses.color_pair(3)) # Instructions def calcx(string1): y, x = myscreen.getmaxyx() return int(x)/2-len(string1)/2 line1 = "The objective of the game is to find the correct code." line2 = "The code is being automatically bruteforced on the left side of the screen." line3 = "The menu on the bottom-left lets you enter a range for the bruteforcer." line4 = "The menu on the right lets you try and test numbers." line5 = "If you test the right number or the bruteforcer finds it, you win." line6 = "Green numbers have 4 bits in common with the code, red numbers do not." line7 = "You are going to need a programmer's calculator to play this game." line8 = "One can be found by switching your computer's calculator to Programmer mode." line9 = "Press any key to go back to the main menu." myscreen.addstr(9, calcx(line1), line1) myscreen.addstr(10, calcx(line2), line2) myscreen.addstr(11, calcx(line3), line3) myscreen.addstr(12, calcx(line4), line4) myscreen.addstr(13, calcx(line5), line5) myscreen.addstr(14, calcx(line6), line6) myscreen.addstr(15, calcx(line7), line7) myscreen.addstr(16, calcx(line8), line8) myscreen.addstr(18, calcx(line9), line9, curses.color_pair(1)|curses.A_BOLD) # Press any key to continue myscreen.refresh() myscreen.getch() startScreen(stdscr)
def banner(): global version from pyfiglet import figlet_format b = figlet_format(" CROZONO") + \ ''' Free Version - {v} www.crozono.com - [email protected] '''.format(v=version) print(b)
def ascii_art(text): """ Draw the Ascii Art """ fi = figlet_format(text, font='doom') print('\n'.join( [next(g['cyc'])(i) for i in fi.split('\n')] ))
async def font(self, ctx, *, txt: str): """Change font for ascii. All fonts: http://www.figlet.org/examples.html for all fonts.""" try: str(figlet_format('test', font=txt)) except (FontError, FontNotFound): return await ctx.send(self.bot.bot_prefix + 'Invalid font type.') write_config_value("optional_config", "ascii_font", txt) await ctx.send(self.bot.bot_prefix + 'Successfully set ascii font.')
def print_score(username, userscore): from pyfiglet import figlet_format import time # big, doom, larry3d,starwars,slant, small,speed,mini, standard; script print figlet_format('WELL DONE', font='straight') print figlet_format('{0}!'.format(username), font='straight') time.sleep(2) print figlet_format('YOUR SCORE:', font='straight') print figlet_format('{0} %!'.format(userscore), font='straight') time.sleep(3)
def _print(self, limit): click.clear() cprint(figlet_format('Croatian Tax Debtors', width=120), 'red') click.echo() categories = self.data['counters'].keys() number_of_categories = len(categories) screen_line_parts = [] for cat in self.data['width'].keys(): screen_line_parts.append('-'*(self.data['width'][cat]+16)) screen_line_parts.append(' '*4) screen_line = ''.join(screen_line_parts) if self._all_count: all_count = '/' + str(self._all_count) else: all_count = '' for i, category in enumerate(categories): cat_width = self.data['width'][category]+20 nl = True if i+1 >= number_of_categories else False color = self.data['colors'][category] category += ' (' + str(self.data['counters'][category]) + all_count + ')' click.secho(category.upper() + (' '*(cat_width-len(category))), nl=nl, fg=color) click.echo(screen_line) cat_line_width = {category: 0 for category in categories} for j in range(int(limit)): for i, category in enumerate(categories): if len(self.data['toplist'][category]) <= j: click.echo(' '*cat_line_width[category]) else: cat_width = self.data['width'][category] nl = True if i+1 >= number_of_categories else False color = self.data['colors'][category] debtor = self.data['toplist'][category][j] dots = '.'*(cat_width-len(debtor[0])) line = click.style(debtor[0], fg=color) + ' ' + \ click.style(dots, dim=True, fg=color) + ' ' + \ click.style(debtor[1], fg=color) line_len = len(debtor[0])+len(dots)+len(debtor[1])+2 click.echo(line + ' '*((cat_width+20)-line_len), nl=nl) cat_line_width[category] = len(line) click.echo(screen_line) click.echo()
def print_splash_page(self): if sys.stdout.isatty(): text = figlet_format('AgentServer', width=120, font='slant').rstrip() cprint(text, 'red', attrs=['blink']) width = reduce(max, map(len, text.split('\n'))) title = 'AgentServer v{0}'.format(__version__) centered_title = title.center(width, ' ') cprint(centered_title, 'red')
def intro(self): print('\t ') cprint(figlet_format("MAKE A NOTE"), 'green') print('-------------------------------------------------------------------------') print('\t\t Hello, Welcome to NoteBook') print('\t A Simple interactive console app for making and modifying notes') print('. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ') print('\t\t For any help please print help then enter') print('-------------------------------------------------------------------------')
async def ascii(self,ctx,text:str,font:str,textcolor='',background=''): """Creates ASCII text.""" if ctx.invoked_subcommand is None: if not textcolor: textcolor = "white" if not background: background = "black" if font == "barbwire": text = text.replace(""," ") img = Image.new('RGB', (2000, 1000)) d = ImageDraw.Draw(img) d.text((20, 20), figlet_format(text, font=font), fill=(255, 0, 0)) text_width, text_height = d.textsize(figlet_format(text, font=font)) img1 = Image.new('RGB', (text_width + 30, text_height + 30),background) d = ImageDraw.Draw(img1) d.text((20, 20), figlet_format(text, font=font), fill=textcolor, anchor="center") text_width, text_height = d.textsize(figlet_format(text, font=font)) img1.save("mods/utils/images/other/ascii.png") await self.bot.send_file(ctx.message.channel,"mods/utils/images/other/ascii.png")
def banner(): global version from pyfiglet import figlet_format b = figlet_format(" CROZONO") + \ ''' Sheila A. Berta - Nicolás Villanueva {v} Software Development Pablo Romanos - Hardware Implementation '''.format(v=version) print(b)
def update ( self ): self.win.clear() self.win.box() t = self.matchTimer.currentTime() t_string = pyfiglet.figlet_format ( str ( t ), font = "big" ) if t is not None: for i, line in enumerate ( t_string.rstrip().split('\n') ): self.win.addstr ( 1 + i, 2, line ) subWin.SubWindow.update ( self )
def get_answer(host): '''Tell the client they are about to learn a random fact.''' print(figlet_format("FACT OF THE DAY!")) server_url = host + 'randomfact' response = requests.get(url=server_url) if response.status_code == 200: answer = response.text else: answer = str(response.status_code) + ' error' return answer
def read_script(filename, characters, start, end): with open(filename) as f: started = False ended = False for line in f: line = line.strip() if not started and line == "<{start}>".format(start=start): started = True elif started and line == "</{end}>".format(end=end): ended = True if not started: continue if any(line == "<{act}>".format(act=act) for act in Acts.all()) or \ any(line == "</{act}>".format(act=act) for act in Acts.all()): # Either the beginning or end of an act, so clear the screen. clear_screen() print_line_in_color(figlet_format(line, font="starwars"), Colors.YELLOW) print_line_in_color(line, Colors.YELLOW, bold=True) # Press [Enter] to continue. input() clear_screen() continue # Figure out if this is a line of dialog. placeholder, dialog = get_character_placeholder_and_dialog(line) # Do name and pronoun replacements for line to be printed on screen. line = replace_gender_pronouns(line, characters) line = replace_placeholder_names(line, characters) if not line: print() elif line and not dialog: # Stage direction. Press [Enter] to continue. print_line_in_color(line, Colors.YELLOW, bold=True, remove_trailing_newline=True) input() else: # Dialog! character = characters.get(placeholder) print_line_in_color(line, character.color) # Do name and pronoun replacements for the dialog to be spoken. dialog = replace_gender_pronouns(dialog, characters) dialog = replace_placeholder_names(dialog, characters) character.say(dialog) if ended: break
def do_art(first_name: str, last_name: str): if False != is_installed('pyfiglet'): from colorama import init init(strip = not sys.stdout.isatty()) # strip colors if stdout is redirected from termcolor import cprint from pyfiglet import figlet_format cprint(figlet_format('{fn} {}'.format(last_name, fn=first_name), font='starwars'), 'yellow', 'on_red', attrs=['bold']) else: print("oh I'm sorry it seems that the system didn't have the correct thing to show the trick")
def prep_news_index(self): ES_CLIENT.indices.create(index="news", body=self.settings) """ for __sub_category in ['f1', 'cricket', 'basketball', 'None', 'tennis', 'football']: ES_CLIENT.indices.put_mapping(index="news", doc_type=__sub_category, body = {__sub_category: self.mappings }) a = "Mappings updated for {0}".format(__sub_category) cprint(figlet_format(a, font='mini'), attrs=['bold']) """ ES_CLIENT.indices.put_mapping(index="news", doc_type="news", body = {"news": self.mappings }) a = "Mappings updated for {0}".format("news") cprint(figlet_format(a, font='mini'), attrs=['bold']) return
import pyfiglet result = pyfiglet.figlet_format("Puan Durumu") print(result) import requests import pandas as pd from bs4 import BeautifulSoup import numpy as np url = "https://tr.beinsports.com/lig/super-lig/puan-durumu" response = requests.get(url) html_icerigi = response.content soup = BeautifulSoup(html_icerigi,"html.parser") players={ "Player1": ['Galatasaray', 'Trabzonspor', 'Fenerbahçe', 'M.Başakşehir', 'DG Sivasspor','Göztepe','Beşiktaş', 'Aytemiz Alanyaspor'], "Player2" : ['M.Başakşehir','Trabzonspor','DG Sivasspor', 'Galatasaray','Fenerbahçe', 'Aytemiz Alanyaspor','Beşiktaş','Göztepe'], "Player3": ['Fenerbahçe', 'Trabzonspor','M.Başakşehir','Galatasaray','Aytemiz Alanyaspor','DG Sivasspor','Göztepe','Beşiktaş'], "Player4": ['Trabzonspor','M.Başakşehir','Galatasaray','Fenerbahçe','DG Sivasspor','Beşiktaş', 'Göztepe','Aytemiz Alanyaspor'], "Player5": ['Galatasaray', 'Trabzonspor', 'Fenerbahçe','Beşiktaş','DG Sivasspor','Aytemiz Alanyaspor','Göztepe','Gaziantep FK'], "Player6" : ['Trabzonspor','M.Başakşehir','Galatasaray','Fenerbahçe','DG Sivasspor','Beşiktaş','Aytemiz Alanyaspor','Göztepe'], "Player7": ['Galatasaray','M.Başakşehir', 'Trabzonspor','Fenerbahçe','DG Sivasspor','Beşiktaş','Aytemiz Alanyaspor','Göztepe'], "Player8": ['Trabzonspor','Galatasaray','M.Başakşehir','Fenerbahçe','DG Sivasspor','Beşiktaş','Aytemiz Alanyaspor','Göztepe'] } teams = [team.text.strip() for team in soup.find_all("td", {"class":"team_link"})] #print('Güncel Puan Tablosu :' "\n", "\n", teams, "\n")
def main(): start = ApkBleach() payload_path = pkg_resources.resource_filename(__name__, f'res/Cache') # Ascii art banner = figlet_format('ApkBleach', font='crawford') print(Fore.BLUE) print('\n'.join( l.center(os.get_terminal_size().columns) for l in banner.splitlines())) print( f'\t\t{Fore.YELLOW}Version: {Fore.BLUE}2.0 {Fore.YELLOW}Author: {Fore.BLUE}graylagx2\n' .center(os.get_terminal_size().columns)) start.check_dependencies() global stop_spin stop_spin = False gen_loading = threading.Thread( target=spin, args=(f"{Fore.YELLOW}Generating payload ", f"{Fore.YELLOW}Payload generated {Fore.GREEN}[*] ")) gen_loading.start() generate = start.generate_payload() stop_spin = True gen_loading.join() print("\n") if generate[0] == 'Error': for repeat in range(2): print("\033[A \033[A") os.remove(f"{payload_path}/apkbleach_error.log") sys.exit(f"\t{Fore.RED}{generate[1]}{Fore.RESET}\n".center( os.get_terminal_size().columns)) stop_spin = False dec_loading = threading.Thread( target=spin, args=(f"{Fore.YELLOW}Decompiling apk ", f"{Fore.YELLOW}Apk decompiled {Fore.GREEN}[*] ")) dec_loading.start() start.decompile_apk() if os.path.isfile( f'{payload_path}/bleach_me.apk') else sys.exit( "Can not find payload Apk") stop_spin = True dec_loading.join() print("\n") start.bleach_apk() print(f"{Fore.YELLOW}Apk bleached {Fore.GREEN}[*] \n") try: if start.icon: stop_spin = False icon_inject_loading = threading.Thread( target=spin, args=(f"{Fore.YELLOW}Injecting icon ", f"{Fore.YELLOW}Icon injected{Fore.GREEN} [*] ")) icon_inject_loading.start() start.icon_inject() stop_spin = True icon_inject_loading.join() print("\n") except AttributeError: pass if start.deploy_all: stop_spin = False icon_inject_loading = threading.Thread( target=spin, args=(f"{Fore.YELLOW}Injecting icons ", f"{Fore.YELLOW}Icons injected{Fore.GREEN} [*] ")) icon_inject_loading.start() start.icon_inject() stop_spin = True icon_inject_loading.join() print("\n") perms_needed = subprocess.call( ['bash', '-c', f'sudo -n true 2>/dev/null'], stdout=subprocess.PIPE) if perms_needed == 1: print( f"{Fore.YELLOW}[ Warning ] Deployment server requires permissions\n" ) subprocess.call([ 'bash', '-c', f'sudo /etc/init.d/apache2 status 1>/dev/null 2>{payload_path}/bleach_server_error.log' ], stdout=subprocess.PIPE) for repeat in range(3): print( "\033[A \033[A" ) stop_spin = False rebuild_loading = threading.Thread( target=spin, args=(f"{Fore.YELLOW}Building server ", f"{Fore.YELLOW}Server Built{Fore.GREEN} [*] ")) rebuild_loading.start() start.rebuild_apk() stop_spin = True rebuild_loading.join() print("\n") if len(os.listdir('/var/www/html/Android-SE/msf_apps')) >= 8: print( f"{Fore.YELLOW}Bleach server is running on localhost {Fore.GREEN} [*]\n\n" ) print( f"\t\t{Fore.YELLOW}[{Fore.BLUE}Info{Fore.YELLOW}] {Fore.BLUE}Use ctrl+c to shut down the deployment server and restore defaults{Fore.BLACK}" .center(os.get_terminal_size().columns)) while True: try: input() print("\033[A \033[A") except KeyboardInterrupt: print('\n\n') print( f"{Fore.YELLOW}[ Warning ] Deployment server is shutting down" .center(os.get_terminal_size().columns)) if os.path.isdir('/var/www/html_backup'): subprocess.call([ 'bash', '-c', f'sudo rm -r /var/www/html && sudo mv /var/www/html_backup /var/www/html' ]) subprocess.call([ 'bash', '-c', f'sudo /etc/init.d/apache2 stop &>/dev/null' ]) sleep(.5) print('\n') print( f"\t{Fore.YELLOW}[{Fore.GREEN}Complete{Fore.YELLOW}]\n{Fore.RESET}" .center(os.get_terminal_size().columns)) sys.exit() else: print( f'\n{Fore.YELLOW}[{Fore.RED}Error{Fore.YELLOW}] Something went wrong in building the server files' ) stop_spin = True rebuild_loading.join() print("\n") sys.exit() else: stop_spin = False rebuild_loading = threading.Thread( target=spin, args=(f"{Fore.YELLOW}Rebuilding apk ", f"{Fore.YELLOW}Apk rebuilt{Fore.GREEN} [*] ")) rebuild_loading.start() start.rebuild_apk() stop_spin = True rebuild_loading.join() print("\n") try: if not os.access(start.app_path, os.W_OK): print( f"{Fore.YELLOW} Your output path is a root path and needs permissions to write to it [*]\n" ) subprocess.call([ 'bash', '-c', f"sudo -k mv {payload_path}/{start.app_name}.apk {start.output_file} " ], stdout=subprocess.PIPE) for repeat in range(3): print( "\033[A \033[A" ) else: subprocess.call([ 'bash', '-c', f"mv {payload_path}/{start.app_name}.apk {start.output_file} " ], stdout=subprocess.PIPE) if os.path.isfile(start.output_file): print(f"{Fore.YELLOW}Rebuilt apk {Fore.GREEN}[*]") print( f"\n{Fore.YELLOW}[{Fore.GREEN}Complete{Fore.YELLOW}]{Fore.RESET}" ) print( f"\t\t\b{Fore.GREEN}\033[4mApk saved as: {start.output_file}{Fore.WHITE}\033[0m" .center(os.get_terminal_size().columns)) print('\n') except Exception as error: print(error)
parser.add_argument('-o', '--output', help="Output file name", type=str) args = parser.parse_args() domain_name = args.domain outputfile = args.output regex = "^((?!-)[A-Za-z0-9-]" + "{1,63}(?<!-)\\.)" + "+[A-Za-z]{2,6}" # Compile the ReGex p = re.compile(regex) if (re.search(p, domain_name)): print(Fore.BLUE + "=========================================================") banner = pyfiglet.figlet_format("SUBCERT", font="slant") print(Fore.WHITE + banner) print(" by: A3h1nt") print(Fore.BLUE + "=========================================================" + Fore.WHITE) else: print("Invalid Domain Name") sys.exit(0) user_agents = [] user_agents.append( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko)' ) user_agents.append( 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko')
def display(s): cprint(figlet_format(s.replace(' ', ' '), font='doom'), 'yellow')
def fig(text): ar = pyfiglet.figlet_format(text) print(ar)
def banner(): bn = pyfiglet.figlet_format(" Insta Analyser", font='slant') print(f"{Fore.GREEN}{bn}{Style.RESET_ALL}") print( f"\t\t\t\t\t\t Author : [{Fore.GREEN}HackersBrain{Style.RESET_ALL}]\n")
def banner(): ascii_banner = pyfiglet.figlet_format("\tURL MANAGER") print(colored((ascii_banner), 'red', 'on_blue')) text = "CODED BY:- MANJUNATHAN.C\nYOUTUBE LINK:-https://bit.ly/2CPKEvh" my_banner = terminal_banner.Banner(text) print(my_banner)
from termcolor import colored from pyfiglet import figlet_format valid_colors = ('red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') message = input('What message do you want to print? ') color = input('In what color? ') if color not in valid_colors: color = 'blue' figlet_message = figlet_format(message) print(colored(figlet_message, color))
def run(self): try: wb = load_workbook(self.argv[1]) padron = self.__cuits_arba(self.argv[2]) except IndexError: self.help_app() exit() sheet = wb['0 - Tickets de Clientes con Fac'] rows = sheet.rows next(rows) next(rows) next(rows) for row in rows: linea = "" # Verifico si se encuentra vacia la fecha, de ser None se termina el for if row[0].value == None: break try: # Verifico el cuit cuit = str(row[7].value) if self.cuit.verificador(str(row[7].value).replace('.', '')): cuit = str(row[7].value).replace('.', '') cuit = f'{cuit[0:2]}-{cuit[2:10]}-{cuit[10:]}' linea += cuit else: continue except TypeError: print( "Ocurrio un error con la cuit {} del nro de operacion {}.\nError ocurrido: Tipo de formato" .format(row[8].value, row[4].value)) # Obtenemos la fecha if row[0].value != "Fecha": try: days = timedelta(days=(int(row[0].value) - 2)) fecha_percepcion = (self.excel_date + days).strftime("%d/%m/%Y") linea += fecha_percepcion except TypeError: dia = row[0].value fecha_percepcion = dia.strftime("%d/%m/%Y") linea += fecha_percepcion if row[3].value == "FACTURA": tipo_comprobante = "F" elif row[3].value == "NOTA DE CREDITO": tipo_comprobante = "C" linea += tipo_comprobante # Obtenemos la letra de la factura letra_comprobante = str(row[5].value) linea += letra_comprobante # Obtenemos el punto de venta punto_venta = int(row[2].value) linea += str(punto_venta).zfill(4) # Numero de comprobante numero_comprobante = row[4].value linea += str(numero_comprobante).zfill(8) # Obtenemos el importe base total = row[10].value iva = row[11].value if total == 0.0: continue else: monto_base = float(total) - float(iva) linea += "{:.2f}".format(monto_base).zfill(12) # Obtenemos el importe percibido if row[7].value in padron.keys(): if padron[str(row[7].value).replace(',', '.')] == '0.00': continue else: alicuota = padron[str(row[7].value)] monto_percibido = monto_base * float( alicuota.replace(',', '.')) / 100 linea += '{:.2f}'.format(monto_percibido).zfill(11) else: continue # Agregamos el dato de tipo de operacion linea += 'A' # Grabamos la linea en un archivo txt with open("arba.txt", mode="a") as ofs: ofs.write(linea + "\r\n") terminal_command("clear") print(figlet_format("Archivo procesado"))
def start(): print(termcolor.colored(pyfiglet.figlet_format("Dad Jokes 3000"), color="red")) user_input = input("What would you like to search for? ") request(user_input)
def main(cfg): # Start cerberus print(pyfiglet.figlet_format("cerberus")) logging.info("Starting ceberus") # Parse and read the config if os.path.isfile(cfg): with open(cfg, 'r') as f: config = yaml.full_load(f) distribution = config["cerberus"].get("distribution", "openshift").lower() kubeconfig_path = config["cerberus"].get("kubeconfig_path", "") watch_nodes = config["cerberus"].get("watch_nodes", False) watch_cluster_operators = config["cerberus"].get( "watch_cluster_operators", False) watch_namespaces = config["cerberus"].get("watch_namespaces", []) watch_url_routes = config["cerberus"].get("watch_url_routes", []) cerberus_publish_status = config["cerberus"].get( "cerberus_publish_status", False) inspect_components = config["cerberus"].get("inspect_components", False) slack_integration = config["cerberus"].get("slack_integration", False) prometheus_url = config["cerberus"].get("prometheus_url", "") prometheus_bearer_token = config["cerberus"].get( "prometheus_bearer_token", "") iterations = config["tunings"].get("iterations", 0) sleep_time = config["tunings"].get("sleep_time", 0) daemon_mode = config["tunings"].get("daemon_mode", False) # Initialize clients if not os.path.isfile(kubeconfig_path): kubeconfig_path = None logging.info("Initializing client to talk to the Kubernetes cluster") kubecli.initialize_clients(kubeconfig_path) if "openshift-sdn" in watch_namespaces: sdn_namespace = kubecli.check_sdn_namespace() watch_namespaces = [ namespace.replace('openshift-sdn', sdn_namespace) for namespace in watch_namespaces ] # Cluster info logging.info("Fetching cluster info") if distribution == "openshift": cluster_version = runcommand.invoke("kubectl get clusterversion") logging.info("\n%s" % (cluster_version)) cluster_info = runcommand.invoke( "kubectl cluster-info | awk 'NR==1' | sed -r " "'s/\x1B\[([0-9]{1,3}(;[0-9]{1,2})?)?[mGK]//g'") # noqa logging.info("%s" % (cluster_info)) # Run http server using a separate thread if cerberus is asked # to publish the status. It is served by the http server. if cerberus_publish_status: address = ("0.0.0.0", 8080) server_address = address[0] port = address[1] logging.info("Publishing cerberus status at http://%s:%s" % (server_address, port)) server.start_server(address) # Create slack WebCleint when slack intergation has been enabled if slack_integration: slack_integration = slackcli.initialize_slack_client() # Run inspection only when the distribution is openshift if distribution == "openshift" and inspect_components: logging.info( "Detailed inspection of failed components has been enabled") inspect.delete_inspect_directory() # get list of all master nodes to verify scheduling master_nodes = kubecli.list_nodes("node-role.kubernetes.io/master") # Use cluster_info to get the api server url api_server_url = cluster_info.split(" ")[-1].strip() + "/healthz" # Counter for if api server is not ok api_fail_count = 0 # Initialize the start iteration to 0 iteration = 0 # Set the number of iterations to loop to infinity if daemon mode is # enabled or else set it to the provided iterations count in the config if daemon_mode: logging.info("Daemon mode enabled, cerberus will monitor forever") logging.info("Ignoring the iterations set\n") iterations = float('inf') else: iterations = int(iterations) # Loop to run the components status checks starts here while (int(iteration) < iterations): # Initialize a dict to store the operations timings per iteration iter_track_time = {} # Capture the start time iteration_start_time = time.time() iteration += 1 # Read the config for info when slack integration is enabled if slack_integration: weekday = runcommand.invoke("date '+%A'")[:-1] cop_slack_member_ID = config["cerberus"]["cop_slack_ID"].get( weekday, None) slack_team_alias = config["cerberus"].get( "slack_team_alias", None) slackcli.slack_tagging(cop_slack_member_ID, slack_team_alias) if iteration == 1: slackcli.slack_report_cerberus_start( cluster_info, weekday, cop_slack_member_ID) # Check if api server url is ok server_status = kubecli.is_url_available(api_server_url) if not server_status: api_fail_count += 1 # Check for NoSchedule taint in all the master nodes once in every 10 iterations if iteration % 10 == 1: check_taint_start_time = time.time() schedulable_masters = kubecli.check_master_taint(master_nodes) iter_track_time['check_master_taint'] = time.time( ) - check_taint_start_time if schedulable_masters: logging.warning( "Iteration %s: Masters without NoSchedule taint: %s\n" % (iteration, schedulable_masters)) # Monitor nodes status if watch_nodes: watch_nodes_start_time = time.time() watch_nodes_status, failed_nodes = kubecli.monitor_nodes() iter_track_time['watch_nodes'] = time.time( ) - watch_nodes_start_time logging.info("Iteration %s: Node status: %s" % (iteration, watch_nodes_status)) else: logging.info( "Cerberus is not monitoring nodes, so setting the status " "to True and assuming that the nodes are ready") watch_nodes_status = True # Monitor cluster operators status if distribution == "openshift" and watch_cluster_operators: watch_co_start_time = time.time() status_yaml = kubecli.get_cluster_operators() watch_cluster_operators_status, failed_operators = \ kubecli.monitor_cluster_operator(status_yaml) iter_track_time['watch_cluster_operators'] = time.time( ) - watch_co_start_time logging.info("Iteration %s: Cluster Operator status: %s" % (iteration, watch_cluster_operators_status)) else: watch_cluster_operators_status = True if iteration == 1: for namespace in watch_namespaces: kubecli.namespace_sleep_tracker(namespace) failed_pods_components = {} failed_pod_containers = {} watch_namespaces_status = True # Monitor each component in the namespace watch_namespaces_start_time = time.time() for namespace in watch_namespaces: watch_component_status, failed_component_pods, failed_containers = \ kubecli.monitor_namespace(namespace) logging.info("Iteration %s: %s: %s" % (iteration, namespace, watch_component_status)) watch_namespaces_status = watch_namespaces_status and watch_component_status if not watch_component_status: failed_pods_components[namespace] = failed_component_pods failed_pod_containers[namespace] = failed_containers iter_track_time['watch_namespaces'] = time.time( ) - watch_namespaces_start_time failed_routes = [] if watch_url_routes: watch_routes_start_time = time.time() for route_info in watch_url_routes: # Might need to get different authorization types here header = {'Accept': 'application/json'} if len(route_info) > 1: header['Authorization'] = route_info[1] route_status = kubecli.is_url_available( route_info[0], header) if not route_status: failed_routes.append(route_info[0]) iter_track_time['watch_routes'] = time.time( ) - watch_routes_start_time # Check for the number of hits if cerberus_publish_status: logging.info("HTTP requests served: %s \n" % (server.SimpleHTTPRequestHandler.requests_served)) # Logging the failed components if not watch_nodes_status: logging.info("Iteration %s: Failed nodes" % (iteration)) logging.info("%s\n" % (failed_nodes)) if not watch_cluster_operators_status: logging.info("Iteration %s: Failed operators" % (iteration)) logging.info("%s\n" % (failed_operators)) if not server_status: logging.info("Api Server is not healthy as reported by %s" % (api_server_url)) if not watch_namespaces_status: logging.info("Iteration %s: Failed pods and components" % (iteration)) for namespace, failures in failed_pods_components.items(): logging.info("%s: %s", namespace, failures) for pod, containers in failed_pod_containers[ namespace].items(): logging.info("Failed containers in %s: %s", pod, containers) logging.info("") # Logging the failed checking of routes if failed_routes: logging.info("Iteration %s: Failed route monitoring" % iteration) for route in failed_routes: logging.info("Route url: %s" % route) logging.info("") # Report failures in a slack channel if not watch_nodes_status or not watch_namespaces_status or \ not watch_cluster_operators_status: if slack_integration: slackcli.slack_logging(cluster_info, iteration, watch_nodes_status, failed_nodes, watch_cluster_operators_status, failed_operators, watch_namespaces_status, failed_pods_components) # Run inspection only when the distribution is openshift if distribution == "openshift" and inspect_components: inspect.inspect_components(failed_pods_components) elif distribution == "kubernetes" and inspect_components: logging.info("Skipping the failed components inspection as " "it's specific to OpenShift") # Aggregate the status and publish it cerberus_status = watch_nodes_status and watch_namespaces_status \ and watch_cluster_operators_status and server_status if cerberus_publish_status: publish_cerberus_status(cerberus_status) # Alert on high latencies # Intialize prometheus client if distribution == "openshift" and not prometheus_url: url = runcommand.invoke( r"""oc get routes -n openshift-monitoring -o=jsonpath='{.items[?(@.metadata.name=="prometheus-k8s")].spec.host}'""" ) # noqa prometheus_url = "https://" + url if distribution == "openshift" and not prometheus_bearer_token: prometheus_bearer_token = runcommand.invoke( "oc -n openshift-monitoring sa get-token prometheus-k8s" ) # noqa if prometheus_url and prometheus_bearer_token: promcli.initialize_prom_client(prometheus_url, prometheus_bearer_token) # Check for high latency alerts query = r"""ALERTS{alertname="KubeAPILatencyHigh", severity="warning"}""" metrics = promcli.get_metrics(query) if metrics: logging.warning( "Kubernetes API server latency is high. " "More than 99th percentile latency for given requests to the kube-apiserver is above 1 second.\n" ) # noqa logging.info("%s\n" % (metrics)) else: logging.info( "Skipping the alerts check as the prometheus url and bearer token are not provided\n" ) # noqa # Sleep for the specified duration logging.info("Sleeping for the specified duration: %s\n" % (sleep_time)) time.sleep(float(sleep_time)) crashed_restarted_pods = defaultdict(list) for namespace in watch_namespaces: crashed_restarted_pods.update( kubecli.namespace_sleep_tracker(namespace)) if crashed_restarted_pods: logging.info( "Pods that were crashed/restarted during the sleep interval of " "iteration %s" % (iteration)) for namespace, pods in crashed_restarted_pods.items(): logging.info("%s: %s" % (namespace, pods)) logging.info("") # Capture total time taken by the iteration iter_track_time['entire_iteration'] = ( time.time() - iteration_start_time) - sleep_time # noqa # Print the captured timing for each operation logging.info( "-------------------------- Iteration Stats ---------------------------" ) for operation, timing in iter_track_time.items(): logging.info( "Time taken to run %s in iteration %s: %s seconds" % (operation, iteration, timing)) logging.info( "----------------------------------------------------------------------\n" ) else: logging.info( "Completed watching for the specified number of iterations: %s" % (iterations)) else: logging.error("Could not find a config at %s, please check" % (cfg)) sys.exit(1)
master_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # needed? master_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) master_socket.bind((IP, PORT)) master_socket.listen(10) # add master socket to active connections list A(readable sockets) ACTIVE_CONNECTIONS_LIST.append(master_socket) ACTIVE_CONNECTIONS_FDMAP[master_socket.fileno()] = master_socket print "\n[*] started C&C server on port {}.\n".format(PORT) print "----------------------------------------------------------------------" print "----------------------------------------------------------------------\n" cprint(figlet_format('C&C\n SERVER', font='colossal'), 'red', attrs=['bold']) print "----------------------------------------------------------------------" print "----------------------------------------------------------------------" if NO_ENCRYPTION: print "*** WARNING: running in plaintext mode (no encryption used, bots will not process commands!). ***" # start main loop while True: ########################################################### # retrieve list of sockets ready to be read using select() read_soccs, write_soccs, error_soccs = select.select(ACTIVE_CONNECTIONS_LIST, [], []) ########################################################### for socc in read_soccs: # case [1]: NEW CONNECTION
async def ascii(self, ctx, *, tekst): ascii_banner = pyfiglet.figlet_format(tekst) await ctx.send(f"```{ascii_banner}```")
import cv2 import geocoder from To_cal_near import neariest_hosp import keyboard from send_message import message import pyfiglet import numpy as np flag = False phone_counter = 0 thres = 0.45 # Threshold to detect object nms_threshold = 0.2 intro = pyfiglet.figlet_format("AcciProof") print(intro) driver = input("Enter the driver name: ") classNames = [] classFile = 'coco.names' with open(classFile, 'rt') as f: classNames = f.read().rstrip('\n').split('\n') configPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt' weightsPath = 'frozen_inference_graph.pb' net = cv2.dnn_DetectionModel(weightsPath, configPath) net.setInputSize(320, 320) net.setInputScale(1.0 / 127.5)
ii=1 playertwobatt() tt=0 if tt==1: ii=2 playertwobatt() else: ii=2 playeronebatt() if z>zz: print(f"{c} won the match ") time.sleep(5) os.system("clear") vv=pyfiglet.figlet_format(f"CONGRATULATIONS {c}",font="slant") print(vv) elif z==zz: print(f"{p} and {c} won the match") time.sleep(5) os.system("clear") vv=pyfiglet.figlet_format(f"CONGRATULATIONS {p} AND {c}",font="slant") print(vv) else: print(f"{p} won the match") time.sleep(5) os.system("clear") vv=pyfiglet.figlet_format(f"CONGRATULATIONS {p}",font="slant") print(vv)
import hashlib # # pip install pyfiglet # import pyfiglet import os print(pyfiglet.figlet_format( "MD5 Hash Generator")) #comment if you don't have pyfiglet installed # # The Actual program starts from here # phrase = input("Enter the Phrase\n> ") # # The phrase would be converted to md5 hash and then encoded in utf-8 firmat by default # phrase_hash = hashlib.md5(phrase.encode()) print("\nSave to file?(Y/N)\n") if input("> ") in 'Yy': file_n = input("Enter the File Name: ") file_name = file_n + ".txt" # # If the file name does not exist then new file would be created # ls = os.listdir(os.getcwd()) if file_name not in ls: file = open(file_name, 'a') # # Converting the md5 hash to a hexadecimal format #
def figfont(text, font2): result = pyfiglet.figlet_format(text, font=font2) print(result)
def welcome(self): """ sweet backend UI """ print(figlet_format('welcome to mettle', font='speed')) print('version 2.4.1 by Ben Ong, Dan Xie, Grace Han')
def log(string, color='white', font="colossal", figlet=False): if colored: if not figlet: six.print_(colored(figlet_format(string, font=font), color)) else: six.print_(string)
import time,os import pyfiglet, random print (pyfiglet.figlet_format('Guess the number!')) fname = 'rules_gg.txt' fh = open(fname, 'rt') for line in fh: print(line) print('*******************************--------------------------*****************************---------------------') n = random.randrange(0,10) def wait(): print('Computer is choosing the number, please wait......') time.sleep(1) print('Computer has chosen a number...') def guess(): print('What\'s your guess\n') try: g = int(input()) if g in range(1,10): if g == n : print('Your guess is correct!') print( '*******************************--------------------------*****************************---------------------') print(pyfiglet.figlet_format('YOU WON',font='slant')) elif g is not n: g = int(input('Nope,let\'s try once more\n')) if g == n: print('Your guess is correct') print( '*******************************--------------------------*****************************---------------------')
import qiskit, pyfiglet,random qiskit.IBMQ.load_accounts() backend = qiskit.providers.ibmq.least_busy(qiskit.IBMQ.backends(simulator=False)) num = 3 qr = qiskit.QuantumRegister(num) cr = qiskit.ClassicalRegister(num) checkStatus = True myList = ['Jorah', 'Death', 'Jon Snow', 'Love', 'White Walkers']; humanScore = 0 robotScore = 0 asciiBanner = pyfiglet.figlet_format("Game Of Thrones") asciiBanner2 = pyfiglet.figlet_format("Duel") print(asciiBanner) print(asciiBanner2) #print("So You Want To Play the Game of Thrones Duel!\n"); print("**************Beware There are Spoilers Ahead!***************\n") print("You Will Be Facing Off Against A Quantum Robot in NY.\n\n") print("Here Are The Instructions:") print("Jon Snow *Beats* Death") print("Death *Caught Up To* Jorah") print("Jorah *Killed* White Walkers") print("White Walkers *DISINTEGRATES* Love") print("Love *Fogs Up* Jon Snow") print("Jon Snow *Decapitated* White Walkers") print("White Walker *IS* Death") print("Death *Destroys* Love")
If the text moves in the wrong direction, change the rotation from 0 to 180. Text output is kind of limited on a pHAT of course because most letters don't fit on the small display of 4x8. """) unicorn.set_layout(unicorn.HAT) unicorn.rotation(0) unicorn.brightness(0.5) width,height=unicorn.get_shape() width=8 height=8 TXT = "Linux Pratique is fun!!!" figletText = figlet_format(TXT+' ', "3-d", width=1000) # banner font generates text with heigth 7 print(figletText) textMatrix = figletText.split("\n")[:width] # width should be 8 on both HAT and pHAT! textHeight = len(textMatrix) if textMatrix[textHeight-1]=='': textHeight = textHeight -1 textWidth = len(textMatrix[0]) # the total length of the result from figlet i = -1 def step(): global i i = 0 if i>=100*textWidth else i+1 # avoid overflow for h in range(height): #for w in range(width): for w in range(textHeight):
#File Name :port_scanner.py #Created by : Dheeraj Deshmukh #last modified : 16 Dec 2020 #python version: Python3.6 and above import socket from IPy import IP import argparse import pyfiglet main_banner = pyfiglet.figlet_format("||..Port_Scanner..||") print(main_banner) parser = argparse.ArgumentParser() parser.add_argument("-t","--target" ,help = "Enter Target Ip Or Domain...") parser.add_argument("-sp","--sport",help = "Enter starting range for port number " ,type=int) parser.add_argument("-cp","--cport",help = "Enter closeing range for port number " ,type=int) parser.add_argument("-p","--port",help = "Enter range of port " ,type=int) args = parser.parse_args() def scan(target): converted_ip = check_ip(target) print('\n' + '[* Scanning target]' + str(target)) if args.cport and args.sport: for ports in range(args.sport,args.cport): scan_port(converted_ip,ports)
import requests from random import choice from termcolor import colored import pyfiglet header = pyfiglet.figlet_format("DAD JOKE 3000!") header = colored(header, color="red") print(header) user_input = input("What would you like to search for? ") url = "https://icanhazdadjoke.com/search" res = requests.get(url, headers={ "Accept": "application/json" }, params={ "term": user_input }).json() num_jokes = res["total_jokes"] results = res["results"] if num_jokes > 1: print(f"I found {num_jokes} jokes about {user_input}. Here's one: ") print(choice(results)["joke"]) elif num_jokes == 1: print("THERE IS ONE JOKE") print(results[0]['joke']) else: print(f"Sorry, couldn't find a joke with your term: {user_input}")
import pyfiglet import termcolor import colorama color_list = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] text = input("What would you like to print? ") print("Choose one:") for color in color_list: print(color) color = input() if color not in color_list: color = 'magenta' colorama.init() colored_text = termcolor.colored(pyfiglet.figlet_format(text), color=color) print(colored_text)
# This project helps us understand about `requests` modules # in Python import requests import pyfiglet import termcolor from random import choice header = pyfiglet.figlet_format("DAD JOKES") header = termcolor.colored(header, color="magnet")
def fermi3D(procar, outcar, bands=-1, scale=1, mode='plain', st=False, **kwargs): """ This function plots 3d fermi surface list of acceptable kwargs : plotting_package nprocess face_colors arrow_colors arrow_spin atom orbital spin """ ################ Welcome Text ####################### print(pyfiglet.figlet_format("PyProcar")) print('A Python library for electronic structure pre/post-processing.\n') print( 'Please cite: Herath, U., Tavadze, P., He, X., Bousquet, E., Singh, S., Muñoz, F. & Romero,\ A., PyProcar: A Python library for electronic structure pre/post-processing.,\ Computer Physics Communications 107080 (2019).\n') ##################################################### # Initilizing the arguments : if 'plotting_package' in kwargs: plotting_package = kwargs['plotting_package'] else: plotting_package = 'mayavi' if 'nprocess' in kwargs: nprocess = kwargs['nprocess'] else: nprocess = 2 if 'face_colors' in kwargs: face_colors = kwargs['face_colors'] else: face_colors = None if 'cmap' in kwargs: cmap = kwargs['cmap'] else: cmap = 'jet' if 'atoms' in kwargs: atoms = kwargs['atoms'] else: atoms = [-1] # project all atoms if 'orbitals' in kwargs: orbitals = kwargs['orbitals'] else: orbitals = [-1] if 'spin' in kwargs: spin = kwargs['spin'] else: spin = [0] if "mask_points" in kwargs: mask_points = kwargs['mask_points'] else: mask_points = 1 if "energy" in kwargs: energy = kwargs['energy'] else: energy = 0 if "transparent" in kwargs: transparent = kwargs['transparent'] else: transparent = False if "arrow_projection" in kwargs: arrow_projection = kwargs['arrow_projection'] else: arrow_projection = 2 if plotting_package == 'mayavi': try: from mayavi import mlab from tvtk.api import tvtk except: print( "You have selected mayavi as plottin package. please install mayavi or choose a different package" ) return elif plotting_package == 'plotly': try: import plotly.plotly as py import plotly.figure_factory as ff import plotly.graph_objs as go cmap = mpl.cm.get_cmap(cmap) figs = [] except: print( "You have selected plotly as plottin package. please install plotly or choose a different package" ) return elif plotting_package == 'matplotlib': try: import matplotlib.pylab as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection except: print( "You have selected matplotlib as plotting package. please install matplotlib or choose a different package" ) return elif plotting_package == 'ipyvolume': try: import ipyvolume.pylab as ipv except: print( "You have selected ipyvolume as plotting package. please install ipyvolume or choose a different package" ) return permissive = False #get fermi from outcar outcarparser = UtilsProcar() e_fermi = outcarparser.FermiOutcar(outcar) print('Fermi=', e_fermi) e_fermi += energy #get reciprocal lattice from outcar recLat = outcarparser.RecLatOutcar(outcar) #parsing the Procar file procarFile = ProcarParser() procarFile.readFile(procar, permissive) poly = get_wigner_seitz(recLat) # plot brilliouin zone if plotting_package == 'mayavi': brillouin_point = [] brillouin_faces = [] point_count = 0 for iface in poly: single_face = [] for ipoint in iface: single_face.append(point_count) brillouin_point.append(list(ipoint)) point_count += 1 brillouin_faces.append(single_face) polydata_br = tvtk.PolyData(points=brillouin_point, polys=brillouin_faces) mlab.pipeline.surface(polydata_br, representation='wireframe', color=(0, 0, 0), line_width=4, name="BRZ") elif plotting_package == 'plotly': for iface in poly: iface = np.pad(iface, ((0, 1), (0, 0)), 'wrap') x, y, z = iface[:, 0], iface[:, 1], iface[:, 2] plane = go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='black', width=4)) figs.append(plane) elif plotting_package == 'matplotlib': fig = plt.figure() ax = fig.add_subplot(111, projection='3d') brillouin_zone = Poly3DCollection(poly, facecolors=["None"] * len(poly), alpha=1, linewidth=4) brillouin_zone.set_edgecolor("k") ax.add_collection3d(brillouin_zone, zs=0, zdir='z') br_points = [] for iface in poly: for ipoint in iface: br_points.append(ipoint) br_points = np.unique(br_points, axis=0) print('Number of bands: %d' % procarFile.bandsCount) print('Number of koints %d' % procarFile.kpointsCount) print('Number of ions: %d' % procarFile.ionsCount) print('Number of orbitals: %d' % procarFile.orbitalCount) print('Number of spins: %d' % procarFile.ispin) #selecting the data data = ProcarSelect(procarFile, deepCopy=True) if bands == -1: bands = range(data.bands.shape[1]) kvector = data.kpoints kmax = np.max(kvector) kmin = np.min(kvector) if abs(kmax) != abs(kmin): print("The mesh provided is gamma center, symmetrizing data") print("For a better fermi surface, use a non-gamma centered k-mesh") data = symmetrize(data) kvector = data.kpoints kvector_red = data.kpoints.copy() kvector_cart = np.dot(kvector_red, recLat) # This section finds points that are outside of the 1st BZ and and creates those points in the 1st BZ kvector_cart, kvector_red, has_points_out = bring_pnts_to_BZ( recLat, kvector_cart, kvector_red, br_points) # has_points_out = False # getting the mesh grid in each dirrection kx_red = np.unique(kvector_red[:, 0]) ky_red = np.unique(kvector_red[:, 1]) kz_red = np.unique(kvector_red[:, 2]) # getting the lengths between kpoints in each direction klength_x = np.abs(kx_red[-1] - kx_red[-2]) klength_y = np.abs(ky_red[-1] - ky_red[-2]) klength_z = np.abs(kz_red[-1] - kz_red[-2]) klengths = [klength_x, klength_y, klength_z] # getting number of kpoints in each direction with the addition of kpoints needed to sample the 1st BZ fully (in reduced) nkx_red = kx_red.shape[0] nky_red = ky_red.shape[0] nkz_red = kz_red.shape[0] # getting numner of kpoints in each direction provided by vasp nkx_orig = np.unique(kvector[:, 0]).shape[0] nky_orig = np.unique(kvector[:, 1]).shape[0] nkz_orig = np.unique(kvector[:, 2]).shape[0] # Amount of kpoints needed to add on to fully sample 1st BZ padding_x = (nkx_red - nkx_orig) // 2 padding_y = (nky_red - nky_orig) // 2 padding_z = (nkz_red - nkz_orig) // 2 if mode == 'parametric': data.selectIspin(spin) data.selectAtoms(atoms, fortran=False) data.selectOrbital(orbitals) elif mode == 'external': if "color_file" in kwargs: rf = open(kwargs['color_file']) lines = rf.readlines() counter = 0 color_kvector = [] color_eigen = [] for iline in lines: if counter < 2: if 'band' in iline: counter += 1 continue temp = [float(x) for x in iline.split()] color_kvector.append([temp[0], temp[1], temp[2]]) counter = -1 for iline in lines: if 'band' in iline: counter += 1 iband = int(iline.split()[-1]) color_eigen.append([]) continue color_eigen[counter].append(float(iline.split()[-1])) rf.close() color_kvector = np.array(color_kvector) color_kvector_red = color_kvector.copy() color_kvector_cart = np.dot(color_kvector, recLat) if has_points_out: color_kvector_cart, color_kvector_red, temp = bring_pnts_to_BZ( recLat, color_kvector_cart, color_kvector_red, br_points) else: print( "mode selected was external, but no color_file name was provided" ) return if st: dataX = ProcarSelect(procarFile, deepCopy=True) dataY = ProcarSelect(procarFile, deepCopy=True) dataZ = ProcarSelect(procarFile, deepCopy=True) dataX.kpoints = data.kpoints dataY.kpoints = data.kpoints dataZ.kpoints = data.kpoints dataX.spd = data.spd dataY.spd = data.spd dataZ.spd = data.spd dataX.bands = data.bands dataY.bands = data.bands dataZ.bands = data.bands dataX.selectIspin([1]) dataY.selectIspin([2]) dataZ.selectIspin([3]) dataX.selectAtoms(atoms, fortran=False) dataY.selectAtoms(atoms, fortran=False) dataZ.selectAtoms(atoms, fortran=False) dataX.selectOrbital(orbitals) dataY.selectOrbital(orbitals) dataZ.selectOrbital(orbitals) ic = 0 for iband in bands: print("Plotting band %d" % iband) eigen = data.bands[:, iband] # mapping the eigen values on the mesh grid to a matrix mapped_func, kpoint_matrix = mapping_func(kvector, eigen) # adding the points from the 2nd BZ to 1st BZ to fully sample the BZ. Check np.pad("wrap") for more information mapped_func = np.pad(mapped_func, ((padding_x, padding_x), (padding_y, padding_y), (padding_z, padding_z)), 'wrap') # Fourier interpolate the mapped function E(x,y,z) surf_equation = fft_interpolate(mapped_func, scale) # after the FFT we loose the center of the BZ, using numpy roll we bring back the center of the BZ surf_equation = np.roll(surf_equation, (scale) // 2, axis=[0, 1, 2]) try: # creating the isosurface if possible verts, faces, normals, values = measure.marching_cubes_lewiner( surf_equation, e_fermi) except: print("No isosurface for this band") continue # the vertices provided are scaled and shifted to start from zero # we center them to zero, and rescale them to fit the real BZ by multiplying by the klength in each direction for ix in range(3): verts[:, ix] -= verts[:, ix].min() verts[:, ix] -= (verts[:, ix].max() - verts[:, ix].min()) / 2 verts[:, ix] *= klengths[ix] / scale # the vertices need to be transformed to reciprocal spcae from recuded space, to find the points that are # in 2nd BZ, to be removed verts = np.dot(verts, recLat) # identifying the points in 2nd BZ and removing them if has_points_out: args = [] for ivert in range(len(verts)): args.append([br_points, verts[ivert]]) p = Pool(nprocess) results = np.array(p.map(is_outside, args)) p.close() out_verts = np.arange(0, len(results))[results] new_faces = [] # outs_bool_mat = np.zeros(shape=faces.shape,dtype=np.bool) for iface in faces: remove = False for ivert in iface: if ivert in out_verts: remove = True continue if not remove: new_faces.append(iface) faces = np.array(new_faces) print("done removing") # At this point we have the plain Fermi surface, we can color the surface depending on the projection # We create the center of faces by averaging coordinates of corners if mode == 'parametric': character = data.spd[:, iband] centers = np.zeros(shape=(len(faces), 3)) for iface in range(len(faces)): centers[iface, 0:3] = np.average(verts[faces[iface]], axis=0) colors = interpolate.griddata(kvector_cart, character, centers, method="nearest") elif mode == 'external': character = np.array(color_eigen[ic]) ic += 1 centers = np.zeros(shape=(len(faces), 3)) for iface in range(len(faces)): centers[iface, 0:3] = np.average(verts[faces[iface]], axis=0) colors = interpolate.griddata(color_kvector_cart, character, centers, method="nearest") if st: projection_x = dataX.spd[:, iband] projection_y = dataY.spd[:, iband] projection_z = dataZ.spd[:, iband] verts_spin, faces_spin, normals, values = measure.marching_cubes_lewiner( mapped_func, e_fermi) for ix in range(3): verts_spin[:, ix] -= verts_spin[:, ix].min() verts_spin[:, ix] -= (verts_spin[:, ix].max() - verts_spin[:, ix].min()) / 2 verts_spin[:, ix] *= klengths[ix] verts_spin = np.dot(verts_spin, recLat) if has_points_out: args = [] for ivert in range(len(verts_spin)): args.append([br_points, verts_spin[ivert]]) p = Pool(nprocess) results = np.array(p.map(is_outside, args)) p.close() out_verts = np.arange(0, len(results))[results] new_faces = [] for iface in faces_spin: remove = False for ivert in iface: if ivert in out_verts: remove = True continue if not remove: new_faces.append(iface) faces_spin = np.array(new_faces) centers = np.zeros(shape=(len(faces_spin), 3)) for iface in range(len(faces_spin)): centers[iface, 0:3] = np.average(verts_spin[faces_spin[iface]], axis=0) colors1 = interpolate.griddata(kvector_cart, projection_x, centers, method="linear") colors2 = interpolate.griddata(kvector_cart, projection_y, centers, method="linear") colors3 = interpolate.griddata(kvector_cart, projection_z, centers, method="linear") spin_arrows = np.vstack((colors1, colors2, colors3)).T if plotting_package == 'mayavi': polydata = tvtk.PolyData(points=verts, polys=faces) if face_colors != None: mlab.pipeline.surface(polydata, representation='surface', color=face_colors[ic], opacity=1, name='band-' + str(iband)) ic += 1 else: if mode == 'plain': if not (transparent): s = mlab.pipeline.surface(polydata, representation='surface', color=(0, 0.5, 1), opacity=1, name='band-' + str(iband)) elif mode == 'parametric' or mode == 'external': polydata.cell_data.scalars = colors polydata.cell_data.scalars.name = 'celldata' mlab.pipeline.surface(polydata, vmin=0, vmax=colors.max(), colormap=cmap) cb = mlab.colorbar(orientation='vertical') if st: x, y, z = list(zip(*centers)) u, v, w = list(zip(*spin_arrows)) pnts = mlab.quiver3d(x, y, z, u, v, w, line_width=5, mode='arrow', resolution=25, reset_zoom=False, name='spin-' + str(iband), mask_points=mask_points, scalars=spin_arrows[:, arrow_projection], vmin=-1, vmax=1, colormap=cmap) pnts.glyph.color_mode = 'color_by_scalar' pnts.glyph.glyph_source.glyph_source.shaft_radius = 0.05 pnts.glyph.glyph_source.glyph_source.tip_radius = 0.1 elif plotting_package == 'plotly': if mode == 'plain': if not (transparent): x, y, z = zip(*verts) fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, simplices=faces, title="band-%d" % ic) figs.append(fig['data'][0]) elif mode == 'parametric' or mode == 'external': face_colors = cmap(colors) colormap = [ 'rgb(%i,%i,%i)' % (x[0], x[1], x[2]) for x in (face_colors * 255).round() ] x, y, z = zip(*verts) fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, show_colorbar=True, title="band-%d" % ic) figs.append(fig['data'][0]) elif plotting_package == 'matplotlib': if mode == 'plain': x, y, z = zip(*verts) ax.plot_trisurf(x, y, faces, z, linewidth=0.2, antialiased=True) elif mode == 'parametric' or mode == 'external': print( 'coloring the faces is not implemented in matplot lib, please use another plotting package.we recomend mayavi.' ) elif plotting_package == 'ipyvolume': if mode == 'plain': ipv.figure() ipv.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], triangles=faces) elif mode == 'paramteric' or mode == 'external': face_colors = cmap(colors) colormap = [ 'rgb(%i,%i,%i)' % (x[0], x[1], x[2]) for x in (face_colors * 255).round() ] ipv.figure() ipv.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], triangles=faces, color=cmap) if plotting_package == 'mayavi': mlab.colorbar(orientation='vertical') #,label_fmt='%.1f') mlab.show() elif plotting_package == 'plotly': layout = go.Layout(showlegend=False) fig = go.Figure(data=figs, layout=layout) py.iplot(fig) elif plotting_package == 'matplotlib': plt.show() elif plotting_package == 'ipyvolume': ipv.show() return
#!/usr/bin/python # coding=utf-8 import random, sys from nounsDictionary import nounsDict from verbsDictionary import verbsDict from questionsDictionary import questionsDict from colorama import init init(strip=not sys.stdout.isatty()) from termcolor import cprint from pyfiglet import figlet_format cprint(figlet_format('SPANISH - LEARNER', font="slant"), "red") def askQuestion(dictionary): thisQuestion, correctAnswer = random.choice(list(dictionary.items())) while True: notQuestion1, wrongAnswer1 = random.choice(list(dictionary.items())) if wrongAnswer1 != correctAnswer: break while True: notQuestion2, wrongAnswer2 = random.choice(list(dictionary.items())) if wrongAnswer2 != correctAnswer and wrongAnswer2 != wrongAnswer1: break while True: notQuestion3, wrongAnswer3 = random.choice(list(dictionary.items())) if wrongAnswer3 != correctAnswer and wrongAnswer3 != wrongAnswer2 and wrongAnswer3 != wrongAnswer1: break
import string import random import pyfiglet import os import time letters=string.ascii_lowercase+" "+","+"."+"?"+"!"+"1"+'2'+'3'+'4'+'5'+'6'+\ '7'+'8'+'9'+'0'+'/'+'('+')'+'['+']'+'@'+'#'\ +'$'+'^'+'&'+'*'+'-'+'_'+'+'+'='+':'+";"+"|"+'<'+'>' start = pyfiglet.figlet_format('encripted notes') for g in start: print(g, end='', flush=True) time.sleep(0.002) User_input = str( input('which do you want , decrypt or encrypt file ?! | type d/e : ')) os.system('clear') if User_input == 'e' or User_input == 'encrypt': Sec_inp = str( input("make new note or continue with exiting note | type n/e")) if Sec_inp == "n" or Sec_inp == "new": def Encrypt(string): num_lst = [] sec_lst = [] real = [] count = 0 in_txt = "" for i in range(len(string)): randoms = random.randint(1, 31)
class InstagramScraper: print(pyfiglet.figlet_format("SMO", font="isometric1")) print("\t\t- Social Media Observatory -\n") def __init__(self, email, password): firefox_profile = webdriver.FirefoxProfile() firefox_profile.set_preference("intl.accept_languages", "en-us") firefox_profile.update_preferences() options = Options() options.headless = False self.driver = webdriver.Firefox(options=options, firefox_profile=firefox_profile) self.email = email self.password = password def login(self): self.driver.get(cfg.loginUrl) try: email_input = WebDriverWait(self.driver, cfg.secondsToWait).until( ec.presence_of_element_located((By.NAME, cfg.usernameInputElementNameToLookFor)) ) email_input.send_keys(self.email) password_input = WebDriverWait(self.driver, cfg.secondsToWait).until( ec.presence_of_element_located((By.NAME, cfg.emailInputElementNameToLookFor)) ) password_input.send_keys(self.password) password_input.send_keys(Keys.ENTER) finally: time.sleep(cfg.secondsToWait) @staticmethod def get_info_for_start_user_and_loop_through_followers(): bot.get_first_info(cfg.scraperStartProfileUrl) time.sleep(5) followers = bot.followers() bot.followings() for follower in followers: time.sleep(cfg.secondsToWait) cfg.privateAccount = False bot.get_first_info(follower) if not cfg.privateAccount: if cfg.followersAmount > 0: bot.followers() if cfg.followingsAmount > 0: bot.followings() def get_first_info(self, scraper_profile_url): self.driver.get(scraper_profile_url) time.sleep(cfg.secondsToWait) soup = BeautifulSoup(self.driver.page_source, cfg.pythonParserUsedByBS4) user_data = soup.find_all(cfg.metaTagName, attrs={cfg.propertyKeyName: cfg.propertyValueName}) text = user_data[0].get(cfg.contentPropertyName).split() # print(', '.join(str(user_data))) script_tag_list = soup.find_all(cfg.scriptTagName) script_tag_inner_html = '' for tag in script_tag_list: if str(tag).__contains__(cfg.userIdStringToLookFor): script_tag_inner_html = tag user_id_end_index = str(script_tag_inner_html).split(cfg.userIdStringToLookFor, 1)[1].find('","') user_id = str(script_tag_inner_html).split(cfg.userIdStringToLookFor, 1)[1][0:user_id_end_index] cfg.username = '******' % (text[-3], text[-2], text[-1]) print('processing ' + cfg.username) if str(text[0]).__contains__('See') or str(text[0]).__contains__('Follow') or \ str(text[0]).__contains__('videos') or str(text[0]).__contains__('from') or \ str(user_data).__contains__('Private') or str(user_data).__contains__('privat'): print("\naccount is private - seen from user info\n") cfg.privateAccount = True return else: # TODO: find (better) way to see if acc is private here i = 0 while i < 3: if text[i].endswith('m'): text[i] = str(text[i]).replace(".", "").replace("m", "00000") if text[i].endswith('k'): text[i] = str(text[i]).replace(".", "").replace("k", "00") if str(text[i]).__contains__(","): text[i] = str(text[i]).replace(",", "") i = i + 2 cfg.followersAmount = int(text[0]) cfg.followingsAmount = int(text[2]) if not cfg.privateAccount: # self.print_findings(cfg.username, text[0], text[2], text[4], user_id) path_to_json = os.getcwd() + '/Outputs/' + cfg.username + '.json' if not os.path.exists(path_to_json): os.makedirs(os.path.dirname(path_to_json), exist_ok=True) f = open(file=path_to_json, mode='w+', encoding="utf-8") f.write('{\n\t\"Username\": \"' + cfg.username + '\",\n\t\"Number of Followers\": ' + text[0] + ',\n\t\"Number of Followings\": ' + text[2] + ',\n\t\"Total number of Posts\": ' + text[4] + ',\n\t\"User ID\": ' + user_id + ',\n') f.close() def followers(self): followers_link = self.driver.find_element_by_css_selector('ul li a') followers_link.click() self.driver.switch_to.default_content() try: WebDriverWait(self.driver, 60).until(ec.presence_of_element_located((By.CSS_SELECTOR, cfg.listElement))) except TimeoutException: print("\naccount is private - seen from followers") return followers_list = self.driver.find_element_by_css_selector(cfg.listElement) followers_list.click() self.driver.switch_to.default_content() time.sleep(10) try: WebDriverWait(self.driver, 60).until(ec.presence_of_element_located((By.CSS_SELECTOR, 'li'))) number_of_followers_in_list = len(followers_list.find_elements_by_css_selector('li')) except StaleElementReferenceException: print("test - " + str(cfg.followersAmount)) number_of_followers_in_list = cfg.followersAmount pass action_chain = webdriver.ActionChains(self.driver) if cfg.followersAmount >= cfg.maximumFollowerToLookAt: cfg.followersAmount = cfg.maximumFollowerToLookAt if cfg.followersAmount <= cfg.maximumFollowerToLookAt: cfg.maximumFollowerToLookAt = cfg.followersAmount i = 0 while number_of_followers_in_list < cfg.maximumFollowerToLookAt: action_chain.key_down(Keys.SPACE).key_up(Keys.SPACE).perform() i = i + 1 time.sleep(cfg.secondsToWait) if number_of_followers_in_list == len(followers_list.find_elements_by_css_selector('li')): break else: number_of_followers_in_list = len(followers_list.find_elements_by_css_selector('li')) followers = [] self.driver.switch_to.default_content() try: WebDriverWait(self.driver, 60).until(ec.presence_of_element_located((By.CSS_SELECTOR, 'li'))) except StaleElementReferenceException: print("\nERROR finding li element - element not found - (╯°□°)╯︵ ┻━┻") return list_element = followers_list.find_elements_by_css_selector('li') for user in list_element: user_link = user.find_element_by_css_selector('a').get_attribute('href') followers.append(user_link) panda_data_frame = pd.DataFrame(followers) # TODO: format panda dataFrame path_to_json = os.getcwd() + '/Outputs/' + cfg.username + '.json' if os.path.exists(path_to_json): f = open(file=path_to_json, mode='a+', encoding="utf-8") json_str = json.dumps(json.loads(panda_data_frame.to_json()), indent=8, sort_keys=True) f.write('\t\"followers\": \n\t' + json_str + '\t,\n') f.close() # self.print_follower_links(followers) find_x_button = self.driver.find_element_by_css_selector('div button svg') find_x_button.click() return followers def followings(self): followings_link = self.driver.find_elements_by_css_selector('ul li a')[1] followings_link.click() self.driver.switch_to.default_content() time.sleep(cfg.secondsToWait) try: WebDriverWait(self.driver, 60).until(ec.presence_of_element_located((By.CSS_SELECTOR, cfg.listElement))) except TimeoutException: print("account is private - seen from followings\n\n") return followings_list = self.driver.find_element_by_css_selector(cfg.listElement) followings_list.click() time.sleep(15) followings = [] self.driver.switch_to.default_content() try: WebDriverWait(self.driver, 60).until(ec.presence_of_element_located((By.CSS_SELECTOR, 'li'))) except StaleElementReferenceException: print("\nERROR finding li element - element not found - (╯°□°)╯︵ ┻━┻") return list_element = followings_list.find_elements_by_css_selector('li') for user in list_element: followers_link = user.find_element_by_css_selector('a').get_attribute('href') followings.append(followers_link) panda_data_frame = pd.DataFrame(followings) # TODO: format panda dataFrame path_to_json = os.getcwd() + '/Outputs/' + cfg.username + '.json' if os.path.exists(path_to_json): f = open(file=path_to_json, mode='a+', encoding="utf-8") json_str = json.dumps(json.loads(panda_data_frame.to_json()), indent=8, sort_keys=True) f.write('\t\"followings\": \n\t' + json_str + '\t\n}') f.close() # self.print_followings_links(followings) close_followings = self.driver.find_element_by_css_selector('div button svg') close_followings.click() @staticmethod def print_findings(user, followers, following, number_of_posts, user_id): print('Username: '******'Number of Followers: ' + followers) print('Number of Followings: ' + following) print('Total number of Posts: ' + number_of_posts) print('User ID: ' + user_id) @staticmethod def print_follower_links(followers): print('\n' + cfg.username + '\'s followers: ' + str(followers)) @staticmethod def print_followings_links(followings): print('\n' + cfg.username + '\' followings: ' + str(followings) + '\n\n') def quit(self): self.driver.quit()
def getPasswords(): print "Unique passwords: " + executeQuery("db.session.distinct('auth_attempts.password').length") if verbose or veryVerbose: passwordList = executeQuery("db.session.aggregate([{\$unwind:'\$auth_attempts'},{\$group:{_id:'\$auth_attempts.password','count':{\$sum:1}}},{\$sort:{count:-1}}]).forEach(function(x){printjson(x)})").split('\n') for pair in passwordList: match = re.search(r'"_id" : "(.*)", "count" : (\d+) }',pair) if match: countByPassword[match.group(1)] = int(match.group(2)) print figlet_format('Passwords', font='small') graph = Pyasciigraph() for line in graph.graph('', sorted(countByPassword.items(), key=operator.itemgetter(1), reverse=True)): print(line) print else: passwordList = executeQuery("db.session.aggregate([{\$unwind:'\$auth_attempts'},{\$group:{_id:'\$auth_attempts.password','count':{\$sum:1}}},{\$sort:{count:-1}},{\$limit:10}]).forEach(function(x){printjson(x)})").split('\n') for pair in passwordList: match = re.search(r'"_id" : "(.*)", "count" : (\d+) }',pair) if match: countByPassword[match.group(1)] = int(match.group(2)) print figlet_format('Passwords ( Top 10 )', font='small') graph = Pyasciigraph() for line in graph.graph('', sorted(countByPassword.items(), key=operator.itemgetter(1), reverse=True)): print(line) print