Strongly inspired from idlelib.ColorDelegator.make_pat
489084
def make_gettext_patterns():
    ""
    kwstr = 'msgid msgstr'
    kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
    fuzzy = any("builtin", [r"#,[^\n]*"])
    links = any("normal", [r"#:[^\n]*"])
    comment = any("comment", [r"#[^\n]*"])
    number = any("number",
                 [r"\b[+-]?[0-9]+[lL]?\b",
                  r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
                  r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
    sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
    dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
    string = any("string", [sqstring, dqstring])
    return "|".join([kw, string, number, fuzzy, links, comment,
                     any("SYNC", [r"\n"])])
332761
def colorize(string, color, *args, **kwargs):
    
    string = string.format(*args, **kwargs)
    return color + string + colorama.Fore.RESET
474884
function colorLines(name, str) {
  return str
    .split('\n')
    .map(function(str) {
      return color(name, str);
    })
    .join('\n');
}
242436
function writePalette() {
    out.writeBytes(colorTab);
    var n = (3 * 256) - colorTab.length;
    for (var i = 0; i < n; i++) out.writeByte(0);
  }
498679
def _coloredhelp(s):
    
    newlines = []
    bigindent = (' ' * 16)
    in_opts = False
    for line in s.split('\n'):
        linestripped = line.strip('\n').strip().strip(':')
        if linestripped == 'Usage':
            # label
            line = line.replace('Usage', str(C('Usage', **ARGS_LABEL)))
        elif linestripped == 'Options':
            line = line.replace('Options', str(C('Options', **ARGS_LABEL)))
            in_opts = True
        elif (':' in line) and (not line.startswith(bigindent)):
            # opt,desc line. colorize it.
            lineparts = line.split(':')
            opt = lineparts[0]
            vals = [lineparts[1]] if len(lineparts) == 2 else lineparts[1:]

            # colorize opt
            if ',' in opt:
                opts = opt.split(',')
            else:
                opts = [opt]
            optstr = ','.join(str(C(o, **ARGS_OPTIONS)) for o in opts)

            # colorize desc
            valstr = ':'.join(str(C(val, **ARGS_DESC)) for val in vals)
            line = ':'.join((optstr, valstr))
        elif in_opts and line.startswith(bigindent):
            # continued desc string..
            # Make any 'Default:Value' parts look the same as the opt,desc.

            line = ':'.join(str(C(s, **ARGS_DESC)) for s in line.split(':'))
        elif (not line.startswith('    ')):
            # header line.
            line = str(C(line, **ARGS_HEADER))
        else:
            # Everything else, usage mainly.
            if SCRIPT:
                line = line.replace(SCRIPT, str(C(SCRIPT, **ARGS_SCRIPT)))

        newlines.append(
            '{}{}'.format(line, C('', style='reset_all'))
        )
    return '\n'.join(newlines)
1195604
def make_pattern( patt, flags=0 ):
    
    # print('input',len(patt))
    patt_letters = utf8.get_letters( patt )
    patt_out = list()
    idx = 0
    # print('output',len(patt_letters))
    patt = [None,None]
    prev = None
    LEN_PATT = len(patt_letters)
    while( idx < LEN_PATT ):
        if utf8.istamil( patt_letters[idx] ) and ( prev == '-' or ((idx+1) < LEN_PATT and patt_letters[idx+1] == u'-') ):
            if (idx+1) < LEN_PATT and patt_letters[idx+1] == u'-':
                patt[0] = patt_letters[idx]
                idx = idx + 2
                prev = "-"
            elif prev == '-':
                patt[1] = patt_letters[idx]
                patt_out.extend( expand_tamil( patt[0], patt[1]) )
                idx = idx + 1
                prev = patt_letters[idx]
            continue
        patt_out.extend( patt_letters[idx] )
        prev = patt_letters[idx]
        idx = idx + 1
    opattern = u"".join( patt_out )
    compile_regexp = re.compile( opattern, flags )        
    return (compile_regexp,opattern)
423577
def led(host, seq, anim, f, d):
    
    at(host, 'LED', seq, [anim, float(f), d])
642209
def nx_ensure_agraph_color(graph):
    
    from plottool import color_funcs
    import plottool as pt
    #import six
    def _fix_agraph_color(data):
        try:
            orig_color = data.get('color', None)
            alpha = data.get('alpha', None)
            color = orig_color
            if color is None and alpha is not None:
                color = [0, 0, 0]
            if color is not None:
                color = pt.ensure_nonhex_color(color)
                #if isinstance(color, np.ndarray):
                #    color = color.tolist()
                color = list(color_funcs.ensure_base255(color))
                if alpha is not None:
                    if len(color) == 3:
                        color += [int(alpha * 255)]
                    else:
                        color[3] = int(alpha * 255)
                color = tuple(color)
                if len(color) == 3:
                    data['color'] = '#%02x%02x%02x' % color
                else:
                    data['color'] = '#%02x%02x%02x%02x' % color
        except Exception as ex:
            import utool as ut
            ut.printex(ex, keys=['color', 'orig_color', 'data'])
            raise

    for node, node_data in graph.nodes(data=True):
        data = node_data
        _fix_agraph_color(data)

    for u, v, edge_data in graph.edges(data=True):
        data = edge_data
        _fix_agraph_color(data)
847583
def make_graph_pydot(self, recs, nodecolor,
                     edgecolor, dpi,
                     draw_parents=True, draw_children=True):
        """"""
        import pydot
        G = pydot.Dot(graph_type='digraph', dpi="{}".format(dpi)) # Directed Graph
        edgeset = set()
        usr_ids = [rec.id for rec in recs]
        for rec in recs:
            if draw_parents:
                edgeset.update(rec.get_all_parent_edges())
            if draw_children:
                edgeset.update(rec.get_all_child_edges())

        lw = self._label_wrap
        rec_id_set = set([rec_id for endpts in edgeset for rec_id in endpts])
        nodes = {str(ID):pydot.Node(
              lw(ID).replace("GO:",""),  # Node name
              shape="box",
              style="rounded, filled",
              # Highlight query terms in plum:
              fillcolor="beige" if ID not in usr_ids else "plum",
              color=nodecolor)
                for ID in rec_id_set}

        # add nodes explicitly via add_node
        for rec_id, node in nodes.items():
            G.add_node(node)

        for src, target in edgeset:
            # default layout in graphviz is top->bottom, so we invert
            # the direction and plot using dir="back"
            G.add_edge(pydot.Edge(nodes[target], nodes[src],
              shape="normal",
              color=edgecolor,
              label="is_a",
              dir="back"))

        return G
593525
def pretty_print(self, obj):
        
        s = repr(obj)
        limit = output_limit()
        if len(s) > limit:
            if self.dom_term:
                s = self.color.py_syntax_highlight(s)
                s = self.dom_term.fold_text_string("", s)
            else:
                s = s[:limit - 3]  # cut before syntax highlighting, to avoid missing color endings
                s = self.color.py_syntax_highlight(s)
                s += "..."
        else:
            s = self.color.py_syntax_highlight(s)
        extra_info = self._pp_extra_info(obj)
        if extra_info != "":
            s += ", " + self.color.py_syntax_highlight(extra_info)
        return s
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)
1274317
def make_comparison_png(self, outpath=None, include_legend=False):
        
        from matplotlib.patches import Patch

        fig, axs = plt.subplots(ncols=2, sharex=True, sharey=True)

        three_color = self.make_three_color()
        axs[0].imshow(three_color)
        axs[0].set_axis_off()

        shape = self.thmap.shape
        axs[1].imshow(self.thmap,
                     origin='lower',
                     interpolation='nearest',
                     cmap=self.config.solar_cmap,
                     vmin=-1, vmax=len(self.config.solar_classes)-1)

        if include_legend:
            legend_elements = [Patch(facecolor=c, label=sc, edgecolor='k')
                               for sc, c in self.config.solar_colors.items()]
            axs[1].legend(handles=legend_elements, fontsize='x-small',
                         bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                         ncol=2, mode="expand", borderaxespad=0.)
        axs[1].set_xlim([0, shape[0]])
        axs[1].set_ylim([0, shape[0]])
        axs[1].set_aspect("equal")
        axs[1].set_axis_off()

        if outpath:
            fig.savefig(outpath, dpi=300,
                        transparent=True,
                        bbox_inches='tight',
                        pad_inches=0.)
            plt.close()
        else:
            plt.show()
391705
def color_interp(data):
    """"""
    from rasterio.enums import ColorInterp as ci
    modes = {'L': [ci.gray],
             'LA': [ci.gray, ci.alpha],
             'YCbCr': [ci.Y, ci.Cb, ci.Cr],
             'YCbCrA': [ci.Y, ci.Cb, ci.Cr, ci.alpha]}

    try:
        mode = ''.join(data['bands'].values)
        return modes[mode]
    except KeyError:
        colors = {'R': ci.red,
                  'G': ci.green,
                  'B': ci.blue,
                  'A': ci.alpha,
                  'C': ci.cyan,
                  'M': ci.magenta,
                  'Y': ci.yellow,
                  'H': ci.hue,
                  'S': ci.saturation,
                  'L': ci.lightness,
                  'K': ci.black,
                  }
        return [colors[band] for band in data['bands'].values]
1152415
def color_string(color, string):
    
    if not color_available:
        return string

    return color + string + colorama.Fore.RESET
136329
def make_colormap(seq):
    
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)
1332751
function (data, colorFunc, state) {
        var gradientPixels = this._gradientPixels;
        var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
        var color = [0, 0, 0, 0];
        var off = 0;
        for (var i = 0; i < 256; i++) {
            colorFunc[state](i / 255, true, color);
            pixelsSingleState[off++] = color[0];
            pixelsSingleState[off++] = color[1];
            pixelsSingleState[off++] = color[2];
            pixelsSingleState[off++] = color[3];
        }
        return pixelsSingleState;
    }
895396
def colorize?
      AwesomePrintLite.force_colors ||= false
      AwesomePrintLite.force_colors || (STDOUT.tty? && ((ENV['TERM'] && ENV['TERM'] != 'dumb') || ENV['ANSICON']))
    end