text:
"""
Specialized distribution constructors.

"""

from __future__ import division

import numpy as np
from six.moves import map, range, zip # pylint: disable=redefined-builtin

from itertools import product
from collections import defaultdict

from random import randint

from .distribution import BaseDistribution
from .exceptions import ditException
from .helpers import parse_rvs
from .npdist import Distribution
from .npscalardist import ScalarDistribution
from .utils import digits, powerset
from .validate import validate_pmf

__all__ = [
    'mixture_distribution',
    'mixture_distribution2',
    'noisy',
    'erasure',
    'modify_outcomes',
    'random_scalar_distribution',
    'random_distribution',
    'simplex_grid',
    'uniform_distribution',
    'uniform_scalar_distribution',
    'insert_rvf',
    'RVFunctions',
    'product_distribution',
    'uniform',
    'uniform_like',
    'all_dist_structures',
    'random_dist_structure',
]

def mixture_distribution(dists, weights, merge=False):
    """
    Create a mixture distribution: $\sum p_i d_i$

    Parameters
    ----------
    dists: [Distribution]
        List of distributions to mix.  Each distribution is assumed to have
        the same base and sample space.

    weights: [float]
        List of weights to use while mixing `dists`.  The weights are assumed
        to be probability represented in the base of the distributions.

    merge: bool
        If `True` then distributions will be mixed even if they do not share
        the same sample space. The idea is that each of the input distributions
        is reinterpreted on a common, merged sample space. If `False`, then
        an exception will be raised if incompatible distributions are mixed.

    Returns
    -------
    mix: Distribution
        The mixture distribution.

    Raises
    ------
    DitException
        Raised if there `dists` and `weights` have unequal lengths.
    InvalidNormalization
        Raised if the weights do not sum to unity.
    InvalidProbability
        Raised if the weights are not valid probabilities.
    IncompatibleOutcome
        Raised if the sample spaces for each distribution are not compatible.

    """
    weights = np.asarray(weights)
    if len(dists) != len(weights):
        msg = "Length of `dists` and `weights` must be equal."
        raise ditException(msg)

    ops = dists[0].ops
    validate_pmf(weights, ops)

    if merge:
        vals = lambda o: [(ops.mult(w, d[o]) if o in d else 0)
                          for w, d in zip(weights, dists)]
    else:
        vals = lambda o: [ops.mult(w, d[o])
                          for w, d in zip(weights, dists)]

    outcomes = set().union(*[d.outcomes for d in dists])
    pmf = [ops.add_reduce(np.array(vals(o))) for o in outcomes]
    mix = dists[0].__class__(tuple(outcomes), pmf, base=ops.get_base())
    return mix

def mixture_distribution2(dists, weights):
    """
    Create a mixture distribution: $\sum p_i d_i$

    This version assumes that the pmf for each distribution is of the same
    form, and as a result, will be faster than `mixture_distribution`.
    Explicitly, it assumes that the sample space is ordered exactly the same
    for each distribution and that the outcomes currently represented in the
    pmf are the same as well. Using it in any other case will result in
    incorrect output or an exception.

    Parameters
    ----------
    dists: [Distribution]
        List of distributions to mix.  Each distribution is assumed to have
        the same base and sample space.

    weights: [float]
        List of weights to use while mixing `dists`.  The weights are assumed
        to be probability represented in the base of the distributions.

    Returns
    -------
    mix: Distribution
        The mixture distribution.

    Raises
    ------
    DitException
        Raised if there `dists` and `weights` have unequal lengths.
    InvalidNormalization
        Raised if the weights do not sum to unity.
    InvalidProbability
        Raised if the weights are not valid probabilities.
    IncompatibleDistribution
        Raised if the sample spaces for each distribution are not compatible.

    """
    weights = np.asarray(weights)
    if len(dists) != len(weights):
        msg = "Length of `dists` and `weights` must be equal."
        raise ditException(msg)

    # Also just quickly make sure that the pmfs have the same length. In
    # general, NumPy should give a value error complaining that it cannot
    # broadcast the smaller array. But if a pmf has length 1, then it can
    # be broadcast. This would make it harder to detect errors.
    shapes = set([dist.pmf.shape for dist in dists])
    if len(shapes) != 1:
        raise ValueError('All pmfs must have the same length.')

    ops = dists[0].ops
    validate_pmf(weights, ops)

    mix = dists[0].copy()
    ops.mult_inplace(mix.pmf, weights[0])
    for dist, weight in zip(dists[1:], weights[1:]):
        ops.add_inplace(mix.pmf, ops.mult(dist.pmf, weight))
    return mix

def noisy(dist, noise=1/2):
    """
    Construct a noisy version of `dist`.

    Parameters
    ----------
    dist : Distribution
        The distribution to fuzz.
    noise : float, 0 <= `noise` <= 1
        The noise level.

    Returns
    -------
    fuzzy: Distribution
        The noisy distribution.
    """
    fuzz = uniform(list(product(*dist.alphabet)))
    if isinstance(dist.outcomes[0], str):
        fuzz = modify_outcomes(fuzz, lambda o: ''.join(o))
    fuzzy = mixture_distribution([dist, fuzz], [1-noise, noise], merge=True)
    return fuzzy

def erasure(dist, epsilon=1/2):
    """
    Construct a version of `dist` where each variable has been passed through
    an erasure channel.

    Parameters
    ----------
    dist : Distribution
        The distribution to fuzz.
    epsilon : float, 0 <= `epsilon` <= 1
        The erasure probability.

    Returns
    -------
    erased : Distribution
        The erased distribution.
    """
    ctor = dist._outcome_ctor
    outcomes = defaultdict(float)
    n = dist.outcome_length()

    for outcome, prob in dist.zipped():
        for o in product(*zip(outcome, '_'*n)):
            count = o.count('_')
            outcomes[ctor(o)] += prob * epsilon**count * (1-epsilon)**(n - count)

    return Distribution(outcomes)

def modify_outcomes(dist, ctor):
    """
    Returns `dist` but with modified outcomes, after passing them to `ctor`.

    Parameters
    ----------
    dist : Distribution, ScalarDistribution
        The distribution to be modified.

    ctor : callable
        The constructor that receives an existing outcome and returns a new
        modified outcome.

    Returns
    -------
    d : Distribution, ScalarDistribution
        The modified distribution.

    Examples
    --------
    Convert joint tuple outcomes to strings.
    >>> d = dit.uniform_distribution(3, ['0', '1'])
    >>> d2 = dit.modify_outcomes(d, lambda x: ''.join(x))

    Increment scalar outcomes by 1.
    >>> d = dit.uniform_scalar_distribution(5)
    >>> d2 = dit.modify_outcomes(d, lambda x: x + 1)
    """
    outcomes = tuple(map(ctor, dist.outcomes))
    ops = dist.ops
    newdist = {}
    for outcome, p in zip(outcomes, dist.pmf):
        newdist[outcome] = ops.add(p, newdist.get(outcome, ops.zero))
    outcomes = list(newdist.keys())
    pmf = np.array(list(newdist.values()))
    d = dist.__class__(outcomes, pmf, base=dist.get_base())
    return d

def random_scalar_distribution(n, base=None, alpha=None, prng=None):
    """
    Returns a random scalar distribution over `n` outcomes.

    The distribution is sampled uniformly over the space of distributions on
    the `n`-simplex. If `alpha` is not `None`, then the distribution is
    sampled from the Dirichlet distribution with parameter `alpha`.

    Parameters
    ----------
    n : int | list
        The number of outcomes, or a list containing the outcomes.

    base : float, 'linear', 'e'
        The desired base for the distribution probabilities.

    alpha : list | None
        The concentration parameters defining that the Dirichlet distribution
        used to draw the random distribution. If `None`, then each of the
        concentration parameters are set equal to 1.

    """
    import dit.math

    if prng is None:
        prng = dit.math.prng

    try:
        nOutcomes = len(n)
    except TypeError:
        nOutcomes = n

    d = uniform_scalar_distribution(n)
    if alpha is None:
        alpha = np.ones(len(d))
    elif len(alpha) != nOutcomes:
        raise ditException('Number of concentration parameters must be `n`.')

    pmf = prng.dirichlet(alpha)
    d.pmf = pmf

    # Maybe we should use ditParams['base'] when base is None?
    if base is not None:
        d.set_base(base)

    return d

def random_distribution(outcome_length, alphabet_size, base=None, alpha=None, prng=None):
    """
    Returns a random distribution drawn uniformly from the simplex.

    The distribution is sampled uniformly over the space of distributions on
    the `n`-simplex, where `n` is equal to `alphabet_size**outcome_length`.
    If `alpha` is not `None`, then the distribution is sampled from the
    Dirichlet distribution with parameter `alpha`.

    Parameters
    ----------
    outcome_length : int
        The length of the outcomes.

    alphabet_size : int, list
        The alphabet used to construct the outcomes of the distribution. If an
        integer, then the alphabet will consist of integers from 0 to k-1 where
        k is the alphabet size.  If a list, then the elements are used as the
        alphabet.

    base : float, 'linear', 'e'
        The desired base for the distribution probabilities.

    alpha : list | None
        The concentration parameters defining that the Dirichlet distribution
        used to draw the random distribution. If `None`, then each of the
        concentration parameters are set equal to 1.

    Returns
    -------
    d : Distribution.
        A uniform sampled distribution.

    """
    import dit.math

    if prng is None:
        prng = dit.math.prng

    d = uniform_distribution(outcome_length, alphabet_size)

    if alpha is None:
        alpha = np.ones(len(d))
    elif len(alpha) != len(d):
        raise ditException('Invalid number of concentration parameters.')

    pmf = prng.dirichlet(alpha)
    d.pmf = pmf

    # Maybe we should use ditParams['base'] when base is None?
    if base is not None:
        d.set_base(base)

    return d

