/*
This function take theme color palette name and returns @theme-color dependent value
.e.g
Input: @theme-1
Output: color(~`colorPalette("@{theme-color}", ' 1 ')`)
485732
function getShade(varName) {
  let [, className, number] = varName.match(/(.*)-(\d)/);
  if (/theme-\d/.test(varName)) className = '@theme-color';
  return 'color(~`colorPalette("@{' + className.replace('@', '') + '}", ' + number + ")`)";
}
1058589
def get_color_scheme(name):
    """"""
    color_scheme = {}
    for key in sh.COLOR_SCHEME_KEYS:
        color_scheme[key] = CONF.get("appearance", "%s/%s" % (name, key))
    return color_scheme
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
907477
def set_palette_colors(self, palette):
        
        palette = palette.split(':')
        for i, pal in enumerate(palette):
            x, color = Gdk.Color.parse(pal)
            self.get_widget('palette_%d' % i).set_color(color)
591473
function palette({ baseColor: themeColor = baseColor, src = 'css/rsuite.min.css', dist } = {}, doneCallback) {

  try {
    if (!dist) {
      throw  `ERROR: [option.dist] is required`;
    }
  } catch (e) {
    console.log(e.red);
    return;
  }

  const originColors = color.calcColors(baseColor);
  const themeColors = color.calcColors(themeColor);
  const distPath = Path.dirname(dist);

  const ensureDir = path => new Promise((resolve) => {
    fse.ensureDir(path, () => resolve());
  });

  const readData = path => new Promise(resolve => {
    fs.readFile(path, 'utf-8', (err, data) => {
      resolve(data || '');
    });
  });

  const writeData = (path, data) => new Promise((resolve, reject) => {
    fs.writeFile(path, data, (err) => {
      if (err) {
        reject(err);
      }
      resolve();
    });
  });

  const handleCallback = (...args) => doneCallback && doneCallback(args);

  const generateThemes = async function () {
    try {
      await ensureDir(distPath);
      let data = await readData(Path.join(rootPath, src));
      originColors.forEach((color, index) => {
        data = data.replace(new RegExp(color, 'g'), themeColors[index]);
      });
      await  writeData(dist, data);
      console.log(`Palette ${dist}` + '[SUCCESS]'.green);
      handleCallback();
    } catch (e) {
      console.log(`Palette ${dist}` + '[FAILD]'.red);
      handleCallback(e);
    }
  };

  generateThemes();

  return module.exports;
}
1281033
public static int getColorAttr(Context ctx, @AttrRes int colorAttrId){
        int[] attrs = new int[] { colorAttrId /* index 0 */};
        TypedArray ta = ctx.obtainStyledAttributes(attrs);
        int colorFromTheme = ta.getColor(0, 0);
        ta.recycle();
        return colorFromTheme;
    }
702558
function colorString(value) {
  const asColor = color(value);
  const r = asColor.r.toString(16);
  const g = asColor.g.toString(16);
  const b = asColor.b.toString(16);

  return `#${r.length === 1 ? '0' : ''}${r}${g.length === 1 ? '0' : ''}${g}${b.length === 1 ? '0' : ''}${b}`;
}
168139
def get_color_index(self, colors, refresh=False):
        
        if refresh:
            self.refresh_complex_value('SupportedColors')

        sup = self.get_complex_value('SupportedColors')
        if sup is None:
            return None

        sup = sup.split(',')
        if not set(colors).issubset(sup):
            return None

        return [sup.index(c) for c in colors]
1342547
def _find_basic_palette(result):
    ''' 
    '''
    pal_name = 'default (xterm)'
    basic_palette = color_tables.xterm_palette4
    if env.SSH_CLIENT:  # fall back to xterm over ssh, info often wrong
        pal_name = 'ssh (xterm)'
    else:
        if os_name == 'nt':
            if sys.getwindowsversion()[2] > 16299: # Win10 FCU, new palette
                pal_name = 'cmd_1709'
                basic_palette = color_tables.cmd1709_palette4
            else:
                pal_name = 'cmd_legacy'
                basic_palette = color_tables.cmd_palette4
        elif sys.platform == 'darwin':
            if env.TERM_PROGRAM == 'Apple_Terminal':
                pal_name = 'termapp'
                basic_palette = color_tables.termapp_palette4
            elif env.TERM_PROGRAM == 'iTerm.app':
                pal_name = 'iterm'
                basic_palette = color_tables.iterm_palette4
        elif os_name == 'posix':
            if env.TERM in ('linux', 'fbterm'):
                pal_name = 'vtrgb'
                basic_palette = parse_vtrgb()
            elif env.TERM.startswith('xterm'):
                # fix: LOW64 - Python on Linux on Windows!
                if 'Microsoft' in os.uname().release:
                    pal_name = 'cmd_1709'
                    basic_palette = color_tables.cmd1709_palette4
                    result = 'truecolor'  # override
                elif sys.platform.startswith('freebsd'):  # vga console :-/
                    pal_name = 'vga'
                    basic_palette = color_tables.vga_palette4
                else:
                    try:  # TODO: check green to identify palette, others?
                        if get_color('index', 2)[0][:2] == '4e':
                            pal_name = 'tango'
                            basic_palette = color_tables.tango_palette4
                        else:
                            raise RuntimeError('not the color scheme.')
                    except (IndexError, RuntimeError):
                        pass
        else:  # Amiga/Atari :-P
            log.warn('Unexpected OS: os.name: %s', os_name)

    return result, pal_name, basic_palette
894403
def get_color_scheme(name):
    """"""
    name = name.lower()
    scheme = {}
    for key in COLOR_SCHEME_KEYS:
        try:
            scheme[key] = CONF.get('appearance', name+'/'+key)
        except:
            scheme[key] = CONF.get('appearance', 'spyder/'+key)
    return scheme
