Extract the girc-formatted colours from the start of the string.

    Extracts the colours from the start, and returns the colour code in IRC
    format, and then the rest of the message.

    If `fill_last`, last number must be zero-padded.
964935
def extract_girc_colours(msg, fill_last):
    
    if not len(msg):
        return '', ''

    if ']' not in msg or not msg.startswith('['):
        return '', msg

    original_msg = msg

    colours, msg = msg.split(']', 1)
    colours = colours.lstrip('[')

    if ',' in colours:
        fore, back = colours.split(',')
        if fore not in colour_name_to_code or back not in colour_name_to_code:
            return '', original_msg
        fore = colour_name_to_code[fore]
        back = colour_name_to_code[back]
        return '{},{}'.format(fore, back.zfill(2) if fill_last else back), msg
    else:
        if colours not in colour_name_to_code:
            return '', original_msg
        fore = colour_name_to_code[colours]
        return '{}'.format(fore.zfill(2) if fill_last else fore), msg
1346011
def _handle_ansi_color_codes(self, s):
    """"""
    parts = HtmlReporter._ANSI_COLOR_CODE_RE.split(s)
    ret = []
    span_depth = 0
    # Note that len(parts) is always odd: text, code, text, code, ..., text.
    for i in range(0, len(parts), 2):
      ret.append(parts[i])
      if i + 1 < len(parts):
        for code in parts[i + 1].split(';'):
          if code == 0:  # Reset.
            while span_depth > 0:
              ret.append('</span>')
              span_depth -= 1
          else:
            ret.append('<span class="ansi-{}">'.format(code))
            span_depth += 1
    while span_depth > 0:
      ret.append('</span>')
      span_depth -= 1

    return ''.join(ret)
1265735
def unwrap_raw(content):
    
    starting_symbol = get_start_symbol(content)
    ending_symbol = ']' if starting_symbol == '[' else '}'
    start = content.find(starting_symbol, 0)
    end = content.rfind(ending_symbol)
    return content[start:end+1]
963487
def red(numbers):
	""""""
	
	line = 0
	deltas = []
	
	for value in numbers:
		deltas.append(value - line)
		line = value
	
	return b64encode(compress(b''.join(chr(i).encode('latin1') for i in deltas))).decode('latin1')
86781
def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str:
    
    start = start or 0
    end = (end or total) - 1
    return "bytes %s-%s/%s" % (start, end, total)
550319
def colorize_log_entry(self, string):
        

        final_string = string
        try:

            # First, do stuff in square brackets
            inside_squares = re.findall(r'\[([^]]*)\]', string)
            for token in inside_squares:
                if token in ['CRITICAL', 'ERROR', 'WARNING', 'DEBUG', 'INFO', 'NOTSET']:
                    final_string = final_string.replace('[' + token + ']', click.style("[", fg='cyan') + click.style(token, fg='cyan', bold=True) + click.style("]", fg='cyan'))
                else:
                    final_string = final_string.replace('[' + token + ']', click.style("[", fg='cyan') + click.style(token, bold=True) + click.style("]", fg='cyan'))

            # Then do quoted strings
            quotes = re.findall(r'"[^"]*"', string)
            for token in quotes:
                final_string = final_string.replace(token, click.style(token, fg="yellow"))

            # And UUIDs
            for token in final_string.replace('\t', ' ').split(' '):
                try:
                    if token.count('-') is 4 and token.replace('-', '').isalnum():
                        final_string = final_string.replace(token, click.style(token, fg="magenta"))
                except Exception: # pragma: no cover
                    pass

                # And IP addresses
                try:
                    if token.count('.') is 3 and token.replace('.', '').isnumeric():
                        final_string = final_string.replace(token, click.style(token, fg="red"))
                except Exception: # pragma: no cover
                    pass

                # And status codes
                try:
                    if token in ['200']:
                        final_string = final_string.replace(token, click.style(token, fg="green"))
                    if token in ['400', '401', '403', '404', '405', '500']:
                        final_string = final_string.replace(token, click.style(token, fg="red"))
                except Exception: # pragma: no cover
                    pass

            # And Zappa Events
            try:
                if "Zappa Event:" in final_string:
                    final_string = final_string.replace("Zappa Event:", click.style("Zappa Event:", bold=True, fg="green"))
            except Exception: # pragma: no cover
                pass

            # And dates
            for token in final_string.split('\t'):
                try:
                    is_date = parser.parse(token)
                    final_string = final_string.replace(token, click.style(token, fg="green"))
                except Exception: # pragma: no cover
                    pass

            final_string = final_string.replace('\t', ' ').replace('   ', ' ')
            if final_string[0] != ' ':
                final_string = ' ' + final_string
            return final_string
        except Exception as e: # pragma: no cover
            return string
