convert a named color definition to an escaped ANSI color
962462
def esc_ansicolor (color):
    """"""
    control = ''
    if ";" in color:
        control, color = color.split(";", 1)
        control = AnsiControl.get(control, '')+";"
    cnum = AnsiColor.get(color, '0')
    return AnsiEsc % (control+cnum)
222718
def alias_color(alias_name, *colors)
      validate(*colors)

      if !(alias_name.to_s =~ /^[\w]+$/)
        fail InvalidAliasNameError, "Invalid alias name `#{alias_name}`"
      elsif ANSI::ATTRIBUTES[alias_name]
        fail InvalidAliasNameError,
             "Cannot alias standard color `#{alias_name}`"
      end

      ALIASES[alias_name.to_sym] = colors.map(&ANSI::ATTRIBUTES.method(:[]))
      colors
    end
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'")
966070
public static Color nameToColor(String strColor)
    {
        final Object[][] obj = {
            {"black", Color.black},
            {"blue", Color.blue},
            {"cyan", Color.cyan},
            {"darkGray", Color.darkGray},
            {"gray", Color.gray},
            {"green", Color.green},
            {"lightGray", Color.lightGray},
            {"magenta", Color.magenta},
            {"orange", Color.orange},
            {"pink", Color.pink},
            {"red", Color.red},
            {"white", Color.white},
            {"yellow", Color.yellow}
        };      // Not static, because this method is usually not called.
        for (int i = 0; i < obj.length; i++)
        {
            if (strColor.equalsIgnoreCase((String)obj[i][0]))
                return (Color)obj[i][1];
        }
        try {
            return Color.decode(strColor);
        } catch (NumberFormatException ex)  {
        }
        return null;
    }
393391
def hilite(s, ok=True, bold=False):
    """"""
    if not term_supports_colors():
        return s
    attr = []
    if ok is None:  # no color
        pass
    elif ok:   # green
        attr.append('32')
    else:   # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
904641
function convertHexToRGB(color) {
  if (color.length === 4) {
    let extendedColor = '#'
    for (let i = 1; i < color.length; i++)
      extendedColor += color.charAt(i) + color.charAt(i)
    color = extendedColor
  }

  const values = {
    r: parseInt(color.substr(1, 2), 16),
    g: parseInt(color.substr(3, 2), 16),
    b: parseInt(color.substr(5, 2), 16)
  }

  return `rgb(${values.r}, ${values.g}, ${values.b})`
}
1007657
def getColorName(c):
    
    c = np.array(getColor(c))  # reformat to rgb
    mdist = 99.0
    kclosest = ""
    for key in colors.keys():
        ci = np.array(getColor(key))
        d = np.linalg.norm(c - ci)
        if d < mdist:
            mdist = d
            kclosest = str(key)
    return kclosest
1318339
public static Color decodeColor(String s) {
		if (s == null)
			return null;
		s = s.toLowerCase().trim();
		try {
			return WebColors.getRGBColor(s);
		}
		catch(IllegalArgumentException iae) {
			return null;
		}
	}
