Pick the color and apply it to the given string as necessary.
------------------------------------------------------------------------------
328524
def colorize(str, type)
      str = CGI.escapeHTML(str) if options[:html]
      if options[:plain] || !options[:color][type] || !inspector.colorize?
        str
      #
      # Check if the string color method is defined by awesome_print and accepts
      # html parameter or it has been overriden by some gem such as colorize.
      #
      elsif str.method(options[:color][type]).arity == -1 # Accepts html parameter.
        str.send(options[:color][type], options[:html])
      else
        str = %Q|<kbd style="color:#{options[:color][type]}">#{str}</kbd>| if options[:html]
        str.send(options[:color][type])
      end
    end
547853
public static function colorize($string, $color)
    {
        if (isset(self::$colors[$color])) {
            return "\033[" . self::$colors[$color] . 'm' . $string . "\033[0m";
        }

        return $string;
    }
142503
def color(string, status=True, warning=False, bold=True):
    
    attr = []
    if status:
        # green
        attr.append('32')
    if warning:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
242180
static public Color fromString (String rgb) {
		if (rgb == null || rgb.length() != 6) return Color.white;
		return new Color(Integer.parseInt(rgb.substring(0, 2), 16), Integer.parseInt(rgb.substring(2, 4), 16), Integer.parseInt(rgb
			.substring(4, 6), 16));
	}
368734
def write_color(string, name, style='normal', when='auto'):
    
    write(color(string, name, style, when))
249107
def color(string, name, style='normal', when='auto'):
    
    if name not in colors:
        from .text import oxford_comma
        raise ValueError("unknown color '{}'.\nknown colors are: {}".format(
            name, oxford_comma(["'{}'".format(x) for x in sorted(colors)])))

    if style not in styles:
        from .text import oxford_comma
        raise ValueError("unknown style '{}'.\nknown styles are: {}".format(
            style, oxford_comma(["'{}'".format(x) for x in sorted(styles)])))

    prefix = '\033[%d;%dm' % (styles[style], colors[name])
    suffix = '\033[%d;%dm' % (styles['normal'], colors['normal'])
    color_string = prefix + string + suffix

    if when == 'always':
        return color_string
    elif when == 'auto':
        return color_string if sys.stdout.isatty() else string
    elif when == 'never':
        return string
    else:
        raise ValueError("when must be one of: 'always', 'auto', 'never'")
474884
function colorLines(name, str) {
  return str
    .split('\n')
    .map(function(str) {
      return color(name, str);
    })
    .join('\n');
}
138962
private String checkColor(String color) {

        if (color != null) {
            if (color.indexOf("#") == -1) {
                // add the "#" to the color string
                color = "#" + color;
            }
            int colLength = color.length();
            if ((colLength == 4) || (colLength == 7)) {
                return color;
            }
        }
        return "#FFFFFF";
    }
516470
def append(self, p_string, p_color):
        
        self.colors[len(self.data)] = p_color
        self.data += p_string
280999
public void setColor(int color) {
		setRed(ColorUtils.getRed(color));
		setGreen(ColorUtils.getGreen(color));
		setBlue(ColorUtils.getBlue(color));
		if (color > 16777215 || color < 0) {
			setAlpha(ColorUtils.getAlpha(color));
		}
	}
1177457
def colorize_invoke_command(self, string):
        

        final_string = string

        try:

            # Line headers
            try:
                for token in ['START', 'END', 'REPORT', '[DEBUG]']:
                    if token in final_string:
                        format_string = '[{}]'
                        # match whole words only
                        pattern = r'\b{}\b'
                        if token == '[DEBUG]':
                            format_string = '{}'
                            pattern = re.escape(token)
                        repl = click.style(
                            format_string.format(token),
                            bold=True,
                            fg='cyan'
                        )
                        final_string = re.sub(
                            pattern.format(token), repl, final_string
                        )
            except Exception: # pragma: no cover
                pass

            # Green bold Tokens
            try:
                for token in [
                    'Zappa Event:',
                    'RequestId:',
                    'Version:',
                    'Duration:',
                    'Billed',
                    'Memory Size:',
                    'Max Memory Used:'
                ]:
                    if token in final_string:
                        final_string = final_string.replace(token, click.style(
                            token,
                            bold=True,
                            fg='green'
                        ))
            except Exception: # pragma: no cover
                pass

            # 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

            return final_string
        except Exception:
            return string