def simplex_grid(length, subdivisions, using=None, inplace=False):
    """Returns a generator over distributions, determined by a grid.

    The grid is "triangular" in Euclidean space.

    The total number of points on the grid is::

        (subdivisions + length - 1)! / (subdivisions)! / (length-1)!

    and is equivalent to the total number of ways ``n`` indistinguishable items
    can be placed into ``k`` distinguishable slots, where n=`subdivisions` and
    k=`length`.

    Parameters
    ----------
    length : int
        The number of elements in each distribution. The dimensionality
        of the simplex is length-1.
    subdivisions : int
        The number of subdivisions for the interval [0, 1]. Each component
        will take on values at the boundaries of the subdivisions. For example,
        one subdivision means each component can take the values 0 or 1 only.
        Two subdivisions corresponds to :math:`[[0, 1/2], [1/2, 1]]` and thus,
        each component can take the values 0, 1/2, or 1. A common use case is
        to exponentially increase the number of subdivisions at each level.
        That is, subdivisions would be: 2**0, 2**1, 2**2, 2**3, ...
    using : None, callable, or distribution
        If None, then scalar distributions on integers are yielded. If `using`
        is a distribution, then each yielded distribution is a copy of `using`
        with its pmf set appropriately. For other callables, a tuple of the
        pmf is passed to the callable and then yielded.
    inplace : bool
        If `True`, then each yielded distribution is the same Python object,
        but with a new probability mass function. If `False`, then each yielded
        distribution is a unique Python object and can be safely stored for
        other calculations after the generator has finished. This keyword has
        an effect only when `using` is None or some distribution.

    Examples
    --------
    >>> list(dit.simplex_grid(2, 2, using=tuple))
    [(0.0, 1.0), (0.25, 0.75), (0.5, 0.5), (0.75, 0.25), (1.0, 0.0)]

    """
    from dit.math.combinatorics import slots

    if subdivisions < 1:
        raise ditException('`subdivisions` must be greater than or equal to 1')
    elif length < 1:
        raise ditException('`length` must be greater than or equal to 1')

    gen = slots(int(subdivisions), int(length), normalized=True)

    if using is None:
        using = random_scalar_distribution(length)

    if using is tuple:
        for pmf in gen:
            yield pmf
    elif not isinstance(using, BaseDistribution):
        for pmf in gen:
            yield using(pmf)
    else:
        if length != len(using.pmf):
            raise Exception('`length` must match the length of pmf')

        if inplace:
            d = using
            for pmf in gen:
                d.pmf[:] = pmf
                yield d
        else:
            for pmf in gen:
                d = using.copy()
                d.pmf[:] = pmf
                yield d

def uniform_scalar_distribution(n, base=None):
    """
    Returns a uniform scalar distribution over `n` outcomes.

    Parameters
    ----------
    n : int, list
        If an integer, then the outcomes are integers from 0 to n-1. If a list
        then the elements are treated as the outcomes.

    Returns
    -------
    d : ScalarDistribution
        A uniform scalar distribution.

    """
    try:
        nOutcomes = len(n)
        outcomes = n
    except TypeError:
        nOutcomes = n
        outcomes = tuple(range(n))

    pmf = [1/nOutcomes] * nOutcomes
    d = ScalarDistribution(outcomes, pmf, base='linear')

    # Maybe we should use ditParams['base'] when base is None?
    if base is not None:
        d.set_base(base)

    return d

def uniform_distribution(outcome_length, alphabet_size, base=None):
    """
    Returns a uniform distribution.

    Parameters
    ----------
    outcome_length : int
        The length of the outcomes.

    alphabet_size : int, list of lists
        The alphabets used to construct the outcomes of the distribution. If an
        integer, then the alphabet for each random variable will be the same,
        consisting of integers from 0 to k-1 where k is the alphabet size.
        If a list, then the elements are used as the alphabet for each random
        variable.  If the list has a single element, then it will be used
        as the alphabet for each random variable.

    base : float, 'linear', 'e'
        The desired base for the distribution probabilities.

    Returns
    -------
    d : Distribution.
        A uniform distribution.

    Examples
    --------
    Each random variable has the same standardized alphabet: [0,1]
    >>> d = dit.uniform_distribution(2, 2)

    Each random variable has its own alphabet.
    >>> d = dit.uniform_distribution(2, [[0,1],[1,2]])

    Both random variables have ['H','T'] as an alphabet.
    >>> d = dit.uniform_distribution(2, [['H','T']])

    """
    try:
        int(alphabet_size)
    except TypeError:
        # Assume it is a list of lists.
        alphabet = alphabet_size

        # Autoextend if only one alphabet is provided.
        if len(alphabet) == 1:
            alphabet = [alphabet[0]] * outcome_length
        elif len(alphabet) != outcome_length:
            raise TypeError("outcome_length does not match number of rvs.")
    else:
        # Build the standard alphabet.
        alphabet = [tuple(range(alphabet_size))] * outcome_length

    try:
        Z = np.prod(list(map(len, alphabet)))
        try:
            # for some reason numpypy.prod returns a list, and pypy can't handle
            #   multiplying a list by a numpy float.
            Z = int(Z[0])
        except:
            pass
    except TypeError:
        raise TypeError("alphabet_size must be an int or list of lists.")

    pmf = [1/Z] * Z
    outcomes = tuple(product(*alphabet))
    d = Distribution(outcomes, pmf, base='linear')

    # Maybe we should use ditParams['base'] when base is None?
    if base is not None:
        d.set_base(base)

    return d

def uniform_like(dist):
    """
    Returns a uniform distribution with the same outcome length, alphabet size, and base as `dist`.

    Parameters
    ----------
    dist : Distribution
        The distribution to mimic.
    """
    outcome_length = dist.outcome_length()
    alphabet_size = dist.alphabet
    base = dist.get_base()
    return uniform_distribution(outcome_length, alphabet_size, base)

def uniform(outcomes, base=None):
    """
    Produces a uniform distribution over `outcomes`.

    Parameters
    ----------
    outcomes : iterable
        The set of outcomes with which to construct the distribution.

    base : float, 'linear', 'e'
        The desired base for the distribution probabilities.

    Returns
    -------
    d : Distribution
        A uniform distribution over `outcomes`.

    Raises
    ------
    ditException
        Raised if the elements of `outcomes` do not all have the same length.
    TypeError
        Raised if `outcomes` is not iterable.
    """
    outcomes = list(outcomes)
    length = len(outcomes)
    pmf = [1/length]*length
    d = Distribution(outcomes, pmf)

    # Maybe we should use ditParams['base'] when base is None?
    if base is not None:
        d.set_base(base)

    return d

def insert_rvf(d, func, index=-1):
    """
    Returns a new distribution with an added random variable at index `index`.

    The new random variable must be a function of the other random variables.
    By this, we mean that the entropy of the new random variable conditioned
    on the original random variables should be zero.

    Parameters
    ----------
    dist : Distribution
        The distribution used to construct the new distribution.
    func : callable | list of callable
        A function which takes a single argument---the value of the previous
        random variables---and returns a new random variable. Note, the return
        value will be added to the outcome using `__add__`, and so it should be
        a hashable, orderable sequence (as every outcome must be). If a list of
        callables is provided, then multiple random variables are added
        simultaneously and will appear in the same order as the list.
    index : int
        The index at which to insert the random variable. A value of -1 is
        will append the random variable to the end.

    Returns
    -------
    d : Distribution
        The new distribution.

    Examples
    --------
    >>> d = dit.Distribution(['00', '01', '10', '11'], [1/4]*4)
    >>> def xor(outcome):
    ...    return str(int(outcome[0] != outcome[1]))
    ...
    >>> d2 = dit.insert_rvf(d, xor)
    >>> d.outcomes
    ('000', '011', '101', '110')

    """
    try:
        func[0]
    except TypeError:
        funcs = [func]
    else:
        funcs = func

    partial_outcomes = [map(func, d.outcomes) for func in funcs]

    # Now "flatten" the new contributions.
    partial_outcomes = [d._outcome_ctor([o for o_list in outcome for o in o_list])
                        for outcome in zip(*partial_outcomes)]

    new_outcomes = zip(d.outcomes, partial_outcomes)
    if index == -1:
        outcomes = [old + new for old, new in new_outcomes]
    else:
        outcomes = [old[:index] + new + old[index:] for old, new in new_outcomes]

    d2 = Distribution(outcomes, d.pmf.copy(), base=d.get_base())
    return d2