1270836
def write_color_old( text, attr=None):
    
    '''
    res = []
    chunks = terminal_escape.split(text)
    n = 0 # count the characters we actually write, omitting the escapes
    if attr is None:#use attribute from initial console
        attr = 15
    for chunk in chunks:
        m = escape_parts.match(chunk)
        if m:
            for part in m.group(1).split(u";"):
                if part == u"0": # No text attribute
                    attr = 0
                elif part == u"7": # switch on reverse
                    attr |= 0x4000
                if part == u"1": # switch on bold (i.e. intensify foreground color)
                    attr |= 0x08
                elif len(part) == 2 and u"30" <= part <= u"37": # set foreground color
                    part = int(part)-30
                    # we have to mirror bits
                    attr = (attr & ~0x07) | ((part & 0x1) << 2) | (part & 0x2) | ((part & 0x4) >> 2)
                elif len(part) == 2 and u"40" <= part <= u"47": # set background color
                    part = int(part) - 40
                    # we have to mirror bits
                    attr = (attr & ~0x70) | ((part & 0x1) << 6) | ((part & 0x2) << 4) | ((part & 0x4) << 2)
                # ignore blink, underline and anything we don't understand
            continue
        n += len(chunk)
        if chunk:
            res.append((u"0x%x"%attr, chunk))
    return res
1196843
def ansi_code(name):
    """"""
    try:
        obj = colorama
        for part in name.split("."):
            obj = getattr(obj, part)
        return obj
    except AttributeError:
        return ""
248762
def hexcolor(color):
    " "
    # first, if this is a hex color already, return!
    # Python 3: needs rewrite for str/unicode change
    if isinstance(color, six.string_types):
        if color[0] == '#' and len(color)==7:
            return color.lower()

    # now, get color to an rgb tuple
    rgb = (0,0,0)
    if isinstance(color, tuple):
        rgb = color
    elif isinstance(color, list):
        rgb = tuple(color)
    elif isinstance(color, six.string_types):
        c = color.lower()
        if c.find(' ')>-1:    c = c.replace(' ','')
        if c.find('gray')>-1: c = c.replace('gray','grey')
        if c in x11_colors:
            rgb = x11_colors[c]
    else:
        try:
            rgb = color.Red(), color.Green(), color.Blue()
        except:
            pass

    # convert rgb to hex color
    col = '#%02x%02x%02x' % (rgb)
    return col.lower()
474884
function colorLines(name, str) {
  return str
    .split('\n')
    .map(function(str) {
      return color(name, str);
    })
    .join('\n');
}
1128136
def ansi(string, *args):
	

	ansi = ''

	for arg in args:
		arg = str(arg)
		if not re.match(ANSI_PATTERN, arg):
			raise ValueError('Additional arguments must be ansi strings')

		ansi += arg
	
	return ansi + string + colorama.Style.RESET_ALL
1057899
def term_color(code):
    
    def inner(text, rl=False):
        """
        Every raw_input with color sequences should be called with
        rl=True to avoid readline messed up the length calculation
        """
        c = code
        if rl:
            return "\001\033[38;5;%sm\002%s\001\033[0m\002" % (c, text)
        else:
            return "\033[38;5;%sm%s\033[0m" % (c, text)
    return inner
354137
def ChargeColorMapping(maptype='jet', reverse=False):
    """"""

    pos_color = '#FF0000'
    neg_color = '#0000FF'
    neut_color = '#000000'

    mapping_d = {'A':neut_color,'R':pos_color,'N':neut_color,\
                 'D':neg_color,'C':neut_color,'Q':neut_color,\
                 'E':neg_color,'G':neut_color,'H':pos_color,\
                 'I':neut_color,'L':neut_color,'K':pos_color,\
                 'M':neut_color,'F':neut_color,'P':neut_color,\
                 'S':neut_color,'T':neut_color,'W':neut_color,\
                 'Y':neut_color,'V':neut_color}

    return (None, mapping_d, None)
1232777
def style_to_ansi_code(style):
    
    ret = ''
    for attr_name in _styles[style]:
        # allow stuff that has found it's way through ansi_code_pattern
        ret += codes.get(attr_name, attr_name)

    return ret
881513
function (sColor) {
				var sHexColor = "";

				if (!sColor || sColor.toLowerCase().indexOf("hsl") !== -1) {
					return undefined;
				}

				// named color
				if (sColor.indexOf("#") === -1) {
					return this.NAME_COLORS_TO_RGB_MAP[sColor.toLowerCase()] ? sColor.toLowerCase() : undefined;
				}

				//HEX value
				if (sColor.length === 4) {
					sHexColor = ["#", sColor[1], sColor[1], sColor[2], sColor[2], sColor[3], sColor[3]].join("");
				} else {
					sHexColor = sColor;
				}

				sHexColor = sHexColor.toUpperCase();

				return this.RGB_TO_NAMED_COLORS_MAP[sHexColor];
			}