Create the color map SLD format from a list of values.
        :rtype: str
184522
def getColorMapAsDiscreetSLD(self, uniqueValues, nodata=-9999):
        
        colorMap = ET.Element('ColorMap', type='values')
        # Add a line for the no-data values (nv)
        ET.SubElement(colorMap, 'ColorMapEntry', color='#000000', quantity=str(nodata), label='NoData', opacity='0.0')

        for value in uniqueValues:
            red, green, blue = self.getColorForValue(value)
            hexRGB = '#%02X%02X%02X' % (red,
                                        green,
                                        blue)

            ET.SubElement(colorMap, 'ColorMapEntry', color=hexRGB, quantity=str(value), label=str(value), opacity=str(self.alpha))

        return ET.tostring(colorMap)
102951
def raster(event_times_list, color='k'):
  
  ax = plt.gca()
  for ith, trial in enumerate(event_times_list):
    plt.vlines(trial, ith + .5, ith + 1.5, color=color)
  plt.ylim(.5, len(event_times_list) + .5)
  return ax
592070
def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP):
        '''
        
        '''
        import numpy as np
        adjusted_weights = np.clip(weights, 0., max_weight) / max_weight
        self.vc = colors_like(adjusted_weights, self.v, colormap=color)
616989
def heatmap(n_x=5,n_y=10):
		
	x=['x_'+str(_) for _ in range(n_x)]
	y=['y_'+str(_) for _ in range(n_y)]
	return pd.DataFrame(surface(n_x-1,n_y-1).values,index=x,columns=y)
342481
def _string_to_rgb(color):
    """"""
    if not color.startswith('#'):
        if color.lower() not in _color_dict:
            raise ValueError('Color "%s" unknown' % color)
        color = _color_dict[color]
        assert color[0] == '#'
    # hex color
    color = color[1:]
    lc = len(color)
    if lc in (3, 4):
        color = ''.join(c + c for c in color)
        lc = len(color)
    if lc not in (6, 8):
        raise ValueError('Hex color must have exactly six or eight '
                         'elements following the # sign')
    color = np.array([int(color[i:i+2], 16) / 255. for i in range(0, lc, 2)])
    return color
105992
def create_colormap(palette):
    """"""
    from trollimage.colormap import Colormap
    fname = palette.get('filename', None)
    if fname:
        data = np.load(fname)
        cmap = []
        num = 1.0 * data.shape[0]
        for i in range(int(num)):
            cmap.append((i / num, (data[i, 0] / 255., data[i, 1] / 255.,
                                   data[i, 2] / 255.)))
        return Colormap(*cmap)

    colors = palette.get('colors', None)
    if isinstance(colors, list):
        cmap = []
        values = palette.get('values', None)
        for idx, color in enumerate(colors):
            if values:
                value = values[idx]
            else:
                value = idx / float(len(colors) - 1)
            cmap.append((value, tuple(color)))
        return Colormap(*cmap)

    if isinstance(colors, str):
        from trollimage import colormap
        import copy
        return copy.copy(getattr(colormap, colors))

    return None
1068650
def rgb_color_list_to_hex(color_list):
    
    color_list_rgb = [[int(x*255) for x in c[0:3]] for c in color_list]
    color_list_hex = ['#{:02X}{:02X}{:02X}'.format(rgb[0], rgb[1], rgb[2]) for rgb in color_list_rgb]
    return color_list_hex
671595
def colors(self, value):
        
        if value is not None:
            assert type(value) is tuple, "'{0}' attribute: '{1}' type is not 'tuple'!".format("colors", value)
            assert len(value) == 2, "'{0}' attribute: '{1}' length should be '2'!".format("colors", value)
            for index in range(len(value)):
                assert type(
                    value[index]) is QColor, "'{0}' attribute element '{1}': '{2}' type is not 'QColor'!".format(
                    "colors", index, value)
        self.__colors = value
764152
def _init_glyph(self, plot, mapping, properties):
        
        properties = mpl_to_bokeh(properties)
        properties = dict(properties, **mapping)
        if 'xs' in mapping:
            renderer = plot.patches(**properties)
        else:
            renderer = plot.quad(**properties)
        if self.colorbar and 'color_mapper' in self.handles:
            self._draw_colorbar(plot, self.handles['color_mapper'])
        return renderer, renderer.glyph
