def save_to_db(db, steam_id, info, db2): regular_doc = create_or_get_documents(db, steam_id) for key in info: try: regular_doc[key] = info[key] db.save(regular_doc) print(cs(f'Saved {steam_id} to db', '#00ff00')) except BaseException as e: print(cs(f'Unable to save {steam_id} to db', '#ff0000')) print(sys.exc_info()) if 'loccountrycode' in info and info['loccountrycode'] == "AU": aus_doc = create_or_get_documents(db2, steam_id) for key in info: try: aus_doc[key] = info[key] db2.save(aus_doc) print(cs(f'Saved {steam_id} to aus db', '#00ff00')) except BaseException as e: print(cs(f'Unable to save {steam_id} to AUS db', '#ff0000')) print(sys.exc_info())
def get_player_data(steam_id, db, db2): global api_count print(cs(f'Fetching player data for steamid {steam_id}', '#b4d3fa')) url = f'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={STEAM_API_KEY}&steamids={steam_id}' api_count += 1 resp = requests.get(url) try: info = resp.json()['response']['players'][0] info.pop('communityvisibilitystate', None) info.pop('profilestate', None) info.pop('profileurl', None) info.pop('avatar', None) info.pop('avatarmedium', None) info.pop('avatarfull', None) info.pop('avatarhash', None) info.pop('personastate', None) info.pop('primaryclanid', None) info.pop('personastateflags', None) info = get_owned_games_data(steam_id, info) save_to_db(db, steam_id, info, db2) except IndexError: print(cs(f'Skipping {steam_id} because no data of player', '#ff0000'))
def get_owned_games_data(steam_id, info): global api_count print(cs(f'Fetching owned game data for steamid {steam_id}', '#b4d3fa')) url = f'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={STEAM_API_KEY}&steamid={steam_id}' resp = requests.get(url) api_count += 1 try: ownedgames = resp.json()['response']['games'] tottime = 0 listy = [] for x in ownedgames: x.pop('playtime_windows_forever', None) x.pop('playtime_mac_forever', None) x.pop('playtime_linux_forever', None) tottime = tottime + x['playtime_forever'] listy.append(x) info['total_playtime'] = tottime info['ownedgames'] = listy except KeyError: print( cs(f'Skipping {steam_id} because no data on owned games', '#ff0000')) return info
def run(self) -> None: prompt = self.prompter() action = 'init' while not action == 'exit': action = input(prompt) try: if action == 'flag': print(self.get_cipher()) elif action == 'shell': exit_code = self.exec_shell() break elif not action == 'exit': print('unknown action') except Exception as e: print(cs(str(e), "#ff0000").bold()) sys.exit(0)
def format(self, record): message = logging.Formatter.format(self, record) config = self.log_colors.get(record.levelname, DEFAULT_COLOR) if isinstance(config, str): config = { "color": config, "background": None, "underline": False, "bold": False, } elif not isinstance(config, dict): raise ValueError("color setting must be a string or dict") message = cs(message, config.get("color", DEFAULT_COLOR), config.get("background", None)) if config.get("underline", False): message = message.underline() if config.get("bold", False): message = message.bold() return str(message)
def run(self) -> None: prompt = self.prompter() action = 'init' while not action == 'exit': action = input(prompt) try: if action == 'play': print("Here, have some toys:") for toy in self.play(self.keywords): print(toy) elif action == 'shell': exit_code = self.exec_shell() break elif not action == 'exit': print('unknown action') except Exception as e: print(cs(str(e), "#ff0000").bold()) sys.exit(0)
def _flattened_pieces(cube: Cube) -> list[cs]: up = cube.pieces[0].flatten() top_rows = np.concatenate([ cube.pieces[1][0], cube.pieces[2][0], cube.pieces[3][0], cube.pieces[4][0] ]) middle_rows = np.concatenate([ cube.pieces[1][1], cube.pieces[2][1], cube.pieces[3][1], cube.pieces[4][1] ]) bottom_rows = np.concatenate([ cube.pieces[1][2], cube.pieces[2][2], cube.pieces[3][2], cube.pieces[4][2] ]) down = cube.pieces[5].flatten() total = np.concatenate([up, top_rows, middle_rows, bottom_rows, down]) colored_total = [] for piece in total: color = "" if piece.lower() == "y": color = "yellow" elif piece.lower() == "o": color = "orange" elif piece.lower() == "b": color = "blue" elif piece.lower() == "w": color = "white" elif piece.lower() == "g": color = "green" elif piece.lower() == "r": color = "red" colored_total.append(cs(piece, color)) return colored_total
import re import locale from termcolor import colored import colorhash as ch import stringcolor as sc from .numbers import F, isnan, NaN colhash = lambda s, h=None: sc.cs(s, f'rgb{ch.ColorHash(h if h else s).rgb}') colhashbold = lambda s, h=None: colhash(s, h).bold() colhashwrap = lambda s: '\n'.join( map(lambda t: colhash(t, s).render(), s.replace('-', ' ').split(' '))) from util.numbers import F def colorize(f, n, d, v): c = d[0] if not isnan(n): for i, v in enumerate(v): if v < n: c = d[i + 1] return colored(f(n), c) # Percentage spc = ['red', 'yellow', 'green', 'cyan', 'magenta'] pct = lambda p: colorize(lambda n: '%0.2f%%' % n, F(p), spc,
def append(self, s: str, colour: str, background_colour: str = None): self._line += cs(s, colour, background_colour) self._len += len(s) if self._len >= self.MAX_LENGTH: self.flush()
def diff_regex_headers(): """ show differences between headers of all files matching regex """ version = "0.0.0" parser = argparse.ArgumentParser(description='regex tester', prog='regex-tester', formatter_class=rawtxt) parser.add_argument("regex", nargs="?", help="regular expression (use quotes!)") parser.add_argument( "--encoding", "-e", help="optional: include file encoding.\ndefaults to utf-8", default="utf-8") parser.add_argument( "--workdir", "-w", help="optional: use a working dir other than the current dir", default="./") parser.add_argument("--delimiter", "-d", help="define a delimiter other than `,`", default=",") parser.add_argument("--json", "-j", action="store_true", help="print json object") parser.add_argument("--table", "-t", action="store_true", help="print table") parser.add_argument("--files", "-f", action="store_true", help="only show matching files") parser.add_argument("--meta", "-m", action="store_true", help="show matching files including meta data") args = parser.parse_args() regex = args.regex encoding = args.encoding working_dir = args.workdir do_json = args.json do_table = args.table do_files = args.files delim = args.delimiter do_meta = args.meta # check for tags if delim == "\\t": delim = "\t" _, _, all_filenames = next(os.walk(working_dir)) regex = re.compile(regex) matching_filenames = [] # find all matching files for filename in all_filenames: if regex.match(filename): matching_filenames.append(filename) # check for enough files if len(matching_filenames) < 2: print( cs("Please use a pattern matching at least 2 files", "yellow", "red")) exit() # show only files if do_files: for filename in matching_filenames: print(cs(filename, "Chartreuse")) exit() if do_meta: for filename in matching_filenames: output = cs(filename, "Chartreuse") rawdata = open(os.path.join(working_dir, filename), 'rb').read() result = chardet.detect(rawdata) charenc = result['encoding'] first_line = head_n_1(os.path.join(working_dir, filename), encoding, delim) num_columns = len(first_line) output = f"{output} - {charenc} - {num_columns} header columnns" print(output) exit() headers = {} columns = [] # get headers from file and build list of all headers for matched_file in matching_filenames: first_line = head_n_1(os.path.join(working_dir, matched_file), encoding, delim) header_dict = [] for index, header in enumerate(first_line): if header not in columns: columns.append(header) header_dict.append({"value": header, "position": index}) headers[matched_file] = header_dict if do_json: print(json.dumps(headers)) elif do_table: # show diff columnar_headers = [""] for column in columns: columnar_headers.append(column) columnar_rows = [] for key, value in headers.items(): colored_key = cs(key, "Cornsilk") this_row = [colored_key] for column in columns: found = False matching_positions = "" for val_pos in value: if val_pos["value"] == column: matching_positions += str(val_pos["position"]) + ", " found = True if not found: this_row.append(cs("0", "red")) else: this_row.append(matching_positions[:-2]) columnar_rows.append(this_row) try: table = columnar(columnar_rows, columnar_headers) except Exception as e: print(cs(str(e), "orange")) exit() print(table) else: # basic output for matched_file in matching_filenames: print(cs(matched_file, "yellow")) first_line = head_n_1(os.path.join(working_dir, matched_file), encoding, delim) print(first_line) # print missing missing = "" for column in columns: if column not in first_line: missing += f"\'{column}\', " if missing: print("Missing:", cs(missing[:-2], "red")) else: print(cs("Nothing missing", "green"))
}, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, 'db': { 'format': str( cs( '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', 'grey')), 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', },
def underscore(): print(cs('____________________________________________', '#24abb3'))
def __init__(self, config_file, guide_file): config = json.load(open(config_file, 'r')) self.username = config['username'] self.host = config['host'] self.port = config['port'] print(cs(open(guide_file, 'r').read(), "#41fdfe").bold())
def print_translation(translation) -> None: print(translation.origin, cs(LANGUAGES[translation.src].title(), "purple")) print(f"\t {cs(translation.text, 'dodgerblue')}") print(f"\t {cs(translation.pronunciation, 'yellow')}") print()
def __init__(self, config_file, guide_file): config = json.load(open(config_file, 'r')) self.username = config['username'] self.keywords = config['keywords'] print(cs(open(guide_file, 'r').read(), "#41fdfe").bold())
def prompter(self): prompt = cs('\naction', "#66ff00").bold() prompt += cs(': ', "#ffffff").bold() return prompt
death = True listofchannels = [] temp = os.listdir("archive/") load = 0 for x in temp: print(x) listofchannels.append(x) #While you are in limbo; i suppose.... while death == True: while state == 1: if redo != 1: underscore() temp = [] print(cs(str(len(listofchannels)) + ' channel found', '#21db65c')) if len(listofchannels) == 0: print('no channels detected.') death = False state = 0 continue for x in range(0, len(listofchannels)): print(cs(str(x), '#21db65c') + ': ' + listofchannels[x]) #channel is the input, reads the input... channel = input( 'please give channel, you can use the digits above to select <3\nx to quit\n' ) #input branch. if channel == 'x': death = False