text:
#include "config.h"
#include "core/css/CSSSelector.h"

#include "core/HTMLNames.h"
#include "core/css/CSSOMUtils.h"
#include "core/css/CSSSelectorList.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "wtf/Assertions.h"
#include "wtf/HashMap.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuilder.h"

#ifndef NDEBUG
#include <stdio.h>
#endif

namespace blink {

using namespace HTMLNames;

struct SameSizeAsCSSSelector {
    unsigned bitfields;
    void *pointers[1];
};

static_assert(sizeof(CSSSelector) == sizeof(SameSizeAsCSSSelector), "CSSSelector should stay small");

void CSSSelector::createRareData()
{
    ASSERT(m_match != Tag);
    if (m_hasRareData)
        return;
    AtomicString value(m_data.m_value);
    if (m_data.m_value)
        m_data.m_value->deref();
    m_data.m_rareData = RareData::create(value).leakRef();
    m_hasRareData = true;
}

unsigned CSSSelector::specificity() const
{
    // make sure the result doesn't overflow
    static const unsigned maxValueMask = 0xffffff;
    static const unsigned idMask = 0xff0000;
    static const unsigned classMask = 0xff00;
    static const unsigned elementMask = 0xff;

    if (isForPage())
        return specificityForPage() & maxValueMask;

    unsigned total = 0;
    unsigned temp = 0;

    for (const CSSSelector* selector = this; selector; selector = selector->tagHistory()) {
        temp = total + selector->specificityForOneSelector();
        // Clamp each component to its max in the case of overflow.
        if ((temp & idMask) < (total & idMask))
            total |= idMask;
        else if ((temp & classMask) < (total & classMask))
            total |= classMask;
        else if ((temp & elementMask) < (total & elementMask))
            total |= elementMask;
        else
            total = temp;
    }
    return total;
}

inline unsigned CSSSelector::specificityForOneSelector() const
{
    // FIXME: Pseudo-elements and pseudo-classes do not have the same specificity. This function
    // isn't quite correct.
    switch (m_match) {
    case Id:
        return 0x10000;
    case PseudoClass:
        if (pseudoType() == PseudoHost || pseudoType() == PseudoHostContext)
            return 0;
        // fall through.
    case AttributeExact:
    case Class:
    case AttributeSet:
    case AttributeList:
    case AttributeHyphen:
    case PseudoElement:
    case AttributeContain:
    case AttributeBegin:
    case AttributeEnd:
        // FIXME: PseudoAny should base the specificity on the sub-selectors.
        // See http://lists.w3.org/Archives/Public/www-style/2010Sep/0530.html
        if (pseudoType() == PseudoNot) {
            ASSERT(selectorList());
            return selectorList()->first()->specificityForOneSelector();
        }
        return 0x100;
    case Tag:
        return (tagQName().localName() != starAtom) ? 1 : 0;
    case Unknown:
        return 0;
    }
    ASSERT_NOT_REACHED();
    return 0;
}

unsigned CSSSelector::specificityForPage() const
{
    // See http://dev.w3.org/csswg/css3-page/#cascading-and-page-context
    unsigned s = 0;

    for (const CSSSelector* component = this; component; component = component->tagHistory()) {
        switch (component->m_match) {
        case Tag:
            s += tagQName().localName() == starAtom ? 0 : 4;
            break;
        case PagePseudoClass:
            switch (component->pseudoType()) {
            case PseudoFirstPage:
                s += 2;
                break;
            case PseudoLeftPage:
            case PseudoRightPage:
                s += 1;
                break;
            case PseudoNotParsed:
                break;
            default:
                ASSERT_NOT_REACHED();
            }
            break;
        default:
            break;
        }
    }
    return s;
}

PseudoId CSSSelector::pseudoId(PseudoType type)
{
    switch (type) {
    case PseudoFirstLine:
        return FIRST_LINE;
    case PseudoFirstLetter:
        return FIRST_LETTER;
    case PseudoSelection:
        return SELECTION;
    case PseudoBefore:
        return BEFORE;
    case PseudoAfter:
        return AFTER;
    case PseudoBackdrop:
        return BACKDROP;
    case PseudoScrollbar:
        return SCROLLBAR;
    case PseudoScrollbarButton:
        return SCROLLBAR_BUTTON;
    case PseudoScrollbarCorner:
        return SCROLLBAR_CORNER;
    case PseudoScrollbarThumb:
        return SCROLLBAR_THUMB;
    case PseudoScrollbarTrack:
        return SCROLLBAR_TRACK;
    case PseudoScrollbarTrackPiece:
        return SCROLLBAR_TRACK_PIECE;
    case PseudoResizer:
        return RESIZER;
    case PseudoUnknown:
    case PseudoEmpty:
    case PseudoFirstChild:
    case PseudoFirstOfType:
    case PseudoLastChild:
    case PseudoLastOfType:
    case PseudoOnlyChild:
    case PseudoOnlyOfType:
    case PseudoNthChild:
    case PseudoNthOfType:
    case PseudoNthLastChild:
    case PseudoNthLastOfType:
    case PseudoLink:
    case PseudoVisited:
    case PseudoAny:
    case PseudoAnyLink:
    case PseudoAutofill:
    case PseudoHover:
    case PseudoDrag:
    case PseudoFocus:
    case PseudoActive:
    case PseudoChecked:
    case PseudoEnabled:
    case PseudoFullPageMedia:
    case PseudoDefault:
    case PseudoDisabled:
    case PseudoOptional:
    case PseudoRequired:
    case PseudoReadOnly:
    case PseudoReadWrite:
    case PseudoValid:
    case PseudoInvalid:
    case PseudoIndeterminate:
    case PseudoTarget:
    case PseudoLang:
    case PseudoNot:
    case PseudoRoot:
    case PseudoScope:
    case PseudoWindowInactive:
    case PseudoCornerPresent:
    case PseudoDecrement:
    case PseudoIncrement:
    case PseudoHorizontal:
    case PseudoVertical:
    case PseudoStart:
    case PseudoEnd:
    case PseudoDoubleButton:
    case PseudoSingleButton:
    case PseudoNoButton:
    case PseudoFirstPage:
    case PseudoLeftPage:
    case PseudoRightPage:
    case PseudoInRange:
    case PseudoOutOfRange:
    case PseudoWebKitCustomElement:
    case PseudoCue:
    case PseudoFutureCue:
    case PseudoPastCue:
    case PseudoUnresolved:
    case PseudoContent:
    case PseudoHost:
    case PseudoHostContext:
    case PseudoShadow:
    case PseudoFullScreen:
    case PseudoFullScreenDocument:
    case PseudoFullScreenAncestor:
    case PseudoSpatialNavigationFocus:
    case PseudoListBox:
        return NOPSEUDO;
    case PseudoNotParsed:
        ASSERT_NOT_REACHED();
        return NOPSEUDO;
    }

    ASSERT_NOT_REACHED();
    return NOPSEUDO;
}

// Could be made smaller and faster by replacing pointer with an
// offset into a string buffer and making the bit fields smaller but
// that could not be maintained by hand.
struct NameToPseudoStruct {
    const char* string;
    unsigned type:8;
};

// These tables should be kept sorted.
const static NameToPseudoStruct pseudoTypeWithoutArgumentsMap[] = {
{"-internal-list-box",            CSSSelector::PseudoListBox},
{"-internal-media-controls-cast-button", CSSSelector::PseudoWebKitCustomElement},
{"-internal-media-controls-overlay-cast-button", CSSSelector::PseudoWebKitCustomElement},
{"-internal-spatial-navigation-focus", CSSSelector::PseudoSpatialNavigationFocus},
{"-webkit-any-link",              CSSSelector::PseudoAnyLink},
{"-webkit-autofill",              CSSSelector::PseudoAutofill},
{"-webkit-drag",                  CSSSelector::PseudoDrag},
{"-webkit-full-page-media",       CSSSelector::PseudoFullPageMedia},
{"-webkit-full-screen",           CSSSelector::PseudoFullScreen},
{"-webkit-full-screen-ancestor",  CSSSelector::PseudoFullScreenAncestor},
{"-webkit-full-screen-document",  CSSSelector::PseudoFullScreenDocument},
{"-webkit-resizer",               CSSSelector::PseudoResizer},
{"-webkit-scrollbar",             CSSSelector::PseudoScrollbar},
{"-webkit-scrollbar-button",      CSSSelector::PseudoScrollbarButton},
{"-webkit-scrollbar-corner",      CSSSelector::PseudoScrollbarCorner},
{"-webkit-scrollbar-thumb",       CSSSelector::PseudoScrollbarThumb},
{"-webkit-scrollbar-track",       CSSSelector::PseudoScrollbarTrack},
{"-webkit-scrollbar-track-piece", CSSSelector::PseudoScrollbarTrackPiece},
{"active",                        CSSSelector::PseudoActive},
{"after",                         CSSSelector::PseudoAfter},
{"backdrop",                      CSSSelector::PseudoBackdrop},
{"before",                        CSSSelector::PseudoBefore},
{"checked",                       CSSSelector::PseudoChecked},
{"content",                       CSSSelector::PseudoContent},
{"corner-present",                CSSSelector::PseudoCornerPresent},
{"cue",                           CSSSelector::PseudoWebKitCustomElement},
{"decrement",                     CSSSelector::PseudoDecrement},
{"default",                       CSSSelector::PseudoDefault},
{"disabled",                      CSSSelector::PseudoDisabled},
{"double-button",                 CSSSelector::PseudoDoubleButton},
{"empty",                         CSSSelector::PseudoEmpty},
{"enabled",                       CSSSelector::PseudoEnabled},
{"end",                           CSSSelector::PseudoEnd},
{"first",                         CSSSelector::PseudoFirstPage},
{"first-child",                   CSSSelector::PseudoFirstChild},
{"first-letter",                  CSSSelector::PseudoFirstLetter},
{"first-line",                    CSSSelector::PseudoFirstLine},
{"first-of-type",                 CSSSelector::PseudoFirstOfType},
{"focus",                         CSSSelector::PseudoFocus},
{"future",                        CSSSelector::PseudoFutureCue},
{"horizontal",                    CSSSelector::PseudoHorizontal},
{"host",                          CSSSelector::PseudoHost},
{"hover",                         CSSSelector::PseudoHover},
{"in-range",                      CSSSelector::PseudoInRange},
{"increment",                     CSSSelector::PseudoIncrement},
{"indeterminate",                 CSSSelector::PseudoIndeterminate},
{"invalid",                       CSSSelector::PseudoInvalid},
{"last-child",                    CSSSelector::PseudoLastChild},
{"last-of-type",                  CSSSelector::PseudoLastOfType},
{"left",                          CSSSelector::PseudoLeftPage},
{"link",                          CSSSelector::PseudoLink},
{"no-button",                     CSSSelector::PseudoNoButton},
{"only-child",                    CSSSelector::PseudoOnlyChild},
{"only-of-type",                  CSSSelector::PseudoOnlyOfType},
{"optional",                      CSSSelector::PseudoOptional},
{"out-of-range",                  CSSSelector::PseudoOutOfRange},
{"past",                          CSSSelector::PseudoPastCue},
{"read-only",                     CSSSelector::PseudoReadOnly},
{"read-write",                    CSSSelector::PseudoReadWrite},
{"required",                      CSSSelector::PseudoRequired},
{"right",                         CSSSelector::PseudoRightPage},
{"root",                          CSSSelector::PseudoRoot},
{"scope",                         CSSSelector::PseudoScope},
{"selection",                     CSSSelector::PseudoSelection},
{"shadow",                        CSSSelector::PseudoShadow},
{"single-button",                 CSSSelector::PseudoSingleButton},
{"start",                         CSSSelector::PseudoStart},
{"target",                        CSSSelector::PseudoTarget},
{"unresolved",                    CSSSelector::PseudoUnresolved},
{"valid",                         CSSSelector::PseudoValid},
{"vertical",                      CSSSelector::PseudoVertical},
{"visited",                       CSSSelector::PseudoVisited},
{"window-inactive",               CSSSelector::PseudoWindowInactive},
};

const static NameToPseudoStruct pseudoTypeWithArgumentsMap[] = {
{"-webkit-any",      CSSSelector::PseudoAny},
{"cue",              CSSSelector::PseudoCue},
{"host",             CSSSelector::PseudoHost},
{"host-context",     CSSSelector::PseudoHostContext},
{"lang",             CSSSelector::PseudoLang},
{"not",              CSSSelector::PseudoNot},
{"nth-child",        CSSSelector::PseudoNthChild},
{"nth-last-child",   CSSSelector::PseudoNthLastChild},
{"nth-last-of-type", CSSSelector::PseudoNthLastOfType},
{"nth-of-type",      CSSSelector::PseudoNthOfType},
};

class NameToPseudoCompare {
public:
    NameToPseudoCompare(const AtomicString& key) : m_key(key) { ASSERT(m_key.is8Bit()); }

    bool operator()(const NameToPseudoStruct& entry, const NameToPseudoStruct&)
    {
        ASSERT(entry.string);
        const char* key = reinterpret_cast<const char*>(m_key.characters8());
        // If strncmp returns 0, then either the keys are equal, or |m_key| sorts before |entry|.
        return strncmp(entry.string, key, m_key.length()) < 0;
    }

private:
    const AtomicString& m_key;
};

static CSSSelector::PseudoType nameToPseudoType(const AtomicString& name, bool hasArguments)
{
    if (name.isNull() || !name.is8Bit())
        return CSSSelector::PseudoUnknown;

    const NameToPseudoStruct* pseudoTypeMap;
    const NameToPseudoStruct* pseudoTypeMapEnd;
    if (hasArguments) {
        pseudoTypeMap = pseudoTypeWithArgumentsMap;
        pseudoTypeMapEnd = pseudoTypeWithArgumentsMap + WTF_ARRAY_LENGTH(pseudoTypeWithArgumentsMap);
    } else {
        pseudoTypeMap = pseudoTypeWithoutArgumentsMap;
        pseudoTypeMapEnd = pseudoTypeWithoutArgumentsMap + WTF_ARRAY_LENGTH(pseudoTypeWithoutArgumentsMap);
    }
    NameToPseudoStruct dummyKey = { 0, CSSSelector::PseudoUnknown };
    const NameToPseudoStruct* match = std::lower_bound(pseudoTypeMap, pseudoTypeMapEnd, dummyKey, NameToPseudoCompare(name));
    if (match == pseudoTypeMapEnd || match->string != name.string())
        return CSSSelector::PseudoUnknown;

    return static_cast<CSSSelector::PseudoType>(match->type);
}

#ifndef NDEBUG
void CSSSelector::show(int indent) const
{
    printf("%*sselectorText(): %s\n", indent, "", selectorText().ascii().data());
    printf("%*sm_match: %d\n", indent, "", m_match);
    printf("%*sisCustomPseudoElement(): %d\n", indent, "", isCustomPseudoElement());
    if (m_match != Tag)
        printf("%*svalue(): %s\n", indent, "", value().ascii().data());
    printf("%*spseudoType(): %d\n", indent, "", pseudoType());
    if (m_match == Tag)
        printf("%*stagQName().localName: %s\n", indent, "", tagQName().localName().ascii().data());
    printf("%*sisAttributeSelector(): %d\n", indent, "", isAttributeSelector());
    if (isAttributeSelector())
        printf("%*sattribute(): %s\n", indent, "", attribute().localName().ascii().data());
    printf("%*sargument(): %s\n", indent, "", argument().ascii().data());
    printf("%*sspecificity(): %u\n", indent, "", specificity());
    if (tagHistory()) {
        printf("\n%*s--> (relation == %d)\n", indent, "", relation());
        tagHistory()->show(indent + 2);
    } else {
        printf("\n%*s--> (relation == %d)\n", indent, "", relation());
    }
}

void CSSSelector::show() const
{
    printf("\n******* CSSSelector::show(\"%s\") *******\n", selectorText().ascii().data());
    show(2);
    printf("******* end *******\n");
}
#endif

CSSSelector::PseudoType CSSSelector::parsePseudoType(const AtomicString& name, bool hasArguments)
{
    PseudoType pseudoType = nameToPseudoType(name, hasArguments);
    if (pseudoType != PseudoUnknown)
        return pseudoType;

    if (name.startsWith("-webkit-"))
        return PseudoWebKitCustomElement;

    return PseudoUnknown;
}

void CSSSelector::extractPseudoType() const
{
    if (m_match != PseudoClass && m_match != PseudoElement && m_match != PagePseudoClass)
        return;

    m_pseudoType = parsePseudoType(value(), !argument().isNull() || selectorList());

    bool element = false; // pseudo-element
    bool compat = false; // single colon compatbility mode
    bool isPagePseudoClass = false; // Page pseudo-class

    switch (m_pseudoType) {
    case PseudoAfter:
    case PseudoBefore:
    case PseudoFirstLetter:
    case PseudoFirstLine:
        compat = true;
    case PseudoBackdrop:
    case PseudoCue:
    case PseudoResizer:
    case PseudoScrollbar:
    case PseudoScrollbarCorner:
    case PseudoScrollbarButton:
    case PseudoScrollbarThumb:
    case PseudoScrollbarTrack:
    case PseudoScrollbarTrackPiece:
    case PseudoSelection:
    case PseudoWebKitCustomElement:
    case PseudoContent:
    case PseudoShadow:
        element = true;
        break;
    case PseudoUnknown:
    case PseudoEmpty:
    case PseudoFirstChild:
    case PseudoFirstOfType:
    case PseudoLastChild:
    case PseudoLastOfType:
    case PseudoOnlyChild:
    case PseudoOnlyOfType:
    case PseudoNthChild:
    case PseudoNthOfType:
    case PseudoNthLastChild:
    case PseudoNthLastOfType:
    case PseudoLink:
    case PseudoVisited:
    case PseudoAny:
    case PseudoAnyLink:
    case PseudoAutofill:
    case PseudoHover:
    case PseudoDrag:
    case PseudoFocus:
    case PseudoActive:
    case PseudoChecked:
    case PseudoEnabled:
    case PseudoFullPageMedia:
    case PseudoDefault:
    case PseudoDisabled:
    case PseudoOptional:
    case PseudoRequired:
    case PseudoReadOnly:
    case PseudoReadWrite:
    case PseudoScope:
    case PseudoValid:
    case PseudoInvalid:
    case PseudoIndeterminate:
    case PseudoTarget:
    case PseudoLang:
    case PseudoNot:
    case PseudoRoot:
    case PseudoWindowInactive:
    case PseudoCornerPresent:
    case PseudoDecrement:
    case PseudoIncrement:
    case PseudoHorizontal:
    case PseudoVertical:
    case PseudoStart:
    case PseudoEnd:
    case PseudoDoubleButton:
    case PseudoSingleButton:
    case PseudoNoButton:
    case PseudoNotParsed:
    case PseudoFullScreen:
    case PseudoFullScreenDocument:
    case PseudoFullScreenAncestor:
    case PseudoInRange:
    case PseudoOutOfRange:
    case PseudoFutureCue:
    case PseudoPastCue:
    case PseudoHost:
    case PseudoHostContext:
    case PseudoUnresolved:
    case PseudoSpatialNavigationFocus:
    case PseudoListBox:
        break;
    case PseudoFirstPage:
    case PseudoLeftPage:
    case PseudoRightPage:
        isPagePseudoClass = true;
        break;
    }

    bool matchPagePseudoClass = (m_match == PagePseudoClass);
    if (matchPagePseudoClass != isPagePseudoClass)
        m_pseudoType = PseudoUnknown;
    else if (m_match == PseudoClass && element) {
        if (!compat)
            m_pseudoType = PseudoUnknown;
        else
            m_match = PseudoElement;
    } else if (m_match == PseudoElement && !element)
        m_pseudoType = PseudoUnknown;
}

bool CSSSelector::operator==(const CSSSelector& other) const
{
    const CSSSelector* sel1 = this;
    const CSSSelector* sel2 = &other;

    while (sel1 && sel2) {
        if (sel1->attribute() != sel2->attribute()
            || sel1->relation() != sel2->relation()
            || sel1->m_match != sel2->m_match
            || sel1->value() != sel2->value()
            || sel1->pseudoType() != sel2->pseudoType()
            || sel1->argument() != sel2->argument()) {
            return false;
        }
        if (sel1->m_match == Tag) {
            if (sel1->tagQName() != sel2->tagQName())
                return false;
        }
        sel1 = sel1->tagHistory();
        sel2 = sel2->tagHistory();
    }

    if (sel1 || sel2)
        return false;

    return true;
}

String CSSSelector::selectorText(const String& rightSide) const
{
    StringBuilder str;

    if (m_match == Tag && !m_tagIsForNamespaceRule) {
        if (tagQName().prefix().isNull())
            str.append(tagQName().localName());
        else {
            str.append(tagQName().prefix().string());
            str.append('|');
            str.append(tagQName().localName());
        }
    }

    const CSSSelector* cs = this;
    while (true) {
        if (cs->m_match == Id) {
            str.append('#');
            serializeIdentifier(cs->value(), str);
        } else if (cs->m_match == Class) {
            str.append('.');
            serializeIdentifier(cs->value(), str);
        } else if (cs->m_match == PseudoClass || cs->m_match == PagePseudoClass) {
            str.append(':');
            str.append(cs->value());

            switch (cs->pseudoType()) {
            case PseudoNot:
                ASSERT(cs->selectorList());
                str.append('(');
                str.append(cs->selectorList()->first()->selectorText());
                str.append(')');
                break;
            case PseudoLang:
            case PseudoNthChild:
            case PseudoNthLastChild:
            case PseudoNthOfType:
            case PseudoNthLastOfType:
                str.append('(');
                str.append(cs->argument());
                str.append(')');
                break;
            case PseudoAny: {
                str.append('(');
                const CSSSelector* firstSubSelector = cs->selectorList()->first();
                for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(*subSelector)) {
                    if (subSelector != firstSubSelector)
                        str.append(',');
                    str.append(subSelector->selectorText());
                }
                str.append(')');
                break;
            }
            case PseudoHost:
            case PseudoHostContext: {
                if (cs->selectorList()) {
                    str.append('(');
                    const CSSSelector* firstSubSelector = cs->selectorList()->first();
                    for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(*subSelector)) {
                        if (subSelector != firstSubSelector)
                            str.append(',');
                        str.append(subSelector->selectorText());
                    }
                    str.append(')');
                }
                break;
            }
            default:
                break;
            }
        } else if (cs->m_match == PseudoElement) {
            str.appendLiteral("::");
            str.append(cs->value());

            if (cs->pseudoType() == PseudoContent) {
                if (cs->relation() == SubSelector && cs->tagHistory())
                    return cs->tagHistory()->selectorText() + str.toString() + rightSide;
            } else if (cs->pseudoType() == PseudoCue) {
                if (cs->selectorList()) {
                    str.append('(');
                    const CSSSelector* firstSubSelector = cs->selectorList()->first();
                    for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(*subSelector)) {
                        if (subSelector != firstSubSelector)
                            str.append(',');
                        str.append(subSelector->selectorText());
                    }
                    str.append(')');
                }
            }
        } else if (cs->isAttributeSelector()) {
            str.append('[');
            const AtomicString& prefix = cs->attribute().prefix();
            if (!prefix.isNull()) {
                str.append(prefix);
                str.append('|');
            }
            str.append(cs->attribute().localName());
            switch (cs->m_match) {
            case AttributeExact:
                str.append('=');
                break;
            case AttributeSet:
                // set has no operator or value, just the attrName
                str.append(']');
                break;
            case AttributeList:
                str.appendLiteral("~=");
                break;
            case AttributeHyphen:
                str.appendLiteral("|=");
                break;
            case AttributeBegin:
                str.appendLiteral("^=");
                break;
            case AttributeEnd:
                str.appendLiteral("$=");
                break;
            case AttributeContain:
                str.appendLiteral("*=");
                break;
            default:
                break;
            }
            if (cs->m_match != AttributeSet) {
                serializeString(cs->value(), str);
                if (cs->attributeMatchType() == CaseInsensitive)
                    str.appendLiteral(" i");
                str.append(']');
            }
        }
        if (cs->relation() != SubSelector || !cs->tagHistory())
            break;
        cs = cs->tagHistory();
    }

    if (const CSSSelector* tagHistory = cs->tagHistory()) {
        switch (cs->relation()) {
        case Descendant:
            return tagHistory->selectorText(" " + str.toString() + rightSide);
        case Child:
            return tagHistory->selectorText(" > " + str.toString() + rightSide);
        case ShadowDeep:
            return tagHistory->selectorText(" /deep/ " + str.toString() + rightSide);
        case DirectAdjacent:
            return tagHistory->selectorText(" + " + str.toString() + rightSide);
        case IndirectAdjacent:
            return tagHistory->selectorText(" ~ " + str.toString() + rightSide);
        case SubSelector:
            ASSERT_NOT_REACHED();
        case ShadowPseudo:
            return tagHistory->selectorText(str.toString() + rightSide);
        }
    }
    return str.toString() + rightSide;
}

void CSSSelector::setAttribute(const QualifiedName& value, AttributeMatchType matchType)
{
    createRareData();
    m_data.m_rareData->m_attribute = value;
    m_data.m_rareData->m_bits.m_attributeMatchType = matchType;
}

void CSSSelector::setArgument(const AtomicString& value)
{
    createRareData();
    m_data.m_rareData->m_argument = value;
}

void CSSSelector::setSelectorList(PassOwnPtr<CSSSelectorList> selectorList)
{
    createRareData();
    m_data.m_rareData->m_selectorList = selectorList;
}

static bool validateSubSelector(const CSSSelector* selector)
{
    switch (selector->match()) {
    case CSSSelector::Tag:
    case CSSSelector::Id:
    case CSSSelector::Class:
    case CSSSelector::AttributeExact:
    case CSSSelector::AttributeSet:
    case CSSSelector::AttributeList:
    case CSSSelector::AttributeHyphen:
    case CSSSelector::AttributeContain:
    case CSSSelector::AttributeBegin:
    case CSSSelector::AttributeEnd:
        return true;
    case CSSSelector::PseudoElement:
    case CSSSelector::Unknown:
        return false;
    case CSSSelector::PagePseudoClass:
    case CSSSelector::PseudoClass:
        break;
    }

    switch (selector->pseudoType()) {
    case CSSSelector::PseudoEmpty:
    case CSSSelector::PseudoLink:
    case CSSSelector::PseudoVisited:
    case CSSSelector::PseudoTarget:
    case CSSSelector::PseudoEnabled:
    case CSSSelector::PseudoDisabled:
    case CSSSelector::PseudoChecked:
    case CSSSelector::PseudoIndeterminate:
    case CSSSelector::PseudoNthChild:
    case CSSSelector::PseudoNthLastChild:
    case CSSSelector::PseudoNthOfType:
    case CSSSelector::PseudoNthLastOfType:
    case CSSSelector::PseudoFirstChild:
    case CSSSelector::PseudoLastChild:
    case CSSSelector::PseudoFirstOfType:
    case CSSSelector::PseudoLastOfType:
    case CSSSelector::PseudoOnlyOfType:
    case CSSSelector::PseudoHost:
    case CSSSelector::PseudoHostContext:
    case CSSSelector::PseudoNot:
    case CSSSelector::PseudoSpatialNavigationFocus:
    case CSSSelector::PseudoListBox:
        return true;
    default:
        return false;
    }
}

bool CSSSelector::isCompound() const
{
    if (!validateSubSelector(this))
        return false;

    const CSSSelector* prevSubSelector = this;
    const CSSSelector* subSelector = tagHistory();

    while (subSelector) {
        if (prevSubSelector->relation() != SubSelector)
            return false;
        if (!validateSubSelector(subSelector))
            return false;

        prevSubSelector = subSelector;
        subSelector = subSelector->tagHistory();
    }

    return true;
}

bool CSSSelector::parseNth() const
{
    if (!m_hasRareData)
        return false;
    if (m_parsedNth)
        return true;
    m_parsedNth = m_data.m_rareData->parseNth();
    return m_parsedNth;
}

bool CSSSelector::matchNth(int count) const
{
    ASSERT(m_hasRareData);
    return m_data.m_rareData->matchNth(count);
}

CSSSelector::RareData::RareData(const AtomicString& value)
    : m_value(value)
    , m_bits()
    , m_attribute(anyQName())
    , m_argument(nullAtom)
{
}

CSSSelector::RareData::~RareData()
{
}

// a helper function for parsing nth-arguments
bool CSSSelector::RareData::parseNth()
{
    String argument = m_argument.lower();

    if (argument.isEmpty())
        return false;

    int nthA = 0;
    int nthB = 0;
    if (argument == "odd") {
        nthA = 2;
        nthB = 1;
    } else if (argument == "even") {
        nthA = 2;
        nthB = 0;
    } else {
        size_t n = argument.find('n');
        if (n != kNotFound) {
            if (argument[0] == '-') {
                if (n == 1)
                    nthA = -1; // -n == -1n
                else
                    nthA = argument.substring(0, n).toInt();
            } else if (!n) {
                nthA = 1; // n == 1n
            } else {
                nthA = argument.substring(0, n).toInt();
            }

            size_t p = argument.find('+', n);
            if (p != kNotFound) {
                nthB = argument.substring(p + 1, argument.length() - p - 1).toInt();
            } else {
                p = argument.find('-', n);
                if (p != kNotFound)
                    nthB = -argument.substring(p + 1, argument.length() - p - 1).toInt();
            }
        } else {
            nthB = argument.toInt();
        }
    }
    setNthAValue(nthA);
    setNthBValue(nthB);
    return true;
}

// a helper function for checking nth-arguments
bool CSSSelector::RareData::matchNth(int count)
{
    if (!nthAValue())
        return count == nthBValue();
    if (nthAValue() > 0) {
        if (count < nthBValue())
            return false;
        return (count - nthBValue()) % nthAValue() == 0;
    }
    if (count > nthBValue())
        return false;
    return (nthBValue() - count) % (-nthAValue()) == 0;
}

} // namespace blink


text:
This is basically a ruby gem for asset pipeline which includes the version
0.1.2 of the awesome [rstacruz][rstacruz]' [nprogress][lib] library.

- [**Original lib**][lib]
- [**Demo**][demo]

[rstacruz]: https://github.com/rstacruz
[lib]: https://github.com/rstacruz/nprogress
[demo]: http://ricostacruz.com/nprogress/

## Installation

Add this line to your application's Gemfile:

    gem 'nprogress-rails'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install nprogress-rails

## Usage

You basically have to add the requires.

In your `application.js.coffee` (or just JS):

```coffeescript
#= require nprogress
#= require nprogress-turbolinks
```

The `nprogress-turbolinks` is required only if you use turbolinks. Using pjax
rather than turbolinks? Simply require `nprogress-pjax` instead. Want it also
for simple jQuery AJAX calls? Just require `nprogress-ajax`. Otherwise,
you will have to deal with show/hide the progress by your own.

Also, into your `application.css.scss` file:

```scss
$nprogress-color: #f1f1f1; // if you want to change the color
@import 'nprogress';
@import 'nprogress-bootstrap';
```

The `nprogress-bootstrap` is required if you use bootstrap and have a fixed
toolbar or anything else. tl;dr: if the console shows no erros, but the
progress doesn't appear, try this.

## Customization

You can use any of the configurations described in the [readme](https://github.com/rstacruz/nprogress#configuration)
with this lib. I just recommend you to do so ASAP, for example, just after
the `nprogress-rails` require:

```coffeescript
# this is the application.js.coffee file:

#= require jquery
#= require jquery_ujs
#= require turbolinks
#= require nprogress
#= require nprogress-turbolinks

NProgress.configure
  showSpinner: false
  ease: 'ease'
  speed: 500
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.elkoserver.server.context.mods (neohabitat 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2017-01-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.elkoserver.server.context.mods

A package of generally useful mods and related objects.

See: Description

Class Summary

Class
Description

Cartesian

Mod to provide an item with 2D (rectangular) geometry.

Census

Mod to enable tracking a context's population.

Chat

Mod to enable users in a context to chat with each other.

Dictionary

Mod to associate a server-moderated hashtable with its object.

Image

Mod to associate an image with an object.

Invisible

Marker mod to indicate that an item should be hidden from clients.

Note

Mod to hold a free-floating chunk of text.

NoteMaker

Mod to enable creation of notes.

PrivateChat

Mod to enable users in a context to chat privately with each other.

StyleDesc

Representation of style information for something containing text.

StyleOptions

Representation of permissible text style information in a context that can
 contain text.

TalkOptions

Mod to hold a context's permissible chat text display style options.

TalkPrefs

Mod to hold a user's current chat text display style settings.

Package org.elkoserver.server.context.mods Description

A package of generally useful mods and related objects.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2017. All rights reserved.


text:
package internalversion

import (
	authorization "github.com/openshift/origin/pkg/authorization/apis/authorization"
	internalinterfaces "github.com/openshift/origin/pkg/authorization/generated/informers/internalversion/internalinterfaces"
	internalclientset "github.com/openshift/origin/pkg/authorization/generated/internalclientset"
	internalversion "github.com/openshift/origin/pkg/authorization/generated/listers/authorization/internalversion"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	watch "k8s.io/apimachinery/pkg/watch"
	cache "k8s.io/client-go/tools/cache"
	time "time"
)

// ClusterPolicyInformer provides access to a shared informer and lister for
// ClusterPolicies.
type ClusterPolicyInformer interface {
	Informer() cache.SharedIndexInformer
	Lister() internalversion.ClusterPolicyLister
}

type clusterPolicyInformer struct {
	factory          internalinterfaces.SharedInformerFactory
	tweakListOptions internalinterfaces.TweakListOptionsFunc
}

// NewClusterPolicyInformer constructs a new informer for ClusterPolicy type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewClusterPolicyInformer(client internalclientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
	return NewFilteredClusterPolicyInformer(client, resyncPeriod, indexers, nil)
}

// NewFilteredClusterPolicyInformer constructs a new informer for ClusterPolicy type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredClusterPolicyInformer(client internalclientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
	return cache.NewSharedIndexInformer(
		&cache.ListWatch{
			ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.Authorization().ClusterPolicies().List(options)
			},
			WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
				if tweakListOptions != nil {
					tweakListOptions(&options)
				}
				return client.Authorization().ClusterPolicies().Watch(options)
			},
		},
		&authorization.ClusterPolicy{},
		resyncPeriod,
		indexers,
	)
}

func (f *clusterPolicyInformer) defaultInformer(client internalclientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
	return NewFilteredClusterPolicyInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}

func (f *clusterPolicyInformer) Informer() cache.SharedIndexInformer {
	return f.factory.InformerFor(&authorization.ClusterPolicy{}, f.defaultInformer)
}

func (f *clusterPolicyInformer) Lister() internalversion.ClusterPolicyLister {
	return internalversion.NewClusterPolicyLister(f.Informer().GetIndexer())
}


text:
package com.roboboost;

import android.app.Activity;
import android.widget.Toast;
import com.pivotallabs.injected.InjectedTestRunner;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.shadows.ShadowToast;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

@RunWith(InjectedTestRunner.class)
public class ToasterTest {
    @Test
    public void showToast_shouldShowAToastWithTheProvidedMessage() throws Exception {
        Toaster.showToast(new Activity(), "Hello");
        assertThat(ShadowToast.shownToastCount(), equalTo(1));
        assertThat(ShadowToast.getTextOfLatestToast(), equalTo("Hello"));
    }

    @Test
    public void showToast_shouldShowTheToastOnTheUIThread() throws Exception {
        Robolectric.pauseMainLooper();

        Toaster.showToast(new Activity(), "Hello");
        assertThat(ShadowToast.shownToastCount(), equalTo(0));

        Robolectric.unPauseMainLooper();
        assertThat(ShadowToast.shownToastCount(), equalTo(1));
    }

    // TODO fix in robolectric - doesn't shadow toast duration correctly
    // @Test
    public void showToast_shouldHaveADefaultDuration() throws Exception {
        Toaster.showToast(new Activity(), "Hello");
        assertThat(ShadowToast.getLatestToast().getDuration(), equalTo(Toast.LENGTH_SHORT));
    }

    // TODO fix in robolectric - doesn't shadow toast duration correctly
    // @Test
    public void showToast_shouldLetYouOverrideTheDuration() throws Exception {
        Toaster.showToast(new Activity(), "Hello", Toast.LENGTH_LONG);
        assertThat(ShadowToast.getLatestToast().getDuration(), equalTo(Toast.LENGTH_LONG));
    }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Phaser Source: input/Key.js</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

			Phaser

					Namespaces

							Phaser

					Classes

							Animation

							AnimationManager

							AnimationParser

							ArrayList

							BitmapData

							BitmapText

							Button

							Cache

							Camera

							Canvas

							Circle

							Color

							Device

							Easing

							Back

							Bounce

							Circular

							Cubic

							Elastic

							Exponential

							Linear

							Quadratic

							Quartic

							Quintic

							Sinusoidal

							Ellipse

							Events

							Filter

							Frame

							FrameData

							Game

							GameObjectCreator

							GameObjectFactory

							Gamepad

							GamepadButton

							Graphics

							Group

							Image

							Input

							InputHandler

							Key

							Keyboard

							Line

							LinkedList

							Loader

							LoaderParser

							Math

							Mouse

							MSPointer

							Net

							Particle

							Particles

							Emitter

							Physics

							Arcade

							Body

							Ninja

							AABB

							Body

							Circle

							Tile

							P2

							Body

							BodyDebug

							CollisionGroup

							ContactMaterial

							DistanceConstraint

							FixtureList

							GearConstraint

							InversePointProxy

							LockConstraint

							Material

							PointProxy

							PrismaticConstraint

							RevoluteConstraint

							Spring

							Plugin

							PluginManager

							Point

							Pointer

							Polygon

							QuadTree

							RandomDataGenerator

							Rectangle

							RenderTexture

							RequestAnimationFrame

							RetroFont

							ScaleManager

							Signal

							SignalBinding

							SinglePad

							Sound

							SoundManager

							Sprite

							SpriteBatch

							Stage

							State

							StateManager

							Text

							Tile

							Tilemap

							TilemapLayer

							TilemapParser

							Tileset

							TileSprite

							Time

							Timer

							TimerEvent

							Touch

							Tween

							TweenManager

							Utils

							Debug

							World

Source: input/Key.js

/**
* @class Phaser.Key
* @classdesc If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {number} keycode - The key code this Key is responsible for.
*/
Phaser.Key = function (game, keycode) {

    /**
    * @property {Phaser.Game} game - A reference to the currently running game.
    */
    this.game = game;

    /**
    * @property {boolean} enabled - An enabled key processes its update and dispatches events. You can toggle this at run-time to disable a key without deleting it.
    * @default
    */
    this.enabled = true;

    /**
    * @property {object} event - Stores the most recent DOM event.
    * @readonly
    */
    this.event = null;

    /**
    * @property {boolean} isDown - The "down" state of the key.
    * @default
    */
    this.isDown = false;

    /**
    * @property {boolean} isUp - The "up" state of the key.
    * @default
    */
    this.isUp = true;

    /**
    * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
    * @default
    */
    this.altKey = false;

    /**
    * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
    * @default
    */
    this.ctrlKey = false;

    /**
    * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
    * @default
    */
    this.shiftKey = false;

    /**
    * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
    */
    this.timeDown = 0;

    /**
    * If the key is down this value holds the duration of that key press and is constantly updated.
    * If the key is up it holds the duration of the previous down session.
    * @property {number} duration - The number of milliseconds this key has been held down for.
    * @default
    */
    this.duration = 0;

    /**
    * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
    * @default
    */
    this.timeUp = -2500;

    /**
    * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
    * @default
    */
    this.repeats = 0;

    /**
    * @property {number} keyCode - The keycode of this key.
    */
    this.keyCode = keycode;

    /**
    * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
    */
    this.onDown = new Phaser.Signal();

    /**
    * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second.
    */
    this.onHoldCallback = null;

    /**
    * @property {object} onHoldContext - The context under which the onHoldCallback will be called.
    */
    this.onHoldContext = null;

    /**
    * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
    */
    this.onUp = new Phaser.Signal();

};

Phaser.Key.prototype = {

    update: function () {

        if (!this.enabled) { return; }

        if (this.isDown)
        {
            this.duration = this.game.time.now - this.timeDown;
            this.repeats++;

            if (this.onHoldCallback)
            {
                this.onHoldCallback.call(this.onHoldContext, this);
            }
        }

    },

    /**
    * Called automatically by Phaser.Keyboard.
    * @method Phaser.Key#processKeyDown
    * @param {KeyboardEvent} event.
    * @protected
    */
    processKeyDown: function (event) {

        if (!this.enabled) { return; }

        this.event = event;

        if (this.isDown)
        {
            return;
        }

        this.altKey = event.altKey;
        this.ctrlKey = event.ctrlKey;
        this.shiftKey = event.shiftKey;

        this.isDown = true;
        this.isUp = false;
        this.timeDown = this.game.time.now;
        this.duration = 0;
        this.repeats = 0;

        this.onDown.dispatch(this);

    },

    /**
    * Called automatically by Phaser.Keyboard.
    * @method Phaser.Key#processKeyUp
    * @param {KeyboardEvent} event.
    * @protected
    */
    processKeyUp: function (event) {

        if (!this.enabled) { return; }

        this.event = event;

        if (this.isUp)
        {
            return;
        }

        this.isDown = false;
        this.isUp = true;
        this.timeUp = this.game.time.now;
        this.duration = this.game.time.now - this.timeDown;

        this.onUp.dispatch(this);

    },

    /**
    * Resets the state of this Key. This sets isDown to false, isUp to true, resets the time to be the current time and clears any callbacks
    * associated with the onDown and onUp events and nulls the onHoldCallback if set.
    *
    * @method Phaser.Key#reset
    * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to this Key. A hard reset will.
    */
    reset: function (hard) {

        if (typeof hard === 'undefined') { hard = true; }

        this.isDown = false;
        this.isUp = true;
        this.timeUp = this.game.time.now;
        this.duration = 0;
        this.enabled = true;

        if (hard)
        {
            this.onDown.removeAll();
            this.onUp.removeAll();
            this.onHoldCallback = null;
            this.onHoldContext = null;
        }

    },

    /**
    * Returns the "just pressed" state of the Key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
    * @method Phaser.Key#justPressed
    * @param {number} [duration=50] - The duration below which the key is considered as being just pressed.
    * @return {boolean} True if the key is just pressed otherwise false.
    */
    justPressed: function (duration) {

        if (typeof duration === "undefined") { duration = 50; }

        return (this.isDown && this.duration < duration);

    },

    /**
    * Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
    * @method Phaser.Key#justReleased
    * @param {number} [duration=50] - The duration below which the key is considered as being just released.
    * @return {boolean} True if the key is just released otherwise false.
    */
    justReleased: function (duration) {

        if (typeof duration === "undefined") { duration = 50; }

        return (!this.isDown && ((this.game.time.now - this.timeUp) < duration));

    }

};

Phaser.Key.prototype.constructor = Phaser.Key;

		Phaser Copyright © 2012-2014 Photon Storm Ltd.

		Documentation generated by JSDoc 3.3.0-dev
		on Fri Jul 18 2014 12:36:36 GMT+0100 (BST) using the DocStrap template.


text:
#pragma once

#include <string>

#include "envoy/common/platform.h"
#include "envoy/config/core/v3/base.pb.h"
#include "envoy/http/request_id_extension.h"
#include "envoy/local_info/local_info.h"
#include "envoy/runtime/runtime.h"
#include "envoy/thread_local/thread_local.h"
#include "envoy/tracing/http_tracer.h"
#include "envoy/upstream/cluster_manager.h"

#include "source/common/http/header_map_impl.h"
#include "source/common/json/json_loader.h"
#include "source/common/tracing/common_values.h"
#include "source/common/tracing/null_span_impl.h"

namespace Envoy {
namespace Tracing {

class HttpTracerUtility {
public:
  /**
   * Get string representation of the operation.
   * @param operation name to convert.
   * @return string representation of the operation.
   */
  static const std::string& toString(OperationName operation_name);

  /**
   * Request might be traceable if the request ID is traceable or we do sampling tracing.
   * Note: there is a global switch which turns off tracing completely on server side.
   *
   * @return decision if request is traceable or not and Reason why.
   **/
  static Decision shouldTraceRequest(const StreamInfo::StreamInfo& stream_info);

  /**
   * Adds information obtained from the downstream request headers as tags to the active span.
   * Then finishes the span.
   */
  static void finalizeDownstreamSpan(Span& span, const Http::RequestHeaderMap* request_headers,
                                     const Http::ResponseHeaderMap* response_headers,
                                     const Http::ResponseTrailerMap* response_trailers,
                                     const StreamInfo::StreamInfo& stream_info,
                                     const Config& tracing_config);

  /**
   * Adds information obtained from the upstream request headers as tags to the active span.
   * Then finishes the span.
   */
  static void finalizeUpstreamSpan(Span& span, const StreamInfo::StreamInfo& stream_info,
                                   const Config& tracing_config);

  /**
   * Adds tags to the current "unfinished" span when processing upstream response headers.
   * NOOP if headers are nullptr.
   */
  static void onUpstreamResponseHeaders(Span& span,
                                        const Http::ResponseHeaderMap* response_headers);

  /**
   * Adds tags to the current "unfinished" span when processing upstream response trailers.
   * NOOP if trailers are nullptr.
   */
  static void onUpstreamResponseTrailers(Span& span,
                                         const Http::ResponseTrailerMap* response_trailers);

private:
  static void setCommonTags(Span& span, const StreamInfo::StreamInfo& stream_info,
                            const Config& tracing_config);

  static const std::string IngressOperation;
  static const std::string EgressOperation;
};

class EgressConfigImpl : public Config {
public:
  // Tracing::Config
  Tracing::OperationName operationName() const override { return Tracing::OperationName::Egress; }
  const CustomTagMap* customTags() const override { return nullptr; }
  bool verbose() const override { return false; }
  uint32_t maxPathTagLength() const override { return Tracing::DefaultMaxPathTagLength; }
};

using EgressConfig = ConstSingleton<EgressConfigImpl>;

class HttpNullTracer : public HttpTracer {
public:
  // Tracing::HttpTracer
  SpanPtr startSpan(const Config&, Http::RequestHeaderMap&, const StreamInfo::StreamInfo&,
                    const Tracing::Decision) override {
    return SpanPtr{new NullSpan()};
  }
};

class HttpTracerImpl : public HttpTracer {
public:
  HttpTracerImpl(DriverSharedPtr driver, const LocalInfo::LocalInfo& local_info);

  // Tracing::HttpTracer
  SpanPtr startSpan(const Config& config, Http::RequestHeaderMap& request_headers,
                    const StreamInfo::StreamInfo& stream_info,
                    const Tracing::Decision tracing_decision) override;

  DriverSharedPtr driverForTest() const { return driver_; }

private:
  DriverSharedPtr driver_;
  const LocalInfo::LocalInfo& local_info_;
};

} // namespace Tracing
} // namespace Envoy


text:
var match = require('../lib/match')
var setName = require('../lib/setName')
var logger = require('../lib/logger')

function getIsArray () {
  return logger(function isArray (o) {
    return Array.isArray(o)
  })
}

module.exports = function arrayOf (args, some) {
  var prefixName = some ? 'some' : 'every'
  var val = match(args)

  var func = function (arr, callback, path) {
    var result = !some
    path = path || ''
    if (!getIsArray()(arr, callback, path)) return false
    for (var i = 0; i < arr.length; i++) {
      result = val(arr[i], callback, path + '[' + i + ']')
      if (some) {
        if (result) {
          return true // if true no needs to go on
        }
      } else {
        if (!result) {
          if (!callback) {
            return false
          }
          result = false // extra check only if callback
        }
      }
    }
    return result
  }
  return setName(func, prefixName + '(' + val.name + ')')
}


text:
using System;

namespace Pantheon.Common.DistributedObjects
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class OwnerSendAttribute : PantheonAttribute
    {
    }
}


text:
package gov.hhs.fha.nhinc.transform.policy;

import gov.hhs.fha.nhinc.common.eventcommon.AdhocQueryRequestEventType;
import gov.hhs.fha.nhinc.common.eventcommon.AdhocQueryResultEventType;
import gov.hhs.fha.nhinc.common.eventcommon.DocRetrieveEventType;
import gov.hhs.fha.nhinc.common.eventcommon.DocRetrieveResultEventType;
import gov.hhs.fha.nhinc.common.eventcommon.FindAuditEventsEventType;
import gov.hhs.fha.nhinc.common.eventcommon.NotifyEventType;
import gov.hhs.fha.nhinc.common.eventcommon.PatDiscReqEventType;
import gov.hhs.fha.nhinc.common.eventcommon.SubscribeEventType;
import gov.hhs.fha.nhinc.common.eventcommon.UnsubscribeEventType;
import gov.hhs.fha.nhinc.common.eventcommon.XDREventType;
import gov.hhs.fha.nhinc.common.eventcommon.XDRResponseEventType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.CheckPolicyRequestType;

/**
 *
 * @author rayj
 */
public class PolicyEngineTransformer {

    public CheckPolicyRequestType transformPatDiscReqToCheckPolicy(
            PatDiscReqEventType transformPatDiscReqToCheckPolicyRequest) {
        return new PatientDiscoveryPolicyTransformHelper()
                .transformPatientDiscoveryNhincToCheckPolicy(transformPatDiscReqToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformAdhocQueryToCheckPolicy(
            AdhocQueryRequestEventType transformAdhocQueryToCheckPolicyRequest) {
        return AdhocQueryTransformHelper.transformAdhocQueryToCheckPolicy(transformAdhocQueryToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformAdhocQueryResultToCheckPolicy(
            AdhocQueryResultEventType transformAdhocQueryResultToCheckPolicyRequest) {
        return AdhocQueryTransformHelper
                .transformAdhocQueryResponseToCheckPolicy(transformAdhocQueryResultToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformDocRetrieveToCheckPolicy(
            DocRetrieveEventType transformDocRetrieveToCheckPolicyRequest) {
        return DocRetrieveTransformHelper.transformDocRetrieveToCheckPolicy(transformDocRetrieveToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformDocRetrieveResultToCheckPolicy(
            DocRetrieveResultEventType transformDocRetrieveResultToCheckPolicyRequest) {
        // TODO implement this method
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    public CheckPolicyRequestType transformFindAuditEventsToCheckPolicy(
            FindAuditEventsEventType transformFindAuditEventsToCheckPolicyRequest) {
        return FindAuditEventsTransformHelper
                .transformFindAuditEventsToCheckPolicy(transformFindAuditEventsToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformSubscribeToCheckPolicy(
            SubscribeEventType transformSubscribeToCheckPolicyRequest) {
        return SubscribeTransformHelper.transformSubscribeToCheckPolicy(transformSubscribeToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformUnsubscribeToCheckPolicy(
            UnsubscribeEventType transformUnsubscribeToCheckPolicyRequest) {
        return UnsubscribeTransformHelper.transformUnsubscribeToCheckPolicy(transformUnsubscribeToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformNotifyToCheckPolicy(NotifyEventType transformNotifyToCheckPolicyRequest) {
        return NotifyTransformHelper.transformNotifyToCheckPolicy(transformNotifyToCheckPolicyRequest);
    }

    public CheckPolicyRequestType transformXDRRequestToCheckPolicy(XDREventType request) {
        return new XDRPolicyTransformHelper().transformXDRToCheckPolicy(request);
    }

    public CheckPolicyRequestType transformXDRResponseInputToCheckPolicy(XDRResponseEventType request) {
        return new XDRPolicyTransformHelper().transformXDRResponseToCheckPolicy(request);
    }

}


text:
get_id () {
    echo `"$@" | awk '/ id / { print $4 }'`
}
unset OS_SERVICE_TOKEN OS_SERVICE_ENDPOINT
export OS_AUTH_URL=http://localhost:5000/v2.0
export OS_TENANT_NAME=demo
export OS_PASSWORD=nomoresecrete
export OS_USERNAME=admin
ADMIN_TOKEN=$(get_id keystone token-get)
while read USER_TOKEN; do
    curl -H "X-Auth-Token:${ADMIN_TOKEN}" http://0.0.0.0:5000/v2.0/tokens/${USER_TOKEN} \
        2>&1 | grep "issued_at" > /dev/null
    if [ "$?" != 0 ]; then
        echo "Token validation failed"
        break
    fi
done < /tmp/tokens_list.txt


text:
namespace IECore
{

/// A simple class to allow, for example, extra data to be added to a class for use in cases where simply
/// adding member data would break the library's binary compatibility.
/// Template with the type of the class that data is being added to, the type of the data being
/// added, and policy for deleting that data when the class is destructed. The latter allows use of
/// dynamically-allocated data and arrays.
///
/// It the responsibility of the client of this class to implement all creation, deletion, and copy semantics.
///
/// Example, which effectively adds an extra member of type "int" to class "A" :
///
/// \code
/// // In file A.h :
/// class A
/// {
///    int &extraMember();
/// };
///
/// // In file A.cpp:
///
/// #include "A.h"
/// #include "IECore/ClassData.h"
///
/// static IECore::ClassData< A, int > g_classData;
///
/// A::A()
/// {
///    g_classData.create( this, 4 );
/// }
///
/// A::~A()
/// {
///    g_classData.erase( this );
/// }
///
/// int &A::extraMember()
/// {
///    return g_classData[ this ];
/// }
/// \endcode
template< typename ClassTypeT, typename DataTypeT, typename DataDeletePolicyT = NullDeleter<DataTypeT> >
class ClassData
{
	public:

		typedef ClassTypeT        ClassType;
		typedef DataTypeT         DataType;
		typedef DataDeletePolicyT DataDeletePolicy;

		/// Exercises DataDeletePolicy on all held data
		virtual ~ClassData();

		/// Create some uninitialized data for the given class
		DataType &create( const ClassType* classOwner );

		/// Create some data with initial value as specified for the given class
		DataType &create( const ClassType* classOwner, const DataType &d );

		/// Const access to the data associated with the class. If the data has not yet been created
		/// the behaviour is undefined.
		const DataType &operator[]( const ClassType *classOwner ) const;

		/// Read/write access to the data associated with the class. If the data has not yet been created
		/// the behaviour is undefined.
		DataType &operator[]( const ClassType *classOwner );

		/// Exercise DataDeletePolicy on the classOwner's data, and remove it. If the data has not yet been created
		/// the behaviour is undefined.
		void erase( const ClassType *classOwner );

	protected:

		typedef std::map< const ClassType*, DataType > ClassDataMap;
		ClassDataMap m_classDataMap;
};

} // namespace IECore

#include "IECore/ClassData.inl"

#endif // IE_CORE_CLASSDATA_H


text:
az network vnet create -g ${RESOURCE_GROUP} -n DualCustomVNET --address-prefixes 10.100.0.0/24 10.200.0.0/24 --subnet-name DualMasterSubnet --subnet-prefix 10.100.0.0/24
az network vnet subnet create --name DualAgentSubnet --address-prefix 10.200.0.0/24 -g ${RESOURCE_GROUP} --vnet-name DualCustomVNET

tempfile="$(mktemp)"
trap "rm -rf \"${tempfile}\"" EXIT

jq ".properties.masterProfile.vnetSubnetId = \"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/DualCustomVNET/subnets/DualMasterSubnet\"" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}

indx=0
for poolname in `jq -r '.properties.agentPoolProfiles[].name' "${CLUSTER_DEFINITION}"`; do
  jq ".properties.agentPoolProfiles[$indx].vnetSubnetId = \"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/DualCustomVNET/subnets/DualAgentSubnet\"" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}
  indx=$((indx+1))
done


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Example.BroadcastReceiver.Dynamic</string>
    <string name="buttonSend">Send Broadcast Intent</string>

</resources>


text:
require 'rails_helper'

describe "pipelines/build_cause.html.erb" do
  it "should render build_cause_popup" do
    @pipeline_instance = double("Pipeline Instance")
    stub_template "shared/_build_cause_popup.html.erb" => "BUILD CAUSE POPUP"

    render

    assert_template partial: "shared/_build_cause_popup", locals: {scope: {pipeline_instance: @pipeline_instance}}
    expect(rendered).to eq("BUILD CAUSE POPUP")
  end
end


text:
// This file can't be once, it gets included multiple times to get definitions and declarations.

#include "Security/Tool/SecurityCommands.h"
#include "SOSCircle/Tool/SOSCommands.h"


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no">
    <title>Angular UI Template</title>
    <link rel="stylesheet" href="css/main.css">


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

	<link href="browser.css" type="text/css" rel="stylesheet" />


text:
fn bad_bang(i: usize) -> ! { //~ ERROR computation may converge in a function marked as diverging
    println!("{}", 3);
}

fn main() { bad_bang(5); }


text:
<?php

namespace Axstrad\DoctrineExtensions\Activatable\Mapping\Event;

use Gedmo\Mapping\Event\AdapterInterface;

/**
 * Axstrad\DoctrineExtensions\Activatable\Mapping\Event\ActivatableAdapter
 *
 * Doctrine event adapter interface for Activatable behavior
 */
interface ActivatableAdapter extends AdapterInterface
{
}


text:
#pragma once

#include "dbms/src/LESSDB.h"

class Database : public LESSDB
{
    public:
    class Handlers
    {
        public:
        Handlers()                                = default;
        virtual void presetChange(uint8_t preset) = 0;
        virtual void factoryResetStart()          = 0;
        virtual void factoryResetDone()           = 0;
        virtual void initialized()                = 0;
    };

    Database(LESSDB::StorageAccess& storageAccess, bool initializeData)
        : LESSDB(storageAccess)
        , _initializeData(initializeData)
    {}

    enum class block_t : uint8_t
    {
        global,
        buttons,
        encoders,
        analog,
        leds,
        display,
        touchscreen,
        AMOUNT
    };

    class Section
    {
        public:
        Section() {}

        enum class global_t : uint8_t
        {
            midiFeatures,
            midiMerge,
            AMOUNT
        };

        enum class button_t : uint8_t
        {
            type,
            midiMessage,
            midiID,
            velocity,
            midiChannel,
            AMOUNT
        };

        enum class encoder_t : uint8_t
        {
            enable,
            invert,
            mode,
            midiID,
            midiChannel,
            pulsesPerStep,
            acceleration,
            remoteSync,
            AMOUNT
        };

        enum class analog_t : uint8_t
        {
            enable,
            invert,
            type,
            midiID,
            lowerLimit,
            upperLimit,
            midiChannel,
            AMOUNT
        };

        enum class leds_t : uint8_t
        {
            global,
            activationID,
            rgbEnable,
            controlType,
            activationValue,
            midiChannel,
            AMOUNT
        };

        enum class display_t : uint8_t
        {
            features,
            setting,
            AMOUNT
        };

        enum class touchscreen_t : uint8_t
        {
            setting,
            xPos,
            yPos,
            width,
            height,
            onScreen,
            offScreen,
            pageSwitchEnabled,
            pageSwitchIndex,
            analogPage,
            analogStartXCoordinate,
            analogEndXCoordinate,
            analogStartYCoordinate,
            analogEndYCoordinate,
            analogType,
            analogResetOnRelease,
            AMOUNT
        };
    };

    using LESSDB::read;
    using LESSDB::update;

    template<typename T>
    int32_t read(T section, size_t index)
    {
        block_t blockIndex = block(section);
        return LESSDB::read(static_cast<uint8_t>(blockIndex), static_cast<uint8_t>(section), index);
    }

    template<typename T>
    bool read(T section, size_t index, int32_t& value)
    {
        block_t blockIndex = block(section);
        return LESSDB::read(static_cast<uint8_t>(blockIndex), static_cast<uint8_t>(section), index, value);
    }

    template<typename T>
    bool update(T section, size_t index, int32_t value)
    {
        block_t blockIndex = block(section);
        return LESSDB::update(static_cast<uint8_t>(blockIndex), static_cast<uint8_t>(section), index, value);
    }

    bool    init();
    bool    factoryReset();
    uint8_t getSupportedPresets();
    bool    setPreset(uint8_t preset);
    uint8_t getPreset();
    bool    setPresetPreserveState(bool state);
    bool    getPresetPreserveState();
    bool    isInitialized();
    void    registerHandlers(Handlers& handlers);

    void customInitGlobal();
    void customInitButtons();
    void customInitEncoders();
    void customInitAnalog();
    void customInitLEDs();
    void customInitDisplay();
    void customInitTouchscreen();

    private:
    block_t block(Section::global_t section)
    {
        return block_t::global;
    }

    block_t block(Section::button_t section)
    {
        return block_t::buttons;
    }

    block_t block(Section::encoder_t section)
    {
        return block_t::encoders;
    }

    block_t block(Section::analog_t section)
    {
        return block_t::analog;
    }

    block_t block(Section::leds_t section)
    {
        return block_t::leds;
    }

    block_t block(Section::display_t section)
    {
        return block_t::display;
    }

    block_t block(Section::touchscreen_t section)
    {
        return block_t::touchscreen;
    }

    bool     isSignatureValid();
    uint16_t getDbUID();
    bool     setDbUID(uint16_t uid);
    bool     setPresetInternal(uint8_t preset);

    Handlers* _handlers = nullptr;

    const bool _initializeData;

    /// Address at which user data starts (after system block).
    /// Used to set correct offset in database for user layout.
    uint32_t _userDataStartAddress;

    /// Address at which next preset should start.
    /// Used to calculate the start address of next preset.
    uint32_t _lastPresetAddress;

    /// Holds total number of supported presets.
    uint16_t _supportedPresets;

    /// Holds currently active preset.
    uint8_t _activePreset = 0;

    bool _initialized = false;
};


text:
import randomNumber from './random-number';

export default function(interval) {
  let value;

  if (Array.isArray(interval) && interval.length === 2) {
    const [min, max] = interval;

    value = randomNumber(min, max);
  } else if (typeof interval === 'function') {
    value = interval();
  } else {
    value = parseInt(interval, 10);
  }

  return value;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>net.jini.url.httpmd (River-Internet vtrunk API Documentation)</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

net.jini.url.httpmd

Classes

Handler

HttpmdIntegrityVerifier

HttpmdUtil

Exceptions

WrongMessageDigestException


text:
tutorial_title = u'ProDy Tutorial'
tutorial_author = u'Ahmet Bakan, Cihan Kaya'
tutorial_logo = u''           # default is ProDy logo
tutorial_version = u''        # default is latest ProDy version
# keep the following part as is

try:
    execfile('../conf.py')
except NameError:
    exec(open('../conf.py').read())


text:
package testevents

// EventListeners are functions that are called when the appropriate event
// is dispatched
//
// Funcs can only be compared to nil, so a listener
// is expected to have a unique numeric ID attached to it.
type EventListener struct {
	Listener func(Event)
	ID       int
}

var listeners map[EventType][]EventListener

func init() {
	listeners = make(map[EventType][]EventListener)
}

// The EventType is exactly what occurred during testing, such as the test passing
// or failing
type EventType uint

const (
	TestStarted EventType = iota
	TestPassed
	TestFinished
	TestFailed
	TestSkipped
)

// An Event is a simple pair of the name of the testing function being executed,
// and the test status (e.g. TestFailed, TestFinished, etc)
type Event struct {
	Name string
	Typ  EventType
}

// Registers a listener for a certain type of test event
//
// If the listener is already registered, this is a no op
func Register(typ EventType, listener EventListener) {
	if IsRegistered(typ, listener) {
		return
	}

	listeners[typ] = append(listeners[typ], listener)
}

// Unregisters a listener for a certain type of event
//
// If the listener is not registered, this is a no op
func Unregister(typ EventType, listener EventListener) {
	index := -1
	for i, l := range listeners[typ] {
		if l.ID == listener.ID {
			index = i
			break
		}
	}

	listeners[typ] = append(listeners[typ][:index], listeners[typ][index+1:]...)
}

// Returns whether or not a listener is registered already
func IsRegistered(typ EventType, listener EventListener) bool {
	for _, l := range listeners[typ] {
		if l.ID == listener.ID {
			return true
		}
	}

	return false
}

// Dispatches an event to all registered listeners
func Dispatch(e Event) {
	for _, l := range listeners[e.Typ] {
		l.Listener(e)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Azure.Communication.Sms;
using Azure.Core;

namespace Azure.Communication.Sms.Models
{
    /// <summary> Response for a successful or multi status send Sms request. </summary>
    internal partial class SmsSendResponse
    {
        /// <summary> Initializes a new instance of SmsSendResponse. </summary>
        /// <param name="value"></param>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        internal SmsSendResponse(IEnumerable<SmsSendResult> value)
        {
            Argument.AssertNotNull(value, nameof(value));

            Value = value.ToList();
        }

        /// <summary> Initializes a new instance of SmsSendResponse. </summary>
        /// <param name="value"></param>
        internal SmsSendResponse(IReadOnlyList<SmsSendResult> value)
        {
            Value = value;
        }

        /// <summary> Gets the value. </summary>
        public IReadOnlyList<SmsSendResult> Value { get; }
    }
}


text:
package marker

import (
	runtime "k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func (in *Defaulted) DeepCopy() *Defaulted {
	if in == nil {
		return nil
	}
	out := new(Defaulted)
	in.DeepCopyInto(out)
	return out
}

func (in *Defaulted) DeepCopyInto(out *Defaulted) {
	*out = *in
	return
}

func (in *Defaulted) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

func (in *DefaultedWithFunction) DeepCopy() *DefaultedWithFunction {
	if in == nil {
		return nil
	}
	out := new(DefaultedWithFunction)
	in.DeepCopyInto(out)
	return out
}

func (in *DefaultedWithFunction) DeepCopyInto(out *DefaultedWithFunction) {
	*out = *in
	return
}

func (in *DefaultedWithFunction) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

func (obj *Defaulted) GetObjectKind() schema.ObjectKind             { return schema.EmptyObjectKind }
func (obj *DefaultedWithFunction) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }