<commit_before>from __future__ import division
import colorsys
from itertools import cycle

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

from .external import husl
from .external.six import string_types
from .external.six.moves import range

from .utils import desaturate, set_hls_values
from .xkcd_rgb import xkcd_rgb
from .crayons import crayons
from .miscplot import palplot


SEABORN_PALETTES = dict(
    deep=["#4C72B0", "#55A868", "#C44E52",
          "#8172B2", "#CCB974", "#64B5CD"],
    muted=["#4878CF", "#6ACC65", "#D65F5F",
           "#B47CC7", "#C4AD66", "#77BEDB"],
    pastel=["#92C6FF", "#97F0AA", "#FF9F9A",
            "#D0BBFF", "#FFFEA3", "#B0E0E6"],
    bright=["#003FFF", "#03ED3A", "#E8000B",
            "#8A2BE2", "#FFC400", "#00D7FF"],
    dark=["#001C7F", "#017517", "#8C0900",
          "#7600A1", "#B8860B", "#006374"],
    colorblind=["#0072B2", "#009E73", "#D55E00",
                "#CC79A7", "#F0E442", "#56B4E9"]
    )


class _ColorPalette(list):
    """Set the color palette in a with statement, otherwise be a list."""
    def __enter__(self):
        """Open the context."""
        from .rcmod import set_palette
        self._orig_palette = color_palette()
        set_palette(self)
        return self

    def __exit__(self, *args):
        """Close the context."""
        from .rcmod import set_palette
        set_palette(self._orig_palette)

    def as_hex(self):
        """Return a color palette with hex codes instead of RGB values."""
        hex = [mpl.colors.rgb2hex(rgb) for rgb in self]
        return _ColorPalette(hex)


def color_palette(palette=None, n_colors=None, desat=None):
    """Return a list of colors defining a color palette.

    Availible seaborn palette names:
        deep, muted, bright, pastel, dark, colorblind

    Other options:
        hls, husl, any named matplotlib palette, list of colors

    Calling this function with ``palette=None`` will return the current
    matplotlib color cycle.

    Matplotlib paletes can be specified as reversed palettes by appending
    "_r" to the name or as dark palettes by appending "_d" to the name.
    (These options are mutually exclusive, but the resulting list of colors
    can also be reversed).

    This function can also be used in a ``with`` statement to temporarily
    set the color cycle for a plot or set of plots.

    Parameters
    ----------
    palette: None, string, or sequence, optional
        Name of palette or None to return current palette. If a sequence, input
        colors are used but possibly cycled and desaturated.
    n_colors : int, optional
        Number of colors in the palette. If ``None``, the default will depend
        on how ``palette`` is specified. Named palettes default to 6 colors,
        but grabbing the current palette or passing in a list of colors will
        not change the number of colors unless this is specified. Asking for
        more colors than exist in the palette will cause it to cycle.
    desat : float, optional
        Proportion to desaturate each color by.

    Returns
    -------
    palette : list of RGB tuples.
        Color palette. Behaves like a list, but can be used as a context
        manager and posses an ``as_hex`` method to convert to hex color codes.

    See Also
    --------
    set_palette : Set the default color cycle for all plots.
    set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to
                      colors from one of the seaborn palettes.

    Examples
    --------

    Show one of the "seaborn palettes", which have the same basic order of hues
    as the default matplotlib color cycle but more attractive colors.

    .. plot::
        :context: close-figs

        >>> import seaborn as sns; sns.set()
        >>> sns.palplot(sns.color_palette("muted"))

    Use discrete values from one of the built-in matplotlib colormaps.

    .. plot::
        :context: close-figs

        >>> sns.palplot(sns.color_palette("RdBu", n_colors=7))

    Make a "dark" matplotlib sequential palette variant. (This can be good
    when coloring multiple lines or points that correspond to an ordered
    variable, where you don't want the lightest lines to be invisible).

    .. plot::
        :context: close-figs

        >>> sns.palplot(sns.color_palette("Blues_d"))

    Use a categorical matplotlib palette, add some desaturation. (This can be
    good when making plots with large patches, which look best with dimmer
    colors).

    .. plot::
        :context: close-figs

        >>> sns.palplot(sns.color_palette("Set1", n_colors=8, desat=.5))

    Use as a context manager:

    .. plot::
        :context: close-figs

        >>> import numpy as np, matplotlib.pyplot as plt
        >>> with sns.color_palette("husl", 8):
        ...    _ = plt.plot(np.c_[np.zeros(8), np.arange(8)].T)

    Convert to hex representation:

    .. plot::
        :context: close-figs

        >>> pal = sns.color_palette("muted", 3)
        >>> pal.as_hex()
        [u'#4878cf', u'#6acc65', u'#d65f5f', u'#b47cc7']

    """
    if palette is None:
        palette = mpl.rcParams["axes.color_cycle"]
        if n_colors is None:
            n_colors = len(palette)

    elif not isinstance(palette, string_types):
        palette = palette
        if n_colors is None:
            n_colors = len(palette)
    else:<commit_msg>Fix as_hex doctest<commit_after>from __future__ import division
import colorsys
from itertools import cycle

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

from .external import husl
from .external.six import string_types
from .external.six.moves import range

