text:
'''
Object for dealing with vertical simultaneities in a fast way w/o Chord's overhead.
'''
import collections
import unittest

from music21 import note
from music21 import tie
from music21 import chord
from music21 import environment
from music21 import exceptions21
#from music21 import key
from music21 import pitch

environLocal = environment.Environment("timespans.verticality")

class VerticalityException(exceptions21.TimespanException):
    pass

class Verticality(object):
    r'''
    A collection of information about elements that are sounding at a given
    offset or just finished at that offset or are continuing from before, etc..

    Create a timespan-stream from a score:

    >>> score = corpus.parse('bwv66.6')
    >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))

    Find the verticality at offset 6.5, or beat 2.5 of measure 2 (there's a one
    beat pickup)

    >>> verticality = tree.getVerticalityAt(6.5)
    >>> verticality
    <Verticality 6.5 {E3 D4 G#4 B4}>

    The representation of a verticality gives the pitches from lowest to
    highest (in sounding notes).

    A verticality knows its offset, but because elements might end at
    different times, it doesn't know its endTime

    >>> verticality.offset
    6.5
    >>> verticality.endTime
    Traceback (most recent call last):
    AttributeError: 'Verticality' object has no attribute 'endTime'

    However, we can find when the next verticality starts by looking at the
    nextVerticality

    >>> nv = verticality.nextVerticality
    >>> nv
    <Verticality 7.0 {A2 C#4 E4 A4}>
    >>> nv.offset
    7.0

    Or more simply:

    >>> verticality.nextStartOffset
    7.0

    (There is also a previousVerticality, but not a previousStartOffset)

    What we just demonstrated is actually very powerful: a Verticality keeps a
    record of exactly where it is in the timespanTree -- scores can be
    recreated with this information.

    Getting back to the task at hand, we can find all the elementTimespans (and
    from there the elements) that start at exactly 6.5.  There's one, it's a
    passing tone D in the tenor and it lastes from offset 6.5 to offset 7.0,
    with respect to the beginning of the score, not to the beginning of the
    measure.  That is to say, it's an eighth note

    >>> verticality.startTimespans
    (<ElementTimespan (6.5 to 7.0) <music21.note.Note D>>,)

    And we can get all the elementTimespans that were already sounding at the
    moment (that is to say, the non-passing tones):

    >>> verticality.overlapTimespans
    (<ElementTimespan (6.0 to 7.0) <music21.note.Note B>>,
     <ElementTimespan (6.0 to 7.0) <music21.note.Note G#>>,
     <ElementTimespan (6.0 to 7.0) <music21.note.Note E>>)

    And we can get all the things that stop right at this moment.  It's the E
    in the tenor preceding the passing tone D:

    >>> verticality.stopTimespans
    (<ElementTimespan (6.0 to 6.5) <music21.note.Note E>>,)
    '''

    ### CLASS VARIABLES ###

    __slots__ = (
        'timespanTree',
        'overlapTimespans',
        'startTimespans',
        'offset',
        'stopTimespans',
        )

    _DOC_ATTR = {
        'timespanTree': r'''
            Returns the timespanTree initially set.
            ''',
        'overlapTimespans': r'''
            Gets timespans overlapping the start offset of a verticality.

            >>> score = corpus.parse('bwv66.6')
            >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
            >>> verticality = tree.getVerticalityAt(0.5)
            >>> verticality
            <Verticality 0.5 {G#3 B3 E4 B4}>
            >>> verticality.overlapTimespans
            (<ElementTimespan (0.0 to 1.0) <music21.note.Note E>>,)
            ''',
        'startTimespans': r'''
            Gets the timespans starting at a verticality's start offset.

            >>> score = corpus.parse('bwv66.6')
            >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
            >>> verticality = tree.getVerticalityAt(1.0)
            >>> verticality
            <Verticality 1.0 {F#3 C#4 F#4 A4}>
            >>> for timespan in verticality.startTimespans:
            ...     timespan
            ...
            <ElementTimespan (1.0 to 2.0) <music21.note.Note A>>
            <ElementTimespan (1.0 to 2.0) <music21.note.Note F#>>
            <ElementTimespan (1.0 to 2.0) <music21.note.Note C#>>
            <ElementTimespan (1.0 to 2.0) <music21.note.Note F#>>
            ''',
        'offset': r'''
            Gets the start offset of a verticality.

            >>> score = corpus.parse('bwv66.6')
            >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
            >>> verticality = tree.getVerticalityAt(1.0)
            >>> verticality
            <Verticality 1.0 {F#3 C#4 F#4 A4}>
            >>> verticality.offset
            1.0
            ''',
        'stopTimespans': r'''
            Gets the timespans stopping at a verticality's start offset.

            >>> score = corpus.parse('bwv66.6')
            >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
            >>> verticality = tree.getVerticalityAt(1.0)
            >>> verticality
            <Verticality 1.0 {F#3 C#4 F#4 A4}>

            Note that none of the elements in the stopTimespans are listed in the repr for the Verticality

            >>> for timespan in verticality.stopTimespans:
            ...     timespan
            ...
            <ElementTimespan (0.0 to 1.0) <music21.note.Note E>>
            <ElementTimespan (0.5 to 1.0) <music21.note.Note B>>
            <ElementTimespan (0.5 to 1.0) <music21.note.Note B>>
            <ElementTimespan (0.5 to 1.0) <music21.note.Note G#>>
            ''',
    }

    ### INITIALIZER ###

    def __init__(
        self,
        offset=None,
        overlapTimespans=None,
        startTimespans=None,
        stopTimespans=None,
        timespanTree=None,
        ):
        from music21.timespans import trees
        prototype = (trees.TimespanTree, type(None))
        if not isinstance(timespanTree, prototype):
            raise VerticalityException("timespanTree %r is not a TimespanTree or None" % (timespanTree,))

        self.timespanTree = timespanTree
        self.offset = offset

        if not isinstance(startTimespans, tuple):
            raise VerticalityException("startTimespans must be a tuple, not %r" % startTimespans)
        if not isinstance(stopTimespans, (tuple, type(None))):
            raise VerticalityException("stopTimespans must be a tuple or None, not %r" % stopTimespans)
        if not isinstance(overlapTimespans, (tuple, type(None))):
            raise VerticalityException("overlapTimespans must be a tuple or None, not %r" % overlapTimespans)

        self.startTimespans = startTimespans
        self.stopTimespans = stopTimespans
        self.overlapTimespans = overlapTimespans

    ### SPECIAL METHODS ###

    def __repr__(self):
        sortedPitches = sorted(self.pitchSet)
        return '<{} {} {{{}}}>'.format(
            type(self).__name__,
            self.offset,
            ' '.join(x.nameWithOctave for x in sortedPitches)
            )

    ### PUBLIC PROPERTIES ###

    @property
    def bassTimespan(self):
        r'''
        Gets the bass timespan in this verticality.

        This is CURRENTLY the lowest PART not the lowest note necessarily.
        TODO: Fix this!

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(1.0)
        >>> verticality
        <Verticality 1.0 {F#3 C#4 F#4 A4}>

        >>> verticality.bassTimespan
        <ElementTimespan (1.0 to 2.0) <music21.note.Note F#>>
        '''
        pitches = sorted(self.pitchSet)
        lowestPitch = pitches[0]
        timespans = self.startTimespans + self.overlapTimespans
        bassTimespans = []
        for timespan in timespans:
            pitches = timespan.pitches
            if lowestPitch in pitches:
                bassTimespans.append(timespan)
        if bassTimespans:
            bassTimespans.sort(
                key=lambda x: x.part.getInstrument().partId,
                reverse=True,
                )
            return bassTimespans[0]
        return None

    @property
    def beatStrength(self):
        r'''
        Gets the beat strength of a verticality.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(1.0)
        >>> verticality.beatStrength
        1.0

        Note that it will return None if there are no startTimespans at this point:

        >>> verticality = tree.getVerticalityAt(1.25)
        >>> verticality
        <Verticality 1.25 {F#3 C#4 F#4 A4}>
        >>> verticality.startTimespans
        ()
        >>> verticality.beatStrength is None
        True
        '''
        try:
            thisElementTimespan = self.startTimespans[0]
        except IndexError:
            return None
        return thisElementTimespan.beatStrength

    def toChord(self):
        '''
        creates a chord object from the verticality
        '''
        pitchSet = sorted(self.pitchSet)
        testChord = chord.Chord(pitchSet)
        return testChord

    @property
    def isConsonant(self):
        r'''
        Is true when the pitch set of a verticality is consonant.

        TODO: remove, and use toChord.isConsonant() instead.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticalities = list(tree.iterateVerticalities())
        >>> for verticality in verticalities[:10]:
        ...     print("%r %r" % (verticality, verticality.isConsonant))
        ...
        <Verticality 0.0 {A3 E4 C#5}> True
        <Verticality 0.5 {G#3 B3 E4 B4}> True
        <Verticality 1.0 {F#3 C#4 F#4 A4}> True
        <Verticality 2.0 {G#3 B3 E4 B4}> True
        <Verticality 3.0 {A3 E4 C#5}> True
        <Verticality 4.0 {G#3 B3 E4 E5}> True
        <Verticality 5.0 {A3 E4 C#5}> True
        <Verticality 5.5 {C#3 E4 A4 C#5}> True
        <Verticality 6.0 {E3 E4 G#4 B4}> True
        <Verticality 6.5 {E3 D4 G#4 B4}> False
        '''
        return self.toChord().isConsonant()

    @property
    def measureNumber(self):
        r'''
        Gets the measure number of the verticality's starting elements.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(7.0)
        >>> verticality.measureNumber
        2
        '''
        return self.startTimespans[0].measureNumber

    @property
    def nextStartOffset(self):
        r'''
        Gets the next start-offset in the verticality's offset-tree.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(1.0)
        >>> verticality.nextStartOffset
        2.0

        If a verticality has no tree attached, then it cannot be

        '''
        tree = self.timespanTree
        if tree is None:
            return None
        offset = tree.getOffsetAfter(self.offset)
        return offset

    @property
    def nextVerticality(self):
        r'''
        Gets the next verticality after a verticality.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(1.0)
        >>> print(verticality)
        <Verticality 1.0 {F#3 C#4 F#4 A4}>

        >>> nextVerticality = verticality.nextVerticality
        >>> print(nextVerticality)
        <Verticality 2.0 {G#3 B3 E4 B4}>

        Verticality objects created by an offset-tree hold a reference back to
        that offset-tree. This means that they determine their next or previous
        verticality dynamically based on the state of the offset-tree only when
        asked. Because of this, it is safe to mutate the offset-tree by
        inserting or removing timespans while iterating over it.

        >>> tree.remove(nextVerticality.startTimespans)
        >>> verticality.nextVerticality
        <Verticality 3.0 {A3 E4 C#5}>
        '''
        tree = self.timespanTree
        if tree is None:
            return None
        offset = tree.getOffsetAfter(self.offset)
        if offset is None:
            return None
        return tree.getVerticalityAt(offset)

    @property
    def pitchSet(self):
        r'''
        Gets the pitch set of all elements in a verticality.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(1.0)
        >>> for pitch in sorted(verticality.pitchSet):
        ...     pitch
        ...
        <music21.pitch.Pitch F#3>
        <music21.pitch.Pitch C#4>
        <music21.pitch.Pitch F#4>
        <music21.pitch.Pitch A4>
        '''
        pitchSet = set()
        for elementTimespan in self.startTimespans:
            element = elementTimespan.element
            if hasattr(element, 'pitches'):
                pitches = [x.nameWithOctave for x in element.pitches]
                pitchSet.update(pitches)
        for elementTimespan in self.overlapTimespans:
            element = elementTimespan.element
            if hasattr(element, 'pitches'):
                pitches = [x.nameWithOctave for x in element.pitches]
                pitchSet.update(pitches)
        pitchSet = set([pitch.Pitch(x) for x in pitchSet])
        return pitchSet

    @property
    def pitchClassSet(self):
        r'''
        Gets the pitch-class set of all elements in a verticality.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(1.0)
        >>> for pitchClass in sorted(verticality.pitchClassSet):
        ...     pitchClass
        ...
        <music21.pitch.Pitch C#>
        <music21.pitch.Pitch F#>
        <music21.pitch.Pitch A>
        '''
        pitchClassSet = set()
        for currentPitch in self.pitchSet:
            pitchClass = pitch.Pitch(currentPitch.name)
            pitchClassSet.add(pitchClass)
        return pitchClassSet

    @property
    def previousVerticality(self):
        r'''
        Gets the previous verticality before a verticality.

        >>> score = corpus.parse('bwv66.6')
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(1.0)
        >>> print(verticality)
        <Verticality 1.0 {F#3 C#4 F#4 A4}>

        >>> previousVerticality = verticality.previousVerticality
        >>> print(previousVerticality)
        <Verticality 0.5 {G#3 B3 E4 B4}>

        Continue it:

        >>> v = tree.getVerticalityAt(1.0)
        >>> while v is not None:
        ...     print(v)
        ...     v = v.previousVerticality
        <Verticality 1.0 {F#3 C#4 F#4 A4}>
        <Verticality 0.5 {G#3 B3 E4 B4}>
        <Verticality 0.0 {A3 E4 C#5}>

        Verticality objects created by an offset-tree hold a reference back to
        that offset-tree. This means that they determine their next or previous
        verticality dynamically based on the state of the offset-tree only when
        asked. Because of this, it is safe to mutate the offset-tree by
        inserting or removing timespans while iterating over it.

        >>> tree.remove(previousVerticality.startTimespans)
        >>> verticality.previousVerticality
        <Verticality 0.0 {A3 E4 C#5}>
        '''
        tree = self.timespanTree
        if tree is None:
            return None
        offset = tree.getOffsetBefore(self.offset)
        if offset is None:
            return None
        return tree.getVerticalityAt(offset)

    ######### makeElement

    def makeElement(self, quarterLength=1.0):
        r'''
        Makes a Chord or Rest from this verticality and quarterLength.

        >>> score = timespans.makeExampleScore()
        >>> tree = timespans.streamToTimespanTree(score, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality = tree.getVerticalityAt(4.0)
        >>> verticality
        <Verticality 4.0 {E3 G3}>
        >>> el = verticality.makeElement(2.0)
        >>> el
        <music21.chord.Chord E3 G3>
        >>> el.duration.quarterLength
        2.0
        >>> el.duration.type
        'half'

        If there is nothing there, then a Rest is created

        >>> verticality = tree.getVerticalityAt(400.0)
        >>> verticality
        <Verticality 400.0 {}>
        >>> el = verticality.makeElement(1./3)
        >>> el
        <music21.note.Rest rest>
        >>> el.duration.fullName
        'Eighth Triplet (1/3 QL)'

        TODO: Consider if this is better to return a Note if only one pitch?
        '''
        if self.pitchSet:
            element = chord.Chord(sorted(self.pitchSet))
            startElements = [x.element for x in self.startTimespans]
            try:
                ties = [x.tie for x in startElements if x.tie is not None]
                if any(x.type == 'start' for x in ties):
                    element.tie = tie.Tie('start')
                elif any(x.type == 'continue' for x in ties):
                    element.tie = tie.Tie('continue')
            except AttributeError:
                pass
        else:
            element = note.Rest()
        element.duration.quarterLength = quarterLength
        return element

    #########  Analysis type things...

    def getAllVoiceLeadingQuartets(self, includeRests = True, includeOblique = True,
                                   includeNoMotion=False, returnObjects=True, partPairNumbers=None):
        '''
        >>> c = corpus.parse('luca/gloria').measures(1,8)
        >>> tsCol = timespans.streamToTimespanTree(c, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality22 = tsCol.getVerticalityAt(22.0)

        >>> from pprint import pprint as pp
        >>> for vlq in verticality22.getAllVoiceLeadingQuartets():
        ...     pp(vlq)
        <music21.voiceLeading.VoiceLeadingQuartet
             v1n1=<music21.note.Note E>, v1n2=<music21.note.Note F>,
             v2n1=<music21.note.Note G>, v2n2=<music21.note.Note C> >
        <music21.voiceLeading.VoiceLeadingQuartet
            v1n1=<music21.note.Note E>, v1n2=<music21.note.Note F>,
            v2n1=<music21.note.Note A>, v2n2=<music21.note.Note A> >
        <music21.voiceLeading.VoiceLeadingQuartet
            v1n1=<music21.note.Note G>, v1n2=<music21.note.Note C>,
            v2n1=<music21.note.Note A>, v2n2=<music21.note.Note A> >

        >>> for vlq in verticality22.getAllVoiceLeadingQuartets(includeRests = False):
        ...     pp(vlq)
        <music21.voiceLeading.VoiceLeadingQuartet
            v1n1=<music21.note.Note E>, v1n2=<music21.note.Note F>,
            v2n1=<music21.note.Note A>, v2n2=<music21.note.Note A> >

        >>> for vlq in verticality22.getAllVoiceLeadingQuartets(includeOblique=False):
        ...     pp(vlq)
        <music21.voiceLeading.VoiceLeadingQuartet
            v1n1=<music21.note.Note E>, v1n2=<music21.note.Note F>,
            v2n1=<music21.note.Note G>, v2n2=<music21.note.Note C> >

        >>> verticality22.getAllVoiceLeadingQuartets(includeOblique=False, includeRests=False)
        []

        Raw output

        >>> for vlqRaw in verticality22.getAllVoiceLeadingQuartets(returnObjects=False):
        ...     pp(vlqRaw)
        ((<ElementTimespan (21.0 to 22.0) <music21.note.Note E>>,
          <ElementTimespan (22.0 to 23.0) <music21.note.Note F>>),
         (<ElementTimespan (19.5 to 21.0) <music21.note.Note G>>,
          <ElementTimespan (22.0 to 22.5) <music21.note.Note C>>))
        ((<ElementTimespan (21.0 to 22.0) <music21.note.Note E>>,
          <ElementTimespan (22.0 to 23.0) <music21.note.Note F>>),
         (<ElementTimespan (21.5 to 22.5) <music21.note.Note A>>,
          <ElementTimespan (21.5 to 22.5) <music21.note.Note A>>))
        ((<ElementTimespan (19.5 to 21.0) <music21.note.Note G>>,
          <ElementTimespan (22.0 to 22.5) <music21.note.Note C>>),
         (<ElementTimespan (21.5 to 22.5) <music21.note.Note A>>,
          <ElementTimespan (21.5 to 22.5) <music21.note.Note A>>))

        >>> for vlq in verticality22.getAllVoiceLeadingQuartets(partPairNumbers=[(0,1)]):
        ...     pp(vlq)
        <music21.voiceLeading.VoiceLeadingQuartet
            v1n1=<music21.note.Note E>, v1n2=<music21.note.Note F>,
            v2n1=<music21.note.Note G>, v2n2=<music21.note.Note C> >

        >>> for vlq in verticality22.getAllVoiceLeadingQuartets(partPairNumbers=[(0,2),(1,2)]):
        ...     pp(vlq)
        <music21.voiceLeading.VoiceLeadingQuartet
            v1n1=<music21.note.Note E>, v1n2=<music21.note.Note F>,
            v2n1=<music21.note.Note A>, v2n2=<music21.note.Note A> >
        <music21.voiceLeading.VoiceLeadingQuartet
            v1n1=<music21.note.Note G>, v1n2=<music21.note.Note C>,
            v2n1=<music21.note.Note A>, v2n2=<music21.note.Note A> >
        '''
        import itertools
        from music21.voiceLeading import VoiceLeadingQuartet
        pairedMotionList = self.getPairedMotion(includeRests=includeRests, includeOblique=includeOblique)
        allQuartets = itertools.combinations(pairedMotionList, 2)
        filteredList = []

        verticalityStreamParts = self.timespanTree.source.parts

        for thisQuartet in allQuartets:
            if includeNoMotion is False:
                if (thisQuartet[0][0].pitches == thisQuartet[0][1].pitches and
                    thisQuartet[1][0].pitches == thisQuartet[1][1].pitches):
                    continue
                if partPairNumbers is not None:
                    isAppropriate = False
                    for pp in partPairNumbers:
                        thisQuartetTopPart = thisQuartet[0][0].part
                        thisQuartetBottomPart = thisQuartet[1][0].part
                        if (((verticalityStreamParts[pp[0]] == thisQuartetTopPart) or
                            (verticalityStreamParts[pp[0]] == thisQuartetBottomPart)) and
                            ((verticalityStreamParts[pp[1]] == thisQuartetTopPart) or
                            (verticalityStreamParts[pp[1]] == thisQuartetBottomPart))
                            ):
                            isAppropriate = True
                            break
                    if (isAppropriate is False):
                        continue

                if returnObjects is False:
                    filteredList.append(thisQuartet)
                else:
                    n11 = thisQuartet[0][0].element
                    n12 = thisQuartet[0][1].element
                    n21 = thisQuartet[1][0].element
                    n22 = thisQuartet[1][1].element
                    vlq = VoiceLeadingQuartet(n11, n12, n21, n22)
                    filteredList.append(vlq)

        return filteredList

    def getPairedMotion(self, includeRests=True, includeOblique=True):
        '''
        Get a list of two-element tuples that are in the same part [TODO: or containing stream??]
        and which move here.

        >>> c = corpus.parse('luca/gloria').measures(1,8)
        >>> tsCol = timespans.streamToTimespanTree(c, flatten=True, classList=(note.Note, chord.Chord))
        >>> verticality22 = tsCol.getVerticalityAt(22.0)
        >>> for pm in verticality22.getPairedMotion():
        ...     print(pm)
        (<ElementTimespan (21.0 to 22.0) <music21.note.Note E>>, <ElementTimespan (22.0 to 23.0) <music21.note.Note F>>)
        (<ElementTimespan (19.5 to 21.0) <music21.note.Note G>>, <ElementTimespan (22.0 to 22.5) <music21.note.Note C>>)
        (<ElementTimespan (21.5 to 22.5) <music21.note.Note A>>, <ElementTimespan (21.5 to 22.5) <music21.note.Note A>>)

        Note that the second one contains a one-beat rest at 21.0-22.0; so includeRests = False will
        get rid of that:

        >>> for pm in verticality22.getPairedMotion(includeRests=False):
        ...     print(pm)
        (<ElementTimespan (21.0 to 22.0) <music21.note.Note E>>, <ElementTimespan (22.0 to 23.0) <music21.note.Note F>>)
        (<ElementTimespan (21.5 to 22.5) <music21.note.Note A>>, <ElementTimespan (21.5 to 22.5) <music21.note.Note A>>)

        Oblique here means a pair that does not move (it could be called noMotion, because there's no motion
        here in a two-note pair, but we still call it includeOblique so it's consistent with
        getAllVoiceLeadingQuartets).

        >>> for pm in verticality22.getPairedMotion(includeOblique=False):
        ...     print(pm)
        (<ElementTimespan (21.0 to 22.0) <music21.note.Note E>>, <ElementTimespan (22.0 to 23.0) <music21.note.Note F>>)
        (<ElementTimespan (19.5 to 21.0) <music21.note.Note G>>, <ElementTimespan (22.0 to 22.5) <music21.note.Note C>>)

        >>> for pm in verticality22.getPairedMotion(includeOblique=False, includeRests=False):
        ...     print(pm)
        (<ElementTimespan (21.0 to 22.0) <music21.note.Note E>>, <ElementTimespan (22.0 to 23.0) <music21.note.Note F>>)
        '''
        stopTss = self.stopTimespans
        startTss = self.startTimespans
        overlapTss = self.overlapTimespans
        allPairedMotions = []

        for startingTs in startTss:
            previousTs = self.timespanTree.findPreviousElementTimespanInSameStreamByClass(startingTs)
            if previousTs is None:
                continue  # first not in piece in this part...

            if includeRests is False:
                if previousTs not in stopTss:
                    continue
            if includeOblique is False and startingTs.pitches == previousTs.pitches:
                continue
            tsTuple = (previousTs, startingTs)
            allPairedMotions.append(tsTuple)

        if includeOblique is True:
            for overlapTs in overlapTss:
                tsTuple = (overlapTs, overlapTs)
                allPairedMotions.append(tsTuple)

        return allPairedMotions

