Create the CAPTCHA image itself.

        :param chars: text to be generated.
        :param color: color of the text.
        :param background: color of the background.

        The color should be a tuple of 3 numbers, such as (0, 255, 255).
174610
def create_captcha_image(self, chars, color, background):
        
        image = Image.new('RGB', (self._width, self._height), background)
        draw = Draw(image)

        def _draw_character(c):
            font = random.choice(self.truefonts)
            w, h = draw.textsize(c, font=font)

            dx = random.randint(0, 4)
            dy = random.randint(0, 6)
            im = Image.new('RGBA', (w + dx, h + dy))
            Draw(im).text((dx, dy), c, font=font, fill=color)

            # rotate
            im = im.crop(im.getbbox())
            im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1)

            # warp
            dx = w * random.uniform(0.1, 0.3)
            dy = h * random.uniform(0.2, 0.3)
            x1 = int(random.uniform(-dx, dx))
            y1 = int(random.uniform(-dy, dy))
            x2 = int(random.uniform(-dx, dx))
            y2 = int(random.uniform(-dy, dy))
            w2 = w + abs(x1) + abs(x2)
            h2 = h + abs(y1) + abs(y2)
            data = (
                x1, y1,
                -x1, h2 - y2,
                w2 + x2, h2 + y2,
                w2 - x2, -y1,
            )
            im = im.resize((w2, h2))
            im = im.transform((w, h), Image.QUAD, data)
            return im

        images = []
        for c in chars:
            if random.random() > 0.5:
                images.append(_draw_character(" "))
            images.append(_draw_character(c))

        text_width = sum([im.size[0] for im in images])

        width = max(text_width, self._width)
        image = image.resize((width, self._height))

        average = int(text_width / len(chars))
        rand = int(0.25 * average)
        offset = int(average * 0.1)

        for im in images:
            w, h = im.size
            mask = im.convert('L').point(table)
            image.paste(im, (offset, int((self._height - h) / 2)), mask)
            offset = offset + w + random.randint(-rand, 0)

        if width > self._width:
            image = image.resize((self._width, self._height))

        return image
863858
def _background_gradient(s, cmap='PuBu', low=0, high=0,
                             text_color_threshold=0.408):
        
        if (not isinstance(text_color_threshold, (float, int)) or
                not 0 <= text_color_threshold <= 1):
            msg = "`text_color_threshold` must be a value from 0 to 1."
            raise ValueError(msg)

        with _mpl(Styler.background_gradient) as (plt, colors):
            smin = s.values.min()
            smax = s.values.max()
            rng = smax - smin
            # extend lower / upper bounds, compresses color range
            norm = colors.Normalize(smin - (rng * low), smax + (rng * high))
            # matplotlib colors.Normalize modifies inplace?
            # https://github.com/matplotlib/matplotlib/issues/5427
            rgbas = plt.cm.get_cmap(cmap)(norm(s.values))

            def relative_luminance(rgba):
                """
                Calculate relative luminance of a color.

                The calculation adheres to the W3C standards
                (https://www.w3.org/WAI/GL/wiki/Relative_luminance)

                Parameters
                ----------
                color : rgb or rgba tuple

                Returns
                -------
                float
                    The relative luminance as a value from 0 to 1
                """
                r, g, b = (
                    x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4)
                    for x in rgba[:3]
                )
                return 0.2126 * r + 0.7152 * g + 0.0722 * b

            def css(rgba):
                dark = relative_luminance(rgba) < text_color_threshold
                text_color = '#f1f1f1' if dark else '#000000'
                return 'background-color: {b};color: {c};'.format(
                    b=colors.rgb2hex(rgba), c=text_color
                )

            if s.ndim == 1:
                return [css(rgba) for rgba in rgbas]
            else:
                return pd.DataFrame(
                    [[css(rgba) for rgba in row] for row in rgbas],
                    index=s.index, columns=s.columns
                )
