def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes: """ Coerce str/bytes into a strictly byte-wise HTTP header key. """ if isinstance(value, bytes): return value.lower() return value.encode(encoding or "ascii").lower()
def _clean_text(text: typing.AnyStr) -> str: # try and approximate unicode with ascii text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode() text = text.lower() # make lowercase text = text.replace("?", ".").replace("!", ".") for c in "/-\n\r": text = text.replace(c, " ") text = "".join(filter(ALPHABET.__contains__, text)) # filter to alphabet chars text = text.lstrip(" .") # filter out leading spaces and periods if text == "": raise ValueError("text needs to have at least one letter") ret = "" for x in text: # ret is a valid string after every iteration if x == ".": ret = ret.rstrip(". ") + ". " elif x == " ": ret = ret.rstrip(" ") + " " else: ret += x ret = ret.rstrip(" ") # strip trailing spaces return ret
def get_dict_val_case_insensitive(source: typing.Dict[typing.AnyStr, typing.AnyStr], key: typing.AnyStr) -> typing.Optional[typing.AnyStr]: match: typing.List[typing.AnyStr] = list(filter(lambda x: x.lower() == key.lower(), source.keys())) if not len(match): return None if len(match) > 1: raise KeyError("overlapping keys") if len(match) == 1: matched_key: typing.AnyStr = match[0] return source[matched_key] raise KeyError("overlapping keys")
def add_color(self, name: typing.AnyStr, r: typing.SupportsInt, g: typing.SupportsInt, b: typing.SupportsInt) -> int: """Add a custom color and return color's number(positive). Return -1 when the current term doesn't support color.""" # Ensure current terminal has colors. if not (curses.has_colors or curses.can_change_color()): return -1 curses.init_color(self.__color_count - 1, r, g, b) self.__color_count += 1 # color + 1 # insert a lowered color name with its rgb self.__colors.append((name.lower(), (r, g, b))) return self.__color_count - 1
def clean_hostname(name: typing.AnyStr) -> str: """ Converts from short to long hostname, if no domain found. """ # bytes? if not isinstance(name, (str, bytes)): cli_warning("Invalid input for hostname: {}".format(name)) name = name.lower() # Assume user is happy with domain, but strip the dot. if name.endswith("."): return name[:-1] # If a dot in name, assume long name. if '.' in name: return name # Append domain name if in config and it does not end with it if 'domain' in config and not name.endswith(config['domain']): return "{}.{}".format(name, config['domain']) return name
def in_hsts_preload(host: typing.AnyStr) -> bool: """Determines if an IDNA-encoded host is on the HSTS preload list""" if isinstance(host, str): host = host.encode("ascii") labels = host.lower().split(b".") # Fast-branch for gTLDs that are registered to preload all sub-domains. if labels[-1] in _GTLD_INCLUDE_SUBDOMAINS: return True with open_pkg_binary("hstspreload.bin") as f: for layer, label in enumerate(labels[::-1]): # None of our layers are greater than 4 deep. if layer > 3: return False # Read the jump table for the layer and label jump_info = _JUMPTABLE[layer][_crc8(label)] if jump_info is None: # No entry: host is not preloaded return False # Read the set of entries for that layer and label f.seek(jump_info[0]) data = bytearray(jump_info[1]) f.readinto(data) for is_leaf, include_subdomains, ent_label in _iter_entries(data): # We found a potential leaf if is_leaf: if ent_label == host: return True if include_subdomains and host.endswith(b"." + ent_label): return True # Continue traversing as we're not at a leaf. elif label == ent_label: break else: return False return False
def in_hsts_preload(host: typing.AnyStr) -> bool: """Determines if an IDNA-encoded host is on the HSTS preload list""" if isinstance(host, str): host = host.encode("ascii") labels = host.lower().split(b".") # Fast-branch for gTLDs that are registered to preload all sub-domains. if labels[-1] in _GTLD_INCLUDE_SUBDOMAINS: return True with open(_HSTSPRELOAD_BIN_PATH, "rb") as f: for layer, label in enumerate(labels[::-1]): # None of our layers are greater than 4 deep. if layer > 3: return False # Read the jump table for the layer and label offset, size = _get_offset_and_size(f, layer, label) if offset == 0: return False # Read the set of entries for that layer f.seek(offset, 1) data = bytearray(size) f.readinto(data) for is_leaf, include_subdomains, ent_label in _iter_entries(data): # We found a potential leaf if is_leaf: if ent_label == host: return True if include_subdomains and host.endswith(b"." + ent_label): return True # Continue traversing as we're not at a leaf. elif label == ent_label: break else: return False return False
def _translate_player_input(player_input: t.AnyStr) -> t.AnyStr: """ >>> _translate_player_input('w') 'player_up' >>> _translate_player_input('s') 'player_down' >>> _translate_player_input('a') 'player_left' >>> _translate_player_input('d') 'player_right' >>> _translate_player_input('q') 'player_quit' >>> _translate_player_input('W') 'player_up' >>> _translate_player_input('foo') 'unknown' """ player_input = player_input.lower() if player_input in ['w']: return PlayerCommands.PLAYER_UP if player_input in ['s']: return PlayerCommands.PLAYER_DOWN if player_input in ['a']: return PlayerCommands.PLAYER_LEFT if player_input in ['d']: return PlayerCommands.PLAYER_RIGHT if player_input in ['b']: return PlayerCommands.SHOW_BACKPACK if player_input in ['q']: return PlayerCommands.PLAYER_QUIT return PlayerCommands.UNKNOWN