def main(): t = Terminal() print(t.yellow('Fetching latest version...')) dl_link, version = get_latest_version() print( t.blue('Found CTRLib version ') + t.bold_blue(str(version)) + t.blue(' available at ') + t.bold_blue(dl_link)) current_version = get_current_version() if current_version >= version: print(t.green('Repository already contains this version. Exiting.')) return print(t.yellow('Repository does not contain this version.')) print(t.yellow('Downloading...')) print(t.blue, end='') buffer = bytearray() with requests.get(dl_link, stream=True) as r: with tqdm(desc='CTRLib ' + str(version), unit='B', unit_scale=True, unit_divisor=1024, miniters=1, file=sys.stdout) as progress_bar: for b in r.iter_content(chunk_size=None): progress_bar.update(len(b)) buffer += b print(t.yellow('Unpacking...')) buffer_as_file = BytesIO(buffer) # pick out file name, then drop `.zip` folder_name = urlparse(dl_link).path.split('/')[-1][:-4] with ZipFile(buffer_as_file) as zipfile: ctr_java_version = CTR_JAVA / str(version) ctr_java_version.mkdir(exist_ok=True) unpack_zip_entry(zipfile, name='java/lib/CTRE_Phoenix.jar', to=(ctr_java_version / ('ctrlib-java-' + str(version) + '.jar'))) unpack_zip_entry(zipfile, name='java/lib/CTRE_Phoenix-sources.jar', to=(ctr_java_version / ('ctrlib-java-' + str(version) + '-sources.jar'))) so_file = _read_entry(zipfile, 'java/lib/libCTRE_PhoenixCCI.so') ctr_cpp_version = CTR_CPP / str(version) ctr_cpp_version.mkdir(exist_ok=True) zip_filename = (ctr_cpp_version / ('ctrlib-cpp-' + str(version) + '-linuxathena.zip')) with ZipFile(zip_filename, mode='w') as cppzip: cppzip.writestr('libCTRE_PhoenixCCI.so', so_file) print(t.green('Unpacked!'))
def tree(path, rel_to, indent=None): import sys from blessings import Terminal t = Terminal() # available in locals() left_t = LEFT_T last_t = LAST_T next_t = NEXT_T none_t = NONE_T if indent is None: sys.stdout.write(t.bold_blue(os.path.relpath(path, rel_to)) + "\n") indent = [] last_index = len(os.listdir(path)) - 1 for index, entry in enumerate(os.listdir(path)): is_last = index == last_index sys.stdout.write(u"{indent}{pre}{entry}\n".format(indent=''.join(indent), pre=is_last and last_t or left_t, entry=entry)) file = join(path, entry) if os.path.isdir(file): if is_last: tree(file, rel_to, indent + [none_t]) else: tree(file, rel_to, indent + [next_t])
def MainMenu(): t = Terminal() MainMenuTitle = t.red_on_green('MAIN MENU') print(MainMenuTitle) UserInterface.displayOptions(t) conn = queries.getConn() userChoice = input() while userChoice != 'q': if userChoice == "q": break elif userChoice == '1': print() UserInterface.TypeRatioQuery(t) print(MainMenuTitle) elif userChoice == '2': UserInterface.CrimeLiquorQuery(t) print(MainMenuTitle) elif userChoice == '3': print( "-----------------------------------------------------------" ) print("Loading...") print() queries.responsibleratio(conn) print( "-----------------------------------------------------------" ) print(MainMenuTitle) elif userChoice == '4': print( "-----------------------------------------------------------" ) queries.liquorstores(conn) print( "-----------------------------------------------------------" ) print(MainMenuTitle) elif userChoice == '5': UserInterface.CrimeChangeQuery(t) print(MainMenuTitle) elif userChoice == '6': UserInterface.LiquorCrimeTypeQuery(t) print(MainMenuTitle) # elif userChoice == '7': # print(Terminal().bold_red(sisMan())) else: print( t.bold_red( "Invalid input. Please type in a number from 1-6")) UserInterface.displayOptions(t) userChoice = input() print() print(t.bold_blue("EXITED APPLICATION")) print()
def main(): t = Terminal() # for colors memory = {} tmp = driver() data = tmp.getPrice() memory['my_usd'] = data['my_usd'] memory['my_btc'] = data['my_btc'] while True: if memory['my_usd'] == data['my_usd'] and memory['my_btc'] == data['my_btc']: print '{t.green}No Change{t.normal}:'.format(t=t),' My USD:', t.green(str(data['my_usd'])), ' My BTC:', t.green(str(data['my_btc'])) pass else: if memory['my_usd'] > data['my_usd']: print t.green('Made Sale!') db.db.transhistory.insert({'previous':str(memory['my_usd']), 'current':str(data['my_usd']), 'action':'Sell' }) else: print t.blue('Made Buy!') db.db.transhistory.insert({'previous':str(memory['my_usd']), 'current':str(data['my_usd']), 'action':'Buy' }) memory['my_usd'] = data['my_usd'] memory['my_btc'] = data['my_btc'] print t.bold_blue('Current Price:'), t.bold_blue(str(data['buy'])) time.sleep(10) try: data = tmp.getPrice() except: time.sleep(30) try: data = tmp.getPrice() except: pass
class List(Lister): "Lists all installed bundles." log = logging.getLogger(__name__) def __init__(self, *args, **kw): super(List, self).__init__(*args, **kw) self.term = Terminal() def take_action(self, parsed_args): lock = Lock.load() result = [] self.app.stdout.write(self.term.bold_blue(u'\nInstalled Bundles:\n')) for bundle in lock.bundles: author, repo = bundle['repo'].split('/') version = bundle['version'] result.append((repo, version, author)) return tuple((('bundle', 'version', 'author'),) + (result, ))
class List(Lister): "Lists all installed bundles." log = logging.getLogger(__name__) def __init__(self, *args, **kw): super(List, self).__init__(*args, **kw) self.term = Terminal() def take_action(self, parsed_args): lock = Lock.load() result = [] self.app.stdout.write(self.term.bold_blue(u'\nInstalled Bundles:\n')) for bundle in lock.bundles: author, repo = bundle['repo'].split('/') version = bundle['version'] result.append((repo, version, author)) return tuple((('bundle', 'version', 'author'), ) + (result, ))
def start(self): # Parse args global args, APs args = parse_args() # Check args check_args(args) # Are you root? if os.geteuid(): sys.exit('[' + R + '-' + W + '] Please run as root') self.network_manager.start() # TODO: We should have more checks here: # Is anything binded to our HTTP(S) ports? # Maybe we should save current iptables rules somewhere # get interfaces for monitor mode and AP mode and set the monitor interface # to monitor mode. shutdown on any errors try: if args.internetinterface: if self.network_manager.is_interface_valid( args.internetinterface, "internet"): internet_interface = args.internetinterface self.network_manager.unblock_interface(internet_interface) if not args.nojamming: if args.jamminginterface and args.apinterface: if self.network_manager.is_interface_valid( args.jamminginterface, "monitor"): mon_iface = args.jamminginterface self.network_manager.unblock_interface(mon_iface) if self.network_manager.is_interface_valid( args.apinterface, "AP"): ap_iface = args.apinterface else: mon_iface, ap_iface = self.network_manager.get_interface_automatically( ) # display selected interfaces to the user print( "[{0}+{1}] Selecting {0}{2}{1} interface for the deauthentication " "attack\n[{0}+{1}] Selecting {0}{3}{1} interface for creating the " "rogue Access Point").format(G, W, mon_iface, ap_iface) # randomize the mac addresses if not args.no_mac_randomization: if args.mac_ap_interface: self.network_manager.set_interface_mac( ap_iface, args.mac_ap_interface) else: self.network_manager.set_interface_mac_random(ap_iface) if args.mac_deauth_interface: self.network_manager.set_interface_mac( mon_iface, args.mac_deauth_interface) else: self.network_manager.set_interface_mac_random( mon_iface) else: if args.apinterface: if self.network_manager.is_interface_valid( args.apinterface, "AP"): ap_iface = args.apinterface else: ap_iface = self.network_manager.get_interface(True, False) mon_iface = ap_iface if not args.no_mac_randomization: if args.mac_ap_interface: self.network_manager.set_interface_mac( ap_iface, args.mac_ap_interface) else: self.network_manager.set_interface_mac_random(ap_iface) print( "[{0}+{1}] Selecting {0}{2}{1} interface for creating the " "rogue Access Point").format(G, W, ap_iface) # randomize the mac addresses if not args.no_mac_randomization: self.network_manager.set_interface_mac_random(ap_iface) # make sure interfaces are not blocked self.network_manager.unblock_interface(ap_iface) self.network_manager.unblock_interface(mon_iface) if not args.internetinterface: kill_interfering_procs() self.network_manager.set_interface_mode(mon_iface, "monitor") except (interfaces.InvalidInterfaceError, interfaces.InterfaceCantBeFoundError, interfaces.InterfaceManagedByNetworkManagerError) as err: print("[{0}!{1}] {2}").format(R, W, err) time.sleep(1) self.stop() if not args.no_mac_randomization: ap_mac = self.network_manager.get_interface_mac(ap_iface) print "[{0}+{1}] {2} mac address becomes is now {3} ".format( G, W, ap_iface, ap_mac) if not args.nojamming: mon_mac = self.network_manager.get_interface_mac(mon_iface) print("[{0}+{1}] {2} mac address becomes {3}".format( G, W, mon_iface, mon_mac)) if args.internetinterface: self.fw.nat(ap_iface, args.internetinterface) set_ip_fwd() else: self.fw.redirect_requests_localhost() set_route_localnet() print '[' + T + '*' + W + '] Cleared leases, started DHCP, set up iptables' time.sleep(1) if args.essid: essid = args.essid channel = str(CHANNEL) ap_mac = None enctype = None else: # let user choose access point access_point = curses.wrapper(select_access_point, mon_iface, self.mac_matcher, self.network_manager) # if the user has chosen a access point continue # otherwise shutdown if access_point: # store choosen access point's information essid = access_point.get_name() channel = access_point.get_channel() ap_mac = access_point.get_mac_address() enctype = access_point.get_encryption() else: self.stop() # create a template manager object self.template_manager = phishingpage.TemplateManager() # get the correct template template = select_template(args.phishingscenario, self.template_manager) print("[" + G + "+" + W + "] Selecting " + template.get_display_name() + " template") # payload selection for browser plugin update if template.has_payload(): payload_path = False # copy payload to update directory while not payload_path or not os.path.isfile(payload_path): # get payload path payload_path = raw_input( "[" + G + "+" + W + "] Enter the [" + G + "full path" + W + "] to the payload you wish to serve: ") if not os.path.isfile(payload_path): print '[' + R + '-' + W + '] Invalid file path!' print '[' + T + '*' + W + '] Using ' + G + payload_path + W + ' as payload ' copyfile(payload_path, PHISHING_PAGES_DIR + template.get_payload_path()) APs_context = [] for i in APs: APs_context.append({ 'channel': APs[i][0] or "", 'essid': APs[i][1] or "", 'bssid': APs[i][2] or "", 'vendor': self.mac_matcher.get_vendor_name(APs[i][2]) or "" }) template.merge_context({'APs': APs_context}) # only get logo path if MAC address is present ap_logo_path = False if ap_mac: ap_logo_path = template.use_file( self.mac_matcher.get_vendor_logo_path(ap_mac)) template.merge_context({ 'target_ap_channel': channel or "", 'target_ap_essid': essid or "", 'target_ap_bssid': ap_mac or "", 'target_ap_encryption': enctype or "", 'target_ap_vendor': self.mac_matcher.get_vendor_name(ap_mac) or "", 'target_ap_logo_path': ap_logo_path or "" }) # We want to set this now for hostapd. Maybe the interface was in "monitor" # mode for network discovery before (e.g. when --nojamming is enabled). self.network_manager.set_interface_mode(ap_iface, "managed") # Start AP self.access_point.set_interface(ap_iface) self.access_point.set_channel(channel) self.access_point.set_essid(essid) if args.presharedkey: self.access_point.set_psk(args.presharedkey) if args.internetinterface: self.access_point.set_internet_interface(args.internetinterface) print '[' + T + '*' + W + '] Starting the fake access point...' try: self.access_point.start() self.access_point.start_dhcp_dns() except BaseException: self.stop() # With configured DHCP, we may now start the web server if not args.internetinterface: # Start HTTP server in a background thread print '[' + T + '*' + W + '] Starting HTTP/HTTPS server at ports ' + str( PORT) + ", " + str(SSL_PORT) webserver = Thread(target=phishinghttp.runHTTPServer, args=(NETWORK_GW_IP, PORT, SSL_PORT, template)) webserver.daemon = True webserver.start() time.sleep(1.5) # We no longer need mac_matcher self.mac_matcher.unbind() clients_APs = [] APs = [] if not args.nojamming: # Start Extension Manager shared_data = { 'target_ap_channel': channel or "", 'target_ap_essid': essid or "", 'target_ap_bssid': ap_mac or "", 'target_ap_encryption': enctype or "", 'target_ap_logo_path': ap_logo_path or "", 'rogue_ap_mac': ap_mac, 'APs': APs_context, 'args': args } self.em.set_interface(mon_iface) extensions = DEFAULT_EXTENSIONS if args.lure10_exploit: extensions.append(LURE10_EXTENSION) self.em.set_extensions(extensions) self.em.init_extensions(shared_data) self.em.start_extensions() # Main loop. try: term = Terminal() with term.fullscreen(): while True: term.clear() with term.hidden_cursor(): print term.move(0, term.width - 30) + "|" print term.move( 1, term.width - 30) + "|" + " " + term.bold_blue("Wifiphisher " + VERSION) print term.move( 2, term.width - 30) + "|" + " ESSID: " + essid print term.move( 3, term.width - 30) + "|" + " Channel: " + channel print term.move( 4, term.width - 30) + "|" + " AP interface: " + ap_iface print term.move(5, term.width - 30) + "|" + "_" * 29 print term.move( 1, 0) + term.blue("Deauthenticating clients: ") if not args.nojamming: # show the 5 most recent entries for line in self.em.get_output()[-5:]: print line print term.move(7, 0) + term.blue("DHCP Leases: ") if os.path.isfile('/var/lib/misc/dnsmasq.leases'): proc = check_output( ['tail', '-5', '/var/lib/misc/dnsmasq.leases']) print term.move(8, 0) + proc print term.move(14, 0) + term.blue("HTTP requests: ") if os.path.isfile('/tmp/wifiphisher-webserver.tmp'): proc = check_output([ 'tail', '-5', '/tmp/wifiphisher-webserver.tmp' ]) print term.move(15, 0) + proc if phishinghttp.terminate and args.quitonsuccess: raise KeyboardInterrupt except KeyboardInterrupt: self.stop()
def run(): print ('[' + T + '*' + W + '] Starting Wifiphisher %s at %s' % (VERSION, time.strftime("%Y-%m-%d %H:%M"))) # Parse args global args, APs, clients_APs, mon_MAC, mac_matcher, hop_daemon_running args = parse_args() # Check args check_args(args) # Are you root? if os.geteuid(): sys.exit('[' + R + '-' + W + '] Please run as root') # TODO: We should have more checks here: # Is anything binded to our HTTP(S) ports? # Maybe we should save current iptables rules somewhere network_manager = interfaces.NetworkManager() mac_matcher = macmatcher.MACMatcher(MAC_PREFIX_FILE) # get interfaces for monitor mode and AP mode and set the monitor interface # to monitor mode. shutdown on any errors try: if not args.nojamming: if args.jamminginterface and args.apinterface: mon_iface = network_manager.get_jam_iface( args.jamminginterface) ap_iface = network_manager.get_ap_iface(args.apinterface) else: mon_iface, ap_iface = network_manager.find_interface_automatically() network_manager.set_jam_iface(mon_iface.get_name()) network_manager.set_ap_iface(ap_iface.get_name()) # display selected interfaces to the user print ("[{0}+{1}] Selecting {0}{2}{1} interface for the deauthentication " "attack\n[{0}+{1}] Selecting {0}{3}{1} interface for creating the " "rogue Access Point").format(G, W, mon_iface.get_name(), ap_iface.get_name()) else: if args.apinterface: ap_iface = network_manager.get_ap_iface( interface_name=args.apinterface) else: ap_iface = network_manager.get_ap_iface() mon_iface = ap_iface network_manager.set_ap_iface(ap_iface.get_name()) print ("[{0}+{1}] Selecting {0}{2}{1} interface for creating the " "rogue Access Point").format(G, W, ap_iface.get_name()) kill_interfering_procs() # set monitor mode to monitor interface network_manager.set_interface_mode(mon_iface, "monitor") except (interfaces.NotEnoughInterfacesFoundError, interfaces.JammingInterfaceInvalidError, interfaces.ApInterfaceInvalidError, interfaces.NoApInterfaceFoundError, interfaces.NoMonitorInterfaceFoundError) as err: print ("[{0}!{1}] " + str(err)).format(R, W) time.sleep(2) shutdown() set_fw_rules() set_kernel_var() network_manager.up_ifaces([ap_iface, mon_iface]) print '[' + T + '*' + W + '] Cleared leases, started DHCP, set up iptables' if args.essid: essid = args.essid channel = str(CHANNEL) args.accesspoint = False args.channel = False ap_mac = None enctype = None else: # Copy AP time.sleep(3) hop = Thread(target=channel_hop, args=(mon_iface,)) hop.daemon = True hop.start() sniffing(mon_iface.get_name(), targeting_cb) channel, essid, ap_mac, enctype = copy_AP() args.accesspoint = ap_mac args.channel = channel hop_daemon_running = False # get the correct template template = select_template(args.phishingscenario) print ("[" + G + "+" + W + "] Selecting " + template.get_display_name() + " template") # payload selection for browser plugin update if template.has_payload(): payload_path = False # copy payload to update directory while not payload_path or not os.path.isfile(payload_path): # get payload path payload_path = raw_input("[" + G + "+" + W + "] Enter the [" + G + "full path" + W + "] to the payload you wish to serve: ") if not os.path.isfile(payload_path): print '[' + R + '-' + W + '] Invalid file path!' print '[' + T + '*' + W + '] Using ' + G + payload_path + W + ' as payload ' copyfile(payload_path, PHISHING_PAGES_DIR + template.get_payload_path()) APs_context = [] for i in APs: APs_context.append({ 'channel': APs[i][0] or "", 'essid': APs[i][1] or "", 'bssid': APs[i][2] or "", 'vendor': mac_matcher.get_vendor_name(APs[i][2]) or "" }) template.merge_context({'APs': APs_context}) ap_logo_path = template.use_file(mac_matcher.get_vendor_logo_path(ap_mac)) template.merge_context({ 'target_ap_channel': args.channel or "", 'target_ap_essid': essid or "", 'target_ap_bssid': ap_mac or "", 'target_ap_encryption': enctype or "", 'target_ap_vendor': mac_matcher.get_vendor_name(ap_mac) or "", 'target_ap_logo_path': ap_logo_path or "" }) # We want to set this now for hostapd. Maybe the interface was in "monitor" # mode for network discovery before (e.g. when --nojamming is enabled). network_manager.set_interface_mode(ap_iface, "managed") # Start AP start_ap(ap_iface.get_name(), channel, essid, args) dhcpconf = dhcp_conf(ap_iface.get_name()) if not dhcp(dhcpconf, ap_iface.get_name()): print('[' + G + '+' + W + '] Could not set IP address on %s!' % ap_iface.get_name() ) shutdown(template) subprocess.call('clear', shell=True) print ('[' + T + '*' + W + '] ' + T + essid + W + ' set up on channel ' + T + channel + W + ' via ' + T + mon_iface.get_name() + W + ' on ' + T + str(ap_iface.get_name()) + W) # With configured DHCP, we may now start the web server # Start HTTP server in a background thread print '[' + T + '*' + W + '] Starting HTTP/HTTPS server at ports ' + str(PORT) + ", " + str(SSL_PORT) webserver = Thread(target=phishinghttp.runHTTPServer, args=(NETWORK_GW_IP, PORT, SSL_PORT, template)) webserver.daemon = True webserver.start() time.sleep(1.5) # We no longer need mac_matcher mac_matcher.unbind() clients_APs = [] APs = [] monitor_on = None conf.iface = mon_iface.get_name() mon_MAC = mon_mac(mon_iface.get_name()) if not args.nojamming: monchannel = channel # Start channel hopping hop = Thread(target=channel_hop2, args=(mon_iface,)) hop.daemon = True hop.start() # Start sniffing sniff_thread = Thread(target=sniff_dot11, args=(mon_iface.get_name(),)) sniff_thread.daemon = True sniff_thread.start() # Main loop. try: term = Terminal() with term.fullscreen(): while 1: term.clear() with term.hidden_cursor(): print term.move(0, term.width - 30) + "|" print term.move(1, term.width - 30) + "|" + " " + term.bold_blue("Wifiphisher " + VERSION) print term.move(2, term.width - 30) + "|" + " ESSID: " + essid print term.move(3, term.width - 30) + "|" + " Channel: " + channel print term.move(4, term.width - 30) + "|" + " AP interface: " + mon_iface.get_name() print term.move(5, term.width - 30) + "|" + "_"*29 print term.move(1,0) + term.blue("Jamming devices: ") if os.path.isfile('/tmp/wifiphisher-jammer.tmp'): proc = check_output(['tail', '-5', '/tmp/wifiphisher-jammer.tmp']) print term.move(4,0) + proc print term.move(9,0) + term.blue("DHCP Leases: ") if os.path.isfile('/var/lib/misc/dnsmasq.leases'): proc = check_output(['tail', '-5', '/var/lib/misc/dnsmasq.leases']) print term.move(10,0) + proc print term.move(17,0) + term.blue("HTTP requests: ") if os.path.isfile('/tmp/wifiphisher-webserver.tmp'): proc = check_output(['tail', '-5', '/tmp/wifiphisher-webserver.tmp']) print term.move(18,0) + proc if phishinghttp.terminate and args.quitonsuccess: raise KeyboardInterrupt except KeyboardInterrupt: shutdown(template, network_manager)
def update(self): def find_match_color(_cell): # 寻找和 _cell 描述的颜色最接近的终端颜色 # color 列表采用了 OS X 的自带终端的配色方案 # Ref: http://en.wikipedia.org/wiki/ANSI_escape_code#Colors colors = { "black": (0, 0, 0), "red": (194, 54, 33), "green": (37, 188, 36), "yellow": (173, 173, 39), "blue": (73, 46, 255), "magenta": (211, 56, 211), "cyan": (51, 187, 200), "white": (203, 204, 205) } # 差异度按欧几里德距离计算 best_color_name = "black" best_color_distance = sqrt(255**2 + 255**2 + 255**2) for name, color in colors.items(): distance = sqrt( sum([(_cell[i] - color[i])**2 for i in range(3)])) if best_color_distance > distance: best_color_name = name best_color_distance = distance return best_color_name # 算法完毕 t = Terminal() self.clear_screen() # 将 active_block 贴到 canvas 上 if self.active_block is not None: self.canvas = deepcopy(self.map.content) for y in range(len(self.active_block)): for x in range(len(self.active_block[0])): if self.active_block[y][x] is not None: self.canvas[y + self.active_block_position[1]][ x + self. active_block_position[0]] = self.active_block[y][x] # 输出游戏地图 # 打印顶部栏杆 print t.red(" /-------") + t.yellow("TETRIS") + t.red("-------\\") # 打印 canvas for index, row in enumerate(self.canvas): print t.red(" |"), for cell in row: if cell is not None: color_name = find_match_color(cell) stdout.write(getattr(t, 'red_on_' + color_name)(' ')) # red_on_ 是随便选的 else: stdout.write(' ') print t.red("|"), print " ", # 下一个方块 if 0 < index: try: for cell in self.next_block[index - 1]: if cell is not None: color_name = find_match_color(cell) stdout.write( getattr(t, 'red_on_' + color_name)(' ')) # red_on_ 是随便选的 else: stdout.write(' ') except IndexError: pass elif 0 == index: print "Next", print # 打印底部栏杆 print t.red(" \\--------------------/") print print t.blue(self.information_bar) print print t.bold_blue(u" 成绩: " + str(self.score)) print " PyTetris 2.33"
# obtain the yaml skelton with open(config.yaml_skelton_path) as f: default_string = f.read() # for each sample that will be generated from search space space for i in xrange(20): timestamp = get_timestamp() print t.bold_red('ITERATION:'), t.bold_red(str(i)), "started at: ", timestamp samp = sample(spa) # generate sample (will give a description of a model) print t.bold_cyan('SAMP'), samp mod = build(samp) # based on description generated build an object that will fit into yaml_parser print t.bold_blue('MODEL'), mod # define weight decay parameters. They depend on the number of layers (there is one parameter fo each layer) weight_decay_coeffs = yp.parse_weight_decay(mod) # generate a filename to store the best model pkl_filename = join(config.path_for_storing, timestamp+"best_"+str(i)+'_'+".pkl") # create dictionary with hyper parameters hyper_params = {'model': yp.parse_to_yaml(mod), 'path': yp.parse_to_yaml(path), 'weight_decay_coeffs': weight_decay_coeffs, 'pkl_filename': pkl_filename} # fill the yaml skelton with hyperparameters yaml_string = default_string % hyper_params # saving the yaml for later analysis
class BasePlugin(Cmd): """ BasePlugin - the base class which all of our plugins should inherit from. It is meant to define all the necessary base functions for plugins. """ prompt = '>> ' ruler = '-' intro = banner() terminators = [] CATEGORY_SHELL = to_bold_cyan('Shell Based Operations') CATEGORY_GENERAL = to_bold_cyan('General Commands') def __init__(self): Cmd.__init__(self, startup_script=read_config().get('STARTUP_SCRIPT', ''), use_ipython=True) self.aliases.update({'exit': 'quit', 'help': 'help -v'}) self.hidden_commands.extend([ 'load', 'pyscript', 'set', 'shortcuts', 'alias', 'unalias', 'shell', 'macro' ]) self.t = Terminal() self.selected_client = None self.prompt = self.get_prompt() self.allow_cli_args = False # Alerts Thread self._stop_thread = False self._seen_clients = set(Client.unique_client_ids()) self._alert_thread = Thread() # Register the hook functions self.register_preloop_hook(self._alert_thread_preloop_hook) self.register_postloop_hook(self._alert_thread_postloop_hook) # Set the window title self.set_window_title('<< JSShell 2.0 >>') categorize([ BasePlugin.do_help, BasePlugin.do_quit, BasePlugin.do_py, BasePlugin.do_ipy, BasePlugin.do_history, BasePlugin.do_edit ], BasePlugin.CATEGORY_GENERAL) self.register_postparsing_hook( self._refresh_client_data_post_parse_hook) def _alert_thread_preloop_hook(self) -> None: """ Start the alerter thread """ self._stop_thread = False self._alert_thread = Thread(name='alerter', target=self._alert_function) self._alert_thread.start() def _alert_thread_postloop_hook(self) -> None: """ Stops the alerter thread """ self._stop_thread = True if self._alert_thread.is_alive(): self._alert_thread.join() def _alert_function(self) -> None: """ When the client list is larger than the one we know of alert the user that a new client has registered """ while not self._stop_thread: if self.terminal_lock.acquire(blocking=False): current_clients = set(Client.unique_client_ids()) delta = current_clients - self._seen_clients if len(delta) > 0: self.async_alert( self.t.bold_blue(' << new client registered >>'), self.prompt) self._seen_clients = current_clients self.terminal_lock.release() sleep(0.5) def print_error(self, text: str, end: str = '\n', start: str = '') -> None: """ Prints a formatted error message """ self.poutput(start + self.t.bold_red('[-]') + ' ' + self.t.red(text), end=end) def print_info(self, text: str, end: str = '\n', start: str = '') -> None: """ Prints a formatted informational message """ self.poutput(start + self.t.bold_yellow('[!]') + ' ' + self.t.yellow(text), end=end) def print_ok(self, text: str, end: str = '\n', start: str = '') -> None: """ Prints a formatted success message """ self.poutput(start + self.t.bold_green('[+]') + ' ' + self.t.green(text), end=end) def print_pairs(self, title: str, body: Dict[str, str], just_return: bool = False, colors: bool = True) -> Union[str, None]: """ Prints pairs of values with a certain title """ if colors: data = [self.t.bold_white_underline(title)] else: data = [title] for key, value in body.items(): k = key + ':' if colors: data.append(f' - {self.t.bold(k)} {value}') else: data.append(f' - {k} {value}') if just_return: return '\n'.join(data) self.ppaged('\n'.join(data)) def select_client(self, client: Client) -> None: """ Handles the operation of selecting a new client """ self.selected_client = client self.update_prompt() def _refresh_client_data_post_parse_hook( self, params: PostparsingData) -> PostparsingData: """ Refreshes the selected client data from the database. We do that because of `mongoengine`s behaviour, where if we set the current client, we do not track for modifications. This way, before every command is parsed we re-select the client """ if self.selected_client: cid = self.selected_client.cid self.select_client(Client.objects(cid=cid).first()) return params def get_prompt(self) -> str: """ Handles the operations of getting the prompt string """ prompt = self.t.bold_cyan('>> ') if self.selected_client: client_id = self.t.bold_red(self.selected_client.cid) prompt = self.t.cyan(f"[Client #{client_id}]") + ' ' + prompt return prompt def update_prompt(self) -> None: """ Handles what is needed when updating the prompt """ self.prompt = get_prompt(self)
def update(self): def find_match_color(_cell): # 寻找和 _cell 描述的颜色最接近的终端颜色 # color 列表采用了 OS X 的自带终端的配色方案 # Ref: http://en.wikipedia.org/wiki/ANSI_escape_code#Colors colors = {"black": (0, 0, 0), "red": (194, 54, 33), "green": (37, 188, 36), "yellow": (173, 173, 39), "blue": (73, 46, 255), "magenta": (211, 56, 211), "cyan": (51, 187, 200), "white": (203, 204, 205)} # 差异度按欧几里德距离计算 best_color_name = "black" best_color_distance = sqrt(255**2 + 255**2 + 255**2) for name, color in colors.items(): distance = sqrt(sum([(_cell[i] - color[i]) ** 2 for i in range(3)])) if best_color_distance > distance: best_color_name = name best_color_distance = distance return best_color_name # 算法完毕 t = Terminal() self.clear_screen() # 将 active_block 贴到 canvas 上 if self.active_block is not None: self.canvas = deepcopy(self.map.content) for y in range(len(self.active_block)): for x in range(len(self.active_block[0])): if self.active_block[y][x] is not None: self.canvas[y+self.active_block_position[1]][x+self.active_block_position[0]] = self.active_block[y][x] # 输出游戏地图 # 打印顶部栏杆 print t.red(" /-------") + t.yellow("TETRIS") + t.red("-------\\") # 打印 canvas for index, row in enumerate(self.canvas): print t.red(" |"), for cell in row: if cell is not None: color_name = find_match_color(cell) stdout.write(getattr(t, 'red_on_'+color_name)(' ')) # red_on_ 是随便选的 else: stdout.write(' ') print t.red("|"), print " ", # 下一个方块 if 0 < index: try: for cell in self.next_block[index-1]: if cell is not None: color_name = find_match_color(cell) stdout.write(getattr(t, 'red_on_'+color_name)(' ')) # red_on_ 是随便选的 else: stdout.write(' ') except IndexError: pass elif 0 == index: print "Next", print # 打印底部栏杆 print t.red(" \\--------------------/") print print t.blue(self.information_bar) print print t.bold_blue(u" 成绩: " + str(self.score)) print " PyTetris 2.33"