737929
public java.awt.Image createAwtImage(Color foreground, Color background) {
        int f = foreground.getRGB();
        int g = background.getRGB();
        Canvas canvas = new Canvas();

        String bCode = code;
        if (extended)
            bCode = getCode39Ex(code);
        if (generateChecksum)
            bCode += getChecksum(bCode);
        int len = bCode.length() + 2;
        int nn = (int)n;
        int fullWidth = len * (6 + 3 * nn) + (len - 1);
        byte bars[] = getBarsCode39(bCode);
        boolean print = true;
        int ptr = 0;
        int height = (int)barHeight;
        int pix[] = new int[fullWidth * height];
        for (int k = 0; k < bars.length; ++k) {
            int w = (bars[k] == 0 ? 1 : nn);
            int c = g;
            if (print)
                c = f;
            print = !print;
            for (int j = 0; j < w; ++j)
                pix[ptr++] = c;
        }
        for (int k = fullWidth; k < pix.length; k += fullWidth) {
            System.arraycopy(pix, 0, pix, k, fullWidth); 
        }
        Image img = canvas.createImage(new MemoryImageSource(fullWidth, height, pix, 0, fullWidth));
        
        return img;
    }
921898
public static String captchaChar(int length, boolean caseSensitivity) {
        StringBuilder sb       = new StringBuilder();
        Random        rand     = new Random();// 随机用以下三个随机生成器
        Random        randdata = new Random();
        int           data     = 0;
        for (int i = 0; i < length; i++) {
            int index = rand.nextInt(caseSensitivity ? 3 : 2);
            // 目的是随机选择生成数字，大小写字母
            switch (index) {
                case 0:
                    data = randdata.nextInt(10);// 仅仅会生成0~9, 0~9的ASCII为48~57
                    sb.append(data);
                    break;
                case 1:
                    data = randdata.nextInt(26) + 97;// 保证只会产生ASCII为97~122(a-z)之间的整数,
                    sb.append((char) data);
                    break;
                case 2: // caseSensitivity为true的时候, 才会有大写字母
                    data = randdata.nextInt(26) + 65;// 保证只会产生ASCII为65~90(A~Z)之间的整数
                    sb.append((char) data);
                    break;
                default:
                    break;
            }
        }
        return sb.toString();
    }