943642
def color_map(lookup, color_stops, default_color='rgb(122,122,122)'):
    
    # if no color_stops, use default color
    if len(color_stops) == 0:
        return default_color
    
    # dictionary to lookup color from match-type color_stops
    match_map = dict((x, y) for (x, y) in color_stops)

    # if lookup matches stop exactly, return corresponding color (first priority)
    # (includes non-numeric color_stop "keys" for finding color by match)
    if lookup in match_map.keys():
        return match_map.get(lookup)

    # if lookup value numeric, map color by interpolating from color scale
    if isinstance(lookup, (int, float, complex)):

        # try ordering stops 
        try:
            stops, colors = zip(*sorted(color_stops))
        
        # if not all stops are numeric, attempt looking up as if categorical stops
        except TypeError:
            return match_map.get(lookup, default_color)

        # for interpolation, all stops must be numeric
        if not all(isinstance(x, (int, float, complex)) for x in stops):
            return default_color

        # check if lookup value in stops bounds
        if float(lookup) <= stops[0]:
            return colors[0]
        
        elif float(lookup) >= stops[-1]:
            return colors[-1]
        
        # check if lookup value matches any stop value
        elif float(lookup) in stops:
            return colors[stops.index(lookup)]
        
        # interpolation required
        else:

            rgb_tuples = [Color(rgb_tuple_from_str(x)) for x in colors]

            # identify bounding color stop values
            lower = max([stops[0]] + [x for x in stops if x < lookup])
            upper = min([stops[-1]] + [x for x in stops if x > lookup])
            
            # colors from bounding stops
            lower_color = rgb_tuples[stops.index(lower)]
            upper_color = rgb_tuples[stops.index(upper)]
            
            # generate color scale for mapping lookup value to interpolated color
            scale = Scale(Color(lower_color), Color(upper_color))

            # compute linear "relative distance" from lower bound color to upper bound color
            distance = (lookup - lower) / (upper - lower)

            # return string representing rgb color value
            return scale(distance).to_string().replace(', ', ',')

    # default color value catch-all
    return default_color
531476
def _get_color_list():
    """"""
    if 'axes.prop_cycle' in plt.rcParams:
        return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])]
    else:
        return plt.rcParams['axes.color_cycle']
1257200
def displayformat(codes=[], fg=None, bg=None):
        """"""
        if isinstance(codes, basestring):
            codes = [codes]
        else:
            codes = list(codes)
        for code in codes:
            if code not in Magic.DISPLAY.keys():
                raise ValueError("'%s' not a valid display value" % code)
        for color in (fg, bg):
            if color != None:
                if color not in Magic.COLORS.keys():
                    raise ValueError("'%s' not a valid color" % color)
        return [codes, fg, bg]
21676
def to_rio(self):
        
        self.colors = (((self.colors * 1.0 - self.colors.min()) /
                        (self.colors.max() - self.colors.min())) * 255)
        return dict(zip(self.values, tuple(map(tuple, self.colors))))
1263000
def build_colormap(palette, dtype, info):
        """"""
        from trollimage.colormap import Colormap
        sqpalette = np.asanyarray(palette).squeeze() / 255.0
        if hasattr(palette, 'attrs') and 'palette_meanings' in palette.attrs:
            meanings = palette.attrs['palette_meanings']
            iterator = zip(meanings, sqpalette)
        else:
            iterator = enumerate(sqpalette[:-1])

        if dtype == np.dtype('uint8'):
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

        elif 'valid_range' in info:
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

            sf = info.get('scale_factor', np.array(1))
            colormap.set_range(
                *info['valid_range'] * sf + info.get('add_offset', 0))

        return colormap, sqpalette
726292
def _SetColour(self, value_list):
        """"""
        if value_list is None:
            self._color = None
            return
        colors = []
        for color in value_list:
            if color in terminal.SGR:
                colors.append(color)
            elif color in terminal.FG_COLOR_WORDS:
                colors += terminal.FG_COLOR_WORDS[color]
            elif color in terminal.BG_COLOR_WORDS:
                colors += terminal.BG_COLOR_WORDS[color]
            else:
                raise ValueError("Invalid colour specification.")
        self._color = list(set(colors))
474884
function colorLines(name, str) {
  return str
    .split('\n')
    .map(function(str) {
      return color(name, str);
    })
    .join('\n');
}
1245683
def from_rgb(r, g=None, b=None):
    
    c = r if isinstance(r, list) else [r, g, b]
    best = {}

    for index, item in enumerate(colors):
        d = __distance(item, c)
        if(not best or d <= best['distance']):
            best = {'distance': d, 'index': index}

    if 'index' in best:
        return best['index']
    else:
        return 1