text:
"""Generate graphs with a given degree sequence or expected degree sequence.
"""
#    Copyright (C) 2004-2013 by
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    All rights reserved.
#    BSD license.
import heapq
from itertools import combinations, permutations
import math
from operator import itemgetter
import random
import networkx as nx
from networkx.utils import random_weighted_sample

__author__ = "\n".join(['Aric Hagberg <aric.hagberg@gmail.com>',
                        'Pieter Swart <swart@lanl.gov>',
                        'Dan Schult <dschult@colgate.edu>'
                        'Joel Miller <joel.c.miller.research@gmail.com>',
                        'Nathan Lemons <nlemons@gmail.com>'
                        'Brian Cloteaux <brian.cloteaux@nist.gov>'])

__all__ = ['configuration_model',
           'directed_configuration_model',
           'expected_degree_graph',
           'havel_hakimi_graph',
           'directed_havel_hakimi_graph',
           'degree_sequence_tree',
           'random_degree_sequence_graph']

def configuration_model(deg_sequence,create_using=None,seed=None):
    """Return a random graph with the given degree sequence.

    The configuration model generates a random pseudograph (graph with
    parallel edges and self loops) by randomly assigning edges to
    match the given degree sequence.

    Parameters
    ----------
    deg_sequence :  list of integers
        Each list entry corresponds to the degree of a node.
    create_using : graph, optional (default MultiGraph)
       Return graph of this type. The instance will be cleared.
    seed : hashable object, optional
        Seed for random number generator.

    Returns
    -------
    G : MultiGraph
        A graph with the specified degree sequence.
        Nodes are labeled starting at 0 with an index
        corresponding to the position in deg_sequence.

    Raises
    ------
    NetworkXError
        If the degree sequence does not have an even sum.

    See Also
    --------
    is_valid_degree_sequence

    Notes
    -----
    As described by Newman [1]_.

    A non-graphical degree sequence (not realizable by some simple
    graph) is allowed since this function returns graphs with self
    loops and parallel edges.  An exception is raised if the degree
    sequence does not have an even sum.

    This configuration model construction process can lead to
    duplicate edges and loops.  You can remove the self-loops and
    parallel edges (see below) which will likely result in a graph
    that doesn't have the exact degree sequence specified.  This
    "finite-size effect" decreases as the size of the graph increases.

    References
    ----------
    .. [1] M.E.J. Newman, "The structure and function of complex networks",
       SIAM REVIEW 45-2, pp 167-256, 2003.

    Examples
    --------
    >>> from networkx.utils import powerlaw_sequence
    >>> z=nx.utils.create_degree_sequence(100,powerlaw_sequence)
    >>> G=nx.configuration_model(z)

    To remove parallel edges:

    >>> G=nx.Graph(G)

    To remove self loops:

    >>> G.remove_edges_from(G.selfloop_edges())
    """
    if not sum(deg_sequence)%2 ==0:
        raise nx.NetworkXError('Invalid degree sequence')

    if create_using is None:
        create_using = nx.MultiGraph()
    elif create_using.is_directed():
        raise nx.NetworkXError("Directed Graph not supported")

    if not seed is None:
        random.seed(seed)

    # start with empty N-node graph
    N=len(deg_sequence)

    # allow multiedges and selfloops
    G=nx.empty_graph(N,create_using)

    if N==0 or max(deg_sequence)==0: # done if no edges
        return G

    # build stublist, a list of available degree-repeated stubs
    # e.g. for deg_sequence=[3,2,1,1,1]
    # initially, stublist=[1,1,1,2,2,3,4,5]
    # i.e., node 1 has degree=3 and is repeated 3 times, etc.
    stublist=[]
    for n in G:
        for i in range(deg_sequence[n]):
            stublist.append(n)

    # shuffle stublist and assign pairs by removing 2 elements at a time
    random.shuffle(stublist)
    while stublist:
        n1 = stublist.pop()
        n2 = stublist.pop()
        G.add_edge(n1,n2)

    G.name="configuration_model %d nodes %d edges"%(G.order(),G.size())
    return G

def directed_configuration_model(in_degree_sequence,
                                 out_degree_sequence,
                                 create_using=None,seed=None):
    """Return a directed_random graph with the given degree sequences.

    The configuration model generates a random directed pseudograph
    (graph with parallel edges and self loops) by randomly assigning
    edges to match the given degree sequences.

    Parameters
    ----------
    in_degree_sequence :  list of integers
       Each list entry corresponds to the in-degree of a node.
    out_degree_sequence :  list of integers
       Each list entry corresponds to the out-degree of a node.
    create_using : graph, optional (default MultiDiGraph)
       Return graph of this type. The instance will be cleared.
    seed : hashable object, optional
        Seed for random number generator.

    Returns
    -------
    G : MultiDiGraph
        A graph with the specified degree sequences.
        Nodes are labeled starting at 0 with an index
        corresponding to the position in deg_sequence.

    Raises
    ------
    NetworkXError
        If the degree sequences do not have the same sum.

    See Also
    --------
    configuration_model

    Notes
    -----
    Algorithm as described by Newman [1]_.

    A non-graphical degree sequence (not realizable by some simple
    graph) is allowed since this function returns graphs with self
    loops and parallel edges.  An exception is raised if the degree
    sequences does not have the same sum.

    This configuration model construction process can lead to
    duplicate edges and loops.  You can remove the self-loops and
    parallel edges (see below) which will likely result in a graph
    that doesn't have the exact degree sequence specified.  This
    "finite-size effect" decreases as the size of the graph increases.

    References
    ----------
    .. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J.
       Random graphs with arbitrary degree distributions and their applications
       Phys. Rev. E, 64, 026118 (2001)

    Examples
    --------
    >>> D=nx.DiGraph([(0,1),(1,2),(2,3)]) # directed path graph
    >>> din=list(D.in_degree().values())
    >>> dout=list(D.out_degree().values())
    >>> din.append(1)
    >>> dout[0]=2
    >>> D=nx.directed_configuration_model(din,dout)

    To remove parallel edges:

    >>> D=nx.DiGraph(D)

    To remove self loops:

    >>> D.remove_edges_from(D.selfloop_edges())
    """
    if not sum(in_degree_sequence) == sum(out_degree_sequence):
        raise nx.NetworkXError('Invalid degree sequences. '
                               'Sequences must have equal sums.')

    if create_using is None:
        create_using = nx.MultiDiGraph()

    if not seed is None:
        random.seed(seed)

    nin=len(in_degree_sequence)
    nout=len(out_degree_sequence)

    # pad in- or out-degree sequence with zeros to match lengths
    if nin>nout:
        out_degree_sequence.extend((nin-nout)*[0])
    else:
        in_degree_sequence.extend((nout-nin)*[0])

    # start with empty N-node graph
    N=len(in_degree_sequence)

    # allow multiedges and selfloops
    G=nx.empty_graph(N,create_using)

    if N==0 or max(in_degree_sequence)==0: # done if no edges
        return G

    # build stublists of available degree-repeated stubs
    # e.g. for degree_sequence=[3,2,1,1,1]
    # initially, stublist=[1,1,1,2,2,3,4,5]
    # i.e., node 1 has degree=3 and is repeated 3 times, etc.
    in_stublist=[]
    for n in G:
        for i in range(in_degree_sequence[n]):
            in_stublist.append(n)

    out_stublist=[]
    for n in G:
        for i in range(out_degree_sequence[n]):
            out_stublist.append(n)

    # shuffle stublists and assign pairs by removing 2 elements at a time
    random.shuffle(in_stublist)
    random.shuffle(out_stublist)
    while in_stublist and out_stublist:
        source = out_stublist.pop()
        target = in_stublist.pop()
        G.add_edge(source,target)

    G.name="directed configuration_model %d nodes %d edges"%(G.order(),G.size())
    return G

def expected_degree_graph(w, seed=None, selfloops=True):
    r"""Return a random graph with given expected degrees.

    Given a sequence of expected degrees `W=(w_0,w_1,\ldots,w_{n-1}`)
    of length `n` this algorithm assigns an edge between node `u` and
    node `v` with probability

    .. math::

       p_{uv} = \frac{w_u w_v}{\sum_k w_k} .

    Parameters
    ----------
    w : list
        The list of expected degrees.
    selfloops: bool (default=True)
        Set to False to remove the possibility of self-loop edges.
    seed : hashable object, optional
        The seed for the random number generator.

    Returns
    -------
    Graph

    Examples
    --------
    >>> z=[10 for i in range(100)]
    >>> G=nx.expected_degree_graph(z)

    Notes
    -----
    The nodes have integer labels corresponding to index of expected degrees
    input sequence.

    The complexity of this algorithm is `\mathcal{O}(n+m)` where `n` is the
    number of nodes and `m` is the expected number of edges.

    The model in [1]_ includes the possibility of self-loop edges.
    Set selfloops=False to produce a graph without self loops.

    For finite graphs this model doesn't produce exactly the given
    expected degree sequence.  Instead the expected degrees are as
    follows.

    For the case without self loops (selfloops=False),

    .. math::

       E[deg(u)] = \sum_{v \ne u} p_{uv}
                = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .

    NetworkX uses the standard convention that a self-loop edge counts 2
    in the degree of a node, so with self loops (selfloops=True),

    .. math::

       E[deg(u)] =  \sum_{v \ne u} p_{uv}  + 2 p_{uu}
                = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .

    References
    ----------
    .. [1] Fan Chung and L. Lu, Connected components in random graphs with
       given expected degree sequences, Ann. Combinatorics, 6,
       pp. 125-145, 2002.
    .. [2] Joel Miller and Aric Hagberg,
       Efficient generation of networks with given expected degrees,
       in Algorithms and Models for the Web-Graph (WAW 2011),
       Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,
       pp. 115-126, 2011.
    """
    n = len(w)
    G=nx.empty_graph(n)
    if n==0 or max(w)==0: # done if no edges
        return G
    if seed is not None:
        random.seed(seed)
    rho = 1/float(sum(w))
    # sort weights, largest first
    # preserve order of weights for integer node label mapping
    order = sorted(enumerate(w),key=itemgetter(1),reverse=True)
    mapping = dict((c,uv[0]) for c,uv in enumerate(order))
    seq = [v for u,v in order]
    last=n
    if not selfloops:
        last-=1
    for u in range(last):
        v = u
        if not selfloops:
            v += 1
        factor = seq[u] * rho
        p = seq[v]*factor
        if p>1:
            p = 1
        while v<n and p>0:
            if p != 1:
                r = random.random()
                v += int(math.floor(math.log(r)/math.log(1-p)))
            if v < n:
                q = seq[v]*factor
                if q>1:
                    q = 1
                if random.random() < q/p:
                    G.add_edge(mapping[u],mapping[v])
                v += 1
                p = q
    return G

def havel_hakimi_graph(deg_sequence,create_using=None):
    """Return a simple graph with given degree sequence constructed
    using the Havel-Hakimi algorithm.

    Parameters
    ----------
    deg_sequence: list of integers
        Each integer corresponds to the degree of a node (need not be sorted).
    create_using : graph, optional (default Graph)
        Return graph of this type. The instance will be cleared.
        Directed graphs are not allowed.

    Raises
    ------
    NetworkXException
        For a non-graphical degree sequence (i.e. one
        not realizable by some simple graph).

    Notes
    -----
    The Havel-Hakimi algorithm constructs a simple graph by
    successively connecting the node of highest degree to other nodes
    of highest degree, resorting remaining nodes by degree, and
    repeating the process. The resulting graph has a high
    degree-associativity.  Nodes are labeled 1,.., len(deg_sequence),
    corresponding to their position in deg_sequence.

    The basic algorithm is from Hakimi [1]_ and was generalized by
    Kleitman and Wang [2]_.

    References
    ----------
    .. [1] Hakimi S., On Realizability of a Set of Integers as
       Degrees of the Vertices of a Linear Graph. I,
       Journal of SIAM, 10(3), pp. 496-506 (1962)
    .. [2] Kleitman D.J. and Wang D.L.
       Algorithms for Constructing Graphs and Digraphs with Given Valences
       and Factors  Discrete Mathematics, 6(1), pp. 79-88 (1973)
    """
    if not nx.is_valid_degree_sequence(deg_sequence):
        raise nx.NetworkXError('Invalid degree sequence')
    if create_using is not None:
        if create_using.is_directed():
            raise nx.NetworkXError("Directed graphs are not supported")

    p = len(deg_sequence)
    G=nx.empty_graph(p,create_using)
    num_degs = []
    for i in range(p):
        num_degs.append([])
    dmax, dsum, n = 0, 0, 0
    for d in deg_sequence:
        # Process only the non-zero integers
        if d>0:
            num_degs[d].append(n)
            dmax, dsum, n = max(dmax,d), dsum+d, n+1
    # Return graph if no edges
    if n==0:
        return G

    modstubs = [(0,0)]*(dmax+1)
    # Successively reduce degree sequence by removing the maximum degree
    while n > 0:
        # Retrieve the maximum degree in the sequence
        while len(num_degs[dmax]) == 0:
            dmax -= 1;
        # If there are not enough stubs to connect to, then the sequence is
        # not graphical
        if dmax > n-1:
            raise nx.NetworkXError('Non-graphical integer sequence')

        # Remove largest stub in list
        source = num_degs[dmax].pop()
        n -= 1
        # Reduce the next dmax largest stubs
        mslen = 0
        k = dmax
        for i in range(dmax):
            while len(num_degs[k]) == 0:
                k -= 1
            target = num_degs[k].pop()
            G.add_edge(source, target)
            n -= 1
            if k > 1:
                modstubs[mslen] = (k-1,target)
                mslen += 1
        # Add back to the list any nonzero stubs that were removed
        for i  in range(mslen):
            (stubval, stubtarget) = modstubs[i]
            num_degs[stubval].append(stubtarget)
            n += 1

    G.name="havel_hakimi_graph %d nodes %d edges"%(G.order(),G.size())
    return G

def directed_havel_hakimi_graph(in_deg_sequence,
                                out_deg_sequence,
                                create_using=None):
    """Return a directed graph with the given degree sequences.

    Parameters
    ----------
    in_deg_sequence :  list of integers
       Each list entry corresponds to the in-degree of a node.
    out_deg_sequence : list of integers
       Each list entry corresponds to the out-degree of a node.
    create_using : graph, optional (default DiGraph)
       Return graph of this type. The instance will be cleared.

    Returns
    -------
    G : DiGraph
        A graph with the specified degree sequences.
        Nodes are labeled starting at 0 with an index
        corresponding to the position in deg_sequence

    Raises
    ------
    NetworkXError
        If the degree sequences are not digraphical.

    See Also
    --------
    configuration_model

    Notes
    -----
    Algorithm as described by Kleitman and Wang [1]_.

    References
    ----------
    .. [1] D.J. Kleitman and D.L. Wang
       Algorithms for Constructing Graphs and Digraphs with Given Valences
       and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
    """
    assert(nx.utils.is_list_of_ints(in_deg_sequence))
    assert(nx.utils.is_list_of_ints(out_deg_sequence))

    if create_using is None:
        create_using = nx.DiGraph()

    # Process the sequences and form two heaps to store degree pairs with
    # either zero or nonzero out degrees
    sumin, sumout, nin, nout = 0, 0, len(in_deg_sequence), len(out_deg_sequence)
    maxn = max(nin, nout)
    G = nx.empty_graph(maxn,create_using)
    if maxn==0:
        return G
    maxin = 0
    stubheap, zeroheap = [ ], [ ]
    for n in range(maxn):
        in_deg, out_deg = 0, 0
        if n<nout:
            out_deg = out_deg_sequence[n]
        if n<nin:
            in_deg = in_deg_sequence[n]
        if in_deg<0 or out_deg<0:
            raise nx.NetworkXError(
                'Invalid degree sequences. Sequence values must be positive.')
        sumin, sumout, maxin = sumin+in_deg, sumout+out_deg, max(maxin, in_deg)
        if in_deg > 0:
            stubheap.append((-1*out_deg, -1*in_deg,n))
        elif out_deg > 0:
            zeroheap.append((-1*out_deg,n))
    if sumin != sumout:
        raise nx.NetworkXError(
            'Invalid degree sequences. Sequences must have equal sums.')
    heapq.heapify(stubheap)
    heapq.heapify(zeroheap)

    modstubs = [(0,0,0)]*(maxin+1)
    # Successively reduce degree sequence by removing the maximum
    while stubheap:
        # Remove first value in the sequence with a non-zero in degree
        (freeout, freein, target) =  heapq.heappop(stubheap)
        freein *= -1
        if freein > len(stubheap)+len(zeroheap):
            raise nx.NetworkXError('Non-digraphical integer sequence')

        # Attach arcs from the nodes with the most stubs
        mslen = 0
        for i in range(freein):
            if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0][0]):
                (stubout, stubsource) = heapq.heappop(zeroheap)
                stubin = 0
            else:
                (stubout, stubin, stubsource) = heapq.heappop(stubheap)
            if stubout == 0:
                raise nx.NetworkXError('Non-digraphical integer sequence')
            G.add_edge(stubsource, target)
            # Check if source is now totally connected
            if stubout+1<0 or stubin<0:
                modstubs[mslen] = (stubout+1, stubin, stubsource)
                mslen += 1

        # Add the nodes back to the heaps that still have available stubs
        for i in range(mslen):
            stub = modstubs[i]
            if stub[1] < 0:
                heapq.heappush(stubheap, stub)
            else:
                heapq.heappush(zeroheap, (stub[0], stub[2]))
        if freeout<0:
            heapq.heappush(zeroheap, (freeout, target))

    G.name="directed_havel_hakimi_graph %d nodes %d edges"%(G.order(),G.size())
    return G

def degree_sequence_tree(deg_sequence,create_using=None):
    """Make a tree for the given degree sequence.

    A tree has #nodes-#edges=1 so
    the degree sequence must have
    len(deg_sequence)-sum(deg_sequence)/2=1
    """

    if not len(deg_sequence)-sum(deg_sequence)/2.0 == 1.0:
        raise nx.NetworkXError("Degree sequence invalid")
    if create_using is not None and create_using.is_directed():
        raise nx.NetworkXError("Directed Graph not supported")

    # single node tree
    if len(deg_sequence)==1:
        G=nx.empty_graph(0,create_using)
        return G

    # all degrees greater than 1
    deg=[s for s in deg_sequence if s>1]
    deg.sort(reverse=True)

    # make path graph as backbone
    n=len(deg)+2
    G=nx.path_graph(n,create_using)
    last=n

    # add the leaves
    for source in range(1,n-1):
        nedges=deg.pop()-2
        for target in range(last,last+nedges):
            G.add_edge(source, target)
        last+=nedges

    # in case we added one too many
    if len(G.degree())>len(deg_sequence):
        G.remove_node(0)
    return G

def random_degree_sequence_graph(sequence, seed=None, tries=10):
    r"""Return a simple random graph with the given degree sequence.

    If the maximum degree `d_m` in the sequence is `O(m^{1/4})` then the
    algorithm produces almost uniform random graphs in `O(m d_m)` time
    where `m` is the number of edges.

    Parameters
    ----------
    sequence :  list of integers
        Sequence of degrees
    seed : hashable object, optional
        Seed for random number generator
    tries : int, optional
        Maximum number of tries to create a graph

    Returns
    -------
    G : Graph
        A graph with the specified degree sequence.
        Nodes are labeled starting at 0 with an index
        corresponding to the position in the sequence.

    Raises
    ------
    NetworkXUnfeasible
        If the degree sequence is not graphical.
    NetworkXError
        If a graph is not produced in specified number of tries

    See Also
    --------
    is_valid_degree_sequence, configuration_model

    Notes
    -----
    The generator algorithm [1]_ is not guaranteed to produce a graph.

    References
    ----------
    .. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi,
       A sequential algorithm for generating random graphs.
       Algorithmica, Volume 58, Number 4, 860-910,
       DOI: 10.1007/s00453-009-9340-1

    Examples
    --------
    >>> sequence = [1, 2, 2, 3]
    >>> G = nx.random_degree_sequence_graph(sequence)
    >>> sorted(G.degree().values())
    [1, 2, 2, 3]
    """
    DSRG = DegreeSequenceRandomGraph(sequence, seed=seed)
    for try_n in range(tries):
        try:
            return DSRG.generate()
        except nx.NetworkXUnfeasible:
            pass
    raise nx.NetworkXError('failed to generate graph in %d tries'%tries)

class DegreeSequenceRandomGraph(object):
    # class to generate random graphs with a given degree sequence
    # use random_degree_sequence_graph()
    def __init__(self, degree, seed=None):
        if not nx.is_valid_degree_sequence(degree):
            raise nx.NetworkXUnfeasible('degree sequence is not graphical')
        if seed is not None:
            random.seed(seed)
        self.degree = list(degree)
        # node labels are integers 0,...,n-1
        self.m = sum(self.degree)/2.0 # number of edges
        try:
            self.dmax = max(self.degree) # maximum degree
        except ValueError:
            self.dmax = 0

    def generate(self):
        # remaining_degree is mapping from int->remaining degree
        self.remaining_degree = dict(enumerate(self.degree))
        # add all nodes to make sure we get isolated nodes
        self.graph = nx.Graph()
        self.graph.add_nodes_from(self.remaining_degree)
        # remove zero degree nodes
        for n,d in list(self.remaining_degree.items()):
            if d == 0:
                del self.remaining_degree[n]
        if len(self.remaining_degree) > 0:
        # build graph in three phases according to how many unmatched edges
            self.phase1()
            self.phase2()
            self.phase3()
        return self.graph

    def update_remaining(self, u, v, aux_graph=None):
        # decrement remaining nodes, modify auxilliary graph if in phase3
        if aux_graph is not None:
            # remove edges from auxilliary graph
            aux_graph.remove_edge(u,v)
        if self.remaining_degree[u] == 1:
            del self.remaining_degree[u]
            if aux_graph is not None:
                aux_graph.remove_node(u)
        else:
            self.remaining_degree[u] -= 1
        if self.remaining_degree[v] == 1:
            del self.remaining_degree[v]
            if aux_graph is not None:
                aux_graph.remove_node(v)
        else:
            self.remaining_degree[v] -= 1

    def p(self,u,v):
        # degree probability
        return 1 - self.degree[u]*self.degree[v]/(4.0*self.m)

    def q(self,u,v):
        # remaining degree probability
        norm = float(max(self.remaining_degree.values()))**2
        return self.remaining_degree[u]*self.remaining_degree[v]/norm

    def suitable_edge(self):
        # Check if there is a suitable edge that is not in the graph
        # True if an (arbitrary) remaining node has at least one possible
        # connection to another remaining node
        nodes = iter(self.remaining_degree)
        u = next(nodes) # one arbitrary node
        for v in nodes: # loop over all other remaining nodes
            if not self.graph.has_edge(u, v):
                return True
        return False

    def phase1(self):
        # choose node pairs from (degree) weighted distribution
        while sum(self.remaining_degree.values()) >= 2 * self.dmax**2:
            u,v = sorted(random_weighted_sample(self.remaining_degree, 2))
            if self.graph.has_edge(u,v):
                continue
            if random.random() < self.p(u,v):  # accept edge
                self.graph.add_edge(u,v)
                self.update_remaining(u,v)

    def phase2(self):
        # choose remaining nodes uniformly at random and use rejection sampling
        while len(self.remaining_degree) >= 2 * self.dmax:
            norm = float(max(self.remaining_degree.values()))**2
            while True:
                u,v = sorted(random.sample(self.remaining_degree.keys(), 2))
                if self.graph.has_edge(u,v):
                    continue
                if random.random() < self.q(u,v):
                    break
            if random.random() < self.p(u,v):  # accept edge
                self.graph.add_edge(u,v)
                self.update_remaining(u,v)

    def phase3(self):
        # build potential remaining edges and choose with rejection sampling
        potential_edges = combinations(self.remaining_degree, 2)
        # build auxilliary graph of potential edges not already in graph
        H = nx.Graph([(u,v) for (u,v) in potential_edges
                      if not self.graph.has_edge(u,v)])
        while self.remaining_degree:
            if not self.suitable_edge():
                raise nx.NetworkXUnfeasible('no suitable edges left')
            while True:
                u,v = sorted(random.choice(H.edges()))
                if random.random() < self.q(u,v):
                    break
            if random.random() < self.p(u,v): # accept edge
                self.graph.add_edge(u,v)
                self.update_remaining(u,v, aux_graph=H)


text:
package org.finra.herd.service.helper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.finra.herd.dao.BusinessObjectFormatDao;
import org.finra.herd.dao.BusinessObjectFormatExternalInterfaceDao;
import org.finra.herd.dao.ExternalInterfaceDao;
import org.finra.herd.model.ObjectNotFoundException;
import org.finra.herd.model.api.xml.BusinessObjectFormatExternalInterfaceKey;
import org.finra.herd.model.api.xml.BusinessObjectFormatKey;
import org.finra.herd.model.jpa.BusinessObjectFormatEntity;
import org.finra.herd.model.jpa.BusinessObjectFormatExternalInterfaceEntity;
import org.finra.herd.model.jpa.ExternalInterfaceEntity;

/**
 * Helper for business object format to external interface mapping related operations which require DAO.
 */
@Component
public class BusinessObjectFormatExternalInterfaceDaoHelper
{
    @Autowired
    private BusinessObjectFormatDao businessObjectFormatDao;

    @Autowired
    private BusinessObjectFormatExternalInterfaceDao businessObjectFormatExternalInterfaceDao;

    @Autowired
    private ExternalInterfaceDao externalInterfaceDao;

    /**
     * Gets a business object format to external interface mapping by its key and makes sure that it exists.
     *
     * @param businessObjectFormatExternalInterfaceKey the business object format to external interface mapping key
     *
     * @return the business object format to external interface mapping entity
     */
    public BusinessObjectFormatExternalInterfaceEntity getBusinessObjectFormatExternalInterfaceEntity(
        BusinessObjectFormatExternalInterfaceKey businessObjectFormatExternalInterfaceKey)
    {
        // Get a business object format entity. Since business object format to external interface
        // mapping is version-less, retrieve the latest version of the business object format.
        BusinessObjectFormatEntity businessObjectFormatEntity = businessObjectFormatDao.getBusinessObjectFormatByAltKey(
            new BusinessObjectFormatKey(businessObjectFormatExternalInterfaceKey.getNamespace(),
                businessObjectFormatExternalInterfaceKey.getBusinessObjectDefinitionName(),
                businessObjectFormatExternalInterfaceKey.getBusinessObjectFormatUsage(),
                businessObjectFormatExternalInterfaceKey.getBusinessObjectFormatFileType(), null));

        // If business object format exists, then try to retrieve specified external interface.
        ExternalInterfaceEntity externalInterfaceEntity = null;
        if (businessObjectFormatEntity != null)
        {
            externalInterfaceEntity = externalInterfaceDao.getExternalInterfaceByName(businessObjectFormatExternalInterfaceKey.getExternalInterfaceName());
        }

        // If business object format and external interface both exist, then try to retrieve business object format to external interface mapping.
        BusinessObjectFormatExternalInterfaceEntity businessObjectFormatExternalInterfaceEntity = null;
        if (externalInterfaceEntity != null)
        {
            businessObjectFormatExternalInterfaceEntity = businessObjectFormatExternalInterfaceDao
                .getBusinessObjectFormatExternalInterfaceByBusinessObjectFormatAndExternalInterface(businessObjectFormatEntity, externalInterfaceEntity);
        }

        // Throw an exception if specified business object format to external interface mapping does not exist.
        if (businessObjectFormatExternalInterfaceEntity == null)
        {
            throw new ObjectNotFoundException(String.format(
                "Business object format to external interface mapping with \"%s\" namespace, \"%s\" business object definition name, " +
                    "\"%s\" business object format usage, \"%s\" business object format file type, and \"%s\" external interface name doesn't exist.",
                businessObjectFormatExternalInterfaceKey.getNamespace(), businessObjectFormatExternalInterfaceKey.getBusinessObjectDefinitionName(),
                businessObjectFormatExternalInterfaceKey.getBusinessObjectFormatUsage(),
                businessObjectFormatExternalInterfaceKey.getBusinessObjectFormatFileType(),
                businessObjectFormatExternalInterfaceKey.getExternalInterfaceName()));
        }

        return businessObjectFormatExternalInterfaceEntity;
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.Management.Security.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The awsOrganization data for the master account
    /// </summary>
    [Newtonsoft.Json.JsonObject("Organization")]
    public partial class AwsOrganizationalDataMaster : AwsOrganizationalData
    {
        /// <summary>
        /// Initializes a new instance of the AwsOrganizationalDataMaster
        /// class.
        /// </summary>
        public AwsOrganizationalDataMaster()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the AwsOrganizationalDataMaster
        /// class.
        /// </summary>
        /// <param name="stacksetName">If the multi cloud account is of
        /// membership type organization, this will be the name of the
        /// onboarding stackset</param>
        /// <param name="excludedAccountIds">If the multi cloud account is of
        /// membership type organization, list of accounts excluded from
        /// offering</param>
        public AwsOrganizationalDataMaster(string stacksetName = default(string), IList<string> excludedAccountIds = default(IList<string>))
        {
            StacksetName = stacksetName;
            ExcludedAccountIds = excludedAccountIds;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets if the multi cloud account is of membership type
        /// organization, this will be the name of the onboarding stackset
        /// </summary>
        [JsonProperty(PropertyName = "stacksetName")]
        public string StacksetName { get; set; }

        /// <summary>
        /// Gets or sets if the multi cloud account is of membership type
        /// organization, list of accounts excluded from offering
        /// </summary>
        [JsonProperty(PropertyName = "excludedAccountIds")]
        public IList<string> ExcludedAccountIds { get; set; }

    }
}


text:
package rpc

import (
	"encoding/gob"
	"io"
)

type GobRPCDecoder struct {
	gobDecoder *gob.Decoder
}

func NewGobRPCDecoder(r io.Reader) *GobRPCDecoder {
	return &GobRPCDecoder{gobDecoder: gob.NewDecoder(r)}
}

func (self *GobRPCDecoder) Decode(eid *string, method *string, args *[]interface{}) error {
	var val gobCall
	err := self.gobDecoder.Decode(&val)
	if err != nil {
		return err
	}
	*eid, *method, *args = val.Eid, val.Method, val.Args
	return nil
}


text:
package com.cloudera.flume.agent;

import java.io.IOException;

import org.junit.Test;

import com.cloudera.flume.conf.FlumeSpecException;
import com.cloudera.util.BenchmarkHarness;

/**
 * Benchmark tests on basic decorators.
 */
public class BenchmarkBasicDecos {
  String[] decos = { "nullDeco", "ackInjector", "ackChecker", };

  String[] batching = { "batch(10)", "batch(100)", "batch(1000)" };

  // TODO (jon) new decorator chaining notation
  // String[] gzips = { "batch(10) gzip", "batch(100) gzip", "batch(1000) gzip"
  // };

  @Test
  public void basicDecorator() throws FlumeSpecException, IOException {
    for (String d : decos) {
      BenchmarkHarness.doDecoBenchmark(d, BenchmarkHarness.varyMsgBytes);
      BenchmarkHarness.doDecoBenchmark(d, BenchmarkHarness.varyNumAttrs);
      BenchmarkHarness.doDecoBenchmark(d, BenchmarkHarness.varyValSize);
    }
  }
}


text:
app.controller('NewsfeedNodeController', function ($scope, $rootScope, $filter, $http,
                                               $location, $routeParams, $timeout,
                                               courseService, authService, toastr, Page) {
    $scope.courseId = $routeParams.courseId;
    $scope.nodeId = $routeParams.nodeId;
    $scope.curUrl = $routeParams;

    $scope.newsfeedData = [];
    $scope.filterDropDown = {};
    $scope.filterDateDropDown = "today";
    //$scope.query = "vote";

    $scope.nfNodeType = [
        {"name": "content node"},
        // {"name": "link"},
        {"name": "external resource"},
        {"name": "pdf annotation"},
        {"name": "video annotation"},
        {"name": "vote"}

    ];

    $scope.filterDropDown = [
        {"name": "today"},
        {"name": "last week"},
        {"name": "last month"}
    ];

    $scope.nfFilterDate = [
        {"name": "today"},
        {"name": "last week"},
        {"name": "last month"}
    ];

    $scope.$watch('filterDateDropDown', function (newValue, oldValue) {

        if ($scope.filterDateDropDown.name == 'today') {
            $http.get('/api/newsfeed-node/cid/'+$scope.courseId+'/nid/'+$scope.nodeId+'/today').success(function (data) {
                $scope.newsfeedData = data.newsfeeds;
                $scope.nfLength = data.newsfeeds.length;
            });
        } else if ($scope.filterDateDropDown.name == 'last week') {
            $http.get('/api/newsfeed-node/cid/'+$scope.courseId+'/nid/'+$scope.nodeId+'/week').success(function (data) {
                $scope.newsfeedData = data.newsfeeds;
                $scope.nfLength = data.newsfeeds.length;
            });
        } else if ($scope.filterDateDropDown.name == 'last month') {
            $http.get('/api/newsfeed-node/cid/'+$scope.courseId+'/nid/'+$scope.nodeId).success(function (data) {
                $scope.newsfeedData = data.newsfeeds;
                $scope.nfLength = data.newsfeeds.length;
            });
        } else {
            $http.get('/api/newsfeed-node/cid/'+$scope.courseId+'/nid/'+$scope.nodeId).success(function (data) {
                $scope.newsfeedData = data.newsfeeds;
                $scope.nfLength = data.newsfeeds.length;
            });
        }

    });

});


text:
<?php

/**
 * @namespace
 */
namespace Opengraph;

use DOMDocument;
use RuntimeException;
use ArrayObject;

class Reader extends Opengraph
{
    /**
     * @var \ArrayObject
     */
    protected static $storage;

    public function __construct()
    {
        static::$storage = new ArrayObject();
    }

    /**
     * parse html tags
     *
     * @param $contents
     * @param bool $includeDefaults
     * @return $this
     */
    public function parse($contents, $includeDefaults = false)
    {
        $old_libxml_error = libxml_use_internal_errors(true);

        $dom = new DOMDocument;

        if(@$dom->loadHTML($contents) === false) {
            throw new RuntimeException("Contents is empty");
        }

        libxml_use_internal_errors($old_libxml_error);

        foreach($dom->getElementsByTagName('meta') as $tag) {
            if($includeDefaults && $tag->hasAttribute('name') && $tag->hasAttribute('content') && $tag->getAttribute('name') == 'description') {
                $this->addMeta('non-og-description', $tag->getAttribute('content'), self::APPEND);
            } else if($tag->hasAttribute('property') && $tag->hasAttribute('content')) {
                $this->addMeta($tag->getAttribute('property'), $tag->getAttribute('content'), self::APPEND);
            }
        }

        if($includeDefaults) {
            $titles = $dom->getElementsByTagName('title');
            if ($titles->length > 0) {
                $this->addMeta('non-og-title', $titles->item(0)->textContent, self::APPEND);
            }
        }

        unset($dom);

        return $this;
    }
}


text:
package com.intellij.usages.impl;

import com.intellij.pom.Navigatable;
import com.intellij.usages.Usage;
import com.intellij.usages.UsageNodePresentation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class UsageNode extends Node implements Comparable<UsageNode>, Navigatable {
  public UsageNode(Node parent, @NotNull Usage usage) {
    setUserObject(usage);
    setParent(parent);
  }

  @Override
  public String toString() {
    return getUsage().toString();
  }

  @Override
  public int compareTo(@NotNull UsageNode usageNode) {
    return UsageViewImpl.USAGE_COMPARATOR.compare(getUsage(), usageNode.getUsage());
  }

  @NotNull
  public Usage getUsage() {
    return (Usage)getUserObject();
  }

  @Override
  public void navigate(boolean requestFocus) {
    getUsage().navigate(requestFocus);
  }

  @Override
  public boolean canNavigate() {
    return getUsage().isValid() && getUsage().canNavigate();
  }

  @Override
  public boolean canNavigateToSource() {
    return getUsage().isValid() && getUsage().canNavigate();
  }

  @Override
  protected boolean isDataValid() {
    return getUsage().isValid();
  }

  @Override
  protected boolean isDataReadOnly() {
    return getUsage().isReadOnly();
  }

  @Override
  protected boolean isDataExcluded() {
    return isExcluded();
  }

  @NotNull
  @Override
  protected String getNodeText() {
    return getUsage().getPresentation().getPlainText();
  }

  @Override
  public @Nullable UsageNodePresentation getCachedPresentation() {
    return getUsage().getPresentation().getCachedPresentation();
  }

  @Override
  protected void updateCachedPresentation() {
    getUsage().getPresentation().updateCachedPresentation();
  }
}


text:
package com.honghei.gank.ui.activity;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

import com.honghei.gank.R;
import com.honghei.gank.ui.fragment.gank.GankFragment;
import com.honghei.gank.ui.fragment.qdaily.QdailyFragment;
import com.honghei.gank.ui.fragment.zhihu.ZhihuNewsFragment;
import com.honghei.gank.util.LayoutUtil;
import com.honghei.gank.widght.SelfDefinedViewPager;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    FloatingActionButton fab;

    /**
     * 表示的是当前选中的是第几页,在dispatchtouch中与手势一起作用于tab的hide和show,如果是1.2.页就直接不显示了
     *
     * 这样考虑的原因是 hide和show方法会影响到fab的gone和visiable属性。
     */
    private int selectedPage = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
                getSupportFragmentManager(), FragmentPagerItems.with(this)
                .add(R.string.smarttablayout_fragmentname_1, ZhihuNewsFragment.class)
                .add(R.string.smarttablayout_fragmentname_2, GankFragment.class)
                .add(R.string.smarttablayout_fragmentname_3, QdailyFragment.class)
                .create());

        SelfDefinedViewPager viewPager = (SelfDefinedViewPager) findViewById(R.id.viewpager);
        viewPager.setPagingEnabled(true);
        viewPager.setAdapter(adapter);

       /* setViewPagerMargin(viewPager);*/

        SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpagertab);
        viewPagerTab.setViewPager(viewPager);
        setTabPageChangeListen(viewPagerTab);
    }

    float x;
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                float nextX = event.getRawY();
                float desX = x-nextX;
                if(selectedPage == 0 && desX >0){
                    fab.hide();
                }else if(selectedPage == 0 && desX<0){
                    fab.show();
                }

                break;
            case MotionEvent.ACTION_UP:

                break;
            default:
                break;
        }

        return super.dispatchTouchEvent(event);
    }

    /**
     * 设置smarttablayout的margintop值。
     */
    private void setViewPagerMargin(SelfDefinedViewPager viewPager) {

        int dimension = (int) getResources().getDimension(R.dimen.tablayout_height);

        TypedValue tv = new TypedValue();
        int actionBarHeight = 0;
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
        }
        LayoutUtil.setViewMargin(viewPager,dimension+actionBarHeight);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void setTabPageChangeListen(SmartTabLayout tabLayout){
        tabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(position == 0){
                    fab.setVisibility(View.VISIBLE);
                }else {
                    fab.setVisibility(View.GONE);
                }
                selectedPage = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

}


text:
export class ArrayChildren {
    constructor(type, children) {
        this._type = type;
        this._children = children;
        for (let i = 0; i < children.length; i++) {
            let child = children[i];
            child._nextSibling = children[i + 1] || null;
            child._previousSibling = children[i - 1] || null;
            child._parent = this;
        }
    }

    appendChild(element) {
        element._parent = this;

        element._previousSibling = this._lastChild;
        element._nextSibling = null;

        this._children[this._children.length] = element;
        if (this._lastChild) {
            this._lastChild._nextSibling = element;
        } else {
            this._firstChild = this._lastChild = element;
        }
        this._lastChild = element;
    }

    removeChild(element) {
        if (element._parent === this) {
            if (element._previousSibling) {
                element._previousSibling._nextSibling = element._nextSibling;
            }

            if (element._nextSibling) {
                element._nextSibling._previousSibling = element._previousSibling;
            }

            if (element === this._lastChild) {
                this._lastChild = element._previousSibling;
            }

            if (element === this._firstChild) {
                this._firstChild = element._nextSibling;
            }

            element._parent = null;

            this._children.splice(this._children.indexOf(element), 1);
        }
    }

    select(type) {
        let result = [];
        if (this._type === type) {
            result.push(this);
        }
        this._select(type, result);
        return result;
    }

    _select(type, result) {
        for (let i = 0; i < this._children.length; i++) {
            let child = this._children[i];
            if (child._type === type) {
                result.push(child);
            }
            child._select(type, result);
        }
    }
}

export class ListChildren {
    constructor(type, children) {
        this._type = type;
        if (children.length > 0) {
            this._firstChild = children[0];
            this._lastChild = children[children.length - 1];
            for (let i = 0; i < children.length; i++) {
                let child = children[i];
                child._nextSibling = children[i + 1] || null;
                child._previousSibling = children[i - 1] || null;
                child._parent = this;
            }
        }
    }

    appendChild(element) {
        element._parent = this;

        element._previousSibling = this._lastChild;
        element._nextSibling = null;

        if (this._lastChild) {
            this._lastChild._nextSibling = element;
        } else {
            this._firstChild = this._lastChild = element;
        }
        this._lastChild = element;
    }

    removeChild(element) {
        if (element._parent === this) {
            if (element._previousSibling) {
                element._previousSibling._nextSibling = element._nextSibling;
            }

            if (element._nextSibling) {
                element._nextSibling._previousSibling = element._previousSibling;
            }

            if (element === this._lastChild) {
                this._lastChild = element._previousSibling;
            }

            if (element === this._firstChild) {
                this._firstChild = element._nextSibling;
            }

            element._parent = null;
        }
    }

    select(type) {
        let result = [];
        if (this._type === type) {
            result.push(this);
        }
        this._select(type, result);
        return result;
    }

    _select(type, result) {
        let child = this._firstChild;
        while (child) {
            if (child._type === type) {
                result.push(child);
            }
            child._select(type, result);
            child = child._nextSibling;
        }
    }
}

export class ListChildrenNonRecursive extends ListChildren {

    select(type) {
        let bulkSize = 100;
        let result = new Array(bulkSize);
        let resultLength = 0;

        let queue = new Array(bulkSize);
        let queueLength = 1;
        queue[0] = this;

        while (queueLength > 0) {
            let item = queue[queueLength - 1];
            queueLength--;

            if (item._type === type) {
                if (result.length === resultLength) {
                    result = result.concat(new Array(bulkSize));
                }
                result[resultLength] = item;
                resultLength++;
            }

            let child = item._firstChild;
            while (child) {
                if (queue.length === queueLength) {
                    queue = queue.concat(new Array(bulkSize));
                }
                queue[queueLength] = child;
                queueLength++;
                child = child._nextSibling;
            }
        }

        return result.slice(0, resultLength);
    }
}

export class ListChildrenRecursiveClosure extends ListChildren {
    select(type) {
        let result = new Array(100);
        let length = 0;
        if (this._type === type) {
            result[0] = this;
            length++;
        }

        select(this);

        function select(item) {
            let child = item._firstChild;
            while (child) {
                if (child._type === type) {
                    if (length === result.length) {
                        result = result.concat(new Array(result.length));
                    }
                    result[length] = child;
                    length++;
                }
                if (child._firstChild) {
                    select(child);
                }
                child = child._nextSibling;
            }
        }

        return result.slice(0, length);
    }
}


text:
.class public final Lcom/sec/android/app/camera/R$styleable;
.super Ljava/lang/Object;
.source "R.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/sec/android/app/camera/R;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "styleable"
.end annotation

# static fields
.field public static final TwImageButton:[I = null

.field public static final TwImageButton_twimagebutton_background_d:I = 0x11

.field public static final TwImageButton_twimagebutton_background_height:I = 0xb

.field public static final TwImageButton_twimagebutton_background_n:I = 0xf

.field public static final TwImageButton_twimagebutton_background_p:I = 0x10

.field public static final TwImageButton_twimagebutton_background_width:I = 0xa

.field public static final TwImageButton_twimagebutton_image_d:I = 0xe

.field public static final TwImageButton_twimagebutton_image_height:I = 0x9

.field public static final TwImageButton_twimagebutton_image_n:I = 0xc

.field public static final TwImageButton_twimagebutton_image_p:I = 0xd

.field public static final TwImageButton_twimagebutton_image_width:I = 0x8

.field public static final TwImageButton_twimagebutton_image_x:I = 0x6

.field public static final TwImageButton_twimagebutton_image_y:I = 0x7

.field public static final TwImageButton_twimagebutton_text:I = 0x0

.field public static final TwImageButton_twimagebutton_text_height:I = 0x4

.field public static final TwImageButton_twimagebutton_text_size:I = 0x5

.field public static final TwImageButton_twimagebutton_text_width:I = 0x3

.field public static final TwImageButton_twimagebutton_text_x:I = 0x1

.field public static final TwImageButton_twimagebutton_text_y:I = 0x2

.field public static final TwIndicatorBattery:[I = null

.field public static final TwIndicatorBattery_indicator_battery_level_0:I = 0x0

.field public static final TwIndicatorBattery_indicator_battery_level_1:I = 0x1

.field public static final TwIndicatorBattery_indicator_battery_level_2:I = 0x2

.field public static final TwIndicatorBattery_indicator_battery_level_3:I = 0x3

.field public static final TwIndicatorBattery_indicator_battery_level_4:I = 0x4

.field public static final TwIndicatorBattery_indicator_battery_level_5:I = 0x5

.field public static final TwIndicatorBattery_indicator_battery_level_6:I = 0x6

.field public static final TwIndicatorBattery_indicator_battery_level_charging:I = 0x7

.field public static final TwIndicatorGPS:[I = null

.field public static final TwIndicatorGPS_indicator_gps_01:I = 0x1

.field public static final TwIndicatorGPS_indicator_gps_02:I = 0x2

.field public static final TwIndicatorGPS_indicator_gps_03:I = 0x3

.field public static final TwIndicatorGPS_indicator_gps_off:I = 0x0

.field public static final TwIndicatorGPS_indicator_gps_on:I = 0x4

.field public static final TwIndicatorStorage:[I = null

.field public static final TwIndicatorStorage_indicator_storage_flash:I = 0x0

.field public static final TwIndicatorStorage_indicator_storage_phone:I = 0x1

.field public static final TwSideMenu:[I = null

.field public static final TwSideMenu_twsidemenu_bottom_bg:I = 0x2

.field public static final TwSideMenu_twsidemenu_mid_bg:I = 0x1

.field public static final TwSideMenu_twsidemenu_top_bg:I = 0x0

.field public static final TwSlider:[I = null

.field public static final TwSlider_slider_bar_image:I = 0x0

.field public static final TwSlider_slider_bar_margin_top:I = 0x4

.field public static final TwSlider_slider_focus_bar_image:I = 0x1

.field public static final TwSlider_slider_focus_bar_margin_top:I = 0x5

.field public static final TwSlider_slider_focus_image_height:I = 0x9

.field public static final TwSlider_slider_focus_image_width:I = 0x8

.field public static final TwSlider_slider_image_height:I = 0x7

.field public static final TwSlider_slider_image_width:I = 0x6

.field public static final TwSlider_slider_layout_width:I = 0x3

.field public static final TwSlider_slider_number_of_guage:I = 0x2

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 20684
    const/16 v0, 0x12

    new-array v0, v0, [I

    fill-array-data v0, :array_0

    sput-object v0, Lcom/sec/android/app/camera/R$styleable;->TwImageButton:[I

    .line 20989
    const/16 v0, 0x8

    new-array v0, v0, [I

    fill-array-data v0, :array_1

    sput-object v0, Lcom/sec/android/app/camera/R$styleable;->TwIndicatorBattery:[I

    .line 21123
    const/4 v0, 0x5

    new-array v0, v0, [I

    fill-array-data v0, :array_2

    sput-object v0, Lcom/sec/android/app/camera/R$styleable;->TwIndicatorGPS:[I

    .line 21209
    const/4 v0, 0x2

    new-array v0, v0, [I

    fill-array-data v0, :array_3

    sput-object v0, Lcom/sec/android/app/camera/R$styleable;->TwIndicatorStorage:[I

    .line 21254
    const/4 v0, 0x3

    new-array v0, v0, [I

    fill-array-data v0, :array_4

    sput-object v0, Lcom/sec/android/app/camera/R$styleable;->TwSideMenu:[I

    .line 21327
    const/16 v0, 0xa

    new-array v0, v0, [I

    fill-array-data v0, :array_5

    sput-object v0, Lcom/sec/android/app/camera/R$styleable;->TwSlider:[I

    return-void

    .line 20684
    :array_0
    .array-data 0x4
        0x0t 0x0t 0x1t 0x7ft
        0x1t 0x0t 0x1t 0x7ft
        0x2t 0x0t 0x1t 0x7ft
        0x3t 0x0t 0x1t 0x7ft
        0x4t 0x0t 0x1t 0x7ft
        0x5t 0x0t 0x1t 0x7ft
        0x6t 0x0t 0x1t 0x7ft
        0x7t 0x0t 0x1t 0x7ft
        0x8t 0x0t 0x1t 0x7ft
        0x9t 0x0t 0x1t 0x7ft
        0xat 0x0t 0x1t 0x7ft
        0xbt 0x0t 0x1t 0x7ft
        0xct 0x0t 0x1t 0x7ft
        0xdt 0x0t 0x1t 0x7ft
        0xet 0x0t 0x1t 0x7ft
        0xft 0x0t 0x1t 0x7ft
        0x10t 0x0t 0x1t 0x7ft
        0x11t 0x0t 0x1t 0x7ft
    .end array-data

    .line 20989
    :array_1
    .array-data 0x4
        0x12t 0x0t 0x1t 0x7ft
        0x13t 0x0t 0x1t 0x7ft
        0x14t 0x0t 0x1t 0x7ft
        0x15t 0x0t 0x1t 0x7ft
        0x16t 0x0t 0x1t 0x7ft
        0x17t 0x0t 0x1t 0x7ft
        0x18t 0x0t 0x1t 0x7ft
        0x19t 0x0t 0x1t 0x7ft
    .end array-data

    .line 21123
    :array_2
    .array-data 0x4
        0x1at 0x0t 0x1t 0x7ft
        0x1bt 0x0t 0x1t 0x7ft
        0x1ct 0x0t 0x1t 0x7ft
        0x1dt 0x0t 0x1t 0x7ft
        0x1et 0x0t 0x1t 0x7ft
    .end array-data

    .line 21209
    :array_3
    .array-data 0x4
        0x1ft 0x0t 0x1t 0x7ft
        0x20t 0x0t 0x1t 0x7ft
    .end array-data

    .line 21254
    :array_4
    .array-data 0x4
        0x2bt 0x0t 0x1t 0x7ft
        0x2ct 0x0t 0x1t 0x7ft
        0x2dt 0x0t 0x1t 0x7ft
    .end array-data

    .line 21327
    :array_5
    .array-data 0x4
        0x21t 0x0t 0x1t 0x7ft
        0x22t 0x0t 0x1t 0x7ft
        0x23t 0x0t 0x1t 0x7ft
        0x24t 0x0t 0x1t 0x7ft
        0x25t 0x0t 0x1t 0x7ft
        0x26t 0x0t 0x1t 0x7ft
        0x27t 0x0t 0x1t 0x7ft
        0x28t 0x0t 0x1t 0x7ft
        0x29t 0x0t 0x1t 0x7ft
        0x2at 0x0t 0x1t 0x7ft
    .end array-data
.end method

.method public constructor <init>()V
    .locals 0

    .prologue
    .line 20639
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
mummyApp.controller('mainCtrl' , function($scope) {

	//messege to show which view your on
	$scope.title = "Table of Contents";
	$scope.table = [

	{"name": "Whoa, Mummy!"},
	{"name": "Mummy Making"},
	{"name": "Natural Mummies"},
	{"name": "Man-made Mummies"},
	{"name": "How To Make a Mummy"},
	{"name": "Tomb of Treasures"},
	{"name": "A Mummy's Curse"},
	{"name": "Animal Wraps"},
	{"name": "Lovely Lady Mummy"},
	{"name": "Mummies Today"},
	{"name": "Secrets Unwrapped"},
	{"name": "Glossary"},

	];

$scope.CurrChapter = null;

function setCurrChapter(chapter) {
	$scope.setCurrChapter = chapter;
}

function isCurrChapter(chapter) {
	return $scope.currChapter != null && chapter.name === $scope.currChapter.name;
}

//Make available to the view via $scope
$scope.setCurrChapter = setCurrChapter;
$scope.isCurrChapter =isCurrChapter;

});


text:
package quasar

import slamdata.Predef._

import quasar.RenderTree.ops._
import quasar.api.ColumnType
import quasar.common.{CPath, CPathField}

import scala.math.Ordering

import scalaz.{Equal, Order, Show}
import scalaz.std.list._
import scalaz.std.map._
import scalaz.std.option._
import scalaz.std.set._
import scalaz.std.string._
import scalaz.std.tuple._
import scalaz.syntax.equal._
import scalaz.syntax.show._

import shims._

sealed trait ScalarStage extends Product with Serializable

object ScalarStage extends ScalarStageInstances {

  /** Stages that refer to their input exactly once. */
  sealed trait Focused extends ScalarStage

  /**
   * Wraps the input to the stage in a singleton object at key `name`, adding
   * another layer of structure.
   */
  final case class Wrap(name: String) extends Focused

  /**
   *`Masks` represents the disjunction of the provided `masks`. An empty map indicates
   * that all values should be dropped. Removes all values which are not in one of the
   * path/type designations. The inner set is assumed to be non-empty.
   */
  final case class Mask(masks: Map[CPath, Set[ColumnType]]) extends Focused

  /**
   * Pivots the indices and keys out of arrays and objects, respectively.
   *
   * `idStatus` determines how values are returned:
   *   - `IncludeId` wraps the id/value pair in a two element array.
   *   - `IdOnly` returns the id unwrapped.
   *   - `ExcludeId` returns the value unwrapped.
   *
   * No values outside of the pivot locus should be retained.
   */
  final case class Pivot(status: IdStatus, structure: ColumnType.Vector)
      extends Focused

  /**
   * Extracts the value at `path`, eliminating all surrounding structure.
   */
  final case class Project(path: CPath) extends Focused

  /**
   * Applies the provided `List[Focused]` to each tupled `CPathField`
   * projection in the `Map` values. Then cartesians those results, wrapping them in the
   * `CPathField` map key.
   */
  final case class Cartesian(cartouches: Map[CPathField, (CPathField, List[Focused])])
      extends ScalarStage
}

sealed abstract class ScalarStageInstances {
  import ScalarStage._

  implicit def scalarStageEqual[S <: ScalarStage]: Equal[S] =
    Equal.equal(equal)

  implicit def scalarStageRenderTree[S <: ScalarStage]: RenderTree[S] =
    RenderTree.make(asRenderedTree)

  implicit def scalarStageShow[S <: ScalarStage]: Show[S] =
    RenderTree.toShow

  ////

  private implicit val columnTypeOrdering: Ordering[ColumnType] =
    Order[ColumnType].toScalaOrdering

  private def equal(x: ScalarStage, y: ScalarStage): Boolean =
    (x, y) match {
      case (Wrap(n1), Wrap(n2)) => n1 === n2
      case (Mask(m1), Mask(m2)) => m1 === m2
      case (Pivot(s1, t1), Pivot(s2, t2)) => s1 === s2 && t1 === t2
      case (Project(p1), Project(p2)) => p1 === p2
      case (Cartesian(c1), Cartesian(c2)) => c1 === c2
      case _ => false
    }

  private def asRenderedTree(ss: ScalarStage): RenderedTree =
    ss match {
      case Wrap(n) => Terminal(List("Wrap"), some(n))

      case Mask(m) =>
        NonTerminal(List("Mask"), none, m.toList map {
          case (p, types) if types === ColumnType.Top =>
            Terminal(List(s"Column[$p]"), some("⊤"))

          case (p, types) =>
            Terminal(List(s"Column[$p]"), some(types.toList.sorted.mkString(", ")))
        })

      case Pivot(s, t) => Terminal(List("Pivot"), some(s"${s.shows}, ${t.shows}"))

      case Project(p) => Terminal(List("Project"), some(p.shows))

      case Cartesian(cs) =>
        val stringified = cs map { case (t, (s, v)) => (t.toString, (s.toString, v)) }
        NonTerminal(List("Cartesian"), none, stringified.render.children)
    }
}


text:
About
-----
Extension for configuring Flask from environment variables.

Requirements
------------
 * Flask

Installation
------------

::

    pip install flask-envconfig

Usage
-----
Simple usage:

::

    from flask import Flask
    from flask.ext.envconfig import EnvConfig

    app = Flask(__name__)
    env = EnvConfig(app)

Or, for the application factory pattern:

::

    env = EnvConfig()
    # At a later time
    env.init_app(app)

Now set your configuration variables in your shell, .env file or whatever:

::

    FLASK_DEBUG=True
    FLASK_SECRET_KEY="Something_or_the_other"

By default only environments variables prefixed with FLASK\_ are processed and added to app.config. The extension strips off the prefix so FLASK_DEBUG becomes app.config['DEBUG'] and so forth.
The extension understands "True" to mean True, "False" to mean False and "None" to mean None. It also understands lists, tuples and dicts and numbers.

::

    FLASK_TRUE=True
    FLASK_FALSE=False
    FLASK_NONE=None
    FLASK_INTEGER=1
    FLASK_FLOAT=1.1
    FLASK_STRING="This is a string"
    FLASK_LIST="['a', 'b', 'c']"
    FLASK_TUPLE="('a', 'b', 'c')"
    FLASK_DICT="{'a': 1, 'b': 6}"

The prefix can be changed if so desired:

::

    EnvConfig(app, 'MYPREFIX_')

Or

::

    env = EnvConfig()
    env.init_app(app, 'MYPREFIX_')


text:
package org.apache.tinkerpop.gremlin.process.traversal.step.map;

import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.process.computer.MapReduce;
import org.apache.tinkerpop.gremlin.process.computer.traversal.TraversalVertexProgram;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.step.MapReducer;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.BulkSet;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.ReducingBarrierStep;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.util.TraverserSet;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalMatrix;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;

import java.io.Serializable;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Supplier;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public final class GroupStep<S, K, V, R> extends ReducingBarrierStep<S, Map<K, R>> implements MapReducer, TraversalParent {

    private char state = 'k';

    private Traversal.Admin<S, K> keyTraversal = null;
    private Traversal.Admin<S, V> valueTraversal = null;
    private Traversal.Admin<Collection<V>, R> reduceTraversal = null;

    public GroupStep(final Traversal.Admin traversal) {
        super(traversal);
        this.setSeedSupplier((Supplier) new GroupMapSupplier());
        this.setBiFunction((BiFunction) new GroupBiFunction());
    }

    @Override
    public <A, B> List<Traversal.Admin<A, B>> getLocalChildren() {
        final List<Traversal.Admin<A, B>> children = new ArrayList<>(3);
        if (null != this.keyTraversal)
            children.add((Traversal.Admin) this.keyTraversal);
        if (null != this.valueTraversal)
            children.add((Traversal.Admin) this.valueTraversal);
        if (null != this.reduceTraversal)
            children.add((Traversal.Admin) this.reduceTraversal);
        return children;
    }

    public Traversal.Admin<Collection<V>, R> getReduceTraversal() {
        return this.reduceTraversal;
    }

    @Override
    public void addLocalChild(final Traversal.Admin<?, ?> kvrTraversal) {
        if ('k' == this.state) {
            this.keyTraversal = this.integrateChild(kvrTraversal);
            this.state = 'v';
        } else if ('v' == this.state) {
            this.valueTraversal = this.integrateChild(kvrTraversal);
            this.state = 'r';
        } else if ('r' == this.state) {
            this.reduceTraversal = this.integrateChild(kvrTraversal);
            this.state = 'x';
        } else {
            throw new IllegalStateException("The key, value, and reduce functions for group()-step have already been set");
        }
    }

    @Override
    public Set<TraverserRequirement> getRequirements() {
        return this.getSelfAndChildRequirements(TraverserRequirement.SIDE_EFFECTS, TraverserRequirement.BULK);
    }

    @Override
    public GroupStep<S, K, V, R> clone() {
        final GroupStep<S, K, V, R> clone = (GroupStep<S, K, V, R>) super.clone();
        if (null != this.keyTraversal)
            clone.keyTraversal = clone.integrateChild(this.keyTraversal.clone());
        if (null != this.valueTraversal)
            clone.valueTraversal = clone.integrateChild(this.valueTraversal.clone());
        if (null != this.reduceTraversal)
            clone.reduceTraversal = clone.integrateChild(this.reduceTraversal.clone());
        return clone;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        for (final Traversal.Admin traversal : this.getLocalChildren()) {
            result ^= traversal.hashCode();
        }
        return result;
    }

    @Override
    public MapReduce<K, Collection<V>, K, R, Map<K, R>> getMapReduce() {
        return new GroupMapReduce<>(this);
    }

    @Override
    public Traverser<Map<K, R>> processNextStart() {
        if (this.byPass) {
            final Traverser.Admin<S> traverser = this.starts.next();
            final Object[] kvPair = new Object[]{TraversalUtil.applyNullable(traverser, (Traversal.Admin<S, Map>) this.keyTraversal), TraversalUtil.applyNullable(traverser, (Traversal.Admin<S, Map>) this.valueTraversal)};
            return traverser.asAdmin().split(kvPair, (Step) this);
        } else {
            return super.processNextStart();
        }
    }

    @Override
    public String toString() {
        return StringFactory.stepString(this, this.keyTraversal, this.valueTraversal, this.reduceTraversal);
    }

    ///////////

    private class GroupBiFunction implements BiFunction<Map<K, Collection<V>>, Traverser.Admin<S>, Map<K, Collection<V>>>, Serializable {

        private GroupBiFunction() {

        }

        @Override
        public Map<K, Collection<V>> apply(final Map<K, Collection<V>> mutatingSeed, final Traverser.Admin<S> traverser) {
            final K key = TraversalUtil.applyNullable(traverser, GroupStep.this.keyTraversal);
            final V value = TraversalUtil.applyNullable(traverser, GroupStep.this.valueTraversal);
            Collection<V> values = mutatingSeed.get(key);
            if (null == values) {
                values = new BulkSet<>();
                mutatingSeed.put(key, values);
            }
            TraversalHelper.addToCollectionUnrollIterator(values, value, traverser.bulk());
            return mutatingSeed;
        }
    }

    //////////

    private class GroupMap extends HashMap<K, Collection<V>> implements FinalGet<Map<K, R>> {

        @Override
        public Map<K, R> getFinal() {
            if (null == GroupStep.this.reduceTraversal)
                return (Map<K, R>) this;
            else {
                final Map<K, R> reduceMap = new HashMap<>();
                this.forEach((k, vv) -> reduceMap.put(k, TraversalUtil.applyNullable(vv, GroupStep.this.reduceTraversal)));
                return reduceMap;
            }
        }
    }

    private class GroupMapSupplier implements Supplier<GroupMap>, Serializable {

        private GroupMapSupplier() {
        }

        @Override
        public GroupMap get() {
            return new GroupMap();
        }
    }

    ///////////

    public static final class GroupMapReduce<K, V, R> implements MapReduce<K, Collection<V>, K, R, Map<K, R>> {

        public static final String GROUP_BY_STEP_STEP_ID = "gremlin.groupStep.stepId";

        private String groupStepId;
        private Traversal.Admin<Collection<V>, R> reduceTraversal;

        private GroupMapReduce() {

        }

        public GroupMapReduce(final GroupStep<?, K, V, R> step) {
            this.groupStepId = step.getId();
            this.reduceTraversal = step.getReduceTraversal();
        }

        @Override
        public void storeState(final Configuration configuration) {
            MapReduce.super.storeState(configuration);
            configuration.setProperty(GROUP_BY_STEP_STEP_ID, this.groupStepId);
        }

        @Override
        public void loadState(final Graph graph, final Configuration configuration) {
            this.groupStepId = configuration.getString(GROUP_BY_STEP_STEP_ID);
            this.reduceTraversal = ((GroupStep) new TraversalMatrix<>(TraversalVertexProgram.getTraversal(graph, configuration)).getStepById(this.groupStepId)).getReduceTraversal();
        }

        @Override
        public boolean doStage(final Stage stage) {
            return !stage.equals(Stage.COMBINE);
        }

        @Override
        public void map(final Vertex vertex, final MapEmitter<K, Collection<V>> emitter) {
            vertex.<TraverserSet<Object[]>>property(TraversalVertexProgram.HALTED_TRAVERSERS).ifPresent(traverserSet -> traverserSet.forEach(traverser -> {
                final Object[] objects = traverser.get();
                if (objects[1] instanceof Collection)
                    emitter.emit((K) objects[0], (Collection<V>) objects[1]);
                else {
                    final List<V> collection = new ArrayList<>();
                    collection.add((V) objects[1]);
                    emitter.emit((K) objects[0], collection);
                }
            }));
        }

        @Override
        public void reduce(final K key, final Iterator<Collection<V>> values, final ReduceEmitter<K, R> emitter) {
            final Set<V> set = new BulkSet<>();
            values.forEachRemaining(set::addAll);
            emitter.emit(key, TraversalUtil.applyNullable(set, this.reduceTraversal));
        }

        @Override
        public Map<K, R> generateFinalResult(final Iterator<KeyValue<K, R>> keyValues) {
            final Map<K, R> map = new HashMap<>();
            keyValues.forEachRemaining(keyValue -> map.put(keyValue.getKey(), keyValue.getValue()));
            return map;
        }

        @Override
        public String getMemoryKey() {
            return REDUCING;
        }

        @Override
        public GroupMapReduce<K, V, R> clone() {
            try {
                final GroupMapReduce<K, V, R> clone = (GroupMapReduce<K, V, R>) super.clone();
                if (null != clone.reduceTraversal)
                    clone.reduceTraversal = this.reduceTraversal.clone();
                return clone;
            } catch (final CloneNotSupportedException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }

        @Override
        public String toString() {
            return StringFactory.mapReduceString(this, this.getMemoryKey());
        }
    }

}


text:
package hudson.security;

import hudson.ExtensionList;
import hudson.cli.CLI;
import hudson.cli.CLICommand;
import jenkins.model.Jenkins;
import jenkins.security.SecurityListener;
import jenkins.security.SpySecurityListener;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.io.input.NullInputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.springframework.dao.DataAccessException;

import java.io.ByteArrayOutputStream;
import java.util.Arrays;

import static org.junit.Assert.*;

/**
 * @author Kohsuke Kawaguchi
 */
@SuppressWarnings("deprecation") // Remoting-based CLI usages intentional
public class CliAuthenticationTest {

    @Rule
    public JenkinsRule j = new JenkinsRule();

    private SpySecurityListener spySecurityListener;

    @Before
    public void prepareListeners(){
        //TODO simplify using #3021 into ExtensionList.lookupSingleton(SpySecurityListener.class)
        this.spySecurityListener = ExtensionList.lookup(SecurityListener.class).get(SpySecurityListenerImpl.class);
    }

    @Test
    public void test() throws Exception {
        // dummy security realm that authenticates when username==password
        j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

        successfulCommand("test","--username","abc","--password","abc");
    }

    private void successfulCommand(String... args) throws Exception {
        assertEquals(0, command(args));
    }

    private void unsuccessfulCommand(String... args) throws Exception {
        assertNotEquals(0, command(args));
    }

    private int command(String... args) throws Exception {
        try (CLI cli = new CLI(j.getURL())) {
            return cli.execute(args);
        }
    }

    private String commandAndOutput(String... args) throws Exception {
        try (CLI cli = new CLI(j.getURL())) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            cli.execute(Arrays.asList(args), new NullInputStream(0), baos, baos);
            return baos.toString();
        }
    }

    @TestExtension
    public static class TestCommand extends CLICommand {
        @Override
        public String getShortDescription() {
            return "test command";
        }

        @Override
        protected int run() throws Exception {
            Authentication auth = Jenkins.getAuthentication();
            assertNotSame(Jenkins.ANONYMOUS,auth);
            assertEquals("abc", auth.getName());
            return 0;
        }
    }

    @TestExtension
    public static class AnonymousCommand extends CLICommand {
        @Override
        public String getShortDescription() {
            return "makes sure that the command is running as anonymous user";
        }

        @Override
        protected int run() throws Exception {
            Authentication auth = Jenkins.getAuthentication();
            assertSame(Jenkins.ANONYMOUS,auth);
            return 0;
        }
    }

    @Test
    @For({hudson.cli.LoginCommand.class, hudson.cli.LogoutCommand.class, hudson.cli.ClientAuthenticationCache.class})
    public void login() throws Exception {
        j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

        successfulCommand("login","--username","abc","--password","abc");
        spySecurityListener.authenticatedCalls.assertLastEventIsAndThenRemoveIt(userDetails -> userDetails.getUsername().equals("abc"));
        spySecurityListener.loggedInCalls.assertLastEventIsAndThenRemoveIt("abc");

        successfulCommand("test"); // now we can run without an explicit credential
        spySecurityListener.authenticatedCalls.assertLastEventIsAndThenRemoveIt(userDetails -> userDetails.getUsername().equals("abc"));
        spySecurityListener.loggedInCalls.assertNoNewEvents();

        successfulCommand("logout");
        spySecurityListener.authenticatedCalls.assertLastEventIsAndThenRemoveIt(userDetails -> userDetails.getUsername().equals("abc"));
        spySecurityListener.loggedOutCalls.assertLastEventIsAndThenRemoveIt("abc");

        successfulCommand("anonymous"); // now we should run as anonymous
        spySecurityListener.authenticatedCalls.assertNoNewEvents();
        spySecurityListener.failedToAuthenticateCalls.assertNoNewEvents();
        spySecurityListener.loggedInCalls.assertNoNewEvents();
        spySecurityListener.loggedOutCalls.assertNoNewEvents();
    }

    @Test
    @Issue("JENKINS-27026")
    public void loginAsALegitimateUserButUnknown() throws Exception {
        j.jenkins.setSecurityRealm(new MockSecurityRealm());

        String username = "alice";

        unsuccessfulCommand("login","--username",username,"--password","badCredentials");
        spySecurityListener.failedToAuthenticateCalls.assertLastEventIsAndThenRemoveIt(username);
        spySecurityListener.failedToLogInCalls.assertNoNewEvents();
        spySecurityListener.authenticatedCalls.assertNoNewEvents();
        spySecurityListener.loggedInCalls.assertNoNewEvents();
//        spySecurityListener.failedToLogInCalls.assertLastEventIsAndThenRemoveIt(username);

        unsuccessfulCommand("login","--username",username,"--password","usernameNotFound");
        spySecurityListener.failedToAuthenticateCalls.assertLastEventIsAndThenRemoveIt(username);
        spySecurityListener.failedToLogInCalls.assertNoNewEvents();
        spySecurityListener.authenticatedCalls.assertNoNewEvents();
        spySecurityListener.loggedInCalls.assertNoNewEvents();
//        spySecurityListener.failedToLogInCalls.assertLastEventIsAndThenRemoveIt(username);

        unsuccessfulCommand("login","--username",username,"--password","mayOrMayNotExist");
        spySecurityListener.failedToAuthenticateCalls.assertLastEventIsAndThenRemoveIt(username);
        spySecurityListener.failedToLogInCalls.assertNoNewEvents();
        spySecurityListener.authenticatedCalls.assertNoNewEvents();
        spySecurityListener.loggedInCalls.assertNoNewEvents();
//        spySecurityListener.failedToLogInCalls.assertLastEventIsAndThenRemoveIt(username);

        // in case of authentication that throw a DataAccessException (see impersonatingUserDetailsService)
        // the CLI login command does not work as expected
        unsuccessfulCommand("login","--username",username,"--password","dataAccess");
        spySecurityListener.failedToAuthenticateCalls.assertNoNewEvents();
        spySecurityListener.failedToLogInCalls.assertNoNewEvents();
        spySecurityListener.authenticatedCalls.assertNoNewEvents();
        spySecurityListener.loggedInCalls.assertNoNewEvents();
//        spySecurityListener.failedToAuthenticateCalls.assertLastEventIsAndThenRemoveIt(username);
//        spySecurityListener.failedToLogInCalls.assertLastEventIsAndThenRemoveIt(username);
    }

    private static class MockSecurityRealm extends AbstractPasswordBasedSecurityRealm {
        @Override protected UserDetails authenticate(String username, String password) throws AuthenticationException {
            switch(password){
                case "badCredentials": throw new BadCredentialsException("BadCredentials requested");
                case "usernameNotFound": throw new UsernameNotFoundException("UsernameNotFound requested");
                case "mayOrMayNotExist": throw new UserMayOrMayNotExistException("MayOrMayNotExist requested");
                case "dataAccess": throw new DataAccessException("DataAccess requested"){};
                default:
                    return new User(
                        username, password,
                        true, true, true,
                        new GrantedAuthority[]{SecurityRealm.AUTHENTICATED_AUTHORITY}
                    );
            }
        }

        @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            return null;
        }

        @Override public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
            return null;
        }
    }

    /**
     * Login failure shouldn't reveal information about the existence of user
     */
    @Test
    public void security110() throws Exception {
        HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false,false,null);
        j.jenkins.setSecurityRealm(realm);
        j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
        realm.createAccount("alice","alice");

        String out1 = commandAndOutput("help", "--username", "alice", "--password", "bogus");
        String out2 = commandAndOutput("help", "--username", "bob", "--password", "bogus");

        assertTrue(out1.contains("Bad Credentials. Search the server log for"));
        assertTrue(out2.contains("Bad Credentials. Search the server log for"));
    }

    @TestExtension
    public static class SpySecurityListenerImpl extends SpySecurityListener {}
}


text:
package javax.accessibility;

import java.util.Locale;

/**
 * The role of an accessible object. For example, this could be "button" or
 * "table". This strongly typed "enumeration" supports localized strings. If
 * the constants of this class are not adequate, new ones may be added in a
 * similar matter, while avoiding a public constructor.
 *
 * @author Eric Blake (ebb9@email.byu.edu)
 * @since 1.2
 * @status updated to 1.4
 */
public class AccessibleRole extends AccessibleBundle
{
  /** The object alerts the user about something. */
  public static final AccessibleRole ALERT
    = new AccessibleRole("alert");

  /** The header for a column of data. */
  public static final AccessibleRole COLUMN_HEADER
    = new AccessibleRole("column header");

  /**
   * The object can be drawn into, and traps events.
   *
   * @see #FRAME
   * @see #GLASS_PANE
   * @see #LAYERED_PANE
   */
  public static final AccessibleRole CANVAS
    = new AccessibleRole("canvas");

  /**
   * A list of choices, which may optionally allow the user to create a new
   * choice.
   */
  public static final AccessibleRole COMBO_BOX
    = new AccessibleRole("combo box");

  /**
   * An iconified frame in a desktop.
   *
   * @see #DESKTOP_PANE
   * @see #INTERNAL_FRAME
   */
  public static final AccessibleRole DESKTOP_ICON
    = new AccessibleRole("desktop icon");

  /**
   * A frame-like object clipped by a desktop pane.
   *
   * @see #DESKTOP_ICON
   * @see #DESKTOP_PANE
   * @see #FRAME
   */
  public static final AccessibleRole INTERNAL_FRAME
    = new AccessibleRole("internal frame");

  /**
   * A pane which supports internal frames and their icons.
   *
   * @see #DESKTOP_ICON
   * @see #INTERNAL_FRAME
   */
  public static final AccessibleRole DESKTOP_PANE
    = new AccessibleRole("desktop pane");

  /**
   * A specialized pane for use in a dialog.
   *
   * @see #DIALOG
   */
  public static final AccessibleRole OPTION_PANE
    = new AccessibleRole("option pane");

  /**
   * A top level window with no title or border.
   *
   * @see #FRAME
   * @see #DIALOG
   */
  public static final AccessibleRole WINDOW
    = new AccessibleRole("window");

  /**
   * A top level window with title, menu bar, border, and so forth. It is
   * often the primary window of an application.
   *
   * @see #DIALOG
   * @see #CANVAS
   * @see #WINDOW
   */
  public static final AccessibleRole FRAME
    = new AccessibleRole("frame");

  /**
   * A top level window title bar and border. It is limited compared to a
   * frame, and is often a secondary window.
   *
   * @see #FRAME
   * @see #WINDOW
   */
  public static final AccessibleRole DIALOG
    = new AccessibleRole("dialog");

  /** A specialized dialog for choosing a color. */
  public static final AccessibleRole COLOR_CHOOSER
    = new AccessibleRole("color chooser");

  /**
   * A pane for navigating through directories.
   *
   * @see #FILE_CHOOSER
   */
  public static final AccessibleRole DIRECTORY_PANE
    = new AccessibleRole("directory pane");

  /**
   * A specialized dialog that allows a user to select a file.
   *
   * @see #DIRECTORY_PANE
   */
  public static final AccessibleRole FILE_CHOOSER
    = new AccessibleRole("file chooser");

  /** An object to fill space between other components. */
  public static final AccessibleRole FILLER
    = new AccessibleRole("filler");

  /** A hypertext anchor. */
  public static final AccessibleRole HYPERLINK
    = new AccessibleRole("hyperlink");

  /** A small picture to decorate components. */
  public static final AccessibleRole ICON
    = new AccessibleRole("icon");

  /** An object to label something in a graphic interface. */
  public static final AccessibleRole LABEL
    = new AccessibleRole("label");

  /**
   * A specialized pane with a glass pane and layered pane as children.
   *
   * @see #GLASS_PANE
   * @see #LAYERED_PANE
   */
  public static final AccessibleRole ROOT_PANE
    = new AccessibleRole("root pane");

  /**
   * A pane guaranteed to be painted on top of panes beneath it.
   *
   * @see #ROOT_PANE
   * @see #LAYERED_PANE
   */
  public static final AccessibleRole GLASS_PANE
    = new AccessibleRole("glass pane");

  /**
   * A specialized pane that allows drawing children in layers. This is often
   * used in menus and other visual components.
   *
   * @see #ROOT_PANE
   * @see #GLASS_PANE
   */
  public static final AccessibleRole LAYERED_PANE
    = new AccessibleRole("layered pane");

  /**
   * An object which presents a list of items for selection. Often contained
   * in a scroll pane.
   *
   * @see #SCROLL_PANE
   * @see #LIST_ITEM
   */
  public static final AccessibleRole LIST
    = new AccessibleRole("list");

  /**
   * An object which represents an item in a list. Often contained in a scroll
   * pane.
   *
   * @see #SCROLL_PANE
   * @see #LIST
   */
  public static final AccessibleRole LIST_ITEM
    = new AccessibleRole("list item");

  /**
   * An object usually at the top of a frame to list available menus.
   *
   * @see #MENU
   * @see #POPUP_MENU
   * @see #LAYERED_PANE
   */
  public static final AccessibleRole MENU_BAR
    = new AccessibleRole("menu bar");

  /**
   * A temporary window with a menu of options, which hides on selection.
   *
   * @see #MENU
   * @see #MENU_ITEM
   */
  public static final AccessibleRole POPUP_MENU
    = new AccessibleRole("popup menu");

  /**
   * An object usually in a menu bar which contains a list of actions to
   * perform. Such actions are usually associated with menu items or submenus.
   *
   * @see #MENU_BAR
   * @see #MENU_ITEM
   * @see #SEPARATOR
   * @see #RADIO_BUTTON
   * @see #CHECK_BOX
   * @see #POPUP_MENU
   */
  public static final AccessibleRole MENU
    = new AccessibleRole("menu");

  /**
   * An object usually in a menu with an action available for the user.
   *
   * @see #MENU_BAR
   * @see #SEPARATOR
   * @see #POPUP_MENU
   */
  public static final AccessibleRole MENU_ITEM
    = new AccessibleRole("menu item");

  /**
   * An object usually in a menu which separates logical sections of items.
   *
   * @see #MENU
   * @see #MENU_ITEM
   */
  public static final AccessibleRole SEPARATOR
    = new AccessibleRole("separator");

  /**
   * An object which presents a series of panels, usually via tabs along the
   * top. Children are all page tabs.
   *
   * @see #PAGE_TAB
   */
  public static final AccessibleRole PAGE_TAB_LIST
    = new AccessibleRole("page tab list");

  /**
   * An object in a page tab list, which contains the panel to display when
   * selected from the list.
   *
   * @see #PAGE_TAB_LIST
   */
  public static final AccessibleRole PAGE_TAB
    = new AccessibleRole("page tab");

  /** A generic container to group objects. */
  public static final AccessibleRole PANEL
    = new AccessibleRole("panel");

  /** An object used to track amount of a task that has completed. */
  public static final AccessibleRole PROGRESS_BAR
    = new AccessibleRole("progress bar");

  /** An object for passwords which should not be shown to the user. */
  public static final AccessibleRole PASSWORD_TEXT
    = new AccessibleRole("password text");

  /**
   * An object that can be manipulated to do something.
   *
   * @see #CHECK_BOX
   * @see #TOGGLE_BUTTON
   * @see #RADIO_BUTTON
   */
  public static final AccessibleRole PUSH_BUTTON
    = new AccessibleRole("push button");

  /**
   * A specialized button which can be on or off, with no separate indicator.
   *
   * @see #PUSH_BUTTON
   * @see #CHECK_BOX
   * @see #RADIO_BUTTON
   */
  public static final AccessibleRole TOGGLE_BUTTON
    = new AccessibleRole("toggle button");

  /**
   * A choice which can be on or off, and has a separate indicator.
   *
   * @see #PUSH_BUTTON
   * @see #TOGGLE_BUTTON
   * @see #RADIO_BUTTON
   */
  public static final AccessibleRole CHECK_BOX
    = new AccessibleRole("check box");

  /**
   * A specialized choice which toggles radio buttons in the group when it
   * is selected.
   *
   * @see #PUSH_BUTTON
   * @see #TOGGLE_BUTTON
   * @see #CHECK_BOX
   */
  public static final AccessibleRole RADIO_BUTTON
    = new AccessibleRole("radio button");

  /** The header for a row of data. */
  public static final AccessibleRole ROW_HEADER
    = new AccessibleRole("row header");

  /**
   * An object which allows an incremental view of a larger pane.
   *
   * @see #SCROLL_BAR
   * @see #VIEWPORT
   */
  public static final AccessibleRole SCROLL_PANE
    = new AccessibleRole("scroll pane");

  /**
   * An object which allows selection of the view in a scroll pane.
   *
   * @see #SCROLL_PANE
   */
  public static final AccessibleRole SCROLL_BAR
    = new AccessibleRole("scroll bar");

  /**
   * An object which represents the visual section in a scroll pane.
   *
   * @see #SCROLL_PANE
   */
  public static final AccessibleRole VIEWPORT
    = new AccessibleRole("viewport");

  /** An object which allows selection in a bounded range. */
  public static final AccessibleRole SLIDER
    = new AccessibleRole("slider");

  /**
   * A specialized pane which presents two other panels, and can often adjust
   * the divider between them.
   */
  public static final AccessibleRole SPLIT_PANE
    = new AccessibleRole("split pane");

  /** An object for presenting data in rows and columns. */
  public static final AccessibleRole TABLE
    = new AccessibleRole("table");

  /**
   * An object which represents text, usually editable by the user.
   *
   * @see #LABEL
   */
  public static final AccessibleRole TEXT
    = new AccessibleRole("text");

  /**
   * An object which represents a hierachical view of data. Subnodes can
   * often be expanded or collapsed.
   */
  public static final AccessibleRole TREE
    = new AccessibleRole("tree");

  /** A bar or pallete with buttons for common actions in an application. */
  public static final AccessibleRole TOOL_BAR
    = new AccessibleRole("tool bar");

  /**
   * An object which provides information about another object. This is often
   * displayed as a "help bubble" when a mouse hovers over the other object.
   */
  public static final AccessibleRole TOOL_TIP
    = new AccessibleRole("tool tip");

  /**
   * An AWT component with nothing else known about it.
   *
   * @see #SWING_COMPONENT
   * @see #UNKNOWN
   */
  public static final AccessibleRole AWT_COMPONENT
    = new AccessibleRole("AWT component");

  /**
   * A swing component with nothing else known about it.
   *
   * @see #AWT_COMPONENT
   * @see #UNKNOWN
   */
  public static final AccessibleRole SWING_COMPONENT
    = new AccessibleRole("SWING component");

  /**
   * An accessible object whose role is unknown.
   *
   * @see #AWT_COMPONENT
   * @see #SWING_COMPONENT
   */
  public static final AccessibleRole UNKNOWN
    = new AccessibleRole("unknown");

  /** A component with multiple labels of status information. */
  public static final AccessibleRole STATUS_BAR
    = new AccessibleRole("statusbar");

  /** A component which allows editing of Date and Time objects. */
  public static final AccessibleRole DATE_EDITOR
    = new AccessibleRole("dateeditor");

  /** A component with spinner arrows for simple numbers. */
  public static final AccessibleRole SPIN_BOX
    = new AccessibleRole("spinbox");

  /** A component for choosing fonts and their attributes. */
  public static final AccessibleRole FONT_CHOOSER
    = new AccessibleRole("fontchooser");

  /** A component with a border to group other components. */
  public static final AccessibleRole GROUP_BOX
    = new AccessibleRole("groupbox");

  /**
   * A formula for creating a value.
   *
   * @since 1.5
   */
  public static final AccessibleRole EDITBAR
    = new AccessibleRole("editbar");

  /**
   * A text-based footer.
   *
   * @since 1.5
   */
  public static final AccessibleRole FOOTER
    = new AccessibleRole("footer");

  /**
   * A text-based header.
   *
   * @since 1.5
   */
  public static final AccessibleRole HEADER
    = new AccessibleRole("header");

  /**
   * A text-based paragraph.
   *
   * @since 1.5
   */
  public static final AccessibleRole PARAGRAPH
    = new AccessibleRole("paragraph");

  /**
   * Represents the current level of progress on a particular task.
   *
   * @since 1.5
   */
  public static final AccessibleRole PROGRESS_MONITOR
    = new AccessibleRole("progress monitor");

  /**
   * A ruler is a method of measuring the distance between two
   * points.
   *
   * @since 1.5
   */
  public static final AccessibleRole RULER
    = new AccessibleRole("ruler");

  /**
   * Create a new constant with a locale independent key. Follow the example,
   * keep the constructor private and make public constants instead.
   *
   * @param key the name of the role
   * @see #toDisplayString(String, Locale)
   */
  protected AccessibleRole(String key)
  {
    this.key = key;
  }
} // class AccessibleRole


text:
package test.invocationcount.issue1719;

import org.testng.TestNG;
import org.testng.annotations.Test;
import test.SimpleBaseTest;

import static org.assertj.core.api.Assertions.assertThat;

public class IssueTest extends SimpleBaseTest {

  @Test
  public void testSuccessPercentageCalculation() {
    TestNG testng = create(TestclassSample.class);
    DummyReporter listener = new DummyReporter();
    testng.addListener(listener);
    testng.run();
    assertThat(listener.getFailures()).isEmpty();
    assertThat(listener.getSkip()).isEmpty();
    assertThat(listener.getSuccess()).isEmpty();
    assertThat(listener.getFailedWithinSuccessPercentage()).hasSize(5);
  }
}