class RVFunctions(object):
    """
    Helper class for building new random variables.

    Each new random variable is a function of the existing random variables.
    So for each outcome in the original distribution, there can be only one
    possible value for the new random variable.

    Some methods may make assumptions about the sample space. For example, the
    :meth:`xor` method assumes the sample space consists of 0-like and 1-like
    outcomes.

    """
    def __init__(self, d):
        """
        Initialize the random variable function creator.

        Parameters
        ----------
        d : Distribution
            The distribution used to create the new random variables.

        Examples
        --------
        >>> d = dit.Distribution(['00', '01', '10', '11'], [1/4]*4)
        >>> bf = dit.RVFunctions(d)
        >>> d = dit.insert_rvf(d, bf.xor([0,1]))
        >>> d = dit.insert_rvf(d, bf.xor([1,2]))
        >>> d.outcomes
        ('0000', '0110', '1011', '1101')

        """
        if not isinstance(d, Distribution):
            raise ditException('`d` must be a Distribution instance.')
        try:
            d.outcomes[0] + ''
        except TypeError:
            is_int = True
        else:
            is_int = False

        self.is_int = is_int
        self.L = d.outcome_length()
        self.ctor = d._outcome_ctor
        self.outcome_class = d._outcome_class

    def xor(self, indices):
        """
        Returns a callable which returns the logical XOR of the given indices.

        Outcomes are assumed to be strings of '0' and '1', or tuples of 0 and 1.
        The returned function handles both cases appropriately.

        Parameters
        ----------
        indices : list
            A list of two indices used to take the XOR.

        Returns
        -------
        func : function
            A callable implementing the XOR function. It receives a single
            argument, the outcome and returns an outcome for the calculation.

        Examples
        --------
        >>> d = dit.Distribution(['00', '01', '10', '11'], [1/4]*4)
        >>> bf = dit.RVFunctions(d)
        >>> d = dit.insert_rvf(d, bf.xor([0,1]))
        >>> d.outcomes
        ('000', '011', '101', '110')

        """
        if self.is_int:
            def func(outcome):
                result = outcome[indices[0]] != outcome[indices[1]]
                return (int(result),)
        else:
            def func(outcome):
                result = outcome[indices[0]] != outcome[indices[1]]
                return str(int(result))

        return func

    def from_mapping(self, mapping, force=True):
        """
        Returns a callable implementing a random variable via a mapping.

        Parameters
        ----------
        mapping : dict
            A mapping from outcomes to values of the new random variable.

        force : bool
            Ideally, the values of `mapping` should be satisfy the requirements
            of all outcomes (hashable, ordered sequences), but if `force` is
            `True`, we will attempt to use the distribution's outcome
            constructor and make sure that they are. If they are not, then
            the outcomes will be placed into a 1-tuple. This is strictly
            a convenience for users. As an example, suppose the outcomes are
            strings, the values of `mapping` can also be strings without issue.
            However, if the outcomes are tuples of integers, then the values
            *should* also be tuples. When `force` is `True`, then the values
            can be integers and then they will be transformed into 1-tuples.

        Returns
        -------
        func : function
            A callable implementing the desired function. It receives a single
            argument, the outcome, and returns an outcome for the calculation.

        Examples
        --------
        >>> d = dit.Distribution(['00', '01', '10', '11'], [1/4]*4)
        >>> bf = dit.RVFunctions(d)
        >>> mapping = {'00': '0', '01': '1', '10': '1', '11': '0'}
        >>> d = dit.insert_rvf(d, bf.from_mapping(mapping))
        >>> d.outcomes
        ('000', '011', '101', '110')

        Same example as above but now with tuples.

        >>> d = dit.Distribution([(0,0), (0,1), (1,0), (1,1)], [1/4]*4)
        >>> bf = dit.RVFunctions(d)
        >>> mapping = {(0,0): 0, (0,1): 1, (1,0): 1, (1,1): 0}
        >>> d = dit.insert_rvf(d, bf.from_mapping(mapping, force=True))
        >>> d.outcomes
        ((0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0))

        See Also
        --------
        dit.modify_outcomes

        """
        ctor = self.ctor
        if force:
            try:
                list(map(ctor, mapping.values()))
            except (TypeError, ditException):
                values = [ctor([o]) for o in mapping.values()]
                mapping = dict(zip(mapping.keys(), values))

        def func(outcome):
            return mapping[outcome]

        return func

    def from_partition(self, partition):
        """
        Returns a callable implementing a function specified by a partition.

        The partition must divide the sample space of the distribution. The
        number of equivalence classes, n, determines the number of values for
        the random variable. The values are integers from 0 to n-1, but if the
        outcome class of the distribution is string, then this function will
        use the first n letters from:
            '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        as values for the random variable. So random variables with more than
        62 outcomes are not supported by this function.

        Parameters
        ----------
        partition : list
            A list of iterables. The outer list is required to determine the
            order of the new random variable

        Returns
        -------
        func : function
            A callable implementing the desired function. It receives a single
            argument, the outcome, and returns an outcome of the new random
            variable that is specified by the partition.

        Examples
        --------
        >>> d = dit.Distribution(['00', '01', '10', '11'], [1/4]*4)
        >>> bf = dit.RVFunctions(d)
        >>> partition = (('00','11'), ('01', '10'))
        >>> d = dit.insert_rvf(d, bf.from_partition(partition))
        >>> d.outcomes
        ('000', '011', '101', '110')

        """
        # Practically, we support the str class. This is bytes in Python
        # versions <3 and unicode >3.
        alphabet = '0123456789'
        letters = 'abcdefghijklmnopqrstuvwxyz'
        alphabet += letters
        alphabet += letters.upper()

        n = len(partition)
        if self.outcome_class == str:
            if n > len(alphabet):
                msg = 'Number of outcomes is too large.'
                raise NotImplementedError(msg)
            vals = alphabet[:n]
        else:
            vals = range(n)

        mapping = {}
        # Probably could do this more efficiently.
        for i, eqclass in enumerate(partition):
            for outcome in eqclass:
                mapping[self.ctor(outcome)] = vals[i]

        return self.from_mapping(mapping, force=True)

    def from_hexes(self, hexes):
        """
        Returns a callable implementing a boolean function on up to 4-bits.

        Outcomes are assumed to be strings of '0' and '1', or tuples of 0 and 1.
        The returned function handles both cases appropriately.

        The original outcomes are represented in base-16 as one of the letters
        in '0123456789ABCDEF' (not case sensitive). Then, each boolean function
        is a specification of the outcomes for which it be should true. The
        random variable will be false for the complement of this set---so this
        function additional assumes full support. For example, if the random
        variable is a function of 3-bits and should be true only for the
        outcomes 2='010' or 7='111', then `hexes` should be '27'. This nicely
        handles 1- and 2-, and 4-bit inputs in a similar fashion.

        Parameters
        ----------
        hexes : str
            A string of base-16 characters, each element represents an
            (up to) 4-bit outcome for which the random variable should be true.

        Returns
        -------
        func : function
            A callable implementing the desired function. It receives a single
            argument, the outcome, and returns an outcome for the calculation.

        Examples
        --------
        >>> outcomes = ['000', '001', '010', '011', '100', '101', '110', '111']
        >>> pmf = [1/8] * 8
        >>> d = dit.Distribution(outcomes, pmf)
        >>> bf = dit.RVFunctions(d)
        >>> d = dit.insert_rvf(d, bf.from_hexes('27'))
        >>> d.outcomes
        ('0000', '0010', '0101', '0110', '1000', '1010', '1100', '1111')

        """
        base = 16
        template = "{0:0{1}b}"
        outcomes = [template.format(int(h, base), self.L) for h in hexes]
        if self.is_int:
            outcomes = [tuple(map(int, o)) for o in outcomes]
        outcomes = set(outcomes)

        if self.is_int:
            def func(outcome):
                result = outcome in outcomes
                return (int(result),)
        else:
            def func(outcome):
                result = outcome in outcomes
                return str(int(result))
        return func

def product_distribution(dist, rvs=None, rv_mode=None, base=None):
    """
    Returns a new distribution which is the product of marginals.

    Parameters
    ----------
    dist : distribution
        The original distribution.

    rvs : sequence
        A sequence whose elements are also sequences.  Each inner sequence
        defines the marginal distribution used to create the new distribution.
        The inner sequences must be pairwise mutually exclusive, but not every
        random variable in the original distribution must be specified. If
        `None`, then a product distribution of one-way marginals is
        constructed.

    rv_mode : str, None
        Specifies how to interpret the elements of `rvs`. Valid options
        are: {'indices', 'names'}. If equal to 'indices', then the elements
        of `rvs` are interpreted as random variable indices. If equal to
        'names', the the elements are interpreted as random variable names.
        If `None`, then the value of `dist._rv_mode` is consulted.

    base : float, 'linear', 'e'
        The desired base for the distribution probabilities.

    Returns
    -------
    d : Distribution
        The product distribution.

    Examples
    --------
    >>> d = dit.example_dists.Xor()
    >>> pd = product_distribution(d, [(0,), (1,), (2,)])

    """
    if not dist.is_joint():
        raise Exception("A joint distribution is required.")

    if rvs is None:
        names = dist.get_rv_names()
        if names is None:
            names = range(dist.outcome_length())

        indexes = [[i] for i in names]

    else:
        # We do not allow repeats and want to keep the order.
        # Use argument [1] since we don't need the names.
        parse = lambda rv: parse_rvs(dist, rv, rv_mode=rv_mode,
                                     unique=True, sort=False)[1]
        indexes = [parse(rv) for rv in rvs]

    all_indexes = [idx for index_list in indexes for idx in index_list]
    if len(all_indexes) != len(set(all_indexes)):
        raise Exception('The elements of `rvs` have nonzero intersection.')

    marginals = [dist.marginal(index_list, rv_mode=rv_mode) for index_list in indexes]
    ctor = dist._outcome_ctor
    ops = dist.ops

    outcomes = []
    pmf = []
    for pairs in product(*[marg.zipped() for marg in marginals]):
        outcome = []
        prob = []
        for pair in pairs:
            outcome.extend(pair[0])
            prob.append(pair[1])
        outcomes.append(ctor(outcome))
        pmf.append(ops.mult_reduce(prob))

    d = Distribution(outcomes, pmf, validate=False)

    # Maybe we should use ditParams['base'] when base is None?
    if base is not None:
        d.set_base(base)

    return d

def all_dist_structures(outcome_length, alphabet_size):
    """
    Return an iterator of distributions over the
    2**(`alphabet_size`**`outcome_length`) possible combinations of joint
    events.

    Parameters
    ----------
    outcome_length : int
        The length of outcomes to consider.
    alphabet_length : int
        The size of the alphabet for each random variable.

    Yields
    ------
    d : Distribution
        A uniform distribution over a subset of the possible joint events.
    """
    alphabet = ''.join(str(i) for i in range(alphabet_size))
    words = product(alphabet, repeat=outcome_length)
    topologies = powerset(words)
    next(topologies) # the first element is the null set
    for t in topologies:
        outcomes = [''.join(_) for _ in t]
        yield uniform(outcomes)

def _int_to_dist(number, outcome_length, alphabet_size):
    """
    Construct the `number`th distribution over `outcome_length` variables each
    with an alphabet of size `alphabet_size`.

    Parameters
    ----------
    number : int
        The index of the distribution to construct.
    outcome_length : int
        The number of random variables in each joint event.
    alphabet_size : int
        The size of the alphabet for each random variable.

    Returns
    -------
    d : Distribution
        A uniform distribution over the joint event specified by the parameters.
    """
    alphabet = ''.join(str(i) for i in range(alphabet_size))
    words = [''.join(word) for word in product(alphabet, repeat=outcome_length)]
    events = digits(number, 2, pad=alphabet_size**outcome_length, big_endian=False)
    pmf = [p/sum(events) for p in events]
    return Distribution(words, pmf)

def random_dist_structure(outcome_length, alphabet_size):
    """
    Return a uniform distribution over a random subset of the
    `alphabet_size`**`outcome_length` possible joint events.

    Parameters
    ----------
    outcome_length : int
        The number of random variables in each joint event.
    alphabet_size : int
        The size of the alphabet for each random variable.

    Returns
    -------
    d : Distribution
        A uniform distribution over a random subset of joint events.
    """
    bound = 2**(alphabet_size**outcome_length)
    return _int_to_dist(randint(1, bound-1), outcome_length, alphabet_size)

def _combine_scalar_dists(d1, d2, op):
    """
    Combines `d1` and `d2` according to `op`, as though they are independent.

    Parameters
    ----------
    d1 : ScalarDistribution
        The first distribution
    d2 : ScalarDistribution
        The second distribution
    op : function
        Function used to combine outcomes

    Returns
    -------
    d : ScalarDistribution
        The two distributions combined via `op`
    """
    # Copy to make sure we don't lose precision when converting.
    d2 = d2.copy(base=d1.get_base())

    dist = defaultdict(float)
    for (o1, p1), (o2, p2) in product(d1.zipped(), d2.zipped()):
        dist[op(o1, o2)] += d1.ops.mult(p1, p2)

    return ScalarDistribution(*zip(*dist.items()), base=d1.get_base())