from .utils import desaturate, set_hls_values
from .xkcd_rgb import xkcd_rgb
from .crayons import crayons
from .miscplot import palplot


SEABORN_PALETTES = dict(
    deep=["#4C72B0", "#55A868", "#C44E52",
          "#8172B2", "#CCB974", "#64B5CD"],
    muted=["#4878CF", "#6ACC65", "#D65F5F",
           "#B47CC7", "#C4AD66", "#77BEDB"],
    pastel=["#92C6FF", "#97F0AA", "#FF9F9A",
            "#D0BBFF", "#FFFEA3", "#B0E0E6"],
    bright=["#003FFF", "#03ED3A", "#E8000B",
            "#8A2BE2", "#FFC400", "#00D7FF"],
    dark=["#001C7F", "#017517", "#8C0900",
          "#7600A1", "#B8860B", "#006374"],
    colorblind=["#0072B2", "#009E73", "#D55E00",
                "#CC79A7", "#F0E442", "#56B4E9"]
    )


class _ColorPalette(list):
    """Set the color palette in a with statement, otherwise be a list."""
    def __enter__(self):
        """Open the context."""
        from .rcmod import set_palette
        self._orig_palette = color_palette()
        set_palette(self)
        return self

    def __exit__(self, *args):
        """Close the context."""
        from .rcmod import set_palette
        set_palette(self._orig_palette)

    def as_hex(self):
        """Return a color palette with hex codes instead of RGB values."""
        hex = [mpl.colors.rgb2hex(rgb) for rgb in self]
        return _ColorPalette(hex)


def color_palette(palette=None, n_colors=None, desat=None):
    """Return a list of colors defining a color palette.

    Availible seaborn palette names:
        deep, muted, bright, pastel, dark, colorblind

    Other options:
        hls, husl, any named matplotlib palette, list of colors

    Calling this function with ``palette=None`` will return the current
    matplotlib color cycle.

    Matplotlib paletes can be specified as reversed palettes by appending
    "_r" to the name or as dark palettes by appending "_d" to the name.
    (These options are mutually exclusive, but the resulting list of colors
    can also be reversed).

    This function can also be used in a ``with`` statement to temporarily
    set the color cycle for a plot or set of plots.

    Parameters
    ----------
    palette: None, string, or sequence, optional
        Name of palette or None to return current palette. If a sequence, input
        colors are used but possibly cycled and desaturated.
    n_colors : int, optional
        Number of colors in the palette. If ``None``, the default will depend
        on how ``palette`` is specified. Named palettes default to 6 colors,
        but grabbing the current palette or passing in a list of colors will
        not change the number of colors unless this is specified. Asking for
        more colors than exist in the palette will cause it to cycle.
    desat : float, optional
        Proportion to desaturate each color by.

    Returns
    -------
    palette : list of RGB tuples.
        Color palette. Behaves like a list, but can be used as a context
        manager and posses an ``as_hex`` method to convert to hex color codes.

    See Also
    --------
    set_palette : Set the default color cycle for all plots.
    set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to
                      colors from one of the seaborn palettes.

    Examples
    --------

    Show one of the "seaborn palettes", which have the same basic order of hues
    as the default matplotlib color cycle but more attractive colors.

    .. plot::
        :context: close-figs

        >>> import seaborn as sns; sns.set()
        >>> sns.palplot(sns.color_palette("muted"))

    Use discrete values from one of the built-in matplotlib colormaps.

    .. plot::
        :context: close-figs

        >>> sns.palplot(sns.color_palette("RdBu", n_colors=7))

    Make a "dark" matplotlib sequential palette variant. (This can be good
    when coloring multiple lines or points that correspond to an ordered
    variable, where you don't want the lightest lines to be invisible).

    .. plot::
        :context: close-figs

        >>> sns.palplot(sns.color_palette("Blues_d"))

    Use a categorical matplotlib palette, add some desaturation. (This can be
    good when making plots with large patches, which look best with dimmer
    colors).

    .. plot::
        :context: close-figs

        >>> sns.palplot(sns.color_palette("Set1", n_colors=8, desat=.5))

    Use as a context manager:

    .. plot::
        :context: close-figs

        >>> import numpy as np, matplotlib.pyplot as plt
        >>> with sns.color_palette("husl", 8):
        ...    _ = plt.plot(np.c_[np.zeros(8), np.arange(8)].T)

    Convert to hex representation:

    .. plot::
        :context: close-figs

        >>> pal = sns.color_palette("muted", 4)
        >>> pal.as_hex()
        [u'#4878cf', u'#6acc65', u'#d65f5f', u'#b47cc7']

    """
    if palette is None:
        palette = mpl.rcParams["axes.color_cycle"]
        if n_colors is None:
            n_colors = len(palette)

    elif not isinstance(palette, string_types):
        palette = palette
        if n_colors is None:
            n_colors = len(palette)
    else:
{'fraction_non_alphanumeric': 0.10736900064237864, 'fraction_numerical': 0.02789758649169496, 'mean_word_length': 2.646035463365674, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7015887', 'n_tokens_mistral': 3591, 'n_tokens_neox': 3333, 'n_words': 1191}