class TerminalView: """ Terminal view to basic CLI information. """ def __init__(self): self.term = Terminal() def print_error_and_exit(self, message): """ Print an error in red and exits the program. """ sys.exit(self.term.bold_red('[ERROR] ' + message)) def print_info(self, message): """ Print an informational text. """ print(message) def text_in_color(self, message, color_code): """ Print with a beautiful color. See codes at the top of this file. """ return self.term.color(color_code) + message + self.term.normal def format_question(self, message): """ Return an info-formatted string. """ return self.term.bold(message)
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 __str__(self): t = Terminal() text = self.token.value msg = ("try removing '{t.bold}{text}{t.normal}' " "".format_map(locals())) line_tokens = get_token_line(self.pos, self.tokens) line = format_line(line_tokens) padding = ' ' * (1 + self.token.column) arrow = padding + t.bold_red('^') suggestion = padding + t.red(text) return '\n'.join((msg, line, arrow, suggestion))
def print_bugs_and_errors(bugs: Iterable[Bug], errs: Iterable[ValidationError]) -> None: t = Terminal() for bug in bugs: print(t.bold_green("✔ ") + t.green(repr(bug))) for err in errs: model = err.model assert isinstance(model, ModelMetaclass) title = model.schema()["title"] for sub_err in err.errors(): (loc, ) = sub_err["loc"] msg = sub_err["msg"] print(t.bold_red("✘ ") + t.red(f"{title}.{loc}: {msg}"))
def __str__(self) -> str: t = Terminal() original = self.token.value replacement = current_language.to_source_text(self.fix.token) msg = (f"try replacing {t.bold_red}{original}{t.normal}" f" with {t.bold_green}{replacement}{t.normal}") line_tokens = get_token_line(self.pos, self.tokens) # TODO: add strikethrough to the token! line = format_line(line_tokens) padding = ' ' * (self.token.column) arrow = padding + t.bold_red('^') suggestion = padding + t.red(replacement) return '\n'.join((msg, line, arrow, suggestion))
class TerminalView(object): """ Terminal view to basic CLI information. """ def __init__(self): self.term = Terminal() def print_error_and_exit(self, message): """ Print an error in red and exits the program. """ sys.exit(self.term.bold_red('[ERROR] ' + message)) def print_info(self, message): """ Print an informational text. """ #print(self.term.bold('[INFO] ') + message) print(message) def format_question(self, message): """ Return an info-formatted string. """ return self.term.bold(message)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import inspect from couchbase.client import Couchbase from blessings import Terminal t = Terminal() os.system('clear') print t.bold_red("--------------------------------------------------------------------------") print t.bold_red("Couchbase Connections") print t.bold_red("--------------------------------------------------------------------------") print # establish connection couchbase = Couchbase("127.0.0.1:8091", "default", "") # set bucket object cb = couchbase["default"] print couchbase.servers # establish connection to beer-sample couchbase = Couchbase("127.0.0.1:8091", "beer-sample", "") # set bucket instance beers = couchbase["beer-sample"]
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)
# prepare all variables that don't need to be updated with each iteration spa = get_search_space() # define search space over possible models # define data paths path = config.data_path # 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),
elif root and cmd.split(" ")[0] == "exit": task = input("Do you really want to leave root? (YES/No) ") if task != "No" or task != "N" or task != "n" or task != "no": root = False elif not root and cmd.split( " ")[0] == "exit" or not root and cmd.split(" ")[0] == "quit": quit_task = input( wrap.bold( "This action will cause the program to self destruct. " + "(YES/No) ")) if quit_task != "No": time_count = 3000 print(wrap.clear()) with wrap.location(0, 0): print(wrap.bold("Make a wish!")) for i in range(time_count, 0, -1): with wrap.location(0, wrap.height - 2): min = int(str(i / 1000).split(".")[0]) mills = int(str(i / 1000).split(".")[1]) print( wrap.bold_red( 'Remained %d.%d seconds before destruction. ' % (min, mills))) time.sleep(0.01) with wrap.location(0, wrap.height - 2): print(wrap.clear_eos()) with wrap.location(0, wrap.height - 2): print(wrap.bold_red_blink("Time's up!")) time.sleep(1) run = False
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import inspect from couchbase.client import Couchbase from blessings import Terminal t = Terminal() os.system('clear') print t.bold_red( "--------------------------------------------------------------------------" ) print t.bold_red("Couchbase Connections") print t.bold_red( "--------------------------------------------------------------------------" ) print # establish connection couchbase = Couchbase("127.0.0.1:8091", "default", "") # set bucket object cb = couchbase["default"] print couchbase.servers # establish connection to beer-sample couchbase = Couchbase("127.0.0.1:8091", "beer-sample", "")
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import unicode_literals from serial import Serial from blessings import Terminal import sys symbols = ['A↓', 'A↑', 'B→', 'B←', 'B↓', 'B↑', 'A→', 'A←'] port = Serial('/dev/ttyUSB0', 9600, timeout=0.1) term = Terminal() try: while True: serial_data = port.read() if serial_data: for input_byte in serial_data: num = ord(input_byte) sys.stdout.write('\r') for i, sym in enumerate(symbols): pwr = 1 << i state = (num & pwr) == pwr sys.stdout.write(('..' if state else term.bold_red(sym)) + ' ') sys.stdout.flush() except KeyboardInterrupt: pass finally: port.close() sys.stdout.write('\n')
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from couchbase import Couchbase from blessings import Terminal from pprint import pprint import json import hashlib t = Terminal() os.system('clear') print t.bold_red( "--------------------------------------------------------------------------" ) print t.bold_red("Couchbase JSON Document Storage Operations") print t.bold_red( "--------------------------------------------------------------------------" ) print # connect to the default bucket cb = Couchbase.connect(bucket='default') # Create a new dictionary mydoc = \ { "doctype": "test", "name": "John Smith" }
for episode in range(300): # 1500 10000 state = env.reset() done = False steps = 0 while not done: action = agent.get_action(state) next_state, reward, done, info = env.step(action) agent.train((state, action, next_state, reward, done)) state = next_state total_reward += reward print("reward:", reward, "state:", state, "action:", action, "episode:", episode, "steps:", steps, "total_reward:", total_reward, "epsilon:", agent.epsilon) env.render() # print(agent.q_table) time.sleep(.01) clear_output(wait=True) steps += 1 print(t.bold_red("Fell into a hole.")) if reward == 0.0 else print(t.bold_green("Success!")) time.sleep(.7) # how many times it fell into a hole vs success per episode agent.episode_plot.append(episode) agent.total_reward_plot.append(total_reward) agent.steps_plot.append(steps) plot_seaborn(agent.episode_plot, agent.total_reward_plot, agent.steps_plot)
#!/usr/bin/env python # -*- coding: utf-8 -*- # sudo pip install blessings (for color terminal output) import os from couchbase.client import Couchbase from blessings import Terminal t = Terminal() os.system('clear') print t.bold_red( "--------------------------------------------------------------------------" ) print t.bold_red("Couchbase Storage Operations") print t.bold_red( "--------------------------------------------------------------------------" ) print # establish connection couchbase = Couchbase("127.0.0.1:8091", "default", "") # connect to default bucket cb = couchbase["default"] print t.bold("Set a Key-Value") print # create a key-value pair, set("key", ttl, flags, value) cb.set("mytest", 0, 0, 1)
class AppCommand(Command): """ A base command class for the application. """ def __init__(self, *args, **kwargs): super(AppCommand, self).__init__(*args, **kwargs) # Create a terminal instance we can use for formatting command line # output. self.t = Terminal() def confirm(self, question, s): """Ask the you user to confirm an action before performing it""" # In test mode we confirms are automatic if current_app.config['ENV'] is 'test': return True # Ask the user to confirm the action by request they repeat a randomly # generated string. answer = input('{t.blue}{question}: {t.bold}{s}{t.normal}\n'.format( question=question, s=s, t=self.t)) # Check the answer if answer != s: print(self.t.bold_red("Strings didn't match")) return False return True def err(self, *errors, **error_dict): """ Output a list of errors to the command line, for example: self.err( 'Unable to find account: foobar', ... ) Optional if a dictionary of errors is sent as keywords (this is typical used to output error information from a form) then that will be automatically converted to a list of error messages. """ # Convert error dict to additional messages if error_dict: errors += tuple((f, ''.join(e)) for f, e in error_dict.items()) # Build the error output output = [('Failed', 'underline_bold_red')] for error in errors: if isinstance(error, tuple): field, error = error output.append(('- {0} - {1}'.format(field, error), 'red')) else: output.append((error, 'red')) self.out(*output) def out(self, *strings): """ Output one or more strings (optionally with formats) to the commandline, for example: self.out( 'hi', ('I am red', 'red'), ... ) """ # We add an additional blank line to the head and tail of the output # accept when testing where we remove these to make it easier to compare # output. if current_app.config['ENV'] != 'test': print() for s in strings: if isinstance(s, tuple): # Formatted string s, fmt = s # When testing we ignore formatting to make it easier to compare # output. if current_app.config['ENV'] == 'test': # Unformatted string print(s) else: # Formatted string fmt = getattr(self.t, fmt) print(fmt(s)) else: # Unformatted string print(s) if current_app.config['ENV'] != 'test': print()
def parse_json( val ): vtype = type(val[2]) if vtype is str: try: json_doc = json.loads(val[2]) return json_doc except: print return val[2] t = Terminal() os.system('clear') print t.bold_red("--------------------------------------------------------------------------") print t.bold_red("Couchbase JSON Document Retrieve Operations") print t.bold_red("--------------------------------------------------------------------------") print user_data1 = \ { "doctype": "learn", "username": "******", "name": "John Smith", "email": "*****@*****.**", "password": "******", "logins": 0 }
class Interface: def __init__(self, config_filename): self.config_filename = config_filename self.config = collections.OrderedDict() self.term = Terminal() self.hline = u'\u2500' self.left_up = u'\u250c' self.right_up = u'\u2510' self.left_down = u'\u2514' self.right_down = u'\u2518' self.left_middle = u'\u251c' self.right_middle = u'\u2524' self.vline = u'\u2502' self.TITLE = [ 'SDNProbe: A Lightweight Tool for Securing SDN Data Plane with Active Probing' .center(self.term.width - 2) ] self.MENU = [ 'Show the configure file', 'Generate test packets from topology file', 'Generate topology graph for the controller as input', 'Start probing', 'Exit (or press q)' ] self.menu_pos = 0 def show_menu(self): while True: os.system('clear') print self.left_up + self.hline * (self.term.width - 2) + self.right_up print self.vline + self.term.bold_cyan(self.TITLE[0]) + self.vline print self.left_middle + self.hline * (self.term.width - 2) + self.right_middle for i, menu in enumerate(self.MENU): if i == self.menu_pos: print self.vline + ' ' + self.term.yellow_reverse( '[' + str(i + 1) + '] ' + menu) + ' ' * ( self.term.width - len(menu) - 7) + self.vline else: print self.vline + ' ' + '[' + str( i + 1) + '] ' + menu + ' ' * ( self.term.width - len(menu) - 7) + self.vline print self.left_down + self.hline * (self.term.width - 2) + self.right_down print press = self.getch() if press == 'up': self.menu_pos = (self.menu_pos - 1) % (len(self.MENU)) elif press == 'down': self.menu_pos = (self.menu_pos + 1) % (len(self.MENU)) elif press == 'exit': return 5 elif press == 'enter': return self.menu_pos + 1 def read_config(self): try: with open(self.config_filename, 'r') as f: for line in f: var, val = line.strip().split('=') self.config[var] = val except IOError: self.print_IOError(self.config_filename) exit() except: print self.term.bold_red('[-] Error') exit() def show_config(self): max_var_len = len(max(self.config.keys(), key=len)) max_val_len = len(max(self.config.values(), key=len)) width = max_var_len + 3 + max_val_len + 1 print self.term.bold_green(' [+] Config file: ' + self.config_filename) print ' ' + self.left_up + self.hline * width + self.right_up for var, val in self.config.iteritems(): print ' ' + self.vline + ' ' + var.ljust( max_var_len) + ' = ' + val.ljust(max_val_len) + self.vline print ' ' + self.left_down + self.hline * width + self.right_down self.check_config() self.show_coninue() def generate_test_packets(self): print self.term.bold_green(' [+] Generating test packets from "' + self.config['TOPOLOGY_FILE'] + '"') if not self.check_config(): self.show_coninue() return False print p = Popen(['make', '-C', 'cmodule/'], stdout=PIPE) print self.term.bold_green(' [+] Make file') for line in iter(p.stdout.readline, b''): print self.term.bold_magenta(' ' * 5 + line.strip()) print p = Popen( ['cmodule/./generate_test_packets', self.config['TOPOLOGY_FILE']], stdout=PIPE) print self.term.bold_green(' [+] Start to generate test packets') for line in iter(p.stdout.readline, b''): if line.startswith(' '): print self.term.bold_magenta(' ' * 5 + line.strip()) elif line.strip() == '': pass else: print self.term.bold_green(' [+] ' + line.strip()) self.show_coninue() def generate_topology_graph(self): print self.term.bold_green(' [+] Generating topology graph from "' + self.config['TOPOLOGY_FILE'] + '" and "' + self.config['TOPOLOGY_FILE'] + '.testpackets"') if not self.check_config(): self.show_coninue() return False p = Popen([ 'pymodule/generate_topology_graph.py', '-i', self.config['TOPOLOGY_FILE'] ], stdout=PIPE) for line in iter(p.stdout.readline, b''): print self.term.bold_green(' [+] ' + line.rstrip()) self.show_coninue() def start_probing(self): p = Popen(['ryu-manager', 'pymodule/controller.py'], stdout=PIPE, stderr=PIPE) for line in iter(p.stderr.readline, b''): try: if line.startswith('---'): print self.term.bold_magenta(' [+] ' + line.strip()) elif line.startswith(' '): print self.term.bold_magenta(' ' * 5 + line.strip()) else: print self.term.bold_green(' [+] ' + line.strip()) except: pass print self.show_coninue() def show_exit(self): print self.term.bold_red(' [+] Exit...\n') def show_coninue(self): print print self.term.bold_green(' [+] Press any key to continue...') self.getch() def check_config(self): if not os.path.exists(self.config['TOPOLOGY_FILE']): self.print_IOError(self.config['TOPOLOGY_FILE']) return False return True def print_IOError(self, filename): print self.term.bold_red(' [-] IOError: No such file: ' + filename) def getch(self): def input_key(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) key = '' try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) if ord(ch) == 13: return 'enter' elif ord(ch) == 113 or ord(ch) == 81: return 'exit' elif ord(ch) != 27: return False ch = sys.stdin.read(1) if ord(ch) != 91: return False ch = sys.stdin.read(1) if ord(ch) == 65: return 'up' elif ord(ch) == 66: return 'down' #elif ord(ch) == 67: return 'right' #elif ord(ch) == 68: return 'left' else: return False finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) while True: press_key = input_key() if press_key != '': break return press_key
action = agent.get_action(state) next_state, reward, done, info = env.step(action) agent.train((state, action, next_state, reward, done)) state = next_state total_reward += reward print("reward:", reward, "state:", state, "action:", action, "episode:", episode, "steps:", steps, "total_reward:", total_reward, "epsilon:", agent.epsilon) # env.render() with tf.variable_scope('q_table', reuse=True): weights = agent.sess.run(tf.get_variable('kernel')) # print(weights) # time.sleep(.01) clear_output(wait=True) steps += 1 print(t.bold_red("Fell into a hole.")) if reward == 0.0 else print( t.bold_green("Success!")) # time.sleep(.7) # how many times it fell into a hole vs success per episode agent.episode_plot.append(episode) agent.total_reward_plot.append(total_reward) agent.steps_plot.append(steps) plot_seaborn(agent.episode_plot, agent.total_reward_plot, agent.steps_plot)
class BaseMixin(Cmd): """The Mqtt-Pwn Base Command Line Interface Mixin""" prompt = '>> ' ruler = '-' intro = banner() CMD_CAT_BROKER_OP = 'Broker Related Operations' CMD_CAT_VICTIM_OP = 'Victim Related Operations' CMD_CAT_GENERAL = 'General Commands' variables_choices = ['victim', 'scan'] def __init__(self): """The class initializer""" Cmd.__init__(self, startup_script=config.STARTUP_SCRIPT) self.aliases.update({'exit': 'quit'}) self.hidden_commands.extend( ['load', 'pyscript', 'set', 'shortcuts', 'alias', 'unalias', 'py']) self.current_victim = None self.mqtt_client = None self.current_scan = None self.t = Terminal() self.base_prompt = get_prompt(self) self.prompt = self.base_prompt categorize(( BaseMixin.do_edit, BaseMixin.do_help, BaseMixin.do_history, BaseMixin.do_quit, BaseMixin.do_shell, ), BaseMixin.CMD_CAT_GENERAL) def print_error(self, text, end='\n', start=''): """Prints an error message with colors""" self.poutput(start + self.t.bold_red('[-]') + ' ' + self.t.red(text), end=end) def print_info(self, text, end='\n', start=''): """Prints an information message with colors""" self.poutput(start + self.t.bold_yellow('[!]') + ' ' + self.t.yellow(text), end=end) def print_ok(self, text, end='\n', start=''): """Prints a successful message with colors""" self.poutput(start + self.t.bold_green('[+]') + ' ' + self.t.green(text), end=end) def print_pairs(self, title, body): """Prints a message that contains pairs for data""" self.poutput(self.t.bold_white_underline(title)) for key, value in body.items(): k = key + ':' self.poutput(f' - {self.t.bold(k)} {value}') def update_prompt(self): """Updates the command prompt""" self.prompt = get_prompt(self)
## General principles: ## - Make math operation, with each guess of the key ## Output format: ## - Wrong guess prints a line with format -<key>: [Err: values too high for ASCII]- ## - A possible guess prints -<key>: <phrase>- from blessings import Terminal ## |-- Some prettyfied terminal output with Blessings t = Terminal() ## | crypted = input('The phrase to decrypt: ') ## The HACK-ing process for key in range(0, 255 + 1): guess = '' tmp = '' for pos, char in enumerate(crypted): tmp += char try: ## Makes sure that -tmp- currently has 3 digits, for any plaintext symbol is always encrypted into a 3-digit number if pos in range(2, 10000, 3): ## Adds a character (stored in -tmp-) to a final guess (for the current key), via guess += str(chr(int(tmp) - 100 - key)) tmp = '' ## It may (and, is likely to do frequently) be so, that the number would be too large for the -chr()- func, so let's leave those blank except ValueError: break if guess == '': print(f'{key}: ' + t.bold_red('[Err: values too high for ASCII]')) else: print(f'{key}: {guess}')
cb = Couchbase.connect(bucket="default") def parse_json( val ): vtype = type(val[2]) if vtype is str: try: json_doc = json.loads(val[2]) return json_doc except: print return val[2] t = Terminal() os.system('clear') print t.bold_red("--------------------------------------------------------------------------") print t.bold_red("Couchbase JSON Document Retrieve Operations") print t.bold_red("--------------------------------------------------------------------------") print user_data1 = \ { "doctype": "learn", "username": "******", "name": "John Smith", "email": "*****@*****.**", "password": "******", "logins": 0 }
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from couchbase.client import Couchbase from blessings import Terminal import json import hashlib t = Terminal() os.system('clear') print t.bold_red("--------------------------------------------------------------------------") print t.bold_red("Couchbase JSON Document Storage Operations") print t.bold_red("--------------------------------------------------------------------------") print # establish connection couchbase = Couchbase("127.0.0.1:8091", "default", "") # connect to default bucket cb = couchbase["default"] mydoc = \ { "doctype": "test", "name": "John Smith" }
subprocess.call(tesserargs) gsargs = [ GHOSTSCRIPT, '-q', '-dNOPAUSE', '-dBATCH', '-sDEVICE=pdfwrite', '-dDEVICEWIDTHPOINTS=%d' % PAGESIZE[0], '-dDEVICEHEIGHTPOINTS=%d' % PAGESIZE[1], '-dPDFFitPage', '-o', outfile, '%s.pdf' % ocrfile ] print(" ".join(gsargs)) subprocess.call(gsargs) q.task_done() if not which(SCANIMAGE): print(t.bold_red('scanimage command not found.')) sys.exit(1) if not which(TESSERACT): print(t.bold_red('tesseract command not found.')) sys.exit(2) if not which(GHOSTSCRIPT): print(t.bold_red('gs command not found.')) sys.exit(2) print("Hi there!") mode = input_selection( 'Scan in color or grayscale?', 'Mode',
cycle = 0 avg_volt = 0 avg_current = 0 volt = float(r_mppt_v.split("V")[0]) curr = float(r_mppt_i.split("A")[0]) avg_volt = avg_volt + volt avg_current = avg_current + curr cycle = cycle + 1 sleep(1) r_mppt_v = avg_volt / cycle; r_mppt_i = avg_current / cycle; if float(r_mppt_i) > float(current_max): result = t.bold_red('FAILED') elif float(r_mppt_i) < float(current_min): result = t.bold_red('FAILED') elif float(r_mppt_v) > float(voltage_max): result = t.bold_red('FAILED') elif float(r_mppt_v) < float(voltage_min): result = t.bold_red('FAILED') else: result = t.bold_green('PASSED') print 'Franz CH%s @ %sV, %sA....[%s]' %(ch, r_mppt_v, r_mppt_i, result) print '' def config_acs(pfc_path): sleep(5) tom = shell.Shell(pfc_path)
#!/usr/bin/env python # -*- coding: utf-8 -*- # sudo pip install blessings (for color terminal output) import os from couchbase.client import Couchbase from blessings import Terminal t = Terminal() os.system('clear') print t.bold_red("--------------------------------------------------------------------------") print t.bold_red("Couchbase Storage Operations") print t.bold_red("--------------------------------------------------------------------------") print # establish connection couchbase = Couchbase("127.0.0.1:8091", "default", "") # connect to default bucket cb = couchbase["default"] print t.bold("Set a Key-Value") print # create a key-value pair, set("key", ttl, flags, value) cb.set("mytest", 0, 0, 1) print t.bold("Retrieve Key-Value") print print "cb.get(\"mytest\")[2] = " + str(cb.get("mytest")[2]) print