text:
<?php

namespace SumoCoders\FrameworkCoreBundle\BreadCrumb;

use Knp\Menu\FactoryInterface;
use Knp\Menu\MenuItem;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use SumoCoders\FrameworkCoreBundle\Event\ConfigureMenuEvent;

final class BreadCrumbBuilder
{
    /**
     * @var bool
     */
    private $extractFromRoute = true;

    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @var FactoryInterface
     */
    private $factory;

    /**
     * @var array
     */
    private $items = [];

    /**
     * @param FactoryInterface         $factory
     * @param EventDispatcherInterface $eventDispatcher
     */
    public function __construct(FactoryInterface $factory, EventDispatcherInterface $eventDispatcher)
    {
        $this->factory = $factory;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * @param RequestStack $requestStack
     * @return \Knp\Menu\ItemInterface
     */
    public function createBreadCrumb(RequestStack $requestStack)
    {
        $this->extractItemsBasedOnTheRequest($requestStack);

        $menu = $this->factory->createItem('root');
        $menu->setChildrenAttribute('class', 'breadcrumb');

        foreach ($this->items as $i => $item) {
            // the last item shouldn't have a link
            if ((count($this->items) - 1) == $i) {
                $item->setUri(null);
            }

            $menu->addChild($item);
        }

        return $menu;
    }

    /**
     * @return BreadCrumbBuilder
     */
    public function dontExtractFromTheRequest()
    {
        $this->extractFromRoute = false;

        return $this;
    }

    /**
     * Extract the items for the breadcrumb based on a uri
     *
     * @param string $uri
     * @param string $locale
     * @return BreadCrumbBuilder
     */
    public function extractItemsBasedOnUri($uri, $locale)
    {
        $this->dontExtractFromTheRequest();

        $item = $this->findItemBasedOnUri(
            $this->getTheMenu(),
            $uri
        );

        if ($item !== null) {
            $this->addItemsBasedOnTheChild($item, $locale);
        }

        return $this;
    }

    /**
     * Add an item into the breadcrumb
     *
     * @param MenuItem $item
     * @return BreadCrumbBuilder
     */
    public function addItem(MenuItem $item)
    {
        $this->items[] = $item;

        return $this;
    }

    /**
     * Add a item into the breadcrumb by passing the label and an optional URI.
     *
     * @param string $label
     * @param string $uri
     * @return BreadCrumbBuilder
     */
    public function addSimpleItem($label, $uri = null)
    {
        $item = new MenuItem($label, $this->factory);
        $item->setLabel($label);
        if ($uri !== null) {
            $item->setUri($uri);
        }

        $this->items[] = $item;

        return $this;
    }

    /**
     * Reset the items and add the given items all at once
     *
     * @param array $items
     * @return BreadCrumbBuilder
     */
    public function overwriteItems(array $items)
    {
        $this->items = $items;

        return $this;
    }

    /**
     * Add items into the breadcrumb based on a given child.
     *
     * @param MenuItem $item
     * @param string   $locale
     */
    private function addItemsBasedOnTheChild(MenuItem $item, $locale)
    {
        if ($item !== null) {
            $items = [];
            $temporaryItem = $item;

            while ($temporaryItem->getParent() !== null) {
                $breadCrumb = new MenuItem($temporaryItem->getName(), $this->factory);
                $breadCrumb->setLabel($temporaryItem->getLabel());

                if ($temporaryItem->getUri() !== '#' && $temporaryItem->getUri() !== null) {
                    $breadCrumb->setUri($temporaryItem->getUri());
                }
                $items[] = $breadCrumb;

                $temporaryItem = $temporaryItem->getParent();
            }

            $home = new MenuItem('core.menu.home', $this->factory);
            $home->setLabel('core.menu.home');
            $home->setUri('/' . $locale);
            $this->items[] = $home;

            $this->items = array_merge($this->items, array_reverse($items));
        }
    }

    /**
     * Grab the menu
     *
     * This method will use the ConfigureMenuEvent to get all the items
     *
     * @return \Knp\Menu\ItemInterface
     */
    private function getTheMenu()
    {
        $menu = $this->factory->createItem('root');

        $this->eventDispatcher->dispatch(
            ConfigureMenuEvent::EVENT_NAME,
            new ConfigureMenuEvent(
                $this->factory,
                $menu
            )
        );

        return $menu;
    }

    /**
     * Find an item in the menu based on its URI
     *
     * @param MenuItem $menuItem
     * @param          $uri
     * @return MenuItem|null
     */
    private function findItemBasedOnUri(MenuItem $menuItem, $uri)
    {
        if ($uri === $menuItem->getUri()) {
            return $menuItem;
        }

        if (!$menuItem->hasChildren()) {
            return null;
        }

        foreach ($menuItem->getChildren() as $child) {
            $item = $this->findItemBasedOnUri(
                $child,
                $uri
            );

            if ($item !== null) {
                return $item;
            }
        }

        return null;
    }

    /**
     * Extract the items for the breadcrumb based on request
     *
     * @param RequestStack $requestStack
     */
    private function extractItemsBasedOnTheRequest(RequestStack $requestStack)
    {
        if (!$this->extractFromRoute) {
            return;
        }

        $this->extractItemsBasedOnUri(
            $requestStack->getCurrentRequest()->getPathInfo(),
            $requestStack->getCurrentRequest()->getLocale()
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intive.intivemvpframework.navigation;

import com.intive.intivemvpframework.view.activity.UserDetailsActivity;
import com.intive.intivemvpframework.view.activity.UserListActivity;

import android.content.Context;
import android.content.Intent;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Class used to navigate through the application.
 */
@Singleton
public class Navigator {

    @Inject
    public Navigator() {
        //empty
    }

    /**
     * Goes to the user list screen.
     *
     * @param context A Context needed to open the destiny activity.
     */
    public void navigateToUserList(final Context context) {
        if (context != null) {
            Intent intentToLaunch = UserListActivity.getCallingIntent(context);
            context.startActivity(intentToLaunch);
        }
    }

    /**
     * Goes to the user details screen.
     *
     * @param context A Context needed to open the destiny activity.
     */
    public void navigateToUserDetails(final Context context, final int userId) {
        if (context != null) {
            Intent intentToLaunch = UserDetailsActivity.getCallingIntent(context, userId);
            context.startActivity(intentToLaunch);
        }
    }
}


text:
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace Jellyfish.Configuration.Sample
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMiddleware<PropertiesMiddleware>();
        }
	}
}


text:
```
# Build a new image from the source path
$ docker build .
Sending build context to Docker daemon 686.1 kB
Sending build context to Docker daemon
Step 0 : FROM nginx
 ---> f1c42afeb4a4
Step 1 : COPY . /usr/share/nginx/html
 ---> Using cache
 ---> b8c178b653b9
Successfully built b8c178b653b9
```

## A Dockerfile
```
FROM        ubuntu:14.04
MAINTAINER  Matthias Luebken <matthias@giantswarm.io>

# To manually trigger cache invalidation
ENV build_date 2014-09-01

RUN apt-get update
RUN apt-get install -y nginx

RUN echo 'Hello world' > /usr/share/nginx/html/index.html

EXPOSE 80

CMD ["/usr/sbin/nginx", "-g", "daemon off;"]
```

## Dockerfile instructions 1

* `FROM` the parent image
* `MAINTAINER` the maintainer of this Dockerfile (optional)
* `RUN <command>` run the command during build time with '/bin/sh -c'
* `EXPOSE <port>` expose a specific port on the container
* `ADD <files>` add files from the build environment into the image with tar extraction
* `ENV <variable>` set environment variables
* `CMD ["<command>", "<arg 1>", "<arg 2>"]` run the commands when container is launched. Can be overwritten via the command line

## Dockerfile instructions 2

* `WORKDIR <dir>` set the working directory for `RUN` and `CMD/ENTRYPOINT`
* `USER <user>` specifies the USER
* `VOLUME ["<dir>"]` adds a volume to a container
* `ONBUILD <build instruction>` execute the instruction when child image is
* `ENTRYPOINT ["<command>", "<arg 1>", "<arg 2>"]` run the commands when container is launched. Command line args will be passed on.

## Excercise 4

1. Build a plain nginx image with a new Dockerfile

   Check with localhost:8000
2. Add a custom index.html
3. Check nginx configuration during build time

   `nginx -t`
4. Ensure that your build breaks with a broken config
5. Add custom logging

```
# /etc/nginx/conf.d/logging.conf
    access_log /run/nginx/access.log;
    error_log /run/nginx/error.log;
```


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lachnea scutellata f. depauperata F.H. Møller

### Remarks
null


text:
using Microsoft.Extensions.Logging;
using System;
// ReSharper disable InconsistentNaming

namespace TWCore.Web.Logger
{
    /// <inheritdoc />
    /// <summary>
    /// Logger for TWCore Log
    /// </summary>
    [IgnoreStackFrameLog]
    public class TWCoreLogger : ILogger
    {
        private readonly string _name;

        #region .ctor
        /// <summary>
        /// Logger for TWCore Log
        /// </summary>
        /// <param name="name">Category Name</param>
        public TWCoreLogger(string name)
        {
            _name = name;
        }
        #endregion

        #region ILogger
        /// <inheritdoc />
        /// <summary>
        /// Begins a logical operation scope.
        /// </summary>
        /// <param name="state">The identifier for the scope.</param>
        /// <returns>An IDisposable that ends the logical operation scope on dispose.</returns>
        public IDisposable BeginScope<TState>(TState state) => null;
        /// <inheritdoc />
        /// <summary>
        /// Checks if the given logLevel is enabled.
        /// </summary>
        /// <param name="logLevel">level to be checked.</param>
        /// <returns>true if enabled.</returns>
        public bool IsEnabled(LogLevel logLevel) => true;
        /// <inheritdoc />
        /// <summary>
        /// Writes a log entry.
        /// </summary>
        /// <param name="logLevel">Entry will be written on this level.</param>
        /// <param name="eventId">Id of the event.</param>
        /// <param name="state">The entry to be written. Can be also an object.</param>
        /// <param name="exception">The exception related to this entry.</param>
        /// <param name="formatter">Function to create a string message of the state and exception.</param>
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (_name.IndexOf("WebHost", StringComparison.OrdinalIgnoreCase) == -1 && logLevel == LogLevel.Information) return;

