def rg(v, format_spec=None): """Returns "v" as str and red or green ANSI colored depending of its sign (+ green, - red). >>> colored_value = rg(0.1) >>> colored_value == '\x1b[32m0.1\x1b[0m\x1b[27m' True :param nums.Number v: number to be colored :param tp.AnyStr format_spec: format specification (python 3 style) :return str: v as str and red or green ANSI colored depending of its sign (+ green, - red) """ if isinstance(v or 0, str): try: v = float(v) except ValueError: return v if isinstance(v or [], nums.Number): v = float(str(v)) is_zero = v == 0.0 is_neg = v < 0.0 try: v = format_spec.format(v) except (ValueError, TypeError): v = f'{v}' if is_zero: return term.format(v, term.white, term.dim) else: return term.format(v, term.red if is_neg else term.green)
class BeautyCLI(Cursor): def __init__(self, clear=True): if clear: tm.sleep(.25) self.cls() cls = lambda self: trm.clear() cls_ln = lambda self: trm.clearLine() fmt = lambda self, *args, **kwargs: trm.format(*args, **kwargs) wrt = lambda self, *args, **kwargs: trm.write(*args, **kwargs) wln = lambda self, *args, **kwargs: trm.writeLine(*args, **kwargs) right = lambda self, t: trm.right(t) center = lambda self, t: trm.center(t) def echo(self, text, row=None, col=None, align='left', *args): formated_text = text if align in 'right': formated_text = self.right(formated_text) elif align in 'center': formated_text = self.center(formated_text) if row is not None and col is not None: self.pos(row, col) elif row is not None and row is None: self.pos(row, 1) elif col is not None and row is None: self.pos(1, col) self.wln(formated_text, *args)
async def choose_book(books, book_file_path): def print_book(i, book): text = term.format("图书序号:", term.cyan, term.bold) \ + term.format(i, term.red, term.bold) \ + term.format(", 书名:%s" % book["title"], term.yellow, term.bold) print("====" * 10 + "<<<" * 3, text, ">>>" * 3 + "====" * 10) term.writeLine("|| title: %s" % book["title"], term.red) term.writeLine("|| subtitle: %s" % book["subtitle"], term.red) term.writeLine("|| authors: %s" % book["authors"], term.red) term.writeLine("|| tags: %s" % book["tags"], term.red) term.writeLine("|| rating: %s" % book["rating"], term.magenta) term.writeLine("|| star: %s" % book["star"], term.magenta) term.writeLine("|| num: %s" % book["num"], term.magenta) term.writeLine("|| price: %s" % book["price"], term.blue) term.writeLine("|| isbn: %s" % book["isbn"], term.blue) term.writeLine("|| publisher: %s" % book["publisher"], term.yellow) term.writeLine("|| date: %s" % book["date"], term.yellow) term.writeLine("|| series: %s" % book["series"], term.yellow) term.writeLine("|| comments: %s" % book["comments"], term.white) print("\n") # 打印书籍信息 for i in range(len(books)): print_book(i, books[i]) # 显示元数据信息 return_code = await exec_command(book_file_path) debug("[choose book] 返回码: ", return_code) if return_code != 0: return None # 选择图书信息 index = 0 if len(books) > 0: text = term.format("\n\n请选择书籍元数据", term.red, term.bold) \ + term.format("[0-%s]" % len(books), term.yellow, term.bold) \ + term.format("之间的数字: ", term.red, term.bold) term.writeLine(text) index = int(input()) book = books[index] term.writeLine("你选择了书籍:%s" % book["title"], term.blue, term.bold) print_book(index, book) return book
def print_book(i, book): text = term.format("图书序号:", term.cyan, term.bold) \ + term.format(i, term.red, term.bold) \ + term.format(", 书名:%s" % book["title"], term.yellow, term.bold) print("====" * 10 + "<<<" * 3, text, ">>>" * 3 + "====" * 10) term.writeLine("|| title: %s" % book["title"], term.red) term.writeLine("|| subtitle: %s" % book["subtitle"], term.red) term.writeLine("|| authors: %s" % book["authors"], term.red) term.writeLine("|| tags: %s" % book["tags"], term.red) term.writeLine("|| rating: %s" % book["rating"], term.magenta) term.writeLine("|| star: %s" % book["star"], term.magenta) term.writeLine("|| num: %s" % book["num"], term.magenta) term.writeLine("|| price: %s" % book["price"], term.blue) term.writeLine("|| isbn: %s" % book["isbn"], term.blue) term.writeLine("|| publisher: %s" % book["publisher"], term.yellow) term.writeLine("|| date: %s" % book["date"], term.yellow) term.writeLine("|| series: %s" % book["series"], term.yellow) term.writeLine("|| comments: %s" % book["comments"], term.white) print("\n")
def init_logging(config_service): log = logging.getLogger('my5t3ry.main') logging.basicConfig(level=logging.INFO) output = term.format( '============================================= ', term.green ) + term.format('imFbAdapter 0.1', term.blue, term.bold) + term.format( ' =============================================\n\n ', term.green) term.writeLine(output) log.info(" === imgur root gallery: '" + str(config_service.config.get("rootImgurGallery")) + "' ===") log.info(" === facebook user: '******' ===") log.info(" === facebook post path: '" + str(config_service.config.get("postPath")) + "' ===") log.info(" === current pile consists of '" + str(len(os.listdir(config_service.config.get("tmpPicDir")))) + "' items ===") log.info(" === press ctrl + D to shutdown threads ===>") log.info(" === dump the shit away ===>\n\n") spinner = SpinnerService() spinner.start()
def _print_fields_usage(self, wrapped_model_instances): self._print_named_value('Used fields', ', '.join(self.total_used_fields)) self._print_named_value('Unused fields', ', '.join(self.total_unused_fields)) self._print_named_value( 'Wasted memory', humanfriendly.format_size(self.total_wasted_memory)) self._print_named_value( 'Recommendations', term.format( self.get_defer_recommendations(self.total_used_fields, self.total_unused_fields), term.reverse))
def report(graph, solutions): solution = solutions['solution'] customer_solution_len = 0 table_data = [[ term.format('server', term.bold), term.format('level', term.bold), term.format('is_customer', term.bold), term.format('request', term.bold), term.format('degree', term.bold), term.format('cap / cost', term.bold), ]] for s in solution: if (graph.nodes[s[0]].request > 0): customer_solution_len = customer_solution_len + 1 table_data.append([ s[0], s[1], "yes" if graph.nodes[s[0]].request > 0 else "no", "%d (%d)" % (graph.nodes[s[0]].request, graph.request_level(graph.nodes[s[0]].request)) if graph.nodes[s[0]].request > 0 else 0, "%d / %d" % (len(graph.nodes[s[0]].edges), graph.max_degree), "%f (%d / %d)" % (float(graph.nodes[s[0]].cap_div_cost) / float(graph.max_cap_div_cost), graph.nodes[s[0]].cap_div_cost, graph.max_cap_div_cost) ]) table = AsciiTable(table_data) term.writeLine('Statistical report for ' + term.format(solutions['name'], term.green)) term.writeLine('The optimum is ' + term.format(solutions['optimum'], term.red, term.bold)) term.writeLine('Customer server number: ' + term.format("%f ( %d / %d )" % \ (float(customer_solution_len)/ float(len(solution)), customer_solution_len, len(solution)), term.red, term.bold)) term.writeLine(table.table)
def header(self): """Frame structure format output""" # upper part bold = term.format("#", term.bold) frame_up = bold.ljust(100, "=") frame_up_format = term.format(frame_up) term.write(frame_up_format+bold) # center section 1 term.pos(3, 0) frame_three = term.format("+".ljust(87, "-")) term.write(frame_three+"+") # center section 2 term.pos(5, 0) frame_five = term.format("+".ljust(87, "-")) term.write(frame_five+"+") # center section 3 frame_centre1 = "+".ljust(87, "=") term.pos(15, 0) term.write(frame_centre1+"+") # center section 4 frame_centre2 = "+".ljust(59, "=") term.pos(17, 0) term.write(frame_centre2) term.pos(17, 88) term.write("|", term.bold) # Producer information kevin = "Kevin.Xiang" term.pos(16, 47) term.write(kevin) # next part frame_down = bold.ljust(100, "=") term.pos(39, 0) term.write(frame_down+bold) # border style for i1 in range(7, 14): term.pos(i1, 26) term.write("|") for i2 in range(16, 39): term.pos(i2, 60) term.write("|", term.bold) # Border output style IO term.pos(16, 61) frame_back = term.format("".rjust(27, " "), term.bgwhite) term.write(frame_back) term.pos(16, 71) frame_network = term.format("NETWORK", term.black, term.bgwhite) term.write(frame_network) term.pos(27, 61) term.write(frame_back) term.pos(27, 73) frame_disk = term.format("DISK", term.black, term.bgwhite) term.write(frame_disk) # Process output style term.pos(18, 0) space = "".center(4, " ") frame = term.format(" USER" + space + "PID" + space + "CPU%" + space + "MEM%" + space + "THRE" + space + "NAME", term.bold) term.write(frame) # Border output style list_down = [2, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38] for i3 in list_down: term.pos(i3, 0) term.write("|", term.bold) term.pos(i3, 88) term.write("|", term.bold)
def main(args): timeframe = args.timeframe if args.timeframe in st.TIMEFRAMES else '1h' filter_by = args.filter_by if args.filter_by in ['losers', 'gainers'] else 'gainers' columns = ['symbol', 'volume24h', 'usd', 'btc', timeframe] if len(args.exchanges) > 1: columns.append('exchanges') rename = dict.fromkeys(columns) for col in columns: rename[col] = f'% {col.upper()}' if col in st.TIMEFRAMES else col.title() cmd_data = None user_exit = False snapshots = collections.OrderedDict() cmc = CoinMarketCap() # per exchange currencies supported exchange_currencies = {ex: cmc.get_exchange_currencies(ex) for ex in args.exchanges} # sorted and unique list of currencies all_currencies = list(sorted(set(sum(list(exchange_currencies.values()), [])))) while args.loop or cmd_data is None: try: data = cmc.gainers if filter_by is True else cmc.losers if data: data = data.get(timeframe) data = data.set_index('symbol') # type: pd.DataFrame data.index.name = 'Symbol' else: continue snapshots.update({epoch(True): data.copy(True)}) print(data.head()) data = data.query(f'volume24h > {args.minvol * 1000.0}') print(data.head()) data['btc'] = data['btc'].apply(lambda x: '{: >12.8f}'.format(x)) data[timeframe] = data[timeframe].apply(lambda x: rg(float(x), '{: >+7.2f} %')) data['usd'] = data['usd'].apply(lambda x: term.format('{: >9,.3f}'.format(float(x)) + ' $', term.bold)) data['volume24h'] = data['volume24h'].apply(lambda x: str(format(float(x), ' >12,.0f') + ' $').rjust(15)) final = data[[c in all_currencies for c in data.index]] exchanges_fmt = lambda s: [e.upper() for e in args.exchanges if s in exchange_currencies[e]] final['exchanges'] = [','.join(exchanges_fmt(s)) for s in final.index] final = final[columns[1:]].rename(rename, axis=1) print(final) hour = f'{dt.now():%H:%M:%S}' print(f' {str("=" * 38)} {hour} {str("=" * 38)} ') except IndexError as err: user_exit = True raise err except KeyboardInterrupt: user_exit = True except Exception as err: user_exit = True raise err finally: if not user_exit: if args.loop > 0: time.sleep(args.loop) else: break