260595
public void jmolColorByChain(){
		String script =
				"function color_by_chain(objtype, color_list) {"+ String.format("%n") +
				""+ String.format("%n") +
				"		 if (color_list) {"+ String.format("%n") +
				"		   if (color_list.type == \"string\") {"+ String.format("%n") +
				"		     color_list = color_list.split(\",\").trim();"+ String.format("%n") +
				"		   }"+ String.format("%n") +
				"		 } else {"+ String.format("%n") +
				"		   color_list = [\"104BA9\",\"AA00A2\",\"C9F600\",\"FFA200\",\"284A7E\",\"7F207B\",\"9FB82E\",\"BF8B30\",\"052D6E\",\"6E0069\",\"83A000\",\"A66A00\",\"447BD4\",\"D435CD\",\"D8FA3F\",\"FFBA40\",\"6A93D4\",\"D460CF\",\"E1FA71\",\"FFCC73\"];"+ String.format("%n") +
				"		 }"+ String.format("%n") +

				"		 var cmd2 = \"\";"+ String.format("%n") +

				"		 if (!objtype) {"+ String.format("%n") +
				"		   var type_list  = [ \"backbone\",\"cartoon\",\"dots\",\"halo\",\"label\",\"meshribbon\",\"polyhedra\",\"rocket\",\"star\",\"strand\",\"strut\",\"trace\"];"+ String.format("%n") +
				"		   cmd2 = \"color \" + type_list.join(\" none; color \") + \" none;\";"+ String.format("%n") +
				"		   objtype = \"atoms\";"+ String.format("%n") +

				"		 }"+ String.format("%n") +

				"		 var chain_list  = script(\"show chain\").trim().lines;"+ String.format("%n") +
				"		 var chain_count = chain_list.length;"+ String.format("%n") +

				"		 var color_count = color_list.length;"+ String.format("%n") +
				"		 var sel = {selected};"+ String.format("%n") +
				"		 var cmds = \"\";"+ String.format("%n") +


				"		 for (var chain_number=1; chain_number<=chain_count; chain_number++) {"+ String.format("%n") +
				"		   // remember, Jmol arrays start with 1, but % can return 0"+ String.format("%n") +
				"		   cmds += \"select sel and :\" + chain_list[chain_number] + \";color \" + objtype + \" [x\" + color_list[(chain_number-1) % color_count + 1] + \"];\" + cmd2;"+ String.format("%n") +
				"		 }"+ String.format("%n") +
				"		 script INLINE @{cmds + \"select sel\"}"+ String.format("%n") +
				"}";

		executeCmd(script);
	}
716432
function parseColor (str) {
    if (str.substr(0,1) === '#') {
      // Handle color shorthands (like #abc)
      var shorthand = str.length === 4,
          m = str.match(shorthand ? /\w/g : /\w{2}/g);

      if (!m) return;
      m = m.map(function(s) { return parseInt(shorthand ? s+s : s, 16) });
      return new nodes.RGBA(m[0],m[1],m[2],1);
    }
    else if (str.substr(0,3) === 'rgb'){
      var m = str.match(/([0-9]*\.?[0-9]+)/g);
      if (!m) return;
      m = m.map(function(s){return parseFloat(s, 10)});
      return new nodes.RGBA(m[0], m[1], m[2], m[3] || 1);
    }
    else {
      var rgb = colors[str];
      if (!rgb) return;
      return new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1);
    }
  }
427245
def blue(cls, string, auto=False):
        
        return cls.colorize('blue', string, auto=auto)
1088603
def update_color(string, name, style='normal', when='auto'):
    
    clear()
    write_color(string, name, style, when)
722324
def highlight(string, fg=None, bg=None, indices=[], end='\n',
              target=sys.stdout):
    
    if not string or not indices or (fg is bg is None):
        return

    p = 0

    # The lambda syntax is necessary to support both Python 2 and 3
    for k, g in itertools.groupby(enumerate(sorted(indices)),
                                  lambda x: x[0]-x[1]):
        tmp = list(map(operator.itemgetter(1), g))
        s, e = tmp[0], tmp[-1]+1
        target.write(string[p:s])
        target.flush()  # Needed for Python 3.x
        _color_manager.set_color(fg, bg)
        target.write(string[s:e])
        target.flush()  # Needed for Python 3.x
        _color_manager.set_defaults()
        p = e

    if p < len(string):
        target.write(string[p:])

    target.write(end)
1325043
function getColor(color)
{
    if (!Array.isArray(color))
    {
        return getSingleColor(color);
    }
    else
    {
        for (let i = 0; i < color.length; ++i)
        {
            color[i] = getSingleColor(color[i]);
        }

        return color;
    }
}