            Diagnostics.Log.LogLevel cLogLevel;
            switch (logLevel)
            {
                case LogLevel.Critical:
                    cLogLevel = Diagnostics.Log.LogLevel.Error;
                    break;
                case LogLevel.Debug:
                    cLogLevel = Diagnostics.Log.LogLevel.Debug;
                    break;
                case LogLevel.Error:
                    cLogLevel = Diagnostics.Log.LogLevel.Error;
                    break;
                case LogLevel.Information:
                    cLogLevel = Diagnostics.Log.LogLevel.InfoMedium;
                    break;
                case LogLevel.Trace:
                    cLogLevel = Diagnostics.Log.LogLevel.InfoDetail;
                    break;
                case LogLevel.Warning:
                    cLogLevel = Diagnostics.Log.LogLevel.Warning;
                    break;
                case LogLevel.None:
                    return;
                default:
                    cLogLevel = Diagnostics.Log.LogLevel.Verbose;
                    break;
            }

            var type = _name ?? string.Empty;
            var dotIdx = type.LastIndexOf(".", StringComparison.Ordinal);
            if (dotIdx > -1)
                type = type.Substring(dotIdx + 1);

            Core.Log.Write(cLogLevel, eventId.Id.ToString(), formatter(state, exception), "AspNetCore", exception, string.Empty, type);
        }
        #endregion
    }
}


text:
<?php

namespace arc;

class hash {

	public static function get( $path, $hash ) {
		return \arc\path::reduce( $path, function( $result, $item ) {
			$item = rawurldecode($item);
			if ( is_array( $result ) && array_key_exists( $item, $result ) ) {
				return $result[$item];
			}
		}, $hash );
	}

	public static function exists( $path, $hash ) {
		$parent = \arc\path::parent($path);
		$filename = rawurldecode(basename( $path ));
		$hash = self::get( $parent, $hash );
		return ( is_array($hash) && array_key_exists( $filename, $hash ) );
	}

	public static function parseName( $name ) {
		// parse name[index][index2] to /name/index/index2/
		$elements = explode( '[', $name );
		$path = array();
		foreach( $elements as $element ) {
			if ( $element[ strlen($element)-1 ] === ']' ) {
				$element = substr($element, 0, -1);
			}
			if ( $element[0] === "'" ) {
				$element = substr($element, 1, -1);
			}
			$path[] = rawurlencode($element);
		}
		return '/'.implode( '/', $path ).'/';
	}

	public static function compileName( $path, $root = '' ) {
		// parse /name/index/index2/ to name[index][index2]
		return \arc\path::reduce( $path, function( $result, $item ) {
			$item = rawurldecode($item);
			return ( !$result ? $item : $result . '[' . $item . ']' );
		}, $root );
	}

	public static function tree( $hash, $parent = null ) {
		if ( !isset( $parent ) ) {
			$parent = \arc\tree::expand();
		}
		if ( is_array( $hash ) || $hash instanceof \Traversable ) {
			foreach ( $hash as $index => $value ) {
				$child = $parent->appendChild( $index );
				if ( is_array( $value ) ) {
					self::tree( $value, $child );
				} else {
					$child->nodeValue = $value;
				}
			}
		} else {
			$parent->nodeValue = $hash;
		}
		return $parent;
	}

}


text:
package com.microsoft.bingads.v12.customermanagement;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="ClientLinks" type="{https://bingads.microsoft.com/Customer/v12/Entities}ArrayOfClientLink" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "clientLinks"
})
@XmlRootElement(name = "UpdateClientLinksRequest")
public class UpdateClientLinksRequest {

    @XmlElement(name = "ClientLinks", nillable = true)
    protected ArrayOfClientLink clientLinks;

    /**
     * Gets the value of the clientLinks property.
     *
     * @return
     *     possible object is
     *     {@link ArrayOfClientLink }
     *
     */
    public ArrayOfClientLink getClientLinks() {
        return clientLinks;
    }

    /**
     * Sets the value of the clientLinks property.
     *
     * @param value
     *     allowed object is
     *     {@link ArrayOfClientLink }
     *
     */
    public void setClientLinks(ArrayOfClientLink value) {
        this.clientLinks = value;
    }

}


text:
'use strict';
/*global describe, it, beforeEach */
var assert = require('assert');
var toFile = require('../lib');
var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');

describe('protocol-less bin', function() {
  var html = '';

  beforeEach(function() {
    html = fs.readFileSync(
      path.join(__dirname, 'fixtures', 'protocol.html'),
      'utf8'
    );
  });

  it('should be the same without a protocol', function() {
    var file = toFile({ html: html, javascript: '', css: '' }, { proto: '' });
    assert(file.trim() === html.trim(), 'output is exactly the same');
  });

  it('should insert http', function() {
    var file = toFile(
      { html: html, javascript: '', css: '' },
      { proto: 'http' }
    );

    var $ = cheerio.load(html);
    $('script').each(function() {
      var src = $(this).attr('src');

      if (src.slice(0, 2) === '//') {
        assert(
          file.indexOf('http:' + src) !== -1,
          'relative protocol on ' + src
        );
      }
    });

    assert(file.trim() !== html.trim(), 'output is different');
  });

  it('should insert https', function() {
    var file = toFile(
      { html: html, javascript: '', css: '' },
      { proto: 'https' }
    );

    var $ = cheerio.load(html);
    $('script').each(function() {
      var src = $(this).attr('src');

      if (src.slice(0, 2) === '//') {
        assert(
          file.indexOf('https:' + src) !== -1,
          'relative protocol on ' + src
        );
      }
    });

    assert(file.trim() !== html.trim(), 'output is different');
  });
});


text:
package com.lordjoe.distributed.spark;

//import org.junit.*;
//import scala.collection.*;
//import scala.collection.Seq;
//import scala.collection.immutable.*;
//
///**
// * com.lordjoe.distributed.spark.ScalaAdaptorsTest
// * User: Steve
// * Date: 12/28/2014
// */
//public class ScalaAdaptorsTest {
//
//    public static final int ONE_K = 1024;
//    public static final int ONE_MEG = ONE_K * ONE_K;
//    public static final int ONE_GIG = ONE_K * ONE_MEG;
//
//    public static final int MAX_RANGE = 1 * ONE_MEG;
//    public static final int MAX_STREAM = 1 * ONE_MEG;  // note runs out of memory if 1 gig
//
//    @Test
//    public void testRange() throws Exception {
//        Seq<Object> items = ScalaJavaAdaptors.makeRange(MAX_RANGE);
//        Assert.assertEquals(items.size(),MAX_RANGE);
//        int index = 0;
//        Stream<Object> objectStream = items.toStream();
//        final Iterator<Object> iterator = objectStream.iterator();
//        while ( iterator.hasNext()) {
//           Integer ix = (Integer)iterator.next();
//            Assert.assertEquals(index++,(int)ix);
//        }
//    }
//    @Test
//      public void testStream() throws Exception {
//          Stream<Object> items = ScalaJavaAdaptors.makeStream(MAX_STREAM);
//          Assert.assertEquals(items.size(),MAX_STREAM);
//          int index = 0;
//          final Iterator<Object> iterator = items.iterator();
//          while ( iterator.hasNext()) {
//             Integer ix = (Integer)iterator.next();
//              Assert.assertEquals(index++,(int)ix);
//          }
//      }
//  }


text:
package config

import (
	"fmt"

	"github.com/spf13/cobra"

	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/client-go/tools/clientcmd"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
	cmdutil "k8s.io/kubectl/pkg/cmd/util"
	"k8s.io/kubectl/pkg/util/i18n"
	"k8s.io/kubectl/pkg/util/templates"
)

var (
	deleteUserExample = templates.Examples(`
		# Delete the minikube user
		kubectl config delete-user minikube`)
)

// DeleteUserOptions holds the data needed to run the command
type DeleteUserOptions struct {
	user string

	configAccess clientcmd.ConfigAccess
	config       *clientcmdapi.Config
	configFile   string

	genericclioptions.IOStreams
}

// NewDeleteUserOptions creates the options for the command
func NewDeleteUserOptions(ioStreams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *DeleteUserOptions {
	return &DeleteUserOptions{
		configAccess: configAccess,
		IOStreams:    ioStreams,
	}
}

// NewCmdConfigDeleteUser returns a Command instance for 'config delete-user' sub command
func NewCmdConfigDeleteUser(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command {
	o := NewDeleteUserOptions(streams, configAccess)

	cmd := &cobra.Command{
		Use:                   "delete-user NAME",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Delete the specified user from the kubeconfig"),
		Long:                  i18n.T("Delete the specified user from the kubeconfig."),
		Example:               deleteUserExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(cmd, args))
			cmdutil.CheckErr(o.Validate())
			cmdutil.CheckErr(o.Run())
		},
	}

	return cmd
}

// Complete sets up the command to run
func (o *DeleteUserOptions) Complete(cmd *cobra.Command, args []string) error {
	config, err := o.configAccess.GetStartingConfig()
	if err != nil {
		return err
	}
	o.config = config

	if len(args) != 1 {
		return cmdutil.UsageErrorf(cmd, "user to delete is required")
	}
	o.user = args[0]

	configFile := o.configAccess.GetDefaultFilename()
	if o.configAccess.IsExplicitFile() {
		configFile = o.configAccess.GetExplicitFile()
	}
	o.configFile = configFile

	return nil
}

// Validate ensures the command has enough info to run
func (o *DeleteUserOptions) Validate() error {
	_, ok := o.config.AuthInfos[o.user]
	if !ok {
		return fmt.Errorf("cannot delete user %s, not in %s", o.user, o.configFile)
	}

	return nil
}

// Run performs the command
func (o *DeleteUserOptions) Run() error {
	delete(o.config.AuthInfos, o.user)

	if err := clientcmd.ModifyConfig(o.configAccess, *o.config, true); err != nil {
		return err
	}

	fmt.Fprintf(o.Out, "deleted user %s from %s\n", o.user, o.configFile)

	return nil
}


text:
import type { SegmentData } from '../core';
import { getMultiValue } from '../core';
import { SvgPath } from '../svg';

export interface NoneInterpolationOptions {
  fillHoles?: boolean;
}

/**
 * This interpolation function does not smooth the path and the result is only containing lines and no curves.
 *
 * @example
 * ```ts
 * const chart = new LineChart('.ct-chart', {
 *   labels: [1, 2, 3, 4, 5],
 *   series: [[1, 2, 8, 1, 7]]
 * }, {
 *   lineSmooth: Interpolation.none({
 *     fillHoles: false
 *   })
 * });
 * ```
 */