10840
function getThemeFromPath(dir, program, cb) {
        var configPath = path.resolve(dir, "theme.json");
        program.log(2, constants.LOG_SEV_INFO, "Attempting to read " + configPath);
        fs.readFile(configPath, { encoding: 'utf-8' }, function (err, data) {
            if (err) {
                program.log(1, constants.LOG_SEV_ERROR, "Error reading " + configPath);
                return cb(err);
            }
            var config;
            try {
                config = eval('(' + data + ')');
            } catch (e) {
                program.log(1, constants.LOG_SEV_ERROR, "Error parsing " + configPath + ".");
                program.log(2, constants.LOG_SEV_ERROR, "\n\n" + data);
                return cb(e);
            }
            var themeConf = config.about;
            if (!themeConf) {
                var errorStr = "No about section found in " + configPath;
                program.log(1, constants.LOG_SEV_ERROR, errorStr);
                return cb(new Error(errorStr));
            }
            themeConf.baseDir = dir;
            themeConf.program = program;
            cb(null, new Theme(themeConf));
        });
    }
633308
function plugin(palettes) {
  /**
   * Attempt to parse color. Copied from Stylus source code.
   *
   * @param {String} str
   * @return {RGBA}
   * @api private
   */
  var parseColor = 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);
    }
  };

  return function (style) {
    var getColor = function (paletteName, colorName) {
      var paletteName = paletteName.toString();
      var colorName = (new nodes.Literal(colorName)).toString().string;
      var color = parseColor(palettes[paletteName][colorName]);

      return color;
    };
    var getPalette = function (paletteName) {
      return function (colorName) {
        return getColor(paletteName, colorName);
      }
    };

    style.define('palette', getColor);

    // Construct custom functions for every palette
    Object.keys(palettes).forEach(function (paletteName) {
      style.define(['palette', paletteName].join('-'), getPalette(paletteName));
    });
  };
}
606648
function sanitizePalette(palette, name) {
    var defaultContrast = palette.contrastDefaultColor;
    var lightColors = palette.contrastLightColors || [];
    var strongLightColors = palette.contrastStrongLightColors || [];
    var darkColors = palette.contrastDarkColors || [];

    // These colors are provided as space-separated lists
    if (typeof lightColors === 'string') lightColors = lightColors.split(' ');
    if (typeof strongLightColors === 'string') strongLightColors = strongLightColors.split(' ');
    if (typeof darkColors === 'string') darkColors = darkColors.split(' ');

    // Cleanup after ourselves
    delete palette.contrastDefaultColor;
    delete palette.contrastLightColors;
    delete palette.contrastStrongLightColors;
    delete palette.contrastDarkColors;

    // Change { 'A100': '#fffeee' } to { 'A100': { value: '#fffeee', contrast:DARK_CONTRAST_COLOR }
    angular.forEach(palette, function(hueValue, hueName) {
      if (angular.isObject(hueValue)) return; // Already converted
      // Map everything to rgb colors
      var rgbValue = colorToRgbaArray(hueValue);
      if (!rgbValue) {
        throw new Error("Color %1, in palette %2's hue %3, is invalid. Hex or rgb(a) color expected."
                        .replace('%1', hueValue)
                        .replace('%2', palette.name)
                        .replace('%3', hueName));
      }

      palette[hueName] = {
        hex: palette[hueName],
        value: rgbValue,
        contrast: getContrastColor()
      };
      function getContrastColor() {
        if (defaultContrast === 'light') {
          if (darkColors.indexOf(hueName) > -1) {
            return DARK_CONTRAST_COLOR;
          } else {
            return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
              : LIGHT_CONTRAST_COLOR;
          }
        } else {
          if (lightColors.indexOf(hueName) > -1) {
            return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
              : LIGHT_CONTRAST_COLOR;
          } else {
            return DARK_CONTRAST_COLOR;
          }
        }
      }
    });
  }
1330729
protected function getColorFromName($colorName)
    {
        if (isset($this->colors[$colorName])) {
            return $this->colors[$colorName];
        }
        return $this->colors['reset'];
    }
1344209
function getColors(rawData) {

    // Regular expression matching colors variables naming pattern
    var REGEX = /^dc-(.*?)[0-9]+$/;

    var content = rawData
        .filter((item) => {
            var group = item.group[0];
            return group === 'colors'
                && item.context.type === 'variable'
                && item.context.name.match(REGEX);
        })
        .map((item) => {
            // extract color name (eg. `dc-magenta10 -> magenta`)
            item.color = item.context.name.replace(REGEX, '$1');
            item.color = _.capitalize(item.color);
            return item;
        });

    // transform colors array in a object, shaped as the view layer expect
    content = _.groupBy(content, (c) => c.color );
    Object.keys(content).forEach((color) => {
        content[color] = content[color].reduce((acc, c) => {
            acc['$' + c.context.name] = c.context.value;
            return acc;
        }, {});
    });
    return content;
}
1310350
function getThemeId(configName) {
    // Search for plugin configured theme
    var configTheme = $.grep(THEMES, function(theme) {
      return theme.config == configName;
    })[0];
    // Fallback to default theme
    return !!configTheme ? configTheme.id : 0;
  }
191076
function parseColor(color, contrast) {
      contrast = contrast || false;
      var rgbValues = $mdTheming.PALETTES[color.palette][color.hue];

      rgbValues = contrast ? rgbValues.contrast : rgbValues.value;

      return $mdUtil.supplant('rgba({0}, {1}, {2}, {3})',
        [rgbValues[0], rgbValues[1], rgbValues[2], rgbValues[3] || color.opacity]
      );
    }