435716
def hexdump(src, length=8, colorize=False):
    
    if not src:
        return str(src)
    if type(src) is not bytes:
        raise yubico_exception.InputError('Hexdump \'src\' must be bytestring (got %s)' % type(src))
    offset = 0
    result = ''
    for this in group(src, length):
        if colorize:
            last, this = this[-1], this[:-1]
            colors = DumpColors()
            color = colors.get('RESET')
            if ord_byte(last) & yubikey_defs.RESP_PENDING_FLAG:
                # write to key
                color = colors.get('BLUE')
            elif ord_byte(last) & yubikey_defs.SLOT_WRITE_FLAG:
                color = colors.get('GREEN')
            hex_s = color + ' '.join(["%02x" % ord_byte(x) for x in this]) + colors.get('RESET')
            hex_s += " %02x" % ord_byte(last)
        else:
            hex_s = ' '.join(["%02x" % ord_byte(x) for x in this])
        result += "%04X   %s\n" % (offset, hex_s)
        offset += length
    return result
939004
def display(self, ret, indent, prefix, out):
        '''
        
        '''
        if isinstance(ret, six.string_types):
            lines = ret.split('\n')
            for line in lines:
                out += '{0}{1}{2}{3}{4}\n'.format(
                        self.colors['RED'],
                        ' ' * indent,
                        prefix,
                        line,
                        self.colors['ENDC'])
        elif isinstance(ret, dict):
            for key in sorted(ret):
                val = ret[key]
                out += '{0}{1}{2}{3}{4}:\n'.format(
                        self.colors['CYAN'],
                        ' ' * indent,
                        prefix,
                        key,
                        self.colors['ENDC'])
                out = self.display(val, indent + 4, '', out)
        return out