export function none(options?: NoneInterpolationOptions) {
  const finalOptions = {
    fillHoles: false,
    ...options
  };

  return function noneInterpolation(
    pathCoordinates: number[],
    valueData: SegmentData[]
  ) {
    const path = new SvgPath();
    let hole = true;

    for (let i = 0; i < pathCoordinates.length; i += 2) {
      const currX = pathCoordinates[i];
      const currY = pathCoordinates[i + 1];
      const currData = valueData[i / 2];

      if (getMultiValue(currData.value) !== undefined) {
        if (hole) {
          path.move(currX, currY, false, currData);
        } else {
          path.line(currX, currY, false, currData);
        }

        hole = false;
      } else if (!finalOptions.fillHoles) {
        hole = true;
      }
    }

    return path;
  };
}


text:
/*!
---
name: Enlighter Settings Page
description: ThemeCustomizer setup
authors:
  - Andi Dittrich

requires:
  - jQuery
...
*/
(function(themeData){
	// fetch console object
	var c = window.console || {};

	// initialize
	jQuery(document).ready(function(){
		// show developer message
		if (c.info){
			c.info('You like to look under the hood? Enlighter is OpenSource, you are welcome to contribute! https://github.com/AndiDittrich/WordPress.Enlighter');
		}

		// initialize tooltipps
		// jQuery(document).tooltip();

		// hide update message
		// --------------------------------------------------------
		var msg = jQuery('#setting-error-settings_updated');
		if (msg){
			msg.delay(1500).fadeOut(500);
		}

		// Tabs/Sections
		// --------------------------------------------------------
		// try to restore last tab
		var lastActiveTab = jQuery.cookie('enlighter-tab');

		// container actions
		var currentTab = (lastActiveTab ? jQuery("#EnlighterTabNav a[data-tab='" + lastActiveTab + "']") : jQuery('#EnlighterTabNav a:first-child'));
		jQuery('#EnlighterTabNav a').each(function(){
			// get current element
			var el = jQuery(this);

			// hide content container
			jQuery('#' + el.attr('data-tab')).hide();

			// click event
			el.click(function(){
				// remove highlight
				currentTab.removeClass('nav-tab-active');

				// hide container
				jQuery('#' + currentTab.attr('data-tab')).hide();

				// store current active tab
				currentTab = el;
				currentTab.addClass('nav-tab-active');

				// show container
				jQuery('#' + currentTab.attr('data-tab')).show();

				// store current tab as cookie - 1 day lifetime
				jQuery.cookie('enlighter-tab', currentTab.attr('data-tab'), { expires: 1 });
			});
		});

		// show first container
		currentTab.click();

		// show navbar
		jQuery('#EnlighterTabNav').show();

		// Live Preview Mode
		// --------------------------------------------------------
		var previewWindow = null;
		jQuery('#enlighter_themePreviewMode').click(function(){
			// window active ?
			if (previewWindow && !previewWindow.closed){
				previewWindow.focus();

			// create new window
			}else{
				// get url
				var u = jQuery(this).attr('data-url');

				// create a new window
				previewWindow = window.open(u, null, "width=800, height=800");
			}
		});

		// live preview update
		window.setInterval(function(){
			// window available and loaded?
			if (!previewWindow || previewWindow.closed || !previewWindow.window.ThemePreview){
				return;
			}

			// fetch data
			var rawData = jQuery('#EnlighterSettings input, #EnlighterSettings select').serializeArray();
			var data = {};

			// convert to object
			jQuery.each(rawData, function(i, el){
				// enlighetr settings ?
				var n = (el.name.substring(0, 10) == 'enlighter-') ? el.name.substring(10) : el.name;

				data[n] = el.value;
			});

			// push settings to preview engine
			previewWindow.window.ThemePreview.update(data);

		}, 800);

		// Color Selection
		// --------------------------------------------------------
		// colorpicker
		jQuery('.EnlighterJSColorChooser').ColorPicker({
			onSubmit : function(hsb, hex, rgb, el){
				jQuery(el).val('#' + hex);
				jQuery(el).css('background-color', '#' + hex);
				jQuery(el).ColorPickerHide();
			},
			onBeforeShow : function(){
				jQuery(this).ColorPickerSetColor(this.value);
			}
		});
		// initialize colors
		jQuery('.EnlighterJSColorChooser').each(function(){
			// get element color value
			var color = jQuery(this).val();

			// color available ?
			if (color.length > 0){
				jQuery(this).css('background-color', color);
			}
		});

		// advanced color settings
		jQuery('#enlighter-defaultTheme').change(function(){
			var value = jQuery('#enlighter-defaultTheme').val();

			// display section only in custom mode !
			if (value == 'wpcustom'){
				jQuery('#EnlighterTabhandleThemeCustomizer').show();
			}else{
				jQuery('#EnlighterTabhandleThemeCustomizer').hide();
			}
		}).change();

		/**
		 * THEME CUSTOMIZER
		 */

		jQuery('#enlighter_loadBasicTheme').click(function(){
			// get selected theme
			var theme = jQuery('#enlighter-customThemeBase').val().trim().toLowerCase();

			// theme data avialable ?
			if (!themeData[theme]){
				return;
			}

			// set font styles
			jQuery('#enlighter-customFontFamily').val(themeData[theme].basestyle['font-family']);
			jQuery('#enlighter-customFontSize').val(themeData[theme].basestyle['font-size']);
			jQuery('#enlighter-customLineHeight').val(themeData[theme].linestyle['line-height']);
			setElementColor('#enlighter-customFontColor', themeData[theme].basestyle['color']);

			// set line-number styles
			jQuery('#enlighter-customLinenumberFontFamily').val(themeData[theme].linestyle['font-family']);
			jQuery('#enlighter-customLinenumberFontSize').val(themeData[theme].linestyle['font-size']);
			setElementColor('#enlighter-customLinenumberFontColor', themeData[theme].linestyle['color']);

			// set raw font styles
			jQuery('#enlighter-customRawFontFamily').val(themeData[theme].rawstyle['font-family']);
			jQuery('#enlighter-customRawFontSize').val(themeData[theme].rawstyle['font-size']);
			jQuery('#enlighter-customRawLineHeight').val(themeData[theme].rawstyle['line-height']);
			setElementColor('#enlighter-customRawFontColor', themeData[theme].rawstyle['color']);
			setElementColor('#enlighter-customRawBackgroundColor', themeData[theme].rawstyle['background-color']);

			// set special styles
			jQuery('#enlighter-customLineHighlightColor').val(themeData[theme].special.highlightColor);
			setElementColor('#enlighter-customLineHighlightColor', themeData[theme].special.highlightColor);
			jQuery('#enlighter-customLineHoverColor').val(themeData[theme].special.hoverColor);
			setElementColor('#enlighter-customLineHoverColor', themeData[theme].special.hoverColor);

			// set token styles
			// format: foreground color, background color, text-decoration, font-weight, font-style
			jQuery.each(themeData[theme].tokens, function(key, value){
				// foreground color
				setElementColor('#enlighter-custom-color-' + key, value[0]);

				// background color
				setElementColor('#enlighter-custom-bgcolor-' + key, value[1]);

				// text decoration
				jQuery('#enlighter-custom-decoration-' + key).val((value[2] ? value[2] : 'normal'));

				// change dropdown selection if value is set
				if (value[3] && value[4]){
					jQuery('#enlighter-custom-fontstyle-' + key).val('bolditalic');
				}else if (value[3]){
					jQuery('#enlighter-custom-fontstyle-' + key).val('bold');
				}else if (value[4]){
					jQuery('#enlighter-custom-fontstyle-' + key).val('italic');
				}else{
					jQuery('#enlighter-custom-fontstyle-' + key).val('normal');
				}
			});
		});
	});

	// set element color
	var setElementColor = (function(id, value){
		// value available ?
		if (value){
			jQuery(id).val(value);
			jQuery(id).css('background-color', value);
		}else{
			jQuery(id).val('');
			jQuery(id).css('background-color', 'transparent');
		}
	});
})(Enlighter_ThemeStyles);


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>NBMRoomClientConnectionState Constants Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				KurentoToolbox

				Nubomedia TI

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

</select>

NBMRoomClientConnectionState Constants Reference

	Declared in
	NBMRoomClient.h

NBMRoomClientConnectionState

Definition

                        typedef NS_ENUM(NSInteger, NBMRoomClientConnectionState ) {

                               NBMRoomClientConnectionStateOpening,

                               NBMRoomClientConnectionStateOpen,

                               NBMRoomClientConnectionStateClosing,

                               NBMRoomClientConnectionStateClosed,

                            };

Constants

NBMRoomClientConnectionStateOpening

		Declared In NBMRoomClient.h.

NBMRoomClientConnectionStateOpen

		Declared In NBMRoomClient.h.

NBMRoomClientConnectionStateClosing

		Declared In NBMRoomClient.h.

NBMRoomClientConnectionStateClosed

		Declared In NBMRoomClient.h.

Copyright © 2016 Nubomedia TI. All rights reserved. Updated: 2016-02-18

Generated by appledoc 2.2.1 (build 1334).


text:
import React from 'react'

import Loss from './Loss'

import Layout from '../../components/Layout'

const props = {
  title: 'Resourceful Response To Loss',
  description:
    'Proven protocol to experience a more peacful, resourceful response to loss',
  path: '/loss',
}

async function action() {
  return {
    chunks: ['loss'],
    ...props,
    component: (
      <Layout path={props.path}>
        <Loss sections={sections()} {...props} />
      </Layout>
    ),
  }
}

export default action

function sections() {
  return [
    {
      title: 'The protocol',
      url: 'protocol',
      description:
        'The steps to experience a more resourceful response to loss',
    },
    {
      title: 'Softening shock response',
      url: 'shock-response',
      description:
        "In addition to the loss, there's often a shock response to the moment of death itself",
    },
    {
      title: 'Regret, guilt, anger & blame',
      url: 'releasing-mixed-feelings',
      description:
        'In case of "unresolved issues" with the loss, we attend to those first',
    },
    {
      title: 'Types of loss',
      url: 'types',
      description:
        'Commonalities and differences of differnet type of loss, and how we attend to each',
    },
    {
      title: 'Common loss pitfalls',
      url: 'common-pitfalls',
      description:
        'Since no one "taught" us how to grieve in a healthy way, we are apt to get "stuck" in unuseful patterns',
    },
    {
      title: 'Resourceful response to loss',
      url: 'resourceful-response',
      description:
        '"They could speak about the lost person with softness, caring and happiness. One woman said, "When I think of Joe, it's as if he is right here with me."',
    },
    {
      title: 'FAQ',
      url: 'faq',
      description:
        'Some questions many share about experiencing loss in a more resourceful way',
    },
    {
      title: 'Get started',
      url: 'participate',
      description:
        "When you are ready to start, we'll schedule a session and explore how you can make use of the protocol",
    },
  ]
}


