def describe(self, name=None): if name is None: # describe all options names = sorted(dir(self)) else: opt = self._get_option(name) if isinstance(opt, Config): return opt.describe() names = [name] extras = "" for name in names: opt = self._get_option(name) if isinstance(opt, Config): extras += "%s [...]\n\n" % term.color("bold", opt.name) continue value = opt.get() comment = ("(default)" if value == opt.default else "(default: %r)" % opt.default) print("%s = %s %s" % (term.color( "bold", opt.name), term.color("bright_green", repr(value)), term.color("bright_black", comment))) for line in opt.doc.strip().split("\n"): print(" " + line) print() if extras: print(extras, end="")
def try_seed(seed): utf8_env = os.environ utf8_env['PYTHONIOENCODING'] = 'utf-8' proc = subprocess.Popen( ["python", "random_attack.py", str(seed)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=utf8_env) try: out, err = proc.communicate(timeout=100) except subprocess.TimeoutExpired: proc.kill() out, err = proc.communicate() rc = proc.returncode if rc == 0 and skip_successful_seeds: return True if rc == 0: status = term.color("bright_green", "OK") elif rc > 0: status = term.color("yellow", "FAIL") elif rc == -9: status = term.color("cyan", "HANG") else: status = term.color("bright_red", "ABORT") if rc != 0: status += " (%d)" % rc print("%-19d: %s" % (seed, status)) if save_logs_to_file: write_to_file("random_attack_logs/%d.txt" % seed, out, err) else: write_to_screen(out, err) return rc == 0
def _handle_(self, *exc_args): if exc_args: # Warning was converted into an exception TTypeError._handle_(self, *exc_args) else: print( term.color("yellow", self.__class__.__name__ + ": ") + term.color("bright_black", str(self)))
def value(self, row): if self._width == 0: return "" v = self._format(self._strdata[row]) if self._color: return term.color(self._color, v) + self._rmargin else: return v + self._rmargin
def _progress_internal(self, progress, status): """ Invoked from the C level to inform that the file reading progress has reached the specified level (expressed as a number from 0 to 1). Parameters ---------- progress: float The overall progress in reading the file. This will be the number between 0 and 1. status: int Status indicator: 0 = the job is running; 1 = the job finished successfully; 2 = the job finished with an exception; 3 = the job was cancelled by the user (via Ctrl+C or some other mechanism). """ line_width = min(80, term.width) if status == 1: print("\r" + " " * line_width, end="\r", flush=True) return bs = self._bar_symbols s0 = "Reading file: " s1 = " %3d%%" % int(100 * progress) bar_width = line_width - len(s0) - len(s1) - 2 n_chars = int(progress * bar_width + 0.001) frac_chars = int((progress * bar_width - n_chars) * len(bs)) out = bs[-1] * n_chars out += bs[frac_chars - 1] if frac_chars > 0 else "" outlen = len(out) if status == 2: out += term.color("red", "(error)") outlen += 7 elif status == 3: out += term.color("yellow", "(cancelled)") outlen += 11 out += " " * (bar_width - outlen) endf, endl = self._bar_ends out = "\r" + s0 + endf + out + endl + s1 print(term.color("bright_black", out), end=("\n" if status else ""), flush=True)
def start_random_attack(n_attacks=None, maxfail=None): if n_attacks is None: n_attacks = 10**10 if maxfail is None: maxfail = n_attacks n_tests = 0 n_errors = 0 try: for i in range(n_attacks): seed = random.getrandbits(63) ret = try_seed(seed) n_tests += 1 n_errors += not ret if n_errors >= maxfail: raise KeyboardInterrupt if skip_successful_seeds: print(term.color("bold", " Seeds tried: %d" % (i + 1)), end="\r") except KeyboardInterrupt: errmsg = "errors: %d" % n_errors if n_errors: errmsg = term.color("bright_red", errmsg) print("\r" + term.color("bright_cyan", "DONE.") + " Seeds tested: %d, %s" % (n_tests, errmsg))
def attack(self, frame=None, rounds=None): t0 = time.time() if rounds is None: rounds = int(random.expovariate(0.05) + 2) assert isinstance(rounds, int) if frame is None: frame = Frame0() print("Launching an attack for %d rounds" % rounds) for _ in range(rounds): self.attack_frame(frame) if exhaustive_checks: frame.check() if time.time() - t0 > 60: print(">>> Stopped early, taking too long <<<") break print("\nAttack ended, checking the outcome... ", end='') frame.check() print(term.color("bright_green", "PASSED")) t1 = time.time() print("Time taken = %.3fs" % (t1 - t0))
def debug(self, message): if message[0] != "[": message = " " + message print(term.color("bright_black", message), flush=True)
def __init__(self): self.width = 3 self.margin = "" self.header = term.color("bright_black", " | ") self.divider = term.color("bright_black", "-+ ")
def header(self): if self._width == 0: return "" else: return (term.color("bright_white", self._format(self._name)) + self._rmargin)
def _draw(self): self._fetch_data() columns = [] # Process key columns keynames = self._conn.key_names keydata = self._conn.key_data keyltypes = self._conn.key_ltypes keystypes = self._conn.key_stypes if keydata: for i, colname in enumerate(keynames): if self._show_types and keystypes[i]: colname = term.color("cyan", keystypes[i].name) oldwidth = self._colwidths.get(colname, 2) col = _Column(name=colname, ctype=keyltypes[i], data=keydata[i], color="bright_black", minwidth=oldwidth) self._colwidths[colname] = col.width columns.append(col) if keynames[0]: columns[-1].margin = "" columns.append(_Divider()) # Process data columns viewnames = self._conn.view_names viewltypes = self._conn.view_ltypes viewstypes = self._conn.view_stypes viewdata = self._conn.view_data if viewdata: for i, colname in enumerate(viewnames): if self._show_types: colname = term.color("cyan", viewstypes[i].name) oldwidth = self._colwidths.get(i + self._view_col0, 2) col = _Column(name=colname, ctype=viewltypes[i], data=viewdata[i], minwidth=oldwidth) if self._view_ncols < self._conn.frame_ncols: col.width = min(col.width, _Column.MAX_WIDTH) self._colwidths[i + self._view_col0] = col.width columns.append(col) columns[-1].margin = "" # Adjust widths of columns total_width = sum(col.width + len(col.margin) for col in columns) extra_space = term.width - total_width - DataFrameWidget.RIGHT_MARGIN if extra_space > 0: if self._view_col0 + self._view_ncols < self._conn.frame_ncols: self._view_ncols += max(1, extra_space // 8) self._draw() return elif self._view_col0 > 0: w = self._fetch_column_width(self._view_col0 - 1) if w + 2 <= extra_space: self._view_col0 -= 1 self._view_ncols += 1 self._max_col0 = self._view_col0 self._draw() return else: if self._max_col0 == self._view_col0: self._max_col0 += 1 available_width = term.width - DataFrameWidget.RIGHT_MARGIN for i, col in enumerate(columns): col.width = min(col.width, available_width) available_width -= col.width + len(col.margin) if available_width <= 0: available_width = 0 col.margin = "" else: self._view_ncols = i + 1 # Generate the elements of the display at_last_row = (self._view_row0 + self._view_nrows == self._conn.frame_nrows) grey = lambda s: term.color("bright_black", s) header = ["".join(col.header for col in columns), grey("".join(col.divider for col in columns))] rows = ["".join(col.value(j) for col in columns) for j in range(self._view_nrows)] srows = plural_form(self._conn.frame_nrows, "row") scols = plural_form(self._conn.frame_ncols, "column") footer = ["" if at_last_row else grey("..."), "[%s x %s]" % (srows, scols), ""] # Display hint about navigation keys if self._show_navbar: remaining_width = term.width if self._jump_string is None: nav_elements = [grey("Press") + " q " + grey("to quit"), " ↑←↓→ " + grey("to move"), " wasd " + grey("to page"), " t " + grey("to toggle types"), " g " + grey("to jump")] for elem in nav_elements: l = term.length(elem) if l > remaining_width: break remaining_width -= l footer[2] += elem else: footer[2] = grey("Go to (row:col): ") + self._jump_string # Render the table lines = header + rows + footer term.rewrite_lines(lines, self._n_displayed_lines) self._n_displayed_lines = len(lines) - 1
def header(self): if self._width == 0: return "" else: return term.color("bold", self._format(self._name)) + self._rmargin
def _handle_(self): print( term.color("yellow", self.__class__.__name__ + ": ") + term.color("bright_black", str(self)))