209985
function extractColor(text, i, color) {
    var matches = [],
        match;
		
	text = text.slice(i);
    while ((match = text.match(/^\x1b\[([\d;]*)m/))) {
        matches.push(match);
        text = text.slice(match[0].length);
		i += match[0].length;
    }
    
    if (!matches.length) {
        return null;
    }
    
    var tokens = matches.map(function(match){
        return match[1].split(";");
    });
    
    tokens = Array.prototype.concat.apply([], tokens);
    
    var span = color.copy();
    span.i = i;
    
    var code;
    
    for (i = 0; i < tokens.length; i++) {
        code = +tokens[i];
        if (code == 0) {
            span.reset();
        } else if (code == 1) {
            span.l = true;
        } else if (code == 5) {
            span.flash = true;
        } else if (code == 7) {
            var t = span.f;
            span.f = span.b;
            span.b = t;
        } else if (code < 40) {
            span.f = code - 30;
        } else if (code < 50) {
            span.b = code - 40;
        }
    }
    return span;
}
1232461
def parse(self, format_string):
        """"""
        txt, state = '', 0
        colorstack = [(None, None)]
        itokens = self.tokenize(format_string)

        for token, escaped in itokens:
            if token == self._START_TOKEN and not escaped:
                if txt:
                    yield txt, colorstack[-1]
                    txt = ''

                state += 1
                colors = self.extract_syntax(colorise.compat.next(itokens)[0])
                colorstack.append(tuple(b or a
                                        for a, b in zip(colorstack[-1],
                                                        colors)))
            elif token == self._FMT_TOKEN and not escaped:
                # if state == 0:
                #     raise ColorSyntaxError("Missing '{0}'"
                #                            .format(self._START_TOKEN))

                if state % 2 != 0:
                    state += 1
                else:
                    txt += token
            elif token == self._STOP_TOKEN and not escaped:
                if state < 2:
                    raise ColorSyntaxError("Missing '{0}' or '{1}'"
                                           .format(self._STOP_TOKEN,
                                                   self._FMT_TOKEN))

                if txt:
                    yield txt, colorstack[-1]
                    txt = ''

                state -= 2
                colorstack.pop()
            else:
                txt += token

        if state != 0:
            raise ColorSyntaxError("Invalid color format")

        if txt:
            yield txt, colorstack[-1]
501647
def convert_color(color):
    
    if color is not None:

        # is the color a string
        if isinstance(color, str):
            # strip the color of white space
            color = color.strip()

            # if it starts with a # check it is a valid color
            if color[0] == "#":

                # check its format
                if len(color) != 7:
                    raise ValueError("{} is not a valid # color, it must be in the format #ffffff.".format(color))
                else:
                    # split the color into its hex values
                    hex_colors = (color[1:3], color[3:5], color[5:7])

                    # check hex values are between 00 and ff
                    for hex_color in hex_colors:
                        try:
                            int_color = int(hex_color, 16)
                        except:
                            raise ValueError("{} is not a valid value, it must be hex 00 - ff".format(hex_color))

                        if not (0 <= int_color <= 255):
                            raise ValueError("{} is not a valid color value, it must be 00 - ff".format(hex_color))

        # if the color is not a string, try and convert it
        else:
            # get the number of colors and check it is iterable
            try:
                no_of_colors = len(color)
            except:
                raise ValueError("A color must be a list or tuple of 3 values (red, green, blue)")

            if no_of_colors != 3:
                raise ValueError("A color must contain 3 values (red, green, blue)")

            # check the color values are between 0 and 255
            for c in color:
                if not (0 <= c <= 255):
                    raise ValueError("{} is not a valid color value, it must be 0 - 255")

            # convert to #ffffff format
            color = "#{:02x}{:02x}{:02x}".format(color[0], color[1], color[2])

    return color
1152415
def color_string(color, string):
    
    if not color_available:
        return string

    return color + string + colorama.Fore.RESET
1322242
def color(self, s, color=None, bold=False):
        
        if not self.enable:
            return s
        code_seq = []
        if color:
            code_seq += [30 + self.ColorIdxTable[color]]  # foreground color
        if bold:
            code_seq += [1]
        if not code_seq:
            return s
        start = "\x1b[%sm" % ";".join(map(str, code_seq))
        end = "\x1b[0m"
        while s[:1] == " ":  # move prefix spaces outside
            start = " " + start
            s = s[1:]
        while s[-1:] == " ":  # move postfix spaces outside
            end += " "
            s = s[:-1]
        return start + s + end
522187
def _colorize(self, msg, color=None, encode=False):
        
        
        # Valid colors
        colors = {
            'red':    '31',
            'green':  '32',
            'yellow': '33'
        }
        
        # No color specified or unsupported color
        if not color or not color in colors:
            return msg
        
        # The colorized string
        if encode:
            return u'\x1b[1;{}m{}\x1b[0m'.format(colors[color], msg)
        return '\x1b[1;{}m{}\x1b[0m'.format(colors[color], msg)
764571
def irc_format!(*settings, string)
      string = string.dup

      attributes = settings.select {|k| @@attributes.has_key?(k)}.map {|k| @@attributes[k]}
      colors = settings.select {|k| @@colors.has_key?(k)}.map {|k| @@colors[k]}
      if colors.size > 2
        raise ArgumentError, "At most two colors (foreground and background) might be specified"
      end

      attribute_string = attributes.join
      color_string = if colors.empty?
                       ""
                     else
                       "\x03#{colors.join(",")}"
                     end

      prepend = attribute_string + color_string
      append = @@attributes[:reset]

      # attributes act as toggles, so e.g. underline+underline = no
      # underline. We thus have to delete all duplicate attributes
      # from nested strings.
      string.delete!(attribute_string)

      # Replace the reset code of nested strings to continue the
      # formattings of the outer string.
      string.gsub!(/#{@@attributes[:reset]}/, @@attributes[:reset] + prepend)
      string.insert(0, prepend)
      string << append
      return string
    end
41952
def guess_phred_format(self):
        """"""
        # Possibilities #
        self.intervals = {
            'Sanger':       (33,  74),         # <- This one is the gold standard
            'Solexa':       (59, 105),
            'Illumina-1.3': (64, 105),         # <- These were abandoned after they wised up.
            'Illumina-1.5': (67, 105),         # <- These were abandoned after they wised up.
        }
        # Initialize variables #
        glob_min  = 9999
        glob_max  = 0
        take_next = False
        # Stop after #
        max_sequences_to_consider = 2000000
        # Error message #
        message = "Multiple PHRED encodings possible for '%s'.\n"
        # Loop #
        self.open()
        for i, line in enumerate(self.handle):
            # Are we on the PHRED line? #
            if not take_next:
                take_next = line.startswith('+')
                continue
            # Now we are on the PHRED line! #
            take_next = False
            current_min, current_max = self.get_qual_range(line.rstrip('\n'))
            if current_min < glob_min or current_max > glob_max:
                glob_min = min(current_min, glob_min)
                glob_max = max(current_max, glob_max)
                valid_encodings = [e for e, r in self.intervals.items() if glob_min >= r[0] and glob_max <= r[1]]
                if len(valid_encodings) == 0:
                    message = "Illegal PHRED encoding for '%s'.\n"
                    break
                if len(valid_encodings) == 1:
                    return valid_encodings[0]
            # Stop condition #
            if i >= max_sequences_to_consider: break
        # It didn't work #
        message += "Maximum detected value is: %s.\n"
        message += "Minimum detected value is: %s.\n"
        message += "Possibilities are: %s."
        message  = message % (self, glob_max, glob_min, ' or '.join(valid_encodings))
        raise Exception(message)
868115
def get_color_indices(color)   # :nodoc:
    invalid = 0x7FFF   # return from Colors#get_color when color is invalid

    index = Colors.new.get_color(color)
    index = invalid if color.respond_to?(:coerce) && (color < 8 || color > 63)
    if index == invalid
      [nil, nil]
    else
      [index, get_color_rbg(index)]
    end
  end