text:
[![Build Status](https://travis-ci.org/wastaz/Hyperboliq.svg?branch=master)](https://travis-ci.org/wastaz/Hyperboliq)

Hyperboliq is a .NET based ORM with the following main goals

1. **Predictability**
    It should be possible to intuit what SQL statements is going to be generated by your code. No magic allowed.
2. **Control**
    Hyperboliq will by design not contain any magic or attempt to second-guess you by performing clever query rewrites behind your back.
    What you see is what you get. No magic allowed.
3. **Expressability**
    Hyperboliq will aim to support as much of the SQL standard as possible (within reason).

# Building Hyperboliq

Hyperboliq targets the .NET framework version 4.5.1 and F# 4.3.1.
Currently there are no plans to support older versions, though this may change.
Apart from this, Hyperboliq does not require anything special to build. Simply restore nuget packages and build the solution with Visual Studio.

# License
Hyperboliq is distributed under the terms of the Apache License v.2.

# Current state of Hyperboliq
Hyperboliq is still considered to be in pre-alpha and can still change drastically from one day to another.
The API is to be considered unstable and you are not recommended to use this in production yet.
Suffice to say **you should probably wait for the first official release if you want to use this library**.

# Getting Started
For now, if you wish to use Hyperboliq you will need to download and build it manually.
When Hyperboliq has reached a state that is stable there will be nuget packages.
Do be aware of the fact that Hyperboliq is currently in a pre-alpha state and as thus may still have breaking API changes etc.

## Selecting data
Hyperboliq aims to use POCOs for accessing data in order to be able to provide as much intellisense/type safety as possible.
Hyperboliq will always generate table aliases for all tables in your query.
You can provide your own aliases if necessary, though as long as you are not referencing the same table more than once in your query you should not have to do this.

### Basic selects

```csharp
Select<Person>(p => p.Name).From<Person>().Where<Person>(p => p.Age > 42)
```

```sql
SELECT PersonRef.Name
FROM Person PersonRef
WHERE PersonRef.Age > 42
```

### Basic joins

```csharp
Select.Star<Person>().Star<Car>().From<Person>().InnerJoin<Person, Car>((p, c) => c.DriverId == p.Id)
```

```sql
SELECT PersonRef.*, CarRef.*
FROM Person PersonRef
INNER JOIN Car CarRef ON CarRef.DriverId = PersonRef.Id
```

### Self-joins
```csharp
var child = Table<Person>.WithReferenceName("child");
var parent = Table<Person>.WithReferenceName("parent");
Select.Column(child, p => p.Name).Column(parent, p => p.Name).From(child).InnerJoin(child, parent, (c, p) => c.ParentId == p.Id)
```

```sql
SELECT child.Name, parent.Name
FROM Person child
INNER JOIN Person parent ON child.ParentId = parent.Id
```

### Windowing functions with OVER/PARTITION BY/ORDER BY
```csharp
Select.Column<Person>(p => p.Name)
      .Column<Person>(
          p => Sql.Sum(p.Age),
          Over.PartitionBy<Person>(p => p.Name).OrderBy<Person>(p => p.Age, Direction.Ascending))
      .From<Person>();
```

```sql
SELECT PersonRef.Name, SUM(PersonRef.Age) OVER (PARTITION BY PersonRef.Name ORDER BY PersonRef.Age ASC)
FROM Person PersonRef
```

### Subquery support
Hyperboliq allows you to create queries that contain subqueries. However due to the nature of C#'s type system these kind of queries are not as type safe. This may let you write queries that translate into SQL that your database will not accept (and thus throw a `SQLException` during runtime). If you use subqueries, be extra careful to match the correct types, number of expected results and number of columns to avoid these exceptions during runtime.

#### Subqueries returning a single value
```csharp
// In this case we need to use the utility method Sql.SubExpr<T> in order to help the C# Type system.
Select.Star<Person>()
      .From<Person>()
      .Where<Person>(p => p.Age > Sql.SubExpr<int>(Select.Column<Car>(c => c.Age)
                                                         .From<Car>()
                                                         .Where<Car>(c => c.Id == 42)));
```

```sql
SELECT PersonRef.* FROM Person PersonRef WHERE PersonRef.Age > (SELECT CarRef.Age FROM Car CarRef WHERE CarRef.Id = 42)
```

#### Subqueries with IN
```csharp
// In the case of subqueries with IN we do not need to use the Sql.SubExpr<T> utility method and can just write the subquery inline.
Select.Star<Person>()
      .From<Person>()
      .Where<Person>(p => Sql.In(p.Id, Select.Column<Car>(c => c.DriverId).From<Car>()));
```

```sql
SELECT PersonRef.* FROM Person PersonRef WHERE PersonRef.Id IN (SELECT CarRef.DriverId FROM Car CarRef)
```

### Common Table Expression support
Hyperboliq lets you use common table expressions in your select queries.
These do however require an extra class in order to specify how the result set for this CTE looks.

#### Simple example

```csharp
// Class for specifying how the result set of our CTE looks
public class PersonLite
{
    public string Name { get; set; }
    public int Age { get; set; }
}

With.Table<PersonLite>(
    Select.Column<Person>(p => new { p.Name, p.Age })
          .From<Person>()
          .Where<Person>(p => p.Age > 15))
    .Query(
        Select.Column<PersonLite>(p => p.Name)
              .From<PersonLite>()
              .Where<PersonLite>(p => p.Age == 42));
```

```sql
WITH PersonLite AS (SELECT PersonRef.Name, PersonRef.Age FROM Person PersonRef WHERE PersonRef.Age > 15)
SELECT PersonLiteRef.Name FROM PersonLite PersonLiteRef WHERE PersonLiteRef.Age = 42
```

#### Multiple CTE's with the same result set

```csharp
// This example uses the same PersonLite class as the example above

// Define two aliases for the same result set in order to be able to refer to them separately
var oldies = Table<PersonLite>.WithTableAlias("Oldies");
var younglings = Table<PersonLite>.WithTableAlias("YoungOnes");

With.Table(
        oldies,
        Select.Column<Person>(p => new { p.Name, p.Age, })
              .From<Person>()
              .Where<Person>(p => p.Age > 40))
    .Table(
        younglings,
        Select.Column<Person>(p => new { p.Name, p.Age, })
              .From<Person>()
              .Where<Person>(p => p.Age <= 15))
    .Query(
        Select.Column(oldies, p => p.Name)
              .Column(younglings, p => p.Name)
              .From(oldies)
              .InnerJoin(oldies, younglings, (old, young) => old.Age - 30 == young.Age));
```

```sql
WITH Oldies AS (SELECT PersonRef.Name, PersonRef.Age FROM Person PersonRef WHERE PersonRef.Age > 40),
     YoungOnes AS (SELECT PersonRef.Name, PersonRef.Age FROM Person PersonRef WHERE PersonRef.Age <= 15)
SELECT OldiesRef.Name, YoungOnesRef.Name FROM Oldies OldiesRef INNER JOIN YoungOnes YoungOnesRef ON OldiesRef.Age - 30 = YoungOnesRef.Age
```

### Basic deletes
```csharp
Delete.From<Person>().Where<Person>(p => p.Age > 42)
```

```sql
DELETE FROM Person PersonRef WHERE PersonRef.Age > 42
```

### Basic inserts
Hyperboliq lets you perform basic inserts both specifying the columns to use, and just specifying a generic "all columns" selector as seen in these examples

```csharp
var val = new Person { Id = 2, Name = "Kalle", Age = 42, LivesAtHouseId = 5, ParentId = 0 };
Insert.Into<Person>().Columns(p => new { p.Name, p.Age }).Value(val);
```

```sql
INSERT INTO Person (Name, Age) VALUES ('Kalle', 42)
```

```csharp
var val = new Person { Id = 2, Name = "Kalle", Age = 42, LivesAtHouseId = 5, ParentId = 0 };
Insert.Into<Person>().AllColumns.Value(val);
// If you use the AllColumns selector all columns will be used and will be added in alphabetical order
```

```sql
INSERT INTO Person (Age, Id, LivesAtHouseId, Name, ParentId) VALUES (42, 2, 5, 'Kalle', 0)
```

```csharp
// It is also possible to perform multi-value inserts using Hyperboliq
var val1 = new Person { Id = 2, Name = "Kalle", Age = 42, LivesAtHouseId = 5, ParentId = 0 };
var val2 = new Person { Id = 3, Name = "Pelle", Age = 12, LivesAtHouseId = 3, ParentId = 2 };
Insert.Into<Person>()
      .AllColumns
      .Values(val1, val2);
```

```sql
INSERT INTO Person (Age, Id, LivesAtHouseId, Name, ParentId) VALUES (42, 2, 5, 'Kalle', 0), (12, 3, 3, 'Pelle', 2)
```

### Basic updates
Hyperboliq aims to allow you to create UPDATE statements that lets you update data without first selecting it (as is necessary in many other ORMs).

#### Updating to a certain static value
```csharp
Update<Person>.Set(p => new { p.Name, p.Age },
                   new { Name = "Kalle", Age = 42})
              .Where(p => p.Id == 5);
```

```sql
UPDATE Person SET Age = 42, Name = 'Kalle' WHERE Id = 5
```

#### Updating "in place"
```csharp
Update<Person>.Set(p => p.Age, p => p.Age + 1).Where(p => p.Name == "Kalle");
```

```sql
UPDATE Person SET Age = Age + 1 WHERE Name = 'Kalle'
```

#### Updating with subqueries
```csharp
Update<Person>.Set(p => p.Age, Select.Column<Car>(c => Sql.Max(c.Age)).From<Car>()).Where(p => p.Name == "Kalle");
```

```sql
    UPDATE Person SET Age = (SELECT MAX(CarRef.Age) FROM Car CarRef) WHERE Name = 'Kalle'
```

# Further documentation

Further documentation will be available on the github wiki pages as the API stabilizes.

Hyperboliq also maintains a large battery of unit tests testing query generation in different ways.
Until the API stabilizes enough to write decent docs, you are encouraged to look at the unit tests to see different ways to use Hyperboliq.

# Versioning

Hyperboliq aims to use semantic versioning.

# Features that will not be implemented

* Support for Linq queries.


text:
<?php

namespace Scribe\Teavee\HtmlGeneratorBundle\Manager;

use Scribe\Teavee\ObjectCacheBundle\Component\Manager\CacheManagerInterface;

/**
 * Interface ManagerInterface.
 */
interface ManagerInterface
{
    /**
     * @var string
     */
    const ERR_ST_EXC = 'throw_exception';

    /**
     * @var string
     */
    const ERR_ST_NULL = 'null_return';

    /**
     * @var string
     */
    const ERR_ST_BOOL = 'boolean_return';

    /**
     * @param mixed   $subject
     * @param mixed[] $ops
     *
     * @return string|null|false
     */
    public function render($subject, array $ops = []);

    /**
     * @return bool
     */
    public function isLastResponseFromCache();

    /**
     * @param \Twig_Environment $environment
     *
     * @return $this
     */
    public function registerTwigEnvironment(\Twig_Environment $environment);

    /**
     * @param CacheManagerInterface|null $manager
     * @param bool|false                 $enabled
     * @param int                        $ttl
     *
     * @return $this
     */
    public function registerCacheManager(CacheManagerInterface $manager = null, $enabled = false, $ttl = 0);

    /**
     * @param string|null $strategy
     *
     * @return $this
     */
    public function registerErrorStrategy($strategy = null);
}

/* EOF */


text:
package host

import (
	"crypto/tls"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"

	"github.com/kataras/iris/core/netutil"
)

func singleJoiningSlash(a, b string) string {
	aslash := strings.HasSuffix(a, "/")
	bslash := strings.HasPrefix(b, "/")
	switch {
	case aslash && bslash:
		return a + b[1:]
	case !aslash && !bslash:
		return a + "/" + b
	}
	return a + b
}

// ProxyHandler returns a new ReverseProxy that rewrites
// URLs to the scheme, host, and base path provided in target. If the
// target's path is "/base" and the incoming request was for "/dir",
// the target request will be for /base/dir.
//
// Relative to httputil.NewSingleHostReverseProxy with some additions.
func ProxyHandler(target *url.URL) *httputil.ReverseProxy {
	targetQuery := target.RawQuery
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.Host = target.Host
		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
		if targetQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = targetQuery + req.URL.RawQuery
		} else {
			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
		}

		if _, ok := req.Header["User-Agent"]; !ok {
			// explicitly disable User-Agent so it's not set to default value
			req.Header.Set("User-Agent", "")
		}
	}
	p := &httputil.ReverseProxy{Director: director}

	if netutil.IsLoopbackHost(target.Host) {
		transport := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		p.Transport = transport
	}

	return p
}