#------------------------------------------------------------------------------

class VerticalitySequence(collections.Sequence):
    r'''
    A segment of verticalities.
    '''

    ### INITIALIZER ###

    def __init__(self, verticalities):
        self._verticalities = tuple(verticalities)

    ### SPECIAL METHODS ###

    def __getitem__(self, item):
        return self._verticalities[item]

    def __len__(self):
        return len(self._verticalities)

    def __repr__(self):
        string = '<VerticalitySequence: [\n\t{}\n\t]>'.format(
            ',\n\t'.join(repr(x) for x in self))
        return string

    ### PUBLIC METHODS ###

    def unwrap(self):
        from music21.timespans.analysis import Horizontality

        unwrapped = {}
        for timespan in self[0].overlapTimespans:
            if timespan.part not in unwrapped:
                unwrapped[timespan.part] = []
            unwrapped[timespan.part].append(timespan)
        for timespan in self[0].startTimespans:
            if timespan.part not in unwrapped:
                unwrapped[timespan.part] = []
            unwrapped[timespan.part].append(timespan)
        for verticality in self[1:]:
            for timespan in verticality.startTimespans:
                if timespan.part not in unwrapped:
                    unwrapped[timespan.part] = []
                unwrapped[timespan.part].append(timespan)
        for part, unused_timespans in unwrapped.items():
            horizontality = Horizontality(timespans=unwrapped[part],)
            unwrapped[part] = horizontality
        return unwrapped