882462
function (colour) {
  if (!colour || !!((colour = String(colour)).indexOf("-") + 1)) {
    return {r: -1, g: -1, b: -1, opacity: -1, error: 1};
  }
  if (colour == "none") {
    return {r: -1, g: -1, b: -1, opacity: -1};
  }
  !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
  if (!colour) {
    return {r: -1, g: -1, b: -1, opacity: -1, error: 1};
  }
  var res,
      red,
      green,
      blue,
      opacity,
      t,
      values,
      rgb = colour.match(colourRegExp);
  if (rgb) {
    if (rgb[2]) {
      blue = parseInt(rgb[2].substring(5), 16);
      green = parseInt(rgb[2].substring(3, 5), 16);
      red = parseInt(rgb[2].substring(1, 3), 16);
    }
    if (rgb[3]) {
      blue = parseInt((t = rgb[3].charAt(3)) + t, 16);
      green = parseInt((t = rgb[3].charAt(2)) + t, 16);
      red = parseInt((t = rgb[3].charAt(1)) + t, 16);
    }
    if (rgb[4]) {
      values = rgb[4].split(commaSpaces);
      red = parseFloat(values[0]);
      values[0].slice(-1) == "%" && (red *= 2.55);
      green = parseFloat(values[1]);
      values[1].slice(-1) == "%" && (green *= 2.55);
      blue = parseFloat(values[2]);
      values[2].slice(-1) == "%" && (blue *= 2.55);
      rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = parseFloat(values[3]));
      values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
    }
    if (rgb[5]) {
      values = rgb[5].split(commaSpaces);
      red = parseFloat(values[0]);
      values[0].slice(-1) == "%" && (red /= 100);
      green = parseFloat(values[1]);
      values[1].slice(-1) == "%" && (green /= 100);
      blue = parseFloat(values[2]);
      values[2].slice(-1) == "%" && (blue /= 100);
      (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
      rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = parseFloat(values[3]));
      values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
      return hsb2rgb(red, green, blue, opacity);
    }
    if (rgb[6]) {
      values = rgb[6].split(commaSpaces);
      red = parseFloat(values[0]);
      values[0].slice(-1) == "%" && (red /= 100);
      green = parseFloat(values[1]);
      values[1].slice(-1) == "%" && (green /= 100);
      blue = parseFloat(values[2]);
      values[2].slice(-1) == "%" && (blue /= 100);
      (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360);
      rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = parseFloat(values[3]));
      values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
      return hsl2rgb(red, green, blue, opacity);
    }
    red = Math.min(Math.round(red), 255);
    green = Math.min(Math.round(green), 255);
    blue = Math.min(Math.round(blue), 255);
    opacity = Math.min(Math.max(opacity, 0), 1);
    rgb = {r: red, g: green, b: blue};
    rgb.opacity = isFinite(opacity) ? opacity : 1;
    return rgb;
  }
  return {r: -1, g: -1, b: -1, opacity: -1, error: 1};
}
354622
def colorize(str, sev: :normal_s)
      return str unless color_enabled?

      cc = COLOR_CODE
      color = cc.key?(sev) ? cc[sev] : ''
      "#{color}#{str.sub(cc[:esc_m], color)}#{cc[:esc_m]}"
    end
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
127782
def write_color(self,text, attr=None):
        
        '''
        if isinstance(attr,AnsiState):
            defaultstate = attr
        elif attr is None:  #use attribute form initial console
            attr = self.defaultstate.copy()
        else:
            defaultstate = AnsiState()
            defaultstate.winattr = attr
            attr = defaultstate
        chunks = terminal_escape.split(text)
        n = 0 # count the characters we actually write, omitting the escapes
        res=[]
        for chunk in chunks:
            m = escape_parts.match(chunk)
            if m:
                parts = m.group(1).split(u";")
                if len(parts) == 1 and parts[0] == u"0":
                    attr = self.defaultstate.copy()
                    continue
                for part in parts:
                    if part == u"0": # No text attribute
                        attr = self.defaultstate.copy()
                        attr.bold=False
                    elif part == u"7": # switch on reverse
                        attr.inverse=True
                    elif part == u"1": # switch on bold (i.e. intensify foreground color)
                        attr.bold=True 
                    elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color
                        attr.color = trtable[int(part) - 30]
                    elif len(part) == 2 and u"40" <= part <= u"47": # set background color
                        attr.backgroundcolor = trtable[int(part) - 40]
                continue
            n += len(chunk)
            if True:
                res.append((attr.copy(), chunk))
        return n,res
729277
def html5_parse_simple_color(input):
    
    # 1. Let input be the string being parsed.
    #
    # 2. If input is not exactly seven characters long, then return an
    #    error.
    if not isinstance(input, unicode) or len(input) != 7:
        raise ValueError(
            u"An HTML5 simple color must be a Unicode string "
            u"exactly seven characters long."
        )

    # 3. If the first character in input is not a U+0023 NUMBER SIGN
    #    character (#), then return an error.
    if not input.startswith('#'):
        raise ValueError(
            u"An HTML5 simple color must begin with the "
            u"character '#' (U+0023)."
        )

    # 4. If the last six characters of input are not all ASCII hex
    #    digits, then return an error.
    if not all(c in string.hexdigits for c in input[1:]):
        raise ValueError(
            u"An HTML5 simple color must contain exactly six ASCII hex digits."
        )

    # 5. Let result be a simple color.
    #
    # 6. Interpret the second and third characters as a hexadecimal
    #    number and let the result be the red component of result.
    #
    # 7. Interpret the fourth and fifth characters as a hexadecimal
    #    number and let the result be the green component of result.
    #
    # 8. Interpret the sixth and seventh characters as a hexadecimal
    #    number and let the result be the blue component of result.
    #
    # 9. Return result.
    return HTML5SimpleColor(
        int(input[1:3], 16),
        int(input[3:5], 16),
        int(input[5:7], 16)
    )
988543
function() {

        // background color
        me.game.world.addChild(new me.ColorLayer("background", "#330000"), 0);

        // static background image
        var background = new me.Sprite(480, 320, {
            image: game.texture,
            region : "backdrop.png"
        });
        me.game.world.addChild(background, 1);

        // character animation
        var animationSheet = game.texture.createAnimationFromName([
            "slice04_04.png", "slice05_05.png", "slice12_12.png", "slice13_13.png"
        ]);
        animationSheet.pos.set(200, 200, 2);
        me.game.world.addChild(animationSheet, 2);
    }
1232413
def get_colors(self, prefix, len_):
        """"""

        def color(tupl):
            """Make a color css"""
            return ((
                '%s.color-{0}, %s.color-{0} a:visited {{\n'
                '  stroke: {1};\n'
                '  fill: {1};\n'
                '}}\n'
            ) % (prefix, prefix)).format(*tupl)

        def value_color(tupl):
            """Make a value color css"""
            return ((
                '%s .text-overlay .color-{0} text {{\n'
                '  fill: {1};\n'
                '}}\n'
            ) % (prefix, )).format(*tupl)

        def ci_color(tupl):
            """Make a value color css"""
            if not tupl[1]:
                return ''
            return (('%s .color-{0} .ci {{\n'
                     '  stroke: {1};\n'
                     '}}\n') % (prefix, )).format(*tupl)

        if len(self.colors) < len_:
            missing = len_ - len(self.colors)
            cycles = 1 + missing // len(self.colors)
            colors = []
            for i in range(0, cycles + 1):
                for color_ in self.colors:
                    colors.append(darken(color_, 33 * i / cycles))
                    if len(colors) >= len_:
                        break
                else:
                    continue
                break
        else:
            colors = self.colors[:len_]

        # Auto compute foreground value color when color is missing
        value_colors = []
        for i in range(len_):
            if i < len(self.value_colors) and self.value_colors[i] is not None:
                value_colors.append(self.value_colors[i])
            else:
                value_colors.append(
                    'white' if is_foreground_light(colors[i]) else 'black'
                )

        return '\n'.join(
            chain(
                map(color, enumerate(colors)),
                map(value_color, enumerate(value_colors)),
                map(ci_color, enumerate(self.ci_colors))
            )
        )
210335
def fill(self, background_shape, img):
        
        background_shape = tuple(background_shape)
        return self._fill(background_shape, img)
667539
def foreground(color, content, readline=False):
    
    return encode(color, readline=readline) + content + encode(DEFAULT, readline=readline)
341753
def colorize(text, color=None, **kwargs):
    
    style = None
    bg = None
    # ================ #
    # Keyword checking #
    # ================ #
    if 'style' in kwargs:
        if kwargs['style'] not in STYLE:
            raise WrongStyle('"{}" is wrong argument for {}'.format(kwargs['style'], 'style'))
        style = kwargs['style']

    if 'bg' in kwargs:
        if kwargs['bg'] not in BACKGROUND:
            raise WrongBackground('"{}" is wrong argument for {}'.format(kwargs['bg'], 'bg'))
        bg = kwargs['bg']

    if color not in COLOR:
        raise WrongColor('"{}" is wrong argument for {}'.format(color, 'color'))
    # ===================== #
    # Colorizing the string #
    # ===================== #
    if '\x1b[0m' not in text:
        text = '\x1b[' + ';'.join([str(STYLE[style]), str(COLOR[color]), str(BACKGROUND[bg])])\
               + 'm' + text + '\x1b[0m'
    else:
        lst = text.split('\x1b[0m')
        text = ''
        for x in lst:
            if not x.startswith('\x1b['):
                x = '\x1b[' + ';'.join([str(STYLE[style]), str(COLOR[color]), str(BACKGROUND[bg])])\
                     + 'm' + x + '\x1b[0m'
            else:
                x += '\x1b[0m'
            text += x
    return text
1268974
def rgb_tuple_from_str(color_string):
    
    try:
        # English color names (limited)
        rgb_string = common_html_colors[color_string]
        return tuple([float(x) for x in re.findall(r'\d{1,3}', rgb_string)]) 
    
    except KeyError:
        try:
            # HEX color code
            hex_string = color_string.lstrip('#')
            return tuple(int(hex_string[i:i+2], 16) for i in (0, 2 ,4))
        
        except ValueError:
            # RGB or RGBA formatted strings
            return tuple([int(x) if float(x) > 1 else float(x) 
                          for x in re.findall(r"[-+]?\d*\.*\d+", color_string)])
1135808
private function generate($text)
    {
        // The implementation of generation algorithm is base on this:
        // https://github.com/yiisoft/yii/blob/master/framework/web/widgets/captcha/CCaptchaAction.php

        // First and foremost we need to create a resource
        $image = imagecreatetruecolor($this->paramBag->getWidth(), $this->paramBag->getHeight());

        // Allocate using RBG
        $backgroundColor = imagecolorallocate(
            $image,
            (int) ($this->paramBag->getBackgroundColor() % 0x1000000 / 0x10000), 
            (int) ($this->paramBag->getBackgroundColor() % 0x10000 / 0x100), 
            (int) ($this->paramBag->getBackgroundColor() % 0x100)
        );

        // Now draw a filled rectangle
        imagefilledrectangle(
            $image, 0, 0, 
            $this->paramBag->getWidth(), 
            $this->paramBag->getHeight(), 
            $backgroundColor
        );

        // Now let's free some memory
        imagecolordeallocate($image, $backgroundColor);

        if ($this->paramBag->getTransparent() == true) {
            imagecolortransparent($image, $backgroundColor);
        }

        $textColor = imagecolorallocate(
            $image, 
            (int) ($this->paramBag->getTextColor() % 0x1000000 / 0x10000), 
            (int) ($this->paramBag->getTextColor() % 0x10000 / 0x100), 
            (int) ($this->paramBag->getTextColor() % 0x100)
        );

        $length = strlen($text);
        $box = imagettfbbox(30, 0, $this->paramBag->getFontFile(), $text);

        $w = $box[4] - $box[0] + $this->paramBag->getOffset() * ($length - 1);
        $h = $box[1] - $box[5];

        $scale = min(
            ($this->paramBag->getWidth() - $this->paramBag->getPadding() * 2) / $w, 
            ($this->paramBag->getHeight() - $this->paramBag->getPadding() * 2) / $h
        );

        $x = 10; // Width
        $y = round($this->paramBag->getHeight() * 27 / 40);

        for ($i = 0; $i < $length; ++$i) {
            $fontSize = (int) (rand(26, 32) * $scale * 0.8);
            $angle = rand(-10, 10);

            $letter = $text[$i];
            $box = imagettftext($image, $fontSize, $angle, $x, $y, $textColor, $this->paramBag->getFontFile(), $letter);
            $x = $box[2] + $this->paramBag->getOffset();
        }

        // Now free the memory
        imagecolordeallocate($image, $textColor);
        return $image;
    }
1217623
def html5_serialize_simple_color(simple_color):
    
    red, green, blue = simple_color

    # 1. Let result be a string consisting of a single "#" (U+0023)
    #    character.
    result = u'#'

    # 2. Convert the red, green, and blue components in turn to
    #    two-digit hexadecimal numbers using lowercase ASCII hex
    #    digits, zero-padding if necessary, and append these numbers
    #    to result, in the order red, green, blue.
    format_string = '{:02x}'
    result += format_string.format(red)
    result += format_string.format(green)
    result += format_string.format(blue)

    # 3. Return result, which will be a valid lowercase simple color.
    return result