// NewProxy returns a new host (server supervisor) which
// redirects all requests to the target.
// It uses the httputil.NewSingleHostReverseProxy.
//
// Usage:
// target, _ := url.Parse("https://mydomain.com")
// proxy := NewProxy("mydomain.com:80", target)
// proxy.ListenAndServe() // use of proxy.Shutdown to close the proxy server.
func NewProxy(hostAddr string, target *url.URL) *Supervisor {
	proxyHandler := ProxyHandler(target)
	proxy := New(&http.Server{
		Addr:    hostAddr,
		Handler: proxyHandler,
	})

	return proxy
}


text:
import { Component, OnInit, Input, trigger, state, style, transition, animate } from '@angular/core';

import { MdDialog, MdDialogRef, MdSnackBar } from '@angular/material';
import { OverlayContainer } from '@angular/material';
import { Response } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { GiphyService } from '../../services/giphy/giphy.service';
@Component({
  selector: 'app-flashcard',
  templateUrl: 'flashcard.component.html',
  styleUrls: ['flashcard.component.css'],
  animations: [
    trigger('flipState', [
      state('active', style({
        transform: 'rotateY(179.9deg)'
      })),
      state('inactive', style({
        transform: 'rotateY(0)'
      })),
      transition('active => inactive', animate('500ms ease-out')),
      transition('inactive => active', animate('500ms ease-in'))
    ])
  ]
})
export class FlashcardComponent implements OnInit {
  @Input() flashcard;
  flip: string = 'inactive';

  giphies = [];
  selectedGif: any;
  constructor(
    private db: AngularFireDatabase,
    private route: ActivatedRoute,
    private router: Router,
    private giphyService: GiphyService
  ) {
  }
  toggleFlip() {
    this.flip = (this.flip == 'inactive') ? 'active' : 'inactive';
  }

  ngOnInit() {
    // this.performTranslationSearch();
    this.giphyService.performTranslationSearch(this.flashcard)
      .subscribe((res: Response) => {
        var giphies = res.json().data;
        this.selectedGif = giphies[Math.floor(Math.random() * giphies.length)];

      });
  }
}


text:
=head1 Name

OpenXPKI::Server::Notification::SMTP - Notification via SMTP

=head1 Description

Base class for all notifications handlers.

=cut

package OpenXPKI::Server::Notification::Base;

use strict;
use warnings;
use English;

use DateTime;
use OpenXPKI::Server::Context qw( CTX );
use OpenXPKI::Exception;
use OpenXPKI::Debug;
use OpenXPKI::FileUtils;
use OpenXPKI::Serialization::Simple;

use Moose;

# Attribute Setup

# The path-string for calling the connector
has 'config' => (
    is  => 'rw',
    isa => 'Str',
);

=head1 Functions

=head2 notify({ MESSAGE, VARS, TOKEN })

Public method to be called to send out a notification.
must be implemented in the parent class, expects
the name of the message and a hashref to the template vars.
TOKEN is optional and exchanges persisted information for this
handler with the workflow.
If the method returns a non-empty value, it is persisted back
into the workflow.

=cut
sub notify {

    OpenXPKI::Exception->throw({
        MESSAGE => 'I18N_OPENXPKI_SERVER_NOTIFICATION_BASE_NOTIFY_UNIMPLEMENTED',
        log => {
            logger   => CTX('log'),
            priority => 'error',
            facility => 'system',
        },
    });

}

=head2 _render_template_file( FILENAME, VARS )

Read template form filename and render using TT.
Expects full path to the template and hashref to the vars.
returns the template with vars inserted as string.

=cut
sub _render_template_file {

    ##! 4: 'start'
    my $self = shift;
    my $filename = shift;
    my $vars = shift;

    ##! 16: 'Load template: ' . $filename
    if (! -e $filename  ) {
        CTX('log')->log(
            MESSAGE  => "Template file missing $filename  ",
            PRIORITY => "error",
            FACILITY => "system",
        );
        return undef;
    }

    my $template = OpenXPKI::FileUtils->read_file( $filename );
    # Parse using TT
    my $output;

    my $tt = Template->new();
    if (!$tt->process(\$template, $vars, \$output)) {
        CTX('log')->log(
            MESSAGE  => "Error parsing templatefile ($filename): " . $tt->error(),
            PRIORITY => "error",
            FACILITY => "system",
        );
        return;
    }

    return $output;

}

=head2 _render_template ( TEMPLATE, VARS )

Render a template using TT.
Expects template string and hashref to the vars.
returns the template with vars inserted as string.

=cut
sub _render_template {

    ##! 4: 'start'
    my $self = shift;
    my $template = shift;
    my $vars = shift;

    # Parse using TT
    my $output;

    my $tt = Template->new();
    if (!$tt->process(\$template, $vars, \$output)) {
        CTX('log')->log(
            MESSAGE  => "Error parsing template ($template): " . $tt->error(),
            PRIORITY => "error",
            FACILITY => "system",
        );
        return;
    }

    return $output;

}

1;

__END__


text:
<?php

$includePath = dirname(dirname(dirname(__FILE__)));
set_include_path(get_include_path() . PATH_SEPARATOR . $includePath);

require_once 'spoon/spoon.php';
require_once 'PHPUnit/Framework/TestCase.php';

class SpoonTest extends PHPUnit_Framework_TestCase
{
	public function testGet()
	{
		$value = 'Speed spelled backwards is deeps.';
		$this->assertEquals(Spoon::set('stored_value', $value), $value);
		$this->assertEquals(Spoon::get('stored_value'), $value);
	}

	/**
	 * @expectedException SpoonException
	 */
	public function testGetFailure()
	{
		$this->assertEquals('I have no idea what I am doing.', Spoon::get('my_custom_value'));
	}

	public function testExists()
	{
		// set value
		Spoon::set('spoon', new stdClass());

		// check value
		$this->assertTrue(Spoon::exists('spoon'));
		$this->assertFalse(spoon::exists('foobar'));
	}

	public function testSet()
	{
		// set value
		$value = array('Davy Hellemans', 'Tijs Verkoyen', 'Dave Lens', 'Matthias Mullie');
		$this->assertEquals(Spoon::set('salad_fingers', $value), $value);

		// get rid of value
		Spoon::set('salad_fingers');
		$this->assertFalse(Spoon::exists('salad_fingers'));
	}
}


text:
using infrastructure.user.models;

namespace infrastructure.user.interfaces
{
    public interface ISocialLoginService
    {
        UserIdentity loginOrSignup(string nameIdentifier, string email, string firstname, string lastname, string provider, int currentLoginId);
        UsernameToken getTokenByUserId(int userid);
    }
}


text:
mkdir -p pack/mine/start pack/mine/opt pack/others/start pack/others/opt .sessions .swap

cd pack/mine/start/
git clone https://github.com/manasthakur/vim-commentor.git
git clone -b jumpers https://github.com/manasthakur/vim-minisnip.git

cd ../opt/
git clone https://github.com/manasthakur/vim-asyncmake.git

cd ../../others/start/
git clone https://github.com/tpope/vim-surround.git
git clone https://github.com/tpope/vim-fugitive.git

cd ../opt/
git clone https://github.com/majutsushi/tagbar
git clone https://github.com/romainl/vim-qf

cd ~
ln -s ~/.vim/vimrc .vimrc


text:
package it.randomtower.graphgametemplate.entities;

import it.marteEngine.entity.Entity;
import it.randomtower.graphgametemplate.model.Edge;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

public class EdgeEntity extends Entity {

	private Edge edge;

	public EdgeEntity(Edge edge) {
		super(0, 0);
		this.edge = edge;
	}

	@Override
	public void render(GameContainer container, Graphics g) throws SlickException {
		int m = NodeEntity.NODE_SIZE / 2;
		g.drawLine(edge.getStart().getX() + m, edge.getStart().getY() + m, edge.getEnd().getX() + m, edge.getEnd()
				.getY() + m);
	}

}