#------------------------------------------------------------------------------

class Test(unittest.TestCase):

    def runTest(self):
        pass

#------------------------------------------------------------------------------

_DOC_ORDER = (Verticality, VerticalitySequence)

#------------------------------------------------------------------------------

if __name__ == "__main__":
    import music21
    music21.mainTest(Test)


text:
Image Commentaries

                Id
                Picture
                Commentary

            <?php if (isset($project['project_pictures']) && !empty($project['project_pictures'])): ?>
               <?php foreach ( $project['project_pictures'] as $pictureId => $pictureUrl ):  ?>

                        <?php echo $pictureId ?>
                        <?php echo ''?>
                        <td class="commentary" data-toggle="modal" data-target="#picture-commentary" data-picture-id="<?php echo $pictureId; ?>" data-project-id="<?php echo $projectId; ?>">

                            <?php
                                if ( $imageCommentaries && count($imageCommentaries) > 0 ) {
                                foreach ( $imageCommentaries as $commentary ) {
                                    if ( $commentary['picture_id'] == $pictureId ){
                                        echo $commentary['commentary'];
                            ?>

                            <?php } } } ?>

                <?php endforeach; ?>

            <?php else: ?>

                            <?php echo "No Images"; ?>

            <?php endif; ?>

                <button type="button" class="close dismiss" aria-hidden="true">×</button>

Picture commentary

                <button type="button" class="btn btn-default dismiss"><?php echo lang('core button cancel'); ?></button>
                <button type="button" class="btn btn-success" id="save-text">Save</button>

redpajama_set_name: RedPajamaGithub


text:
var map;
var panoramio;
var drawingManager;

var figureList = {};
var selected = [];

var isCtrl = false;
var infowindowMode = false;
var infowindowcurrent;

var tools = [
    {name: "marker", class: google.maps.drawing.OverlayType.MARKER},
    {name: "polyline", class: google.maps.drawing.OverlayType.POLYLINE},
    {name: "polygon", class: google.maps.drawing.OverlayType.POLYGON},
    {name: "rectangle", class: google.maps.drawing.OverlayType.RECTANGLE},
    {name: "circle", class: google.maps.drawing.OverlayType.CIRCLE}
];

var selectedFigure = {
    editable: true,
    draggable: true,
    strokeOpacity: 1,
    fillOpacity: 0.30
};

var unselectedFigure = {
    editable: false,
    draggable: false,
    strokeOpacity: 0.7,
    fillOpacity: 0.20
};

var mapOptions = {
    center: new google.maps.LatLng(-34.397, 150.644),
    zoom: 8,

    mapTypeControl: true,
    mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        position: google.maps.ControlPosition.TOP_RIGHT
    },
    streetViewControl: true,
    streetViewControlOptions: {
        position: google.maps.ControlPosition.RIGHT_BOTTOM
    },
    disableDefaultUI: true,
    overviewMapControl: true
};

var contentString =
    '
' +
    '<textarea id="carea" class="form-control" placeholder="Write here"></textarea>' +
    '<button type="button" class="btn btn-default">Cancel</button>' +
    '<button type="button" class="btn btn-primary" onclick="saveInfoWindow();">Save</button>' +
    '
';

/**
 * Function to get user layer id from the url string
 * like map.php?lid={id}
 * @returns {id}
 */
function getLayerId() {
    return getParameterByName('lid');
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

/**
 * Get user objects from database
 */

function displayObjectsFromDB() {
    if(getLayerId())
        $.ajax({
            url: 'classes/getLayerObjects.php',
            method: 'GET',
            dataType: 'json',
            data: {layer: getLayerId()},
            success: function(json) {
                console.log(json);
            }
        });
}

/**
 * Sign in function
 */
function signIn() {
    $.ajax({
        url: 'classes/signAction.php',
        type: 'POST',
        data: {signin: true, email: $("#mail-field").val(), password: $("#pass-field").val()},
        success: function(data) {
            if(data.length == 4)
                location.reload();
        }
    });
}

/**
 * [loadTrack function. Allowed to load kml/kmz track onto server]
 * @return {[type]} [description]
 */
function loadFile(type, file) {
    $.ajax({
        url: 'classes/loadFile.php',
        type: 'POST',
        data: {type: type, file: file},
        success: function(data) {
            console.log(data);
        },
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress', displayLoadingProgress, false); // For handling the progress of the upload
            }
            return myXhr;
        }
    });
}

function displayLoadingProgress() {
    if(e.lengthComputable){
        // $('progress').attr({value:e.loaded,max:e.total});
        console.log(e.loaded);
        console.log(e.total);
    }
}

function initialize() {
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    panoramio = new google.maps.panoramio.PanoramioLayer();

    var menu = document.getElementById("signinbar");
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(menu);
    menu = document.getElementById("menubar");
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(menu);
    var toolbar = document.getElementById("toolbar");
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(toolbar);

    var ctaLayer = new google.maps.KmlLayer({
        url: 'http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml'
    });
    ctaLayer.setMap(map);

    var defaultMarkerOptions = {
        draggable: true,
        zIndex: 2,
        flat: false
    };

    var defaultOptions = {
        strokeColor: '#FF0000',
        strokeOpacity: 0.7,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.20,
        clickable: false,
        draggable: false,
        zIndex: 1,
        editable: false
    };

    var defaultPolylineOptions = jQuery.extend({}, defaultOptions);
    defaultPolylineOptions.strokeWeight = 3;

    drawingManager = new google.maps.drawing.DrawingManager({
        drawingControl: false,
        markerOptions: defaultMarkerOptions,
        polylineOptions: defaultPolylineOptions,
        polygonOptions: defaultOptions,
        rectangleOptions: defaultOptions,
        circleOptions: defaultOptions
    });
    drawingManager.setMap(map);

    createListeners();

    setTimeout(function() {
        $("#signinbar").show();
        $("#menubar").show();
        $("#toolbar").show();
    }, 300);

    displayObjectsFromDB();
}

/**
 * Listeners
 */

function createListeners() {
    listenMap();
    listenMenu();
    listenKeyboard();
    tools.forEach(listenToolBtn);
    listenFigureOnComplete();
    listenInfoTool();
}

function listenMap() {
    google.maps.event.addListener(map, 'click', function () {
        $("#dropdown-menu").hide();
        unselectAll();
    });
    google.maps.event.addListener(map, 'rightclick', function () {
        closeTool();
        $("#dropdown-menu").hide();
        unselectAll();
    });
}

function listenMenu() {
    $("#zoom-in").click(function () {
        map.setZoom(map.getZoom() + 1);
    });
    $("#zoom-out").click(function () {
        map.setZoom(map.getZoom() - 1);
    });
    $("#panoramio").click(function () {
        panoramio.setMap(panoramio.getMap() == null ? map : null);
    });
    $("#toolBtn").click(function () {
        $("#toolbar").toggle();
    });
    $("#sign-in").click(function () {
        signIn();
    });
    $("#load-track").click(function () {
        loadFile('track', $("#gps-input"));
    });
    $("#load-image").click(function () {
        loadFile('img', $("#img-input"));
    });
}

function listenKeyboard() {
    $(document).keyup(function (e) {
        if(e.keyCode == 17)
            isCtrl = false;
    }).keydown(function (e) {
        if(e.keyCode == 17)
            isCtrl = true;
        if(e.keyCode == 27)
            closeTool();
        if(e.keyCode == 46)
            delFigure();
        if((e.keyCode == 65 || e.keyCode == 97)&& isCtrl == true) {
            selectAll();
            e.preventDefault();
        }
    });
}

function listenToolBtn(tool) {
    var $btn = $("#" + tool.name);

    $btn.click(function () {
        if (!$btn.hasClass("btn-primary")) {
            closeTool();
            drawingManager.setOptions({
                drawingMode: tool.class
            });
            unselectAll();
            setClickableAll(false);
            $btn.addClass("btn-primary");
        } else {
            closeTool();
        }
    });
}

function listenInfoTool() {
    var $btn = $("#infowindow");

    $btn.click(function () {
        if (!$btn.hasClass("btn-primary")) {
            closeTool();
            map.setOptions({draggableCursor: 'crosshair'});
            infowindowMode = true;
            $btn.addClass("btn-primary");
        } else {
            closeTool();
        }
    });
}

function closeTool() {
    map.setOptions({draggableCursor: null});
    drawingManager.setOptions({drawingMode: null});
    $(".btn-tool").removeClass("btn-primary");
    $("#dropdown-menu").hide();
    infowindowMode = false;
    setClickableAll(true);
}

function listenFigureOnComplete() {
    google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
        var figure = event.overlay;
        figure.type = event.type;
        var toolName = event.type;
        var dragold;

        tools.forEach(function (tool) {
            if (event.type == tool.class) {
                toolName = tool.class;
            }
        });

        google.maps.event.addListener(figure, "click", function () {
            if (figure.type == google.maps.drawing.OverlayType.MARKER && infowindowMode) {
                figure.infowindow = new google.maps.InfoWindow({content: contentString});
            }
            if (figure.infowindow) {
                figure.infowindow.open(map, figure);
                infowindowcurrent = figure.infowindow;
            }
            if (!isCtrl)
                unselectAll();
            selected.indexOf(figure) >= 0 ? unselectFigure(figure) : selectFigure(figure);
        });

        google.maps.event.addListener(figure, "rightclick", function (event) {
            if (selected.length > 1) {
                if (selected.indexOf(figure) >= 0) {
                    showContextMenu(event.latLng, "this objects: " + selected.length);
                }
            } else {
                showContextMenu(event.latLng, toolName, figure.__gm_id);
            }
        });

        google.maps.event.addListener(figure, "dragstart", function (event) {
            dragold = event.latLng;
            console.log("dragstart");
        });

        google.maps.event.addListener(figure, "drag", function (event) {
            if (selected.length > 1) {
                if (dragold) {
                    var dragnew = event.latLng;
                    var dlat = dragnew.lat() - dragold.lat();
                    var dlng = dragnew.lng() - dragold.lng();

                    selected.forEach(function(sel) {
                        if (figure.__gm_id != sel.__gm_id) {
                            switch (sel.type) {
                                case google.maps.drawing.OverlayType.MARKER :
                                    sel.setPosition(new google.maps.LatLng(sel.getPosition().lat() + dlat, sel.getPosition().lng() + dlng));
                                    break;
                                case google.maps.drawing.OverlayType.POLYLINE :
                                case google.maps.drawing.OverlayType.POLYGON :
                                    var path = sel.getPath();
                                    path.forEach(function(point, index) {
                                        path.setAt(index, new google.maps.LatLng(point.lat() + dlat, point.lng() + dlng));
                                    });
                                    break;
                                case google.maps.drawing.OverlayType.RECTANGLE :
                                    var bounds = sel.getBounds();
                                    var sw = new google.maps.LatLng(bounds.getSouthWest().lat() + dlat, bounds.getSouthWest().lng() + dlng);
                                    var ne = new google.maps.LatLng(bounds.getNorthEast().lat() + dlat, bounds.getNorthEast().lng() + dlng);
                                    sel.setBounds(new google.maps.LatLngBounds(sw, ne));
                                    break;
                                case google.maps.drawing.OverlayType.CIRCLE :
                                    sel.setCenter(new google.maps.LatLng(sel.getCenter().lat() + dlat, sel.getCenter().lng() + dlng));
                                    break;
                            }
                        }
                    });
                    dragold = dragnew;
                }
            }
        });

        google.maps.event.addListener(figure, "dragend", function (event) {
            console.log("dragend");
        });

        figureList[figure.__gm_id] = figure;
        saveObjectToDB(figure);
    });
}

function delFigure(id) {
    if (arguments.length == 1 && id != undefined) {
        console.log(id);
        figureList[id].setMap(null);
    } else {
        selected.forEach(function (figure) {
            figure.setMap(null);
        });
    }
}

function setClickableAll(clickable) {
    if (arguments.length == 0)
        clickable = true;
    Object.keys(figureList).forEach(function (temp) {
        figureList[temp].setOptions({
            clickable: clickable
        });
    });
}

function selectFigure(figure) {
    figure.setOptions(selectedFigure);
    selected.push(figure);
}

function unselectFigure(figure) {
    figure.setOptions(unselectedFigure);
    selected.splice(selected.indexOf(figure), 1);
}

function selectAll() {
    Object.keys(figureList).forEach(function (temp) {
        figureList[temp].setOptions(selectedFigure);
        selected.push(temp);
    });
}

function unselectAll() {
    Object.keys(figureList).forEach(function (temp) {
        figureList[temp].setOptions(unselectedFigure);
    });
    selected = [];
}

/**
 * Save to DataBase functions
 */

function saveObjectToDB(figure) {
    var object = {
        id: figure.__gm_id,
        type: figure.type
    };
    switch (object.type) {
        case google.maps.drawing.OverlayType.MARKER :
            object.position = figure.getPosition();
            break;
        case google.maps.drawing.OverlayType.POLYLINE :
        case google.maps.drawing.OverlayType.POLYGON :
            object.path = figure.getPath().getArray();
            break;
        case google.maps.drawing.OverlayType.RECTANGLE :
            object.bounds = figure.getBounds();
            break;
        case google.maps.drawing.OverlayType.CIRCLE :
            object.center = figure.getCenter();
            object.radius = figure.getRadius();
            break;
    }

    console.log(JSON.stringify(object));

    $.ajax({
        url: 'classes/saveObjects.php',
        type: 'POST',
        data: {object: JSON.stringify(object), layer_id: getLayerId()},
        dataType: 'json',
        success: function (data) {
            console.log(data);
        }
    });
}

/**
 * Context menu
 */

function showContextMenu(currentLatLng, name, id) {
    setMenuXY(currentLatLng);
    $("#dropdown-menu").show();
    var $dropdown = $('#dropdown-menu-a');
    $dropdown.text("Delete " + name);
    $dropdown.click(function () {
        delFigure(id);
        $("#dropdown-menu").hide();
    });
}

function getCanvasXY(currentLatLng) {
    var scale = Math.pow(2, map.getZoom());
    var nw = new google.maps.LatLng(
        map.getBounds().getNorthEast().lat(),
        map.getBounds().getSouthWest().lng()
    );
    var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
    var worldCoordinate = map.getProjection().fromLatLngToPoint(currentLatLng);
    return new google.maps.Point(
        Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
        Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
    );
}

function setMenuXY(currentLatLng) {
    var clickedPosition = getCanvasXY(currentLatLng);

    var $dropdown = $('#dropdown-menu');
    $dropdown.css('left', clickedPosition.x);
    $dropdown.css('top', clickedPosition.y);
}

function saveInfoWindow() {
    var text = '
' + $("#carea").val() + "
Edit...
";
    infowindowcurrent.setContent(text);
}

function editInfoWindow() {
    var text = infowindowcurrent.getContent();
    $("#ccontainer").html(contentString);
    $("#carea").val(text);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

EJB Services Sample Guide

Introduction

            EJB Services feature in WSO2 Application Server to expose an externally deployed J2EE
            compliant Enterprise Java Beans (EJB) application as a web service. So an existing EJB
            service can be exposed as a SOA web service and this service will also be eligible for
            the fill advantages of WSO2 carbon features such as security, throttling, caching, etc.
            In the sample EJB library system is implemented. Its build as a java enterprise archive
            (ear) ans needs to be deployed in an external J2EE compliant application server. Then
            the library system cam be exposed as a WS via WSO2 Application Server. The sample is
            based on EJB 3.x.

Building the Sample

Sample contains the following items.

            |-- build.xml ant build file
            |-- ejb/ module for creating the EJB jar archive and java sources bundle
            `-- ear/ module for creating the enterprise application archive

If you are using windows get a command line shell,

go to, CARBON_HOME\samples\EJBLibrary\
            then run, \EJBLibrary\> ant

If in linux from console,

go to CARBON_HOME/samples/EJBLibrary/
            and run, /EJBLibrary$ ant

Now all the resources for the sample are built. Required resources for the sample are
            following,

EJBLibrary/ejb/target/library.jar - jar archive containing ejb sources

EJBLibrary/ear/target/library.ear - enterprise application archive

Running the sample

To deploy and run the sample follow the instruction below.

Deploy the Enterprise Application Archive

Deploy the ear archive (library.ear) in a J2EE compliant application server.

eg: jboss, glassfish, bea weblogic, apache gerenimo

Exposing the deployed EJB application as a web service

This needs to be configured via the WSO2 Application Server's ejb-services UI.

Adding the clients jars of the external application server into WSO2 Application
                Server. Client jar(s) should be copied into CARBON_HOME/repository/components/lib

eg: If the EJB is deployed in,

jboss application server -> copy jbossall-client.jar into,

CARBON_HOME/repository/components/lib

glassfish application server -> copy the gf-client.jar into,

CARBON_HOME/repository/components/lib

Also add EJBLibrary/ejb/target/library.jar into CARBON_HOME/lib

create the ejb-service via WSO2 Application Server console

go to Manage > WebServices > EJB Service

Add a new application server type or use an existing if you have already defined.

Click next

upload the library.jar and click next

Provide the EJB details.

                        Remote Interface : org.wso2.appserver.samples.ejb.LibraryManager
                        Bean JNDI Name : LibraryManager (Please use the correct JNDI name is
                        its different from the given value)

Click "Deploy Service"

Now the ejb-service would be created and deployed. For more information on using the
            ejb-services UI, please refer to ejb-services
            userguide.

Testing the created ejb-service

If the created ejb-service is successfully deployed it will be shown under web services
            listing in the WSO2 Application Server.

go to Manage > Web Services > List and you will be able to see the deployed ejb-service
            (library). Click on the service and it will show the service dashboard. Now click
            try-it and the try-it page for the service open. This can be used to invoke the
            ejb-service and hence EJB service deployed in the external application server.

Important

                For some application servers their client jar is a empty jar wchich is referring to
                a collection of jars through manifest references. Since these references are
                relative and we need to copy the client jars in to WSO2 Application Server, just
                copying these empty client jars wouldn't work. [1] describes a way how you can
                bundle all these referred jars into one bundle.

Some of the packages in external application server's client jar(s) may clash with
                the existing packages in WSO2 Application Server's classpath. This might lead to
                class loading issues. So users may need to remove those conflicting packages from
                client jars for the ejb-service to function properly.

            [1] http://devgrok.blogspot.com/2010/02/building-your-own-jbossall-clientjar.html


text:
.. Licensed to the Apache Software Foundation (ASF) under one
.. or more contributor license agreements.  See the NOTICE file
.. distributed with this work for additional information
.. regarding copyright ownership.  The ASF licenses this file
.. to you under the Apache License, Version 2.0 (the
.. "License"); you may not use this file except in compliance
.. with the License.  You may obtain a copy of the License at
..
..     http://www.apache.org/licenses/LICENSE-2.0
..
.. Unless required by applicable law or agreed to in writing, software
.. distributed under the License is distributed on an "AS IS" BASIS,
.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
.. See the License for the specific language governing permissions and
.. limitations under the License.

sstableexpiredblockers
----------------------

During compaction, entire sstables can be dropped if they contain only expired tombstones, and if it is guaranteed that the data is not newer than the data in other sstables. An expired sstable can be blocked from getting dropped if its newest timestamp is newer than the oldest data in another sstable.

This tool is used to list all sstables that are blocking other sstables from getting dropped (by having older data than the newest tombstone in an expired sstable) so a user can figure out why certain sstables are still on disk.

ref: https://issues.apache.org/jira/browse/CASSANDRA-10015

Cassandra must be stopped before this tool is executed, or unexpected results will occur. Note: the script does not verify that Cassandra is stopped.

Usage
^^^^^

sstableexpiredblockers <keyspace> <table>

Output blocked sstables
^^^^^^^^^^^^^^^^^^^^^^^

If the sstables exist for the table, but no tables have older data than the newest tombstone in an expired sstable, the script will return nothing.

Otherwise, the script will return `<sstable> blocks <#> expired sstables from getting dropped` followed by a list of the blocked sstables.

Example::

    sstableexpiredblockers keyspace1 standard1

    [BigTableReader(path='/var/lib/cassandra/data/keyspace1/standard1-0665ae80b2d711e886c66d2c86545d91/mc-2-big-Data.db') (minTS = 5, maxTS = 5, maxLDT = 2147483647)],  blocks 1 expired sstables from getting dropped: [BigTableReader(path='/var/lib/cassandra/data/keyspace1/standard1-0665ae80b2d711e886c66d2c86545d91/mc-3-big-Data.db') (minTS = 1536349775157606, maxTS = 1536349780311159, maxLDT = 1536349780)],

    [BigTableReader(path='/var/lib/cassandra/data/keyspace1/standard1-0665ae80b2d711e886c66d2c86545d91/mc-1-big-Data.db') (minTS = 1, maxTS = 10, maxLDT = 2147483647)],  blocks 1 expired sstables from getting dropped: [BigTableReader(path='/var/lib/cassandra/data/keyspace1/standard1-0665ae80b2d711e886c66d2c86545d91/mc-3-big-Data.db') (minTS = 1536349775157606, maxTS = 1536349780311159, maxLDT = 1536349780)],


text:
require 'digest/sha1'
module ContentHelper
  def category_links(article, prefix="Posted in")
    _(prefix) + " " + article.categories.map { |c| link_to h(c.name), category_url(c), :rel => 'tag'}.join(", ")
  end

  def tag_links(article, prefix="Tags")
    _(prefix) + " " + article.tags.map { |tag| link_to tag.display_name, tag.permalink_url, :rel => "tag"}.sort.join(", ")
  end

  def next_link(article, prefix="")
    n = article.next
    prefix = (prefix.blank?) ? "#{n.title} »" : prefix
    return  n ? link_to_permalink(n, prefix) : ''
  end

  def prev_link(article, prefix="")
    p = article.previous
    prefix = (prefix.blank?) ? "« #{p.title}" : prefix
    return p ? link_to_permalink(p, prefix) : ''
  end

  def render_to_string(*args, &block)
    controller.send(:render_to_string, *args, &block)
  end
end


text:
	<title>Sarah Hudspith's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Sarah Hudspith's panel show appearances

Sarah Hudspith has appeared in 1 episodes between 2002-2002. Note that these appearances may be for more than one person if multiple people have the same name.

2002

2002-04-25 / In Our Time


text:
package no.kantega.publishing.admin.security.action;

import no.kantega.commons.client.util.RequestParameters;
import no.kantega.publishing.api.model.BaseObject;
import no.kantega.publishing.eventlog.Event;
import no.kantega.publishing.eventlog.EventLog;
import no.kantega.publishing.security.SecuritySession;
import no.kantega.publishing.security.data.Permission;
import no.kantega.publishing.security.data.Role;
import no.kantega.publishing.security.data.SecurityIdentifier;
import no.kantega.publishing.security.data.User;
import no.kantega.publishing.security.data.enums.NotificationPriority;
import no.kantega.publishing.security.data.enums.Privilege;
import no.kantega.publishing.security.data.enums.RoleType;
import no.kantega.publishing.security.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class SavePermissionsAction extends AbstractController {
    private String view;

    @Autowired
    private EventLog eventLog;

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        RequestParameters param = new RequestParameters(request, "utf-8");

        HttpSession session = request.getSession(true);

        List<Permission> permissions = new ArrayList<>();
        Enumeration params = request.getParameterNames();
        while(params.hasMoreElements()) {
            String name = (String)params.nextElement();
            int priv = param.getInt(name);

            if (priv != -1 && name.contains("role_")) {
                Permission permission = new Permission();
                permission.setPrivilege(priv);

                String role = name.substring(name.indexOf("_") + 1, name.length());
                String roletype = param.getString("roletype_" + role);

                int notification = param.getInt("notification_" + role);
                if (priv >= Privilege.APPROVE_CONTENT && notification > 0) {
                    permission.setNotificationPriority(NotificationPriority.getNotificationPriorityAsEnum(notification));
                } else {
                    permission.setNotificationPriority(null);
                }

                SecurityIdentifier newRole;
                if (RoleType.USER.equalsIgnoreCase(roletype)) {
                    newRole = new User();
                } else {
                    newRole = new Role();
                }
                newRole.setId(role);
                permission.setSecurityIdentifier(newRole);
                permissions.add(permission);
            }

        }

        BaseObject object = (BaseObject)session.getAttribute(EditPermissionsAction.PERMISSIONS_OBJECT);
        if (object != null) {
            setUpdatedPermissions(request, permissions, object);
        }

        session.removeAttribute(EditPermissionsAction.PERMISSIONS_OBJECT);
        session.removeAttribute(EditPermissionsAction.PERMISSIONS_LIST);

        return new ModelAndView(view);
    }

    private void setUpdatedPermissions(HttpServletRequest request, List<Permission> permissions, BaseObject object) {
        eventLog.log(SecuritySession.getInstance(request), request, Event.SET_PERMISSIONS, object.getName(), object);
        SecurityService.setPermissions(object, permissions);
    }

    public void setView(String view) {
        this.view = view;
    }
}


text:
export function selectImage(uuid: string | undefined) {
  return { type: "SELECT_IMAGE", payload: uuid };
}


text:
module.exports = function(grunt) {
  // Grunt utilities.
  var task = grunt.task;
  var file = grunt.file;
  var utils = grunt.utils;
  var log = grunt.log;
  var verbose = grunt.verbose;
  var fail = grunt.fail;
  var option = grunt.option;
  var config = grunt.config;
  var template = grunt.template;

  // External libs.
  var jshint = require('jshint').JSHINT;

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('lint', 'Validate files with JSHint.', function() {
    // Get flags and globals, allowing target-specific options and globals to
    // override the default options and globals.
    var options, globals, tmp;

    tmp = config(['jshint', this.target, 'options']);
    if (typeof tmp === 'object') {
      verbose.writeln('Using "' + this.target + '" JSHint options.');
      options = tmp;
    } else {
      verbose.writeln('Using master JSHint options.');
      options = config('jshint.options');
    }
    verbose.writeflags(options, 'Options');

    tmp = config(['jshint', this.target, 'globals']);
    if (typeof tmp === 'object') {
      verbose.writeln('Using "' + this.target + '" JSHint globals.');
      globals = tmp;
    } else {
      verbose.writeln('Using master JSHint globals.');
      globals = config('jshint.globals');
    }
    verbose.writeflags(globals, 'Globals');

    // Lint specified files.
    file.expandFiles(this.file.src).forEach(function(filepath) {
      grunt.helper('lint', file.read(filepath), options, globals, filepath);
    });

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }

    // Otherwise, print a success message.
    log.writeln('Lint free.');
  });

  // ==========================================================================
  // HELPERS
  // ==========================================================================

  // No idea why JSHint treats tabs as options.indent # characters wide, but it
  // does. See issue: https://github.com/jshint/jshint/issues/430
  function getTabStr(options) {
    // Do something that's going to error.
    jshint('\tx', options || {});
    // If an error occurred, figure out what character JSHint reported and
    // subtract one.
    var character = jshint.errors && jshint.errors[0] && jshint.errors[0].character - 1;
    // If character is actually a number, use it. Otherwise use 1.
    var tabsize = isNaN(character) ? 1 : character;
    // If tabsize > 1, return something that should be safe to use as a
    // placeholder. \uFFFF repeated 2+ times.
    return tabsize > 1 && utils.repeat(tabsize, '\uFFFF');
  }

  var tabregex = /\t/g;

  // Lint source code with JSHint.
  grunt.registerHelper('lint', function(src, options, globals, extraMsg) {
    // JSHint sometimes modifies objects you pass in, so clone them.
    options = utils._.clone(options);
    globals = utils._.clone(globals);
    // Enable/disable debugging if option explicitly set.
    if (option('debug') !== undefined) {
      options.devel = options.debug = option('debug');
      // Tweak a few things.
      if (option('debug')) {
        options.maxerr = Infinity;
      }
    }
    var msg = 'Linting' + (extraMsg ? ' ' + extraMsg : '') + '...';
    verbose.write(msg);
    // Tab size as reported by JSHint.
    var tabstr = getTabStr(options);
    var placeholderregex = new RegExp(tabstr, 'g');
    // Lint.
    var result = jshint(src, options || {}, globals || {});
    // Attempt to work around JSHint erroneously reporting bugs.
    // if (!result) {
    //   // Filter out errors that shouldn't be reported.
    //   jshint.errors = jshint.errors.filter(function(o) {
    //     return o && o.something === 'something';
    //   });
    //   // If no errors are left, JSHint actually succeeded.
    //   result = jshint.errors.length === 0;
    // }
    if (result) {
      // Success!
      verbose.ok();
    } else {
      // Something went wrong.
      verbose.or.write(msg);
      log.error();
      // Iterate over all errors.
      jshint.errors.forEach(function(e) {
        // Sometimes there's no error object.
        if (!e) { return; }
        var pos;
        var evidence = e.evidence;
        var character = e.character;
        if (evidence) {
          // Manually increment errorcount since we're not using log.error().
          grunt.fail.errorcount++;
          // Descriptive code error.
          pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + character).yellow + ']'.red;
          log.writeln(pos + ' ' + e.reason.yellow);
          // If necessary, eplace each tab char with something that can be
          // swapped out later.
          if (tabstr) {
            evidence = evidence.replace(tabregex, tabstr);
          }
          if (character > evidence.length) {
            // End of line.
            evidence = evidence + ' '.inverse.red;
          } else {
            // Middle of line.
            evidence = evidence.slice(0, character - 1) + evidence[character - 1].inverse.red +
              evidence.slice(character);
          }
          // Replace tab placeholder (or tabs) but with a 2-space soft tab.
          evidence = evidence.replace(tabstr ? placeholderregex : tabregex, '  ');
          log.writeln(evidence);
        } else {
          // Generic "Whoops, too many errors" error.
          log.error(e.reason);
        }
      });
      log.writeln();
    }
  });

};


text:
<mm-loading hide-until="commentsLoaded">

= 0">
        {{ 'mm.core.commentscount' | translate : {'$a': commentsCount} }}

    <div ng-if="commentsCount < 0">
        {{ 'mm.core.commentsnotworking' | translate }}

</mm-loading>


text:
(function() {
  var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['clients.hbs'] = template({"1":function(container,depth0,helpers,partials,data) {
    var helper, alias1=container.escapeExpression;

  return "
"
    + alias1(((helper = (helper = helpers.index || (data && data.index)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"index","hash":{},"data":data}) : helper)))
    + ". "
    + alias1(container.lambda(depth0, depth0))
    + "
\n";
},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
    var stack1;

  return "
\n"
    + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.clients : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "")
    + "
\n";
},"useData":true});
})();


text:
layout: page
title: Koch 50th Anniversary
date: 2016-05-24
author: Joyce Boyd
tags: weekly links, java
status: published
summary: Sed at volutpat ipsum. Cras scelerisque eu tellus vel.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 06/11/2019
  endDate: 06/14/2019
  ctyhocn: BSWVEHX
  groupCode: K5A
published: true
---
Etiam sit amet molestie quam. Vivamus sit amet pharetra ex. Nunc ultricies massa in velit scelerisque imperdiet. Nunc non ligula in lorem convallis semper non eget orci. Proin eget auctor odio, laoreet facilisis arcu. Sed et mauris a lectus fermentum lacinia id non tortor. Vivamus suscipit magna et neque pulvinar, in rhoncus est sollicitudin. Mauris dapibus, velit et tempor egestas, ex tellus semper enim, eget bibendum nulla est vel purus. In sem eros, sagittis nec luctus at, luctus id metus. Fusce id tortor pellentesque, faucibus nibh non, placerat justo. Pellentesque eget tincidunt risus. Maecenas luctus diam ut est dignissim, sit amet tempus sem venenatis. Vestibulum eleifend urna nisl, at cursus leo fermentum in. Sed blandit pharetra massa, eu pulvinar diam laoreet vitae.
Donec elementum dapibus risus, sit amet condimentum velit varius eu. Duis efficitur, lectus sit amet porta condimentum, turpis felis euismod quam, non volutpat dui turpis sit amet libero. Aenean volutpat at leo et semper. Mauris in dolor ut nisi eleifend semper auctor at nulla. Quisque viverra sapien at nulla malesuada finibus. Proin vitae bibendum elit. Integer ullamcorper aliquam leo, ut facilisis velit interdum sed. Aliquam diam diam, mollis quis purus interdum, convallis auctor tellus. Fusce velit risus, cursus nec commodo et, faucibus sit amet tellus. Aenean ut egestas ligula. Sed malesuada mattis urna, ut pellentesque urna aliquam at.

* Mauris faucibus dui ac ex vestibulum vulputate
* Sed in ex sit amet risus pretium sodales
* Vestibulum eu urna ac nunc dictum dictum
* Aenean scelerisque purus vitae massa feugiat vestibulum sed non arcu
* Etiam fermentum ipsum quis ante tempor imperdiet.

Vivamus quis augue ut quam ultricies ultricies. Pellentesque sed vehicula nisi, facilisis ultrices eros. Praesent in elit risus. Vivamus sit amet mi quis libero pharetra pretium. Nunc sapien ante, maximus at massa a, tincidunt viverra purus. Quisque vel dolor sem. Vivamus leo mauris, semper sit amet lacus sed, consequat fringilla nibh.


text:
require 'test_helper'

class FamiliaHelperTest < ActionView::TestCase
end


text:
package spanner

import (
	"context"
	"errors"
	"sync"
	"testing"
	"time"

	"cloud.google.com/go/spanner/internal/testutil"
	sppb "google.golang.org/genproto/googleapis/spanner/v1"
	"google.golang.org/grpc/codes"
)

var (
	errAbrt = spannerErrorf(codes.Aborted, "")
	errUsr  = errors.New("error")
)

// setup sets up a Client using mockclient
func mockClient(t *testing.T) (*sessionPool, *testutil.MockCloudSpannerClient, *Client) {
	var (
		mc       = testutil.NewMockCloudSpannerClient(t)
		spc      = SessionPoolConfig{}
		database = "mockdb"
	)
	spc.getRPCClient = func() (sppb.SpannerClient, error) {
		return mc, nil
	}
	sp, err := newSessionPool(database, spc, nil)
	if err != nil {
		t.Fatalf("cannot create session pool: %v", err)
	}
	return sp, mc, &Client{
		database:     database,
		idleSessions: sp,
	}
}

// TestReadOnlyAcquire tests acquire for ReadOnlyTransaction.
func TestReadOnlyAcquire(t *testing.T) {
	t.Parallel()
	_, mc, client := mockClient(t)
	defer client.Close()
	mc.SetActions(
		testutil.Action{"BeginTransaction", errUsr},
		testutil.Action{"BeginTransaction", nil},
		testutil.Action{"BeginTransaction", nil},
	)

	// Singleuse should only be used once.
	txn := client.Single()
	defer txn.Close()
	_, _, e := txn.acquire(context.Background())
	if e != nil {
		t.Errorf("Acquire for single use, got %v, want nil.", e)
	}
	_, _, e = txn.acquire(context.Background())
	if wantErr := errTxClosed(); !testEqual(e, wantErr) {
		t.Errorf("Second acquire for single use, got %v, want %v.", e, wantErr)
	}
	// Multiuse can recover from acquire failure.
	txn = client.ReadOnlyTransaction()
	_, _, e = txn.acquire(context.Background())
	if wantErr := toSpannerError(errUsr); !testEqual(e, wantErr) {
		t.Errorf("Acquire for multi use, got %v, want %v.", e, wantErr)
	}
	_, _, e = txn.acquire(context.Background())
	if e != nil {
		t.Errorf("Acquire for multi use, got %v, want nil.", e)
	}
	txn.Close()
	// Multiuse can not be used after close.
	_, _, e = txn.acquire(context.Background())
	if wantErr := errTxClosed(); !testEqual(e, wantErr) {
		t.Errorf("Second acquire for multi use, got %v, want %v.", e, wantErr)
	}
	// Multiuse can be acquired concurrently.
	txn = client.ReadOnlyTransaction()
	defer txn.Close()
	mc.Freeze()
	var (
		sh1 *sessionHandle
		sh2 *sessionHandle
		ts1 *sppb.TransactionSelector
		ts2 *sppb.TransactionSelector
		wg  = sync.WaitGroup{}
	)
	acquire := func(sh **sessionHandle, ts **sppb.TransactionSelector) {
		defer wg.Done()
		var e error
		*sh, *ts, e = txn.acquire(context.Background())
		if e != nil {
			t.Errorf("Concurrent acquire for multiuse, got %v, expect nil.", e)
		}
	}
	wg.Add(2)
	go acquire(&sh1, &ts1)
	go acquire(&sh2, &ts2)
	<-time.After(100 * time.Millisecond)
	mc.Unfreeze()
	wg.Wait()
	if !testEqual(sh1.session, sh2.session) {
		t.Errorf("Expect acquire to get same session handle, got %v and %v.", sh1, sh2)
	}
	if !testEqual(ts1, ts2) {
		t.Errorf("Expect acquire to get same transaction selector, got %v and %v.", ts1, ts2)
	}
}

// TestRetryOnAbort tests transaction retries on abort.
func TestRetryOnAbort(t *testing.T) {
	t.Parallel()
	_, mc, client := mockClient(t)
	defer client.Close()
	// commit in writeOnlyTransaction
	mc.SetActions(
		testutil.Action{"Commit", errAbrt}, // abort on first commit
		testutil.Action{"Commit", nil},
	)

	ms := []*Mutation{
		Insert("Accounts", []string{"AccountId", "Nickname", "Balance"}, []interface{}{int64(1), "Foo", int64(50)}),
		Insert("Accounts", []string{"AccountId", "Nickname", "Balance"}, []interface{}{int64(2), "Bar", int64(1)}),
	}
	if _, e := client.Apply(context.Background(), ms, ApplyAtLeastOnce()); e != nil {
		t.Errorf("applyAtLeastOnce retry on abort, got %v, want nil.", e)
	}
	// begin and commit in ReadWriteTransaction
	mc.SetActions(
		testutil.Action{"BeginTransaction", nil},     // let takeWriteSession succeed and get a session handle
		testutil.Action{"Commit", errAbrt},           // let first commit fail and retry will begin new transaction
		testutil.Action{"BeginTransaction", errAbrt}, // this time we can fail the begin attempt
		testutil.Action{"BeginTransaction", nil},
		testutil.Action{"Commit", nil},
	)

	if _, e := client.Apply(context.Background(), ms); e != nil {
		t.Errorf("ReadWriteTransaction retry on abort, got %v, want nil.", e)
	}
}

// TestBadSession tests bad session (session not found error).
// TODO: session closed from transaction close
func TestBadSession(t *testing.T) {
	t.Parallel()
	ctx := context.Background()
	sp, mc, client := mockClient(t)
	defer client.Close()
	var sid string
	// Prepare a session, get the session id for use in testing.
	if s, e := sp.take(ctx); e != nil {
		t.Fatal("Prepare session failed.")
	} else {
		sid = s.getID()
		s.recycle()
	}

	wantErr := spannerErrorf(codes.NotFound, "Session not found: %v", sid)
	// ReadOnlyTransaction
	mc.SetActions(
		testutil.Action{"BeginTransaction", wantErr},
		testutil.Action{"BeginTransaction", wantErr},
		testutil.Action{"BeginTransaction", wantErr},
	)
	txn := client.ReadOnlyTransaction()
	defer txn.Close()
	if _, _, got := txn.acquire(ctx); !testEqual(wantErr, got) {
		t.Errorf("Expect acquire to fail, got %v, want %v.", got, wantErr)
	}
	// The failure should recycle the session, we expect it to be used in following requests.
	if got := txn.Query(ctx, NewStatement("SELECT 1")); !testEqual(wantErr, got.err) {
		t.Errorf("Expect Query to fail, got %v, want %v.", got.err, wantErr)
	}
	if got := txn.Read(ctx, "Users", KeySets(Key{"alice"}, Key{"bob"}), []string{"name", "email"}); !testEqual(wantErr, got.err) {
		t.Errorf("Expect Read to fail, got %v, want %v.", got.err, wantErr)
	}
	// writeOnlyTransaction
	ms := []*Mutation{
		Insert("Accounts", []string{"AccountId", "Nickname", "Balance"}, []interface{}{int64(1), "Foo", int64(50)}),
		Insert("Accounts", []string{"AccountId", "Nickname", "Balance"}, []interface{}{int64(2), "Bar", int64(1)}),
	}
	mc.SetActions(testutil.Action{"Commit", wantErr})
	if _, got := client.Apply(context.Background(), ms, ApplyAtLeastOnce()); !testEqual(wantErr, got) {
		t.Errorf("Expect applyAtLeastOnce to fail, got %v, want %v.", got, wantErr)
	}
}

func TestFunctionErrorReturned(t *testing.T) {
	t.Parallel()
	_, mc, client := mockClient(t)
	defer client.Close()
	mc.SetActions(
		testutil.Action{"BeginTransaction", nil},
		testutil.Action{"Rollback", nil},
	)

	want := errors.New("an error")
	_, got := client.ReadWriteTransaction(context.Background(),
		func(context.Context, *ReadWriteTransaction) error { return want })
	if got != want {
		t.Errorf("got <%v>, want <%v>", got, want)
	}
	mc.CheckActionsConsumed()
}


text:
namespace policy {

IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
  // Verifies that a default search is made using the provider configured via
  // policy. Also checks that default search can be completely disabled.
  const std::u16string kKeyword(u"testsearch");
  const std::string kSearchURL("http://search.example/search?q={searchTerms}");
  const std::string kAlternateURL0(
      "http://search.example/search#q={searchTerms}");
  const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
  const std::string kImageURL("http://test.com/searchbyimage/upload");
  const std::string kImageURLPostParams(
      "image_content=content,image_url=http://test.com/test.png");
  const std::string kNewTabURL("http://search.example/newtab");

  TemplateURLService* service =
      TemplateURLServiceFactory::GetForProfile(browser()->profile());
  search_test_utils::WaitForTemplateURLServiceToLoad(service);
  const TemplateURL* default_search = service->GetDefaultSearchProvider();
  ASSERT_TRUE(default_search);
  EXPECT_NE(kKeyword, default_search->keyword());
  EXPECT_NE(kSearchURL, default_search->url());
  EXPECT_FALSE(default_search->alternate_urls().size() == 2 &&
               default_search->alternate_urls()[0] == kAlternateURL0 &&
               default_search->alternate_urls()[1] == kAlternateURL1 &&
               default_search->image_url() == kImageURL &&
               default_search->image_url_post_params() == kImageURLPostParams &&
               default_search->new_tab_url() == kNewTabURL);

  // Override the default search provider using policies.
  PolicyMap policies;
  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(true),
               nullptr);
  policies.Set(key::kDefaultSearchProviderKeyword, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(kKeyword),
               nullptr);
  policies.Set(key::kDefaultSearchProviderSearchURL, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(kSearchURL),
               nullptr);
  base::Value alternate_urls(base::Value::Type::LIST);
  alternate_urls.Append(kAlternateURL0);
  alternate_urls.Append(kAlternateURL1);
  policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               std::move(alternate_urls), nullptr);
  policies.Set(key::kDefaultSearchProviderImageURL, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(kImageURL),
               nullptr);
  policies.Set(key::kDefaultSearchProviderImageURLPostParams,
               POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(kImageURLPostParams), nullptr);
  policies.Set(key::kDefaultSearchProviderNewTabURL, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(kNewTabURL),
               nullptr);
  UpdateProviderPolicy(policies);
  default_search = service->GetDefaultSearchProvider();
  ASSERT_TRUE(default_search);
  EXPECT_EQ(kKeyword, default_search->keyword());
  EXPECT_EQ(kSearchURL, default_search->url());
  EXPECT_EQ(2U, default_search->alternate_urls().size());
  EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
  EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
  EXPECT_EQ(kImageURL, default_search->image_url());
  EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
  EXPECT_EQ(kNewTabURL, default_search->new_tab_url());

  // Verify that searching from the omnibox uses kSearchURL.
  chrome::FocusLocationBar(browser());
  ui_test_utils::SendToOmniboxAndSubmit(browser(), "stuff to search for");
  OmniboxEditModel* model =
      browser()->window()->GetLocationBar()->GetOmniboxView()->model();
  EXPECT_TRUE(model->CurrentMatch(nullptr).destination_url.is_valid());
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  GURL expected("http://search.example/search?q=stuff+to+search+for");
  EXPECT_EQ(expected, web_contents->GetURL());

  // Verify that searching from the omnibox can be disabled.
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)));
  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(false),
               nullptr);
  EXPECT_TRUE(service->GetDefaultSearchProvider());
  UpdateProviderPolicy(policies);
  EXPECT_FALSE(service->GetDefaultSearchProvider());
  ui_test_utils::SendToOmniboxAndSubmit(browser(), "should not work");
  // This means that submitting won't trigger any action.
  EXPECT_FALSE(model->CurrentMatch(nullptr).destination_url.is_valid());
  EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
}

}  // namespace policy


text:
echo "Starting Bot..."
node --harmony index.js


text:
package com.graphhopper.routing.ev;

import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.storage.IntsRef;
import com.graphhopper.util.Helper;

import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;

/**
 * Implementation of the IntEncodedValue via a limited number of bits and without a sign. It introduces handling
 * of "backward"- and "forward"-edge information.
 */
public class UnsignedIntEncodedValue implements IntEncodedValue {

    private final String name;

    /**
     * There are multiple int values possible per edge. Here we specify the index into this integer array.
     */
    private int fwdDataIndex;
    private int bwdDataIndex;
    private final boolean storeTwoDirections;
    final int bits;
    int maxValue;
    int fwdShift = -1;
    int bwdShift = -1;
    int fwdMask;
    int bwdMask;

    /**
     * This constructor reserves the specified number of bits in the underlying data structure or twice the amount if
     * storeTwoDirections is true.
     *
     * @param storeTwoDirections if true this EncodedValue can store different values for the forward and backward
     *                           direction.
     */
    public UnsignedIntEncodedValue(String name, int bits, boolean storeTwoDirections) {
        if (!EncodingManager.isValidEncodedValue(name))
            throw new IllegalArgumentException("EncodedValue name wasn't valid: " + name + ". Use lower case letters, underscore and numbers only.");
        if (bits <= 0)
            throw new IllegalArgumentException(name + ": bits cannot be zero or negative");
        if (bits > 31)
            throw new IllegalArgumentException(name + ": at the moment the number of reserved bits cannot be more than 31");
        this.bits = bits;
        this.name = name;
        this.storeTwoDirections = storeTwoDirections;
    }

    @Override
    public final int init(EncodedValue.InitializerConfig init) {
        if (isInitialized())
            throw new IllegalStateException("Cannot call init multiple times");

        init.next(bits);
        this.fwdMask = init.bitMask;
        this.fwdDataIndex = init.dataIndex;
        this.fwdShift = init.shift;
        if (storeTwoDirections) {
            init.next(bits);
            this.bwdMask = init.bitMask;
            this.bwdDataIndex = init.dataIndex;
            this.bwdShift = init.shift;
        }

        this.maxValue = (1 << bits) - 1;
        return storeTwoDirections ? 2 * bits : bits;
    }

    boolean isInitialized() {
        return fwdMask != 0;
    }

    private void checkValue(int value) {
        if (!isInitialized())
            throw new IllegalStateException("EncodedValue " + getName() + " not initialized");
        if (value > maxValue)
            throw new IllegalArgumentException(name + " value too large for encoding: " + value + ", maxValue:" + maxValue);
        if (value < 0)
            throw new IllegalArgumentException("negative value for " + name + " not allowed! " + value);
    }

    @Override
    public final void setInt(boolean reverse, IntsRef ref, int value) {
        checkValue(value);
        uncheckedSet(reverse, ref, value);
    }

    final void uncheckedSet(boolean reverse, IntsRef ref, int value) {
        if (reverse && !storeTwoDirections)
            throw new IllegalArgumentException(getName() + ": value for reverse direction would overwrite forward direction. Enable storeTwoDirections for this EncodedValue or don't use setReverse");

        if (reverse) {
            int flags = ref.ints[bwdDataIndex + ref.offset];
            // clear value bits
            flags &= ~bwdMask;
            ref.ints[bwdDataIndex + ref.offset] = flags | (value << bwdShift);
        } else {
            int flags = ref.ints[fwdDataIndex + ref.offset];
            flags &= ~fwdMask;
            ref.ints[fwdDataIndex + ref.offset] = flags | (value << fwdShift);
        }
    }

    @Override
    public final int getInt(boolean reverse, IntsRef ref) {
        int flags;
        // if we do not store both directions ignore reverse == true for convenient reading
        if (storeTwoDirections && reverse) {
            flags = ref.ints[bwdDataIndex + ref.offset];
            return (flags & bwdMask) >>> bwdShift;
        } else {
            flags = ref.ints[fwdDataIndex + ref.offset];
            return (flags & fwdMask) >>> fwdShift;
        }
    }

    @Override
    public int getMaxInt() {
        return maxValue;
    }

    @Override
    public final boolean isStoreTwoDirections() {
        return storeTwoDirections;
    }

    @Override
    public final String getName() {
        return name;
    }

    @Override
    public final String toString() {
        return getName() + "|version=" + getVersion() + "|bits=" + bits + "|index=" + fwdDataIndex + "|shift=" + fwdShift + "|store_both_directions=" + storeTwoDirections;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UnsignedIntEncodedValue that = (UnsignedIntEncodedValue) o;
        return fwdDataIndex == that.fwdDataIndex &&
                bwdDataIndex == that.bwdDataIndex &&
                bits == that.bits &&
                maxValue == that.maxValue &&
                fwdShift == that.fwdShift &&
                bwdShift == that.bwdShift &&
                fwdMask == that.fwdMask &&
                bwdMask == that.bwdMask &&
                storeTwoDirections == that.storeTwoDirections &&
                Objects.equals(name, that.name);
    }

    @Override
    public final int hashCode() {
        return getVersion();
    }

    @Override
    public int getVersion() {
        int val = Helper.staticHashCode(name);
        val = 31 * val + (storeTwoDirections ? 1231 : 1237);
        return staticHashCode(val, fwdDataIndex, bwdDataIndex, bits, maxValue, fwdShift, bwdShift, fwdMask, bwdMask);
    }

    /**
     * Produces a static hashcode for an integer arrays that is platform independent and still compatible to the default
     * of openjdk.
     *
     * @see Arrays#hashCode(int[])
     */
    static int staticHashCode(int... vals) {
        if (vals == null)
            return 0;
        int len = vals.length;
        int val = 1;
        for (int idx = 0; idx < len; ++idx) {
            val = 31 * val + vals[idx];
        }

        return val;
    }

    /**
     * Produces a static hashcode for an Enum arrays that is platform independent and still compatible to the default
     * of openjdk.
     */
    static int staticHashCode(Enum<?>... vals) {
        if (vals == null)
            return 0;
        int len = vals.length;
        int val = 1;
        for (int idx = 0; idx < len; ++idx) {
            val = 31 * val + vals[idx].ordinal();
        }

        return val;
    }

    /**
     * Produces a static hashcode for a collection of Strings that is platform independent and still compatible to the default
     * of openjdk.
     */
    static int staticHashCode(Collection<String> vals) {
        if (vals == null)
            return 0;
        int val = 1;
        for (String str : vals) {
            val = 31 * val + Helper.staticHashCode(str);
        }

        return val;
    }

    /**
     * Produces a static hashcode for an integer arrays that is platform independent and still compatible to the default
     * of openjdk
     *
     * @see Double#hashCode
     */
    static int staticHashCode(double val) {
        long var2 = Double.doubleToLongBits(val);
        return (int) (var2 ^ var2 >>> 32);
    }
}


text:
FactoryGirl.define do
  factory :coffee_script, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-coffee:latest'
    association :file_type, factory: :dot_coffee
    help
    name 'CoffeeScript'
    network_enabled false
    permitted_execution_time 10.seconds
    pool_size 0
    run_command 'coffee'
    singleton_execution_environment
  end

  factory :html, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-html:latest'
    association :file_type, factory: :dot_html
    help
    name 'HTML5'
    network_enabled false
    permitted_execution_time 10.seconds
    pool_size 0
    run_command 'touch'
    singleton_execution_environment
    test_command 'rspec %{filename} --format documentation'
    testing_framework 'RspecAdapter'
  end

  factory :java, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-java:latest'
    association :file_type, factory: :dot_java
    help
    name 'Java 8'
    network_enabled false
    permitted_execution_time 10.seconds
    pool_size 0
    run_command 'make run'
    singleton_execution_environment
    test_command 'make test CLASS_NAME="%{class_name}" FILENAME="%{filename}"'
    testing_framework 'JunitAdapter'
  end

  factory :jruby, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-jruby:latest'
    association :file_type, factory: :dot_rb
    help
    name 'JRuby 1.7'
    network_enabled false
    permitted_execution_time 10.seconds
    pool_size 0
    run_command 'jruby %{filename}'
    singleton_execution_environment
    test_command 'rspec %{filename} --format documentation'
    testing_framework 'RspecAdapter'
  end

  factory :node_js, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-node:latest'
    association :file_type, factory: :dot_js
    help
    name 'Node.js'
    network_enabled false
    permitted_execution_time 10.seconds
    pool_size 0
    run_command 'node %{filename}'
    singleton_execution_environment
  end

  factory :python, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-python:latest'
    association :file_type, factory: :dot_py
    help
    name 'Python 3.4'
    network_enabled false
    permitted_execution_time 10.seconds
    pool_size 0
    run_command 'python3 %{filename}'
    singleton_execution_environment
    test_command 'python3 -m unittest --verbose %{module_name}'
    testing_framework 'PyUnitAdapter'
  end

  factory :ruby, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-ruby:latest'
    association :file_type, factory: :dot_rb
    help
    name 'Ruby 2.2'
    network_enabled false
    permitted_execution_time 10.seconds
    pool_size 0
    run_command 'ruby %{filename}'
    singleton_execution_environment
    test_command 'rspec %{filename} --format documentation'
    testing_framework 'RspecAdapter'
  end

  factory :sinatra, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-sinatra:latest'
    association :file_type, factory: :dot_rb
    exposed_ports '4567'
    help
    name 'Sinatra'
    network_enabled true
    permitted_execution_time 15.minutes
    pool_size 0
    run_command 'ruby %{filename}'
    singleton_execution_environment
    test_command 'rspec %{filename} --format documentation'
    testing_framework 'RspecAdapter'
  end

  factory :sqlite, class: ExecutionEnvironment do
    created_by_teacher
    default_memory_limit
    docker_image 'hklement/ubuntu-sqlite:latest'
    association :file_type, factory: :dot_sql
    help
    name 'SQLite'
    network_enabled false
    permitted_execution_time 1.minute
    pool_size 0
    run_command 'sqlite3 /database.db -init %{filename} -html'
    singleton_execution_environment
    test_command 'ruby %{filename}'
    testing_framework 'SqlResultSetComparatorAdapter'
  end

  trait :default_memory_limit do
    memory_limit DockerClient::DEFAULT_MEMORY_LIMIT
  end

  trait :help do
    help { Forgery(:lorem_ipsum).words(Forgery(:basic).number(at_least: 50, at_most: 100)) }
  end

  trait :singleton_execution_environment do
    initialize_with { ExecutionEnvironment.where(name: name).first_or_create }
  end
end


text:
package springfox.documentation.swagger2.annotations;

import org.springframework.context.annotation.Import;
import springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Indicates that Swagger support should be enabled.
 *

 * This should be applied to a Spring java config and should have an accompanying '@Configuration' annotation.
 *

 * Loads all required beans defined in @see SpringSwaggerConfig
 *
 * @see springfox.documentation.spring.web.plugins.Docket
 * Use {@link EnableSwagger2} instead
 * @deprecated @since 3.0.0
 */
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = {java.lang.annotation.ElementType.TYPE})
@Documented
@Import(Swagger2DocumentationConfiguration.class)
@Deprecated
public @interface EnableSwagger2WebMvc {
}