text:
import crypto from 'crypto';
import { Logger } from '../logger';
import { ADMIN, CLIENT, FRONTEND } from '../types/permissions';
import { IUnleashStores } from '../types/stores';
import { IUnleashConfig } from '../types/option';
import ApiUser from '../types/api-user';
import {
    ApiTokenType,
    IApiToken,
    ILegacyApiTokenCreate,
    IApiTokenCreate,
    validateApiToken,
    validateApiTokenEnvironment,
    mapLegacyToken,
    mapLegacyTokenWithSecret,
} from '../types/models/api-token';
import { IApiTokenStore } from '../types/stores/api-token-store';
import { FOREIGN_KEY_VIOLATION } from '../error/db-error';
import BadDataError from '../error/bad-data-error';
import { minutesToMilliseconds } from 'date-fns';
import { IEnvironmentStore } from 'lib/types/stores/environment-store';
import { constantTimeCompare } from '../util/constantTimeCompare';

const resolveTokenPermissions = (tokenType: string) => {
    if (tokenType === ApiTokenType.ADMIN) {
        return [ADMIN];
    }

    if (tokenType === ApiTokenType.CLIENT) {
        return [CLIENT];
    }

    if (tokenType === ApiTokenType.FRONTEND) {
        return [FRONTEND];
    }

    return [];
};

export class ApiTokenService {
    private store: IApiTokenStore;

    private environmentStore: IEnvironmentStore;

    private logger: Logger;

    private timer: NodeJS.Timeout;

    private activeTokens: IApiToken[] = [];

    constructor(
        {
            apiTokenStore,
            environmentStore,
        }: Pick<IUnleashStores, 'apiTokenStore' | 'environmentStore'>,
        config: Pick<IUnleashConfig, 'getLogger' | 'authentication'>,
    ) {
        this.store = apiTokenStore;
        this.environmentStore = environmentStore;
        this.logger = config.getLogger('/services/api-token-service.ts');
        this.fetchActiveTokens();
        this.timer = setInterval(
            () => this.fetchActiveTokens(),
            minutesToMilliseconds(1),
        ).unref();
        if (config.authentication.initApiTokens.length > 0) {
            process.nextTick(async () =>
                this.initApiTokens(config.authentication.initApiTokens),
            );
        }
    }

    async fetchActiveTokens(): Promise<void> {
        try {
            this.activeTokens = await this.getAllActiveTokens();
        } finally {
            // eslint-disable-next-line no-unsafe-finally
            return;
        }
    }

    public async getAllTokens(): Promise<IApiToken[]> {
        return this.store.getAll();
    }

    public async getAllActiveTokens(): Promise<IApiToken[]> {
        return this.store.getAllActive();
    }

    private async initApiTokens(tokens: ILegacyApiTokenCreate[]) {
        const tokenCount = await this.store.count();
        if (tokenCount > 0) {
            return;
        }
        try {
            const createAll = tokens
                .map(mapLegacyTokenWithSecret)
                .map((t) => this.insertNewApiToken(t));
            await Promise.all(createAll);
        } catch (e) {
            this.logger.error('Unable to create initial Admin API tokens');
        }
    }

    public getUserForToken(secret: string): ApiUser | undefined {
        if (!secret) {
            return undefined;
        }

        let token = this.activeTokens.find(
            (activeToken) =>
                Boolean(activeToken.secret) &&
                constantTimeCompare(activeToken.secret, secret),
        );

        // If the token is not found, try to find it in the legacy format with alias.
        // This allows us to support the old format of tokens migrating to the embedded proxy.
        if (!token) {
            token = this.activeTokens.find(
                (activeToken) =>
                    Boolean(activeToken.alias) &&
                    constantTimeCompare(activeToken.alias, secret),
            );
        }

        if (token) {
            return new ApiUser({
                username: token.username,
                permissions: resolveTokenPermissions(token.type),
                projects: token.projects,
                environment: token.environment,
                type: token.type,
                secret: token.secret,
            });
        }

        return undefined;
    }

    public async updateExpiry(
        secret: string,
        expiresAt: Date,
    ): Promise<IApiToken> {
        return this.store.setExpiry(secret, expiresAt);
    }

    public async delete(secret: string): Promise<void> {
        return this.store.delete(secret);
    }

    /**
     * @deprecated This may be removed in a future release, prefer createApiTokenWithProjects
     */
    public async createApiToken(
        newToken: Omit<ILegacyApiTokenCreate, 'secret'>,
    ): Promise<IApiToken> {
        const token = mapLegacyToken(newToken);
        return this.createApiTokenWithProjects(token);
    }

    public async createApiTokenWithProjects(
        newToken: Omit<IApiTokenCreate, 'secret'>,
    ): Promise<IApiToken> {
        validateApiToken(newToken);

        const environments = await this.environmentStore.getAll();
        validateApiTokenEnvironment(newToken, environments);

        const secret = this.generateSecretKey(newToken);
        const createNewToken = { ...newToken, secret };
        return this.insertNewApiToken(createNewToken);
    }

    // TODO: Remove this service method after embedded proxy has been released in
    // 4.16.0
    public async createMigratedProxyApiToken(
        newToken: Omit<IApiTokenCreate, 'secret'>,
    ): Promise<IApiToken> {
        validateApiToken(newToken);

        const secret = this.generateSecretKey(newToken);
        const createNewToken = { ...newToken, secret };
        return this.insertNewApiToken(createNewToken);
    }

    private async insertNewApiToken(
        newApiToken: IApiTokenCreate,
    ): Promise<IApiToken> {
        try {
            const token = await this.store.insert(newApiToken);
            this.activeTokens.push(token);
            return token;
        } catch (error) {
            if (error.code === FOREIGN_KEY_VIOLATION) {
                let { message } = error;
                if (error.constraint === 'api_token_project_project_fkey') {
                    message = `Project=${this.findInvalidProject(
                        error.detail,
                        newApiToken.projects,
                    )} does not exist`;
                } else if (error.constraint === 'api_tokens_environment_fkey') {
                    message = `Environment=${newApiToken.environment} does not exist`;
                }
                throw new BadDataError(message);
            }
            throw error;
        }
    }

    private findInvalidProject(errorDetails, projects) {
        if (!errorDetails) {
            return 'invalid';
        }
        let invalidProject = projects.find((project) => {
            return errorDetails.includes(`=(${project})`);
        });
        return invalidProject || 'invalid';
    }

    private generateSecretKey({ projects, environment }) {
        const randomStr = crypto.randomBytes(28).toString('hex');
        if (projects.length > 1) {
            return `[]:${environment}.${randomStr}`;
        } else {
            return `${projects[0]}:${environment}.${randomStr}`;
        }
    }

    destroy(): void {
        clearInterval(this.timer);
        this.timer = null;
    }
}


text:
namespace Twitterizer.Streaming
{
    using System;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    public class TwitterStreamEvent
    {
        /// <summary>
        /// Gets or sets the type of the event.
        /// </summary>
        /// <value>The type of the event.</value>
        [JsonProperty(PropertyName = "event")]
        [JsonConverter(typeof(StringEnumConverter))]
        public TwitterSteamEvent EventType { get; set; }

        /// <summary>
        /// Gets or sets the source of the event. This is always the user who initiated the event.
        /// </summary>
        /// <value>The source.</value>
        public TwitterUser Source { get; set; }

        /// <summary>
        /// Gets or sets the target of the event. This is the user who was affected, or who owns the affected object.
        /// </summary>
        /// <value>The source.</value>
        public TwitterUser Target { get; set; }

        /// <summary>
        /// Gets or sets the target object.
        /// </summary>
        /// <value>The target object.</value>
        public Twitterizer.Core.TwitterObject TargetObject { get; set; }

        /// <summary>
        /// Gets or sets the creation date.
        /// </summary>
        /// <value>The creation date.</value>
        [JsonProperty(PropertyName = "created_at")]
        [JsonConverter(typeof(TwitterizerDateConverter))]
        public DateTime CreatedAt { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
% recover from spike2 crash that ruins masterstimfile
% gets the needed values to add to the latest intact masterstimfile from
% the alltrialsfile.
% TO USE:
%1. locate the most recent intact masterstimfile and copy it to the animal's stim folder
%2. note the date/time of this file and convert this to 'usetrailsafterthisdate/time below
%3. update the subjectid below
%4. run the code
%5. add the values in X to the appropriate columns in the masterstimfile

usetrialsafterthisdate = 20111014;
usetrialsafterthistime = 1509;
subjectid = 'st639';

%
%
%
alltrialsfilename = SM_getAllTrialsFileName(subjectid);
[alltrials rdatstyle] = SM_readalltrialsfile(alltrialsfilename);

trials = ND_picktrials(rdatstyle,'datetime+',[usetrialsafterthisdate usetrialsafterthistime]);

stims = ND_getstims(trials)

X={};1
for i = 1:length(stims)
x = ND_picktrials(trials,'stimulus',stims{i});
numpresentations(i) = size(x,1);

x = ND_picktrials(trials,'stimulus',stims{i},'responseAccuracy',1);
numcorrect(i) = size(x,1);

x = ND_picktrials(trials,'stimulus',stims{i},'responseAccuracy',0);
numincorrect(i) = size(x,1);

x = ND_picktrials(trials,'stimulus',stims{i},'responseAccuracy',2);
numnoresponse(i) = size(x,1);

X{i,1} = stims{i};
X{i,2} = numpresentations(i);
X{i,3} = numcorrect(i);
X{i,4} = numincorrect(i);
X{i,5} = numnoresponse(i);
end


text:
package com.technorage.demo.drools.monitoring;

/**
 * An activation is a record of when a rule has fired in a knowledge session.
 * Key is the name of the rule that fired, but there may also be metadata.
 *
 * @author Stephen Masters
 */
public class Activation {

	/**
	 * The name of the rule which was activated.
	 */
	private String ruleName;

	/**
	 * Default no-args constructor.
	 */
	public Activation() {
	}

	/**
	 * Simple constructor for just noting a rule name for an activation.
	 *
	 * @param ruleName
	 *            The name of the rule which was activated.
	 */
	public Activation(String ruleName) {
		this.ruleName = ruleName;
	}

	/**
	 * @return The name of the rule which was activated.
	 */
	public String getRuleName() {
		return ruleName;
	}

	/**
	 * @param ruleName The name of the rule which was activated.
	 */
	public void setRuleName(String ruleName) {
		this.ruleName = ruleName;
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Activation[ruleName=" + ruleName);
		sb.append("]");
		return sb.toString();
	}

}


text:
+++
title = "Hab CLI"
description = "Hab CLI"

[menu]
  [menu.habitat]
    title = "Hab CLI"
    identifier = "habitat/overview/concepts/concepts/hab"
    parent = "habitat/overview/concepts"

+++

Almost anything you could want to do in Chef Habitat can be managed via the `hab` CLI.

It includes subcommands for executing package builds, loading services into the process Supervisor, uploading packages to Builder, and entering the Studio. For more information on all of the functionality of `hab` checkout our [CLI command documentation](/docs/habitat-cli).


text:
layout: default
type: arguendo
---
{% assign description = page.description %}
{% assign questions = site.arguendo-questions | sort: date | reverse %}

    {% include _arguendo-page-heading.html %}

  {% for object in questions %}
    {% assign question = object.title %}
    {% assign slug = object.slug %}
    {% assign theContent = object.content %}
    {% assign date = object.date %}
	  {% include _arguendo-question.html %}
  {% endfor %}


text:
#ifndef Element_h
#define Element_h

#include "HTMLNames.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
#include "core/dom/SpaceSplitString.h"
#include "core/html/CollectionType.h"
#include "core/platform/ScrollTypes.h"
#include "core/rendering/RegionOversetState.h"

namespace WebCore {

class Animation;

class Attr;
class ClientRect;
class ClientRectList;
class DOMStringMap;
class DOMTokenList;
class Element;
class ElementRareData;
class ElementShadow;
class InputMethodContext;
class IntSize;
class Locale;
class PseudoElement;
class RenderRegion;
class ShadowRoot;
class ShareableElementData;
class StylePropertySet;
class UniqueElementData;

class ElementData : public RefCounted<ElementData> {
    WTF_MAKE_FAST_ALLOCATED;
public:
    // Override RefCounted's deref() to ensure operator delete is called on
    // the appropriate subclass type.
    void deref();

    void clearClass() const { m_classNames.clear(); }
    void setClass(const AtomicString& className, bool shouldFoldCase) const { m_classNames.set(className, shouldFoldCase); }
    const SpaceSplitString& classNames() const { return m_classNames; }

    const AtomicString& idForStyleResolution() const { return m_idForStyleResolution; }
    void setIdForStyleResolution(const AtomicString& newId) const { m_idForStyleResolution = newId; }

    const StylePropertySet* inlineStyle() const { return m_inlineStyle.get(); }

    const StylePropertySet* presentationAttributeStyle() const;

    size_t length() const;
    bool isEmpty() const { return !length(); }

    const Attribute* attributeItem(unsigned index) const;
    const Attribute* getAttributeItem(const QualifiedName&) const;
    size_t getAttributeItemIndex(const QualifiedName&) const;
    size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
    size_t getAttrIndex(Attr*) const;

    bool hasID() const { return !m_idForStyleResolution.isNull(); }
    bool hasClass() const { return !m_classNames.isNull(); }

    bool isEquivalent(const ElementData* other) const;

    void reportMemoryUsage(MemoryObjectInfo*) const;

    bool isUnique() const { return m_isUnique; }

protected:
    ElementData();
    ElementData(unsigned arraySize);
    ElementData(const ElementData&, bool isUnique);

    unsigned m_isUnique : 1;
    unsigned m_arraySize : 28;
    mutable unsigned m_presentationAttributeStyleIsDirty : 1;
    mutable unsigned m_styleAttributeIsDirty : 1;
    mutable unsigned m_animatedSVGAttributesAreDirty : 1;

    mutable RefPtr<StylePropertySet> m_inlineStyle;
    mutable SpaceSplitString m_classNames;
    mutable AtomicString m_idForStyleResolution;

private:
    friend class Element;
    friend class StyledElement;
    friend class ShareableElementData;
    friend class UniqueElementData;
    friend class SVGElement;

    const Attribute* attributeBase() const;
    const Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
    size_t getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const;

    PassRefPtr<UniqueElementData> makeUniqueCopy() const;
};

#if COMPILER(MSVC)
#pragma warning(push)
#pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
#endif

class ShareableElementData : public ElementData {
    // This is needed because we malloc() space for a ShareableElementData plus
    // optional following attributes, as a performance tweak.
    NEW_DELETE_SAME_AS_MALLOC_FREE;
public:
    static PassRefPtr<ShareableElementData> createWithAttributes(const Vector<Attribute>&);

    explicit ShareableElementData(const Vector<Attribute>&);
    explicit ShareableElementData(const UniqueElementData&);
    ~ShareableElementData();

    Attribute m_attributeArray[0];
};

#if COMPILER(MSVC)
#pragma warning(pop)
#endif

class UniqueElementData : public ElementData {
public:
    static PassRefPtr<UniqueElementData> create();
    PassRefPtr<ShareableElementData> makeShareableCopy() const;

    // These functions do no error/duplicate checking.
    void addAttribute(const QualifiedName&, const AtomicString&);
    void removeAttribute(size_t index);

    Attribute* attributeItem(unsigned index);
    Attribute* getAttributeItem(const QualifiedName&);

    UniqueElementData();
    explicit UniqueElementData(const ShareableElementData&);
    explicit UniqueElementData(const UniqueElementData&);

    mutable RefPtr<StylePropertySet> m_presentationAttributeStyle;
    Vector<Attribute, 4> m_attributeVector;
};

enum AffectedSelectorType {
    AffectedSelectorChecked = 1,
    AffectedSelectorEnabled = 1 << 1,
    AffectedSelectorDisabled = 1 << 2,
    AffectedSelectorIndeterminate = 1 << 3,
    AffectedSelectorLink = 1 << 4,
    AffectedSelectorTarget = 1 << 5,
    AffectedSelectorVisited = 1 << 6
};
typedef int AffectedSelectorMask;

enum SpellcheckAttributeState {
    SpellcheckAttributeTrue,
    SpellcheckAttributeFalse,
    SpellcheckAttributeDefault
};

class Element : public ContainerNode {
public:
    static PassRefPtr<Element> create(const QualifiedName&, Document*);
    virtual ~Element();

    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);

    // These four attribute event handler attributes are overridden by HTMLBodyElement
    // and HTMLFrameSetElement to forward to the DOMWindow.
    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(blur);
    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(error);
    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(focus);
    DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(load);

    // WebKit extensions
    DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);

    bool hasAttribute(const QualifiedName&) const;
    const AtomicString& getAttribute(const QualifiedName&) const;
    void setAttribute(const QualifiedName&, const AtomicString& value);
    void setSynchronizedLazyAttribute(const QualifiedName&, const AtomicString& value);
    void removeAttribute(const QualifiedName&);

    // Typed getters and setters for language bindings.
    int getIntegralAttribute(const QualifiedName& attributeName) const;
    void setIntegralAttribute(const QualifiedName& attributeName, int value);
    unsigned getUnsignedIntegralAttribute(const QualifiedName& attributeName) const;
    void setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value);

    // Call this to get the value of an attribute that is known not to be the style
    // attribute or one of the SVG animatable attributes.
    bool fastHasAttribute(const QualifiedName&) const;
    const AtomicString& fastGetAttribute(const QualifiedName&) const;
#ifndef NDEBUG
    bool fastAttributeLookupAllowed(const QualifiedName&) const;
#endif

#ifdef DUMP_NODE_STATISTICS
    bool hasNamedNodeMap() const;
#endif
    bool hasAttributes() const;
    // This variant will not update the potentially invalid attributes. To be used when not interested
    // in style attribute or one of the SVG animation attributes.
    bool hasAttributesWithoutUpdate() const;

    bool hasAttribute(const AtomicString& name) const;
    bool hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const;

    const AtomicString& getAttribute(const AtomicString& name) const;
    const AtomicString& getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const;

    void setAttribute(const AtomicString& name, const AtomicString& value, ExceptionCode&);
    static bool parseAttributeName(QualifiedName&, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode&);
    void setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode&);

    bool isIdAttributeName(const QualifiedName&) const;
    const AtomicString& getIdAttribute() const;
    void setIdAttribute(const AtomicString&);

    const AtomicString& getNameAttribute() const;
    const AtomicString& getClassAttribute() const;

    // Call this to get the value of the id attribute for style resolution purposes.
    // The value will already be lowercased if the document is in compatibility mode,
    // so this function is not suitable for non-style uses.
    const AtomicString& idForStyleResolution() const;

    // Internal methods that assume the existence of attribute storage, one should use hasAttributes()
    // before calling them.
    size_t attributeCount() const;
    const Attribute* attributeItem(unsigned index) const;
    const Attribute* getAttributeItem(const QualifiedName&) const;
    size_t getAttributeItemIndex(const QualifiedName& name) const { return elementData()->getAttributeItemIndex(name); }
    size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const { return elementData()->getAttributeItemIndex(name, shouldIgnoreAttributeCase); }

    void scrollIntoView(bool alignToTop = true);
    void scrollIntoViewIfNeeded(bool centerIfNeeded = true);

    void scrollByLines(int lines);
    void scrollByPages(int pages);

    int offsetLeft();
    int offsetTop();
    int offsetWidth();
    int offsetHeight();

    // FIXME: Replace uses of offsetParent in the platform with calls
    // to the render layer and merge bindingsOffsetParent and offsetParent.
    Element* bindingsOffsetParent();

    Element* offsetParent();
    int clientLeft();
    int clientTop();
    int clientWidth();
    int clientHeight();
    virtual int scrollLeft();
    virtual int scrollTop();
    virtual void setScrollLeft(int);
    virtual void setScrollTop(int);
    virtual int scrollWidth();
    virtual int scrollHeight();

    IntRect boundsInRootViewSpace();

    PassRefPtr<ClientRectList> getClientRects();
    PassRefPtr<ClientRect> getBoundingClientRect();

    // Returns the absolute bounding box translated into screen coordinates:
    IntRect screenRect() const;

    void removeAttribute(const AtomicString& name);
    void removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName);

    PassRefPtr<Attr> detachAttribute(size_t index);

    PassRefPtr<Attr> getAttributeNode(const AtomicString& name);
    PassRefPtr<Attr> getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName);
    PassRefPtr<Attr> setAttributeNode(Attr*, ExceptionCode&);
    PassRefPtr<Attr> setAttributeNodeNS(Attr*, ExceptionCode&);
    PassRefPtr<Attr> removeAttributeNode(Attr*, ExceptionCode&);

    PassRefPtr<Attr> attrIfExists(const QualifiedName&);
    PassRefPtr<Attr> ensureAttr(const QualifiedName&);

    const Vector<RefPtr<Attr> >& attrNodeList();

    virtual CSSStyleDeclaration* style();

    const QualifiedName& tagQName() const { return m_tagName; }
    String tagName() const { return nodeName(); }
    bool hasTagName(const QualifiedName& tagName) const { return m_tagName.matches(tagName); }

    // A fast function for checking the local name against another atomic string.
    bool hasLocalName(const AtomicString& other) const { return m_tagName.localName() == other; }
    bool hasLocalName(const QualifiedName& other) const { return m_tagName.localName() == other.localName(); }

    virtual const AtomicString& localName() const OVERRIDE { return m_tagName.localName(); }
    virtual const AtomicString& prefix() const OVERRIDE { return m_tagName.prefix(); }
    virtual const AtomicString& namespaceURI() const OVERRIDE { return m_tagName.namespaceURI(); }

    virtual KURL baseURI() const OVERRIDE FINAL;

    virtual String nodeName() const;

    PassRefPtr<Element> cloneElementWithChildren();
    PassRefPtr<Element> cloneElementWithoutChildren();

    void scheduleSyntheticStyleChange();

    void normalizeAttributes();
    String nodeNamePreservingCase() const;

    void setBooleanAttribute(const QualifiedName& name, bool);

    // For exposing to DOM only.
    NamedNodeMap* attributes() const;

    enum AttributeModificationReason {
        ModifiedDirectly,
        ModifiedByCloning
    };

    // This method is called whenever an attribute is added, changed or removed.
    virtual void attributeChanged(const QualifiedName&, const AtomicString&, AttributeModificationReason = ModifiedDirectly);
    virtual void parseAttribute(const QualifiedName&, const AtomicString&) { }

    // Only called by the parser immediately after element construction.
    void parserSetAttributes(const Vector<Attribute>&);

    // Remove attributes that might introduce scripting from the vector leaving the element unchanged.
    void stripScriptingAttributes(Vector<Attribute>&) const;

    const ElementData* elementData() const { return m_elementData.get(); }
    UniqueElementData* ensureUniqueElementData();

    void synchronizeAllAttributes() const;

    // Clones attributes only.
    void cloneAttributesFromElement(const Element&);

    // Clones all attribute-derived data, including subclass specifics (through copyNonAttributeProperties.)
    void cloneDataFromElement(const Element&);

    bool hasEquivalentAttributes(const Element* other) const;

    virtual void copyNonAttributePropertiesFromElement(const Element&) { }

    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
    virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
    virtual RenderObject* createRenderer(RenderStyle*);
    virtual bool rendererIsNeeded(const NodeRenderingContext&);
    void recalcStyle(StyleChange = NoChange);
    void didAffectSelector(AffectedSelectorMask);

    ElementShadow* shadow() const;
    ElementShadow* ensureShadow();
    PassRefPtr<ShadowRoot> createShadowRoot(ExceptionCode&);
    ShadowRoot* shadowRoot() const;
    void ensureDistribution();

    bool hasAuthorShadowRoot() const { return shadowRoot(); }

    ShadowRoot* userAgentShadowRoot() const;
    ShadowRoot* ensureUserAgentShadowRoot();

    virtual const AtomicString& shadowPseudoId() const;

    RenderStyle* computedStyle(PseudoId = NOPSEUDO);

    // Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.)
    bool styleAffectedByEmpty() const { return hasRareData() && rareDataStyleAffectedByEmpty(); }
    bool childrenAffectedByHover() const { return hasRareData() && rareDataChildrenAffectedByHover(); }
    bool childrenAffectedByActive() const { return hasRareData() && rareDataChildrenAffectedByActive(); }
    bool childrenAffectedByDrag() const { return hasRareData() && rareDataChildrenAffectedByDrag(); }
    bool childrenAffectedByPositionalRules() const { return hasRareData() && (rareDataChildrenAffectedByForwardPositionalRules() || rareDataChildrenAffectedByBackwardPositionalRules()); }
    bool childrenAffectedByFirstChildRules() const { return hasRareData() && rareDataChildrenAffectedByFirstChildRules(); }
    bool childrenAffectedByLastChildRules() const { return hasRareData() && rareDataChildrenAffectedByLastChildRules(); }
    bool childrenAffectedByDirectAdjacentRules() const { return hasRareData() && rareDataChildrenAffectedByDirectAdjacentRules(); }
    bool childrenAffectedByForwardPositionalRules() const { return hasRareData() && rareDataChildrenAffectedByForwardPositionalRules(); }
    bool childrenAffectedByBackwardPositionalRules() const { return hasRareData() && rareDataChildrenAffectedByBackwardPositionalRules(); }
    unsigned childIndex() const { return hasRareData() ? rareDataChildIndex() : 0; }

    bool hasFlagsSetDuringStylingOfChildren() const;

    void setStyleAffectedByEmpty();
    void setChildrenAffectedByHover(bool);
    void setChildrenAffectedByActive(bool);
    void setChildrenAffectedByDrag(bool);
    void setChildrenAffectedByFirstChildRules();
    void setChildrenAffectedByLastChildRules();
    void setChildrenAffectedByDirectAdjacentRules();
    void setChildrenAffectedByForwardPositionalRules();
    void setChildrenAffectedByBackwardPositionalRules();
    void setChildIndex(unsigned);

    void setIsInCanvasSubtree(bool);
    bool isInCanvasSubtree() const;

    bool isUnresolvedCustomElement();

    void setRegionOversetState(RegionOversetState);
    RegionOversetState regionOversetState() const;

    AtomicString computeInheritedLanguage() const;
    Locale& locale() const;

    virtual void accessKeyAction(bool /*sendToAnyEvent*/) { }

    virtual bool isURLAttribute(const Attribute&) const { return false; }
    virtual bool isHTMLContentAttribute(const Attribute&) const { return false; }

    KURL getURLAttribute(const QualifiedName&) const;
    KURL getNonEmptyURLAttribute(const QualifiedName&) const;

    virtual const AtomicString& imageSourceURL() const;
    virtual String target() const { return String(); }

    virtual void focus(bool restorePreviousSelection = true, FocusDirection = FocusDirectionNone);
    virtual void updateFocusAppearance(bool restorePreviousSelection);
    virtual void blur();

    String innerText();
    String outerText();

    String textFromChildren();

    virtual String title() const;

    const AtomicString& pseudo() const;
    void setPseudo(const AtomicString&);

    LayoutSize minimumSizeForResizing() const;
    void setMinimumSizeForResizing(const LayoutSize&);

    virtual void didBecomeFullscreenElement() { }
    virtual void willStopBeingFullscreenElement() { }

    bool isFinishedParsingChildren() const { return isParsingChildrenFinished(); }
    virtual void finishParsingChildren();
    virtual void beginParsingChildren() OVERRIDE FINAL;

    PseudoElement* pseudoElement(PseudoId) const;
    RenderObject* pseudoElementRenderer(PseudoId) const;

    virtual bool matchesReadOnlyPseudoClass() const;
    virtual bool matchesReadWritePseudoClass() const;
    bool webkitMatchesSelector(const String& selectors, ExceptionCode&);
    virtual bool shouldAppearIndeterminate() const;

    DOMTokenList* classList();

    DOMStringMap* dataset();

    static bool isMathMLElement() { return false; }
    virtual bool isMediaElement() const { return false; }

#if ENABLE(INPUT_SPEECH)
    virtual bool isInputFieldSpeechButtonElement() const { return false; }
#endif
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
    virtual bool isDateTimeEditElement() const;
    virtual bool isDateTimeFieldElement() const;
    virtual bool isPickerIndicatorElement() const;
#endif

    virtual bool isFormControlElement() const { return false; }
    virtual bool isSpinButtonElement() const { return false; }
    virtual bool isTextFormControl() const { return false; }
    virtual bool isOptionalFormControl() const { return false; }
    virtual bool isRequiredFormControl() const { return false; }
    virtual bool isDefaultButtonForForm() const { return false; }
    virtual bool willValidate() const { return false; }
    virtual bool isValidFormControlElement() { return false; }
    virtual bool isInRange() const { return false; }
    virtual bool isOutOfRange() const { return false; }
    virtual bool isFrameElementBase() const { return false; }
    virtual bool isTextFieldDecoration() const { return false; }
    virtual bool isClearButtonElement() const;

    virtual bool canContainRangeEndPoint() const { return true; }

    virtual const AtomicString& formControlType() const { return nullAtom; }

    virtual bool wasChangedSinceLastFormControlChangeEvent() const;
    virtual void setChangedSinceLastFormControlChangeEvent(bool);
    virtual void dispatchFormControlChangeEvent() { }

    // Used for disabled form elements; if true, prevents mouse events from being dispatched
    // to event listeners, and prevents DOMActivate events from being sent at all.
    virtual bool isDisabledFormControl() const { return false; }

    bool isInert() const;
    virtual bool shouldBeReparentedUnderRenderView(const RenderStyle*) const { return isInTopLayer(); }

    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
    bool hasPendingResources() const;
    void setHasPendingResources();
    void clearHasPendingResources();
    virtual void buildPendingResource() { };

    enum {
        ALLOW_KEYBOARD_INPUT = 1 << 0,
        LEGACY_MOZILLA_REQUEST = 1 << 1,
    };

    void webkitRequestFullScreen(unsigned short flags);
    bool containsFullScreenElement() const;
    void setContainsFullScreenElement(bool);
    void setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool);

    // W3C API
    void webkitRequestFullscreen();

    bool isInTopLayer() const;
    void setIsInTopLayer(bool);

    void webkitRequestPointerLock();

    bool isSpellCheckingEnabled() const;

    PassRefPtr<RenderStyle> styleForRenderer();
    PassRefPtr<RenderStyle> originalStyleForRenderer();

    RenderRegion* renderRegion() const;
    const AtomicString& webkitRegionOverset() const;
    Vector<RefPtr<Range> > webkitGetRegionFlowRanges() const;

    bool hasID() const;
    bool hasClass() const;
    const SpaceSplitString& classNames() const;

    IntSize savedLayerScrollOffset() const;
    void setSavedLayerScrollOffset(const IntSize&);

    virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE;

    void addActiveAnimation(Animation*);
    void removeActiveAnimation(Animation*);
    bool hasActiveAnimations() const;
    Vector<Animation*>* activeAnimations() const;

    InputMethodContext* getInputContext();

protected:
    Element(const QualifiedName& tagName, Document* document, ConstructionType type)
        : ContainerNode(document, type)
        , m_tagName(tagName)
    {
        ScriptWrappable::init(this);
    }

    virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
    virtual void removedFrom(ContainerNode*) OVERRIDE;
    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
    virtual void removeAllEventListeners() OVERRIDE FINAL;

    virtual void willRecalcStyle(StyleChange);
    virtual void didRecalcStyle(StyleChange);
    virtual PassRefPtr<RenderStyle> customStyleForRenderer();

    virtual bool shouldRegisterAsNamedItem() const { return false; }
    virtual bool shouldRegisterAsExtraNamedItem() const { return false; }

    void clearTabIndexExplicitlyIfNeeded();
    void setTabIndexExplicitly(short);
    virtual bool supportsFocus() const OVERRIDE;
    virtual short tabIndex() const OVERRIDE;
    virtual bool rendererIsFocusable() const OVERRIDE;

    PassRefPtr<HTMLCollection> ensureCachedHTMLCollection(CollectionType);
    HTMLCollection* cachedHTMLCollection(CollectionType);

    // classAttributeChanged() exists to share code between
    // parseAttribute (called via setAttribute()) and
    // svgAttributeChanged (called when element.className.baseValue is set)
    void classAttributeChanged(const AtomicString& newClassString);

private:
    void updatePseudoElement(PseudoId, StyleChange);
    void createPseudoElementIfNeeded(PseudoId);

    virtual bool areAuthorShadowsAllowed() const { return true; }
    virtual void didAddUserAgentShadowRoot(ShadowRoot*) { }
    virtual bool alwaysCreateUserAgentShadowRoot() const { return false; }

    // FIXME: Remove the need for Attr to call willModifyAttribute/didModifyAttribute.
    friend class Attr;

    enum SynchronizationOfLazyAttribute { NotInSynchronizationOfLazyAttribute = 0, InSynchronizationOfLazyAttribute };

    void didAddAttribute(const QualifiedName&, const AtomicString&);
    void willModifyAttribute(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue);
    void didModifyAttribute(const QualifiedName&, const AtomicString&);
    void didRemoveAttribute(const QualifiedName&);

    void synchronizeAttribute(const QualifiedName&) const;
    void synchronizeAttribute(const AtomicString& localName) const;

    void updateId(const AtomicString& oldId, const AtomicString& newId);
    void updateId(TreeScope*, const AtomicString& oldId, const AtomicString& newId);
    void updateName(const AtomicString& oldName, const AtomicString& newName);
    void updateLabel(TreeScope*, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue);

    void scrollByUnits(int units, ScrollGranularity);

    virtual void setPrefix(const AtomicString&, ExceptionCode&) OVERRIDE FINAL;
    virtual NodeType nodeType() const OVERRIDE FINAL;
    virtual bool childTypeAllowed(NodeType) const OVERRIDE FINAL;

    void setAttributeInternal(size_t index, const QualifiedName&, const AtomicString& value, SynchronizationOfLazyAttribute);
    void addAttributeInternal(const QualifiedName&, const AtomicString& value, SynchronizationOfLazyAttribute);
    void removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute);
    void attributeChangedFromParserOrByCloning(const QualifiedName&, const AtomicString&, AttributeModificationReason);

#ifndef NDEBUG
    virtual void formatForDebugger(char* buffer, unsigned length) const;
#endif

    bool pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle);

    void cancelFocusAppearanceUpdate();

    virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return computedStyle(pseudoElementSpecifier); }

    // cloneNode is private so that non-virtual cloneElementWithChildren and cloneElementWithoutChildren
    // are used instead.
    virtual PassRefPtr<Node> cloneNode(bool deep) OVERRIDE;
    virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();

    QualifiedName m_tagName;
    bool rareDataStyleAffectedByEmpty() const;
    bool rareDataChildrenAffectedByHover() const;
    bool rareDataChildrenAffectedByActive() const;
    bool rareDataChildrenAffectedByDrag() const;
    bool rareDataChildrenAffectedByFirstChildRules() const;
    bool rareDataChildrenAffectedByLastChildRules() const;
    bool rareDataChildrenAffectedByDirectAdjacentRules() const;
    bool rareDataChildrenAffectedByForwardPositionalRules() const;
    bool rareDataChildrenAffectedByBackwardPositionalRules() const;
    unsigned rareDataChildIndex() const;

    SpellcheckAttributeState spellcheckAttributeState() const;

    void updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName);
    void updateExtraNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName);

    void unregisterNamedFlowContentNode();

    void createUniqueElementData();

    bool shouldInvalidateDistributionWhenAttributeChanged(ElementShadow*, const QualifiedName&, const AtomicString&);

    ElementRareData* elementRareData() const;
    ElementRareData* ensureElementRareData();

    void detachAllAttrNodesFromElement();
    void detachAttrNodeFromElementWithValue(Attr*, const AtomicString& value);
    void detachAttrNodeAtIndex(Attr*, size_t index);

    void createRendererIfNeeded(const AttachContext&);

    bool isJavaScriptURLAttribute(const Attribute&) const;

    RefPtr<ElementData> m_elementData;
};

inline Element* toElement(Node* node)
{
    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isElementNode());
    return static_cast<Element*>(node);
}

inline const Element* toElement(const Node* node)
{
    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isElementNode());
    return static_cast<const Element*>(node);
}

// This will catch anyone doing an unnecessary cast.
void toElement(const Element*);

inline bool isDisabledFormControl(const Node* node)
{
    return node->isElementNode() && toElement(node)->isDisabledFormControl();
}

inline bool Node::hasTagName(const QualifiedName& name) const
{
    return isElementNode() && toElement(this)->hasTagName(name);
}

inline bool Node::hasLocalName(const AtomicString& name) const
{
    return isElementNode() && toElement(this)->hasLocalName(name);
}

inline bool Node::hasAttributes() const
{
    return isElementNode() && toElement(this)->hasAttributes();
}

inline NamedNodeMap* Node::attributes() const
{
    return isElementNode() ? toElement(this)->attributes() : 0;
}

inline Element* Node::parentElement() const
{
    ContainerNode* parent = parentNode();
    return parent && parent->isElementNode() ? toElement(parent) : 0;
}

inline Element* Node::previousElementSibling() const
{
    Node* n = previousSibling();
    while (n && !n->isElementNode())
        n = n->previousSibling();
    return toElement(n);
}

inline Element* Node::nextElementSibling() const
{
    Node* n = nextSibling();
    while (n && !n->isElementNode())
        n = n->nextSibling();
    return toElement(n);
}

inline bool Element::fastHasAttribute(const QualifiedName& name) const
{
    ASSERT(fastAttributeLookupAllowed(name));
    return elementData() && getAttributeItem(name);
}

inline const AtomicString& Element::fastGetAttribute(const QualifiedName& name) const
{
    ASSERT(fastAttributeLookupAllowed(name));
    if (elementData()) {
        if (const Attribute* attribute = getAttributeItem(name))
            return attribute->value();
    }
    return nullAtom;
}

inline bool Element::hasAttributesWithoutUpdate() const
{
    return elementData() && !elementData()->isEmpty();
}

inline const AtomicString& Element::idForStyleResolution() const
{
    ASSERT(hasID());
    return elementData()->idForStyleResolution();
}

inline bool Element::isIdAttributeName(const QualifiedName& attributeName) const
{
    // FIXME: This check is probably not correct for the case where the document has an id attribute
    // with a non-null namespace, because it will return false, a false negative, if the prefixes
    // don't match but the local name and namespace both do. However, since this has been like this
    // for a while and the code paths may be hot, we'll have to measure performance if we fix it.
    return attributeName == document()->idAttributeName();
}

inline const AtomicString& Element::getIdAttribute() const
{
    return hasID() ? fastGetAttribute(document()->idAttributeName()) : nullAtom;
}

inline const AtomicString& Element::getNameAttribute() const
{
    return hasName() ? fastGetAttribute(HTMLNames::nameAttr) : nullAtom;
}

inline const AtomicString& Element::getClassAttribute() const
{
    if (!hasClass())
        return nullAtom;
    if (isSVGElement())
        return getAttribute(HTMLNames::classAttr);
    return fastGetAttribute(HTMLNames::classAttr);
}

inline void Element::setIdAttribute(const AtomicString& value)
{
    setAttribute(document()->idAttributeName(), value);
}

inline const SpaceSplitString& Element::classNames() const
{
    ASSERT(hasClass());
    ASSERT(elementData());
    return elementData()->classNames();
}

inline size_t Element::attributeCount() const
{
    ASSERT(elementData());
    return elementData()->length();
}

inline const Attribute* Element::attributeItem(unsigned index) const
{
    ASSERT(elementData());
    return elementData()->attributeItem(index);
}

inline const Attribute* Element::getAttributeItem(const QualifiedName& name) const
{
    ASSERT(elementData());
    return elementData()->getAttributeItem(name);
}

inline bool Element::hasID() const
{
    return elementData() && elementData()->hasID();
}

inline bool Element::hasClass() const
{
    return elementData() && elementData()->hasClass();
}

inline UniqueElementData* Element::ensureUniqueElementData()
{
    if (!elementData() || !elementData()->isUnique())
        createUniqueElementData();
    return static_cast<UniqueElementData*>(m_elementData.get());
}

// Put here to make them inline.
inline bool Node::hasID() const
{
    return isElementNode() && toElement(this)->hasID();
}

inline bool Node::hasClass() const
{
    return isElementNode() && toElement(this)->hasClass();
}

inline Node::InsertionNotificationRequest Node::insertedInto(ContainerNode* insertionPoint)
{
    ASSERT(insertionPoint->inDocument() || isContainerNode());
    if (insertionPoint->inDocument())
        setFlag(InDocumentFlag);
    if (parentOrShadowHostNode()->isInShadowTree())
        setFlag(IsInShadowTreeFlag);
    return InsertionDone;
}

inline void Node::removedFrom(ContainerNode* insertionPoint)
{
    ASSERT(insertionPoint->inDocument() || isContainerNode());
    if (insertionPoint->inDocument())
        clearFlag(InDocumentFlag);
    if (isInShadowTree() && !treeScope()->rootNode()->isShadowRoot())
        clearFlag(IsInShadowTreeFlag);
}

inline bool isShadowHost(const Node* node)
{
    return node && node->isElementNode() && toElement(node)->shadow();
}

inline size_t ElementData::length() const
{
    if (isUnique())
        return static_cast<const UniqueElementData*>(this)->m_attributeVector.size();
    return m_arraySize;
}

inline const StylePropertySet* ElementData::presentationAttributeStyle() const
{
    if (!m_isUnique)
        return 0;
    return static_cast<const UniqueElementData*>(this)->m_presentationAttributeStyle.get();
}

inline const Attribute* ElementData::getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const
{
    size_t index = getAttributeItemIndex(name, shouldIgnoreAttributeCase);
    if (index != notFound)
        return attributeItem(index);
    return 0;
}

inline const Attribute* ElementData::attributeBase() const
{
    if (m_isUnique)
        return static_cast<const UniqueElementData*>(this)->m_attributeVector.begin();
    return static_cast<const ShareableElementData*>(this)->m_attributeArray;
}

inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name) const
{
    const Attribute* begin = attributeBase();
    for (unsigned i = 0; i < length(); ++i) {
        const Attribute& attribute = begin[i];
        if (attribute.name().matches(name))
            return i;
    }
    return notFound;
}

// We use a boolean parameter instead of calling shouldIgnoreAttributeCase so that the caller
// can tune the behavior (hasAttribute is case sensitive whereas getAttribute is not).
inline size_t ElementData::getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const
{
    unsigned len = length();
    bool doSlowCheck = shouldIgnoreAttributeCase;

    // Optimize for the case where the attribute exists and its name exactly matches.
    const Attribute* begin = attributeBase();
    for (unsigned i = 0; i < len; ++i) {
        const Attribute& attribute = begin[i];
        if (!attribute.name().hasPrefix()) {
            if (name == attribute.localName())
                return i;
        } else
            doSlowCheck = true;
    }

    if (doSlowCheck)
        return getAttributeItemIndexSlowCase(name, shouldIgnoreAttributeCase);
    return notFound;
}

inline const Attribute* ElementData::getAttributeItem(const QualifiedName& name) const
{
    const Attribute* begin = attributeBase();
    for (unsigned i = 0; i < length(); ++i) {
        const Attribute& attribute = begin[i];
        if (attribute.name().matches(name))
            return &attribute;
    }
    return 0;
}

inline const Attribute* ElementData::attributeItem(unsigned index) const
{
    RELEASE_ASSERT(index < length());
    return attributeBase() + index;
}

} // namespace

#endif


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Cassette.Utilities;

namespace Cassette.BundleProcessing
{
    class ConcatenatedAsset : AssetBase, IDisposable
    {
        readonly string path;
        readonly byte[] hash;
        readonly IEnumerable<IAsset> children;
        readonly MemoryStream stream;
        readonly string separator;

        public ConcatenatedAsset(string path, IEnumerable<IAsset> children, string separator)
        {
            this.path = path;
            this.children = children.ToArray();
            this.separator = separator ?? Environment.NewLine;
            stream = CopyAssetsIntoSingleStream(this.children);
            hash = stream.ComputeSHA1Hash();
        }

        public override void Accept(IBundleVisitor visitor)
        {
            visitor.Visit(this);
            foreach (var child in children)
            {
                visitor.Visit(child);
            }
        }

        public override string Path
        {
            get { return path; }
        }

        public override byte[] Hash
        {
            get { return hash; }
        }

        public override Type AssetCacheValidatorType
        {
            get
            {
                var first = children.FirstOrDefault();
                if (first != null) return first.AssetCacheValidatorType;
                throw new InvalidOperationException();
            }
        }

        public override IEnumerable<AssetReference> References
        {
            get { return children.SelectMany(c => c.References); }
        }

        public override void AddReference(string path, int lineNumber)
        {
            throw new NotSupportedException();
        }

        public override void AddRawFileReference(string relativeFilename)
        {
            throw new NotSupportedException();
        }

        protected override Stream OpenStreamCore()
        {
            return new MemoryStream(stream.ToArray());
        }

        public void Dispose()
        {
            stream.Dispose();
        }

        MemoryStream CopyAssetsIntoSingleStream(IEnumerable<IAsset> assets)
        {
            var outputStream = new MemoryStream();
            var writer = new StreamWriter(outputStream);
            var isFirstAsset = true;
            foreach (var asset in assets)
            {
                if (isFirstAsset)
                {
                    isFirstAsset = false;
                }
                else
                {
                    writer.Write(separator);
                }
                WriteAsset(asset, writer);
            }

            writer.Flush();
            outputStream.Position = 0;
            return outputStream;
        }

        void WriteAsset(IAsset asset, StreamWriter writer)
        {
            using (var reader = new StreamReader(asset.OpenStream()))
            {
                var isFirstLine = true;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (isFirstLine)
                    {
                        isFirstLine = false;
                    }
                    else
                    {
                        writer.WriteLine();
                    }
                    writer.Write(line);
                }
            }
        }
    }
}


text:
  <md-toolbar color="primary" class="page-footer">

     Островець Іванна © 2016 - {{ currentYear }}

      MIT License

  </md-toolbar>


text:
Badcow DNS Zone Library
=======================

This library constructs DNS zone records based on [RFC1035](http://www.ietf.org/rfc/rfc1035.txt) and subsequent standards.

## Build Status
[![Build Status](https://travis-ci.org/Badcow/DNS.png)](https://travis-ci.org/Badcow/DNS) [![Code Coverage](https://scrutinizer-ci.com/g/Badcow/DNS/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/Badcow/DNS/?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/Badcow/DNS/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/Badcow/DNS/?branch=master)

## Example usage

```php

require_once __DIR__ . '/vendor/autoload.php';

use Badcow\DNS\Zone;
use Badcow\DNS\Rdata\Factory;
use Badcow\DNS\ResourceRecord;
use Badcow\DNS\AlignedBuilder;

$zone = new Zone('example.com.');
$zone->setDefaultTtl(3600);

$soa = new ResourceRecord;
$soa->setName('@');
$soa->setRdata(Factory::Soa(
    'example.com.',
    'post.example.com.',
    date('Ymd01'),
    3600,
    14400,
    604800,
    3600
));

$ns = new ResourceRecord;
$ns->setName('@');
$ns->setRdata(Factory::Ns('n1.nameserver.com.'));

$a = new ResourceRecord;
$a->setName('sub.domain');
$a->setRdata(Factory::A('192.168.1.42'));
$a->setComment('This is a local ip.');

$a6 = new ResourceRecord;
$a6->setName('ipv6.domain');
$a6->setRdata(Factory::Aaaa('::1'));
$a6->setComment('This is an IPv6 domain.');

$zone->addResourceRecord($soa);
$zone->addResourceRecord($ns);
$zone->addResourceRecord($a);
$zone->addResourceRecord($a6);

$zoneBuilder = new AlignedBuilder();

echo $zoneBuilder->build($zone);
```

### Output
```txt
$ORIGIN example.com.
$TTL 3600
@            IN SOA  (
                     example.com.      ; MNAME
                     post.example.com. ; RNAME
                     2015072601        ; SERIAL
                     3600              ; REFRESH
                     14400             ; RETRY
                     604800            ; EXPIRE
                     3600              ; MINIMUM
                     )

; NS RECORDS
@            IN NS   n1.nameserver.com.

; A RECORDS
sub.domain   IN A    192.168.1.42; This is a local ip.

; AAAA RECORDS
ipv6.domain  IN AAAA ::1; This is an IPv6 domain.
```
## Running the tests

Simply use phpunit to run the tests. You can run additional tests if you have BIND installed. Add the environment variable to `phpunit.xml`:
    <env name="CHECKZONE_PATH" value="/path/to/named-checkzone"/>

Or add it at run-time:

    CHECKZONE_PATH="/path/to/named-checkzone" phpunit .


text:
require 'capistrano/recipes/deploy/strategy/copy'
require 'fileutils'
require 'capifony_symfony2'

module Capistrano
  module Deploy
    module Strategy
      class CapifonyCopyLocal < Copy
        print "--> Using Copy Local Strategy\n"
        # Deploy
        def deploy!
          copy_cache ? run_copy_cache_strategy : run_copy_strategy
          create_revision_file
          $temp_destination = destination  # Make temp location avaliable globally.
          symfony.composer.install
          symfony.bootstrap.build
          compress_repository
          distribute!
        ensure
          rollback_changes
        end
      end
    end
  end
end


text:
package com.eu.pojo;

import java.util.List;

/**
 * Created by lip on 17/4/8.
 */
public class UserListResult {

    // 200 成功,400 失败, 500 异常
    private Integer status;

    // ok/错误信息
    private String msg;

    // 传递的数据 登陆成功返回 token,验证返回true/false,短信验证返回验证码
    private List<Userinfo> data;

    public void setStatus(Integer status) {
        this.status = status;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setData(List<Userinfo> data) {
        this.data = data;
    }

    public Integer getStatus() {
        return status;
    }

    public String getMsg() {
        return msg;
    }

    public List<Userinfo> getData() {
        return data;
    }

    public UserListResult(Integer status, String msg, List<Userinfo> data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
}


text:
sleep 15

#wait until rabbitmq up
/wait-for-it.sh rabbitmq:5672

cd simple_site_requester
celery -A simple_site_requester worker -B -l info


text:
package com.grietenenknapen.sithandroid.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.support.annotation.StringDef;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.SOURCE;

public final class ResourceUtils {

    @Retention(SOURCE)
    @StringDef({RES_TYPE_RAW, RES_TYPE_DRAWABLE, RES_TYPE_STRING, RES_TYPE_COLOR})
    public @interface ResType {
    }

    public static final String RES_TYPE_RAW = "raw";
    public static final String RES_TYPE_COLOR = "color";
    public static final String RES_TYPE_DRAWABLE = "drawable";
    public static final String RES_TYPE_STRING = "string";

    private static final double DEFAULT_CARD_ITEM_PERCENTAGE = 0.40;

    private ResourceUtils() {

    }

    /**
     * Fetch the resource Id for the corresponding resource name and type
     *
     * @param context
     * @param resString
     * @param resType
     * @return A valid resource Id or 0 when no valid Id was found
     */
    public static int getResIdFromResString(final Context context,
                                            final String resString,
                                            @ResType final String resType) {

        return context.getResources().getIdentifier(resString, resType, context.getPackageName());

    }

    public static float getPxFromDp(final Context context, final float dp) {
        Resources r = context.getResources();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
    }

    public static int getScreenWidth(final WindowManager windowManager) {
        Display display = windowManager.getDefaultDisplay();
        final Point size = new Point();
        display.getSize(size);
        return size.x;
    }

    public static int getDefaultCardItemSize(final WindowManager windowManager) {
        return (int) (getScreenWidth(windowManager) * DEFAULT_CARD_ITEM_PERCENTAGE);
    }
}


text:
package com.lucidastar.callback;

public class SimpleTask extends Task{

	@Override
	public void execute() {

		System.out.println("I do this a simple task");
	}

}


text:
declare -a volArray=()

#volArray[$[${#volArray[@]}+1]]="elememt4"
volArray[$[${#volArray[@]}]]="elememt4"

## now loop through the above array
for i in "${volArray[@]}"
do
   echo "$i"
   # or do whatever with individual element of the array
done

# You can access them using echo "${arr[0]}", "${arr[1]}" also

arrayCount=${#volArray[@]}
let arrayCount-=1

until [ $arrayCount -lt 0 ]; do
	echo "****LOOP****"
	echo ArrayCount is $arrayCount
	echo Array Entry is ${volArray[$arrayCount]}
	let arrayCount-=1
done


text:
/*
 * File:   CELL.hpp
 * Author: Koncord <koncord at rwa.su>
 *
 * Created on 8 Апрель 2015 г., 17:03
 */

#ifndef CELL_HPP
#define	CELL_HPP

#include "../Record.hpp"

class RecordCELL : public Record
{
public:

    struct DATA
    {
        std::string edid;
        std::string name;
        uint8_t flags;
        enum FLAG
        {
            IsInteriorCell = 0x01,
            HasWater = 0x02,
            InvertFastTravelBehaviour = 0x04,
            NoLODWater = 0x08,
            Unknown = 0x10,
            PublicPlace = 0x20,
            HandChanged = 0x40,
            BehaveLikeExterior = 0x80
        };

        float waterHeight;
        std::vector<formid> regions;
        formid encounterZone;
        formid climate;
        formid water;
        formid owner;           // ownership. FormID of a FACT, ACHR or NPC_ record.
        int32_t factionRank;    // ownership.
        struct LightTemplate
        {
            formid templateId;
            uint32_t inherit;
            enum InheritFlag
            {
                AmbientColor = 0x00000001,
                DirectionalColor = 0x00000002,
                FogColor = 0x00000004,
                FogNear = 0x00000008,
                FogFar = 0x00000010,
                DirectionalRotation = 0x00000020,
                DirectionalFade = 0x00000040,
                FogClipDistance = 0x00000080,
                FogPower = 0x00000100
            };
        }lightTemplate;
        #pragma pack(push, 1)
        struct Grid
        {
            int32_t x, y;
            uint32_t forceHideLand; //flags
            enum ForceHideLand
            {
                Quad1 = 0x00000001,
                Quad2 = 0x00000002,
                Quad3 = 0x00000004,
                Quad4 = 0x00000008
            };
        } grid;
        struct Lighting
        {
            rgba ambientColor;
            rgba directionalColor;
            rgba fogColor;
            float fogNear;
            float fogFar;
            int32_t directionalRotationXY;
            int32_t DirectionalRotationZ;
            float directionalFade;
            float fogClipDistance;
            float fogPower;
        } lighting;
        #pragma pack(pop)
    } data;

    explicit RecordCELL(const RecHeader &head) : Record(head) { Parse(); }

    RecordCELL() : Record() { Parse(); }
    virtual bool DoParse();
};

#endif	/* CELL_HPP */


text:
EPIC Variability Extraction and Removal for Exoplanet Science Targets: A pipeline for de-trending K2 light curves with pixel level decorrelation and Gaussian processes. Here you'll find the Python code used to generate the EVEREST catalog, as well as tools for accessing and interacting with the de-trended light curves.

To install the latest EVEREST release (**2.0.12**):

pip install everest-pipeline

You can also install the current development version of EVEREST (**2.0.12**) from source:

git clone https://github.com/rodluger/everest
cd everest
python setup.py install --user

For more information on how to install and use EVEREST, please refer to the documentation.


text:
@extends('admin.layouts.main')
@section('content')

                {{ Config::get('administrator.title') }}
                {{ $config->getOption('title') }}

 Dashboard

{{ $config->getOption('title') }}

                <?php $tmpRouteName = Route::getCurrentRoute()->getName(); ?>
                @if( $tmpRouteName == 'admin_index')
                    @include($config->getOption('model_table_view'))
                @else
                    @include($config->getOption('model_form_view'))
                @endif

@endsection


text:
<?php

namespace App\Http\Controllers\Admin\API;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\TemplateSectionField;

use Log;

class TemplateSectionFieldController extends Controller
{
	/**
    * Store a template section field.
    *
    * @param  Request  $request
    * @return TemplateSectionField  $templateSectionField
    */
	public function store(Request $request)
    {

    	//Log::info($request);

    	$user = Auth::user();

    	if ($request['field_id']) {

    		$templateSectionField = TemplateSectionField::find($request['field_id']);

			if ($request['field_title']) {
				if ($request['field_title'] != $templateSectionField->field_title) {
					$this->validate($request, [
                	'field_title' => 'unique:template_section_fields,field_title,NULL,id,template_section_id,'.$request['template_section_id'].''
            		]);
					$templateSectionField->field_title = $request['field_title'];
				}
			}

			if ($request['field_required']) {
				if ($request['field_required'] == "true") {
					$request['field_required'] = 1;
				}
				else {
					$request['field_required'] = 0;
				}

				$templateSectionField->required = $request['field_required'];
			}

			$templateSectionField->save();
    	}
    	else {

    		//Log::info($request['field_title']);

    		$this->validate($request, [
                'field_title' => 'unique:template_section_fields,field_title,NULL,id,template_section_id,'.$request['template_section_id'].''
            ]);

            $templateSectionField = TemplateSectionField::create([
                'field_title' => $request['field_title'],
                'template_id' => $request['template_id'],
                'template_section_id' => $request['template_section_id'],
                'order' => $request['order'],
                'created_by_user_id' => $user->id,
                'updated_by_user_id' => $user->id,
            ]);
    	}

    	return $templateSectionField;

    }
}


text:
import { Component, HostListener, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { StatsDetailsDTO } from '../../classes/city.dto';
import { DepartmentDTO } from '../../classes/department.dto';
import { BatimapService } from '../../services/batimap.service';
import { JosmService } from '../../services/josm.service';
import { AboutDialogComponent } from '../about-dialog/about-dialog.component';

@Component({
    templateUrl: './department-details-dialog.component.html',
    styleUrls: ['./department-details-dialog.component.css'],
})
export class DepartmentDetailsDialogComponent {
    department: DepartmentDTO;
    details$: Observable<StatsDetailsDTO>;
    osmId: number;
    lastImport: string;

    constructor(
        @Inject(MAT_DIALOG_DATA) data: [DepartmentDTO, number],
        public josmService: JosmService,
        private readonly dialogRef: MatDialogRef<DepartmentDetailsDialogComponent>,
        private readonly matDialog: MatDialog,
        batimapService: BatimapService
    ) {
        this.department = data[0];
        this.osmId = data[1];
        this.lastImport = this.computeLastImport();
        this.details$ = batimapService.departmentDetails(this.department.insee);
    }

    // no need to add hostListener here, there is already one present for help
    openHelp(): void {
        this.matDialog.open(AboutDialogComponent);
    }

    @HostListener('document:keydown.f') close(): void {
        this.dialogRef.close(0);
    }

    computeLastImport(): string {
        const d = this.department ? this.department.date : undefined;
        if (!d || d === 'never') {
            return "Le bâti n'a en majorité jamais été importé.";
        }
        if (d === 'raster') {
            return 'Département principalement raster.';
        }
        if (d === 'unfinished') {
            return 'Des bâtiments sont de géométrie simple, à vérifier.';
        }
        if (Number.isInteger(+d)) {
            return `Dernier import moyen sur l'ensemble du département en ${d}.`;
        }

        return 'Le bâti existant ne semble globalement pas provenir du cadastre.';
    }

    editNodes(nodes: number[]): void {
        this.josmService.openNodes(nodes, this.department.insee, this.department.name).subscribe();
    }
}


text:
<resources>
    <string name="app_name">CreditCardInput</string>
    <string name="action_settings">Settings</string>

    <string name="amex">American Express</string>
    <string name="aura">Aura</string>
    <string name="diners">Diners</string>
    <string name="elo">Elo</string>
    <string name="hipercard">Hipercard</string>
    <string name="redecardcredito">MasterCard</string>
    <string name="visacredito">Visa</string>
    <string name="visaelectron">Visa Electron</string>
    <string name="other">Other</string>

    <string name="edit_card">Other card</string>
    <string name="save_data">Save card</string>
    <string name="realize_payment">Pay</string>
    <string name="expiration">Expire date</string>
    <string name="cvv">CVV</string>
    <string name="owner_name">Owner name</string>
    <string name="owner_card">OWNER NAME</string>
    <string name="expiration_date">VALID THRU</string>
    <string name="portions">Installments</string>
    <string name="option_pay_using_other_card_chosen">You chose input another card</string>
    <string name="undo">Undo</string>
    <string name="hint_credit_expire_date">MM/YY</string>
    <string name="no">No</string>
    <string name="yes">Yes</string>
    <string name="hint_credit_card_2">Number</string>
    <string name="hint_credit_card_security_code_3">XXX</string>
    <string name="total">TOTAL</string>

    <string name="currency">$</string>
    <string name="hint_credit_card_flag">Choose a flag</string>
    <string name="invalid_credit_card_flag">You need choose a flag</string>
    <string name="choose_flag">Choose a credit card flag</string>
    <string name="nubank">Nubank</string>
    <string name="paypal">Paypal</string>
</resources>


text:
@startDocuBlock JSF_get_api_database_new
@brief creates a new database

@RESTHEADER{POST /_api/database, Create database}

@RESTBODYPARAM{name,string,required,string}
Has to contain a valid database name.

@RESTBODYPARAM{users,array,optional,JSF_get_api_database_new_USERS}
Has to be an array of user objects to initially create for the new database.
User information will not be changed for users that already exist.
If *users* is not specified or does not contain any users, a default user
*root* will be created with an empty string password. This ensures that the
new database will be accessible after it is created.
Each user object can contain the following attributes:

@RESTSTRUCT{username,JSF_get_api_database_new_USERS,string,required,string}
Loginname of the user to be created

@RESTSTRUCT{passwd,JSF_get_api_database_new_USERS,string,required,string}
The user password as a string. If not specified, it will default to an empty string.

@RESTSTRUCT{active,JSF_get_api_database_new_USERS,boolean,required,}
A flag indicating whether the user account should be activated or not.
The default value is *true*. If set to *false*, the user won't be able to
log into the database.

@RESTSTRUCT{extra,JSF_get_api_database_new_USERS,object,optional,}
A JSON object with extra user information. The data contained in *extra*
will be stored for the user but not be interpreted further by ArangoDB.

@RESTDESCRIPTION
Creates a new database

The response is a JSON object with the attribute *result* set to *true*.

**Note**: creating a new database is only possible from within the *_system* database.

@RESTRETURNCODES

@RESTRETURNCODE{201}
is returned if the database was created successfully.

@RESTRETURNCODE{400}
is returned if the request parameters are invalid or if a database with the
specified name already exists.

@RESTRETURNCODE{403}
is returned if the request was not executed in the *_system* database.

@RESTRETURNCODE{409}
is returned if a database with the specified name already exists.

@EXAMPLES

Creating a database named *example*.

@EXAMPLE_ARANGOSH_RUN{RestDatabaseCreate}
    var url = "/_api/database";
    var name = "example";
    try {
      db._dropDatabase(name);
    }
    catch (err) {
    }

    var data = {
      name: name
    };
    var response = logCurlRequest('POST', url, data);

    db._dropDatabase(name);
    assert(response.code === 201);

    logJsonResponse(response);
@END_EXAMPLE_ARANGOSH_RUN

Creating a database named *mydb* with two users.

@EXAMPLE_ARANGOSH_RUN{RestDatabaseCreateUsers}
    var url = "/_api/database";
    var name = "mydb";
    try {
      db._dropDatabase(name);
    }
    catch (err) {
    }

    var data = {
      name: name,
      users: [
        {
          username : "admin",
          passwd : "secret",
          active: true
        },
        {
          username : "tester",
          passwd : "test001",
          active: false
        }
      ]
    };
    var response = logCurlRequest('POST', url, data);

    db._dropDatabase(name);
    assert(response.code === 201);

    logJsonResponse(response);
@END_EXAMPLE_ARANGOSH_RUN
@endDocuBlock


text:
#include <spine/Slot.h>
#include <spine/extension.h>

typedef struct {
	spSlot super;
	float attachmentTime;
} _spSlot;

spSlot* spSlot_create (spSlotData* data, spBone* bone) {
	spSlot* self = SUPER(NEW(_spSlot));
	CONST_CAST(spSlotData*, self->data) = data;
	CONST_CAST(spBone*, self->bone) = bone;
	spSlot_setToSetupPose(self);
	return self;
}

void spSlot_dispose (spSlot* self) {
	FREE(self->attachmentVertices);
	FREE(self);
}

void spSlot_setAttachment (spSlot* self, spAttachment* attachment) {
	if (attachment == self->attachment) return;
	CONST_CAST(spAttachment*, self->attachment) = attachment;
	SUB_CAST(_spSlot, self)->attachmentTime = self->bone->skeleton->time;
	self->attachmentVerticesCount = 0;
}

void spSlot_setAttachmentTime (spSlot* self, float time) {
	SUB_CAST(_spSlot, self)->attachmentTime = self->bone->skeleton->time - time;
}

float spSlot_getAttachmentTime (const spSlot* self) {
	return self->bone->skeleton->time - SUB_CAST(_spSlot, self) ->attachmentTime;
}

void spSlot_setToSetupPose (spSlot* self) {
	self->r = self->data->r;
	self->g = self->data->g;
	self->b = self->data->b;
	self->a = self->data->a;

	if (!self->data->attachmentName)
		spSlot_setAttachment(self, 0);
	else {
		spAttachment* attachment = spSkeleton_getAttachmentForSlotIndex(
				self->bone->skeleton, self->data->index, self->data->attachmentName);
		CONST_CAST(spAttachment*, self->attachment) = 0;
		spSlot_setAttachment(self, attachment);
	}
}


text:
using System;
using System.Collections.Generic;

using OpenTK;
using OpenTK.Graphics.OpenGL;
using System.Drawing;
namespace MasterBlaster
{
	public class Pane
	{
		public RectangleF bounds;
		private Color bordercolor;
		private Color backgroundcolor;
		private float linewidth;
		private List<Label> contents;
		private List<Button> buttons;
		private float Depth = 0.5f;
		public int selected = 0;
		//private Selector selector;
		private float nextY;
		private float layoutoffset = 0.2f;

		public Pane (RectangleF bounds, float linewidth = 1.0f)
		{
			this.bordercolor = Color.White;
			this.backgroundcolor = Color.Black;
			this.bounds = bounds;
			this.contents = new List<Label> ();
			this.buttons = new List<Button> ();
			this.linewidth = linewidth;
			//this.selector = new Selector (-0.2f, 0.0f);
			this.nextY = 0.6f;
		}

		public void addLabel(Label l){
			//l.location.Y = nextY;
			//nextY -= layoutoffset;
			contents.Add (l);
		}

		public void addButton(Button b){
			//b.location.Y = nextY;
			//nextY -= layoutoffset;
			buttons.Add (b);
		}

		public void draw(){

			//GL.Disable (EnableCap.Texture2D);
			//GL.ClearDepth (1.0f);
			//draw background square
			//GL.Disable (EnableCap.Blend);
			GL.Color3 (backgroundcolor);
			GL.Begin (PrimitiveType.Polygon);
			GL.Vertex3 (bounds.X, bounds.Y, Depth);
			GL.Vertex3 (bounds.X + bounds.Width, bounds.Y, Depth);
			GL.Vertex3 (bounds.X + bounds.Width, bounds.Y + bounds.Height, Depth);
			GL.Vertex3 (bounds.X, bounds.Y + bounds.Height, Depth);
			GL.Vertex3 (bounds.X, bounds.Y, Depth);
			GL.End ();

			//draw border
			GL.Color4 (bordercolor);
			GL.LineWidth (linewidth);
			GL.Begin (PrimitiveType.LineLoop);
			GL.Vertex3 (bounds.X, bounds.Y, Depth);
			GL.Vertex3 (bounds.X + bounds.Width, bounds.Y, Depth);
			GL.Vertex3 (bounds.X + bounds.Width, bounds.Y + bounds.Height, Depth);
			GL.Vertex3 (bounds.X, bounds.Y + bounds.Height, Depth);
			GL.End ();
			//GL.ClearDepth (0.7);
			//GL.Clear(ClearBufferMask.DepthBufferBit);

			//GL.Enable (EnableCap.Blend);
			//;
			//draw labels
			//contents.ForEach (c => c.draw ());
			//selector.draw (new PointF(0.0f, 0.0f));

		}

		public void DrawText(){
			contents.ForEach (c => c.draw ());
			buttons.ForEach (b => b.draw ());

		}

		public void Dispose(){
			contents.ForEach (c => c.Dispose ());
			buttons.ForEach (b => b.Dispose ());
		}
	}
}


text:
require 'jtestr/rspec_helper_formatter'

module JtestR
  class RSpecStoryResultHandler < RSpecHelperFormatter
    def initialize(result_handler)
      @result_handler = result_handler
    end

    def run_started(count)
      @result_handler.starting
    end

    def story_started(title, narrative)
    end

    def scenario_started(story_title, scenario_name)
      @result_handler.starting_single("#{scenario_name}(#{story_title})")
    end

    def scenario_succeeded(story_title, scenario_name)
      @result_handler.succeed_single(scenario_name)
    end

    def scenario_failed(story_title, scenario_name, err)
      @result_handler.add_fault(err)
      if err.exception.is_a?(::Spec::Expectations::ExpectationNotMetError)
        @result_handler.fail_single(scenario_name)
      else
        @result_handler.error_single(scenario_name)
      end
    end

    def scenario_pending(story_title, scenario_name, msg)
      @result_handler.add_pending("#{scenario_name}(#{story_title}): #{msg}")
      @result_handler.pending_single(scenario_name)
    end

    def story_ended(title, narrative)
    end

    def collected_steps(steps)
    end

    def run_ended
      @result_handler.ending
    end

    def method_missing(sym, *args, &block) #:nodoc:
      # noop - ignore unknown messages
    end
  end
end


text:
/**
 * Column options for enum-typed columns.
 */
export interface ColumnEnumOptions {

    /**
     * Array of possible enumerated values.
     */
    enum?: any[]|Object;
    /**
     * Exact name of enum
     */
    enumName?: string;

}


text:
package collector

import (
	"github.com/go-kit/kit/log"
	"github.com/prometheus/client_golang/prometheus"
)

type execCollector struct {
	sysctls []bsdSysctl
	logger  log.Logger
}

func init() {
	registerCollector("exec", defaultEnabled, NewExecCollector)
}

// NewExecCollector returns a new Collector exposing system execution statistics.
func NewExecCollector(logger log.Logger) (Collector, error) {
	// From sys/vm/vm_meter.c:
	// All are of type CTLTYPE_UINT.
	//
	// vm.stats.sys.v_swtch: Context switches
	// vm.stats.sys.v_trap: Traps
	// vm.stats.sys.v_syscall: System calls
	// vm.stats.sys.v_intr: Device interrupts
	// vm.stats.sys.v_soft: Software interrupts
	// vm.stats.vm.v_forks: Number of fork() calls

	return &execCollector{
		sysctls: []bsdSysctl{
			{
				name:        "exec_context_switches_total",
				description: "Context switches since system boot.  Resets at architecture unsigned integer.",
				mib:         "vm.stats.sys.v_swtch",
			},
			{
				name:        "exec_traps_total",
				description: "Traps since system boot.  Resets at architecture unsigned integer.",
				mib:         "vm.stats.sys.v_trap",
			},
			{
				name:        "exec_system_calls_total",
				description: "System calls since system boot.  Resets at architecture unsigned integer.",
				mib:         "vm.stats.sys.v_syscall",
			},
			{
				name:        "exec_device_interrupts_total",
				description: "Device interrupts since system boot.  Resets at architecture unsigned integer.",
				mib:         "vm.stats.sys.v_intr",
			},
			{
				name:        "exec_software_interrupts_total",
				description: "Software interrupts since system boot.  Resets at architecture unsigned integer.",
				mib:         "vm.stats.sys.v_soft",
			},
			{
				name:        "exec_forks_total",
				description: "Number of fork() calls since system boot.  Resets at architecture unsigned integer.",
				mib:         "vm.stats.vm.v_forks",
			},
		},
		logger: logger,
	}, nil
}

// Update pushes exec statistics onto ch
func (c *execCollector) Update(ch chan<- prometheus.Metric) error {
	for _, m := range c.sysctls {
		v, err := m.Value()
		if err != nil {
			return err
		}

		ch <- prometheus.MustNewConstMetric(
			prometheus.NewDesc(
				namespace+"_"+m.name,
				m.description,
				nil, nil,
			), prometheus.CounterValue, v)
	}

	return nil
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis;

internal interface OptionsProvider<TOptions>
{
    ValueTask<TOptions> GetOptionsAsync(LanguageServices languageServices, CancellationToken cancellationToken);
}


text:
//-----------------------------------------------------------------------------------
//    The confidential and proprietary information contained in this file may
//    only be used by a person authorised under and to the extent permitted
//    by a subsisting licensing agreement from ARM Limited or its affiliates
//    or between you and a party authorised by ARM
//
//           (C) COPYRIGHT [2016] ARM Limited or its affiliates
//               ALL RIGHT RESERVED
//
//    This entire notice must be reproduced on all copies of this file
//    and copies of this files may only be made by a person if such person is
//    permitted to do so under the terms of a subsisting license agreement
//    from ARM Limited or its affiliates or between you and a party authorised by ARM
//-----------------------------------------------------------------------------------

#ifndef CRYS_ECPKI_KG_H
#define CRYS_ECPKI_KG_H

/*! @file
@brief Defines the API for generation of ECC private and public keys.
*/

#include "crys_error.h"
#include "crys_rnd.h"
#include "crys_ecpki_types.h"

#ifdef __cplusplus
extern "C"
{
#endif

/*****************  CRYS_ECPKI_GenKeyPair function   **********************/
/*!
@brief Generates a pair of private and public keys in internal representation according to [ANS X9.62].

@return CRYS_OK on success.
@return A non-zero value on failure as defined crys_ecpki_error.h.
*/
CIMPORT_C CRYSError_t CRYS_ECPKI_GenKeyPair(
                        CRYS_RND_Context_t         *pRndContext,      /*!< [in/out] Pointer to the RND context buffer. */
                        const CRYS_ECPKI_Domain_t  *pDomain,          /*!< [in]  Pointer to EC domain (curve). */
                        CRYS_ECPKI_UserPrivKey_t   *pUserPrivKey,     /*!< [out] Pointer to the private key structure. This structure is used as input to the
										 ECPKI cryptographic primitives. */
                        CRYS_ECPKI_UserPublKey_t   *pUserPublKey,     /*!< [out] Pointer to the public key structure. This structure is used as input to the
										 ECPKI cryptographic primitives. */
			CRYS_ECPKI_KG_TempData_t   *pTempData,        /*!< [in] Temporary buffers for internal use, defined in ::CRYS_ECPKI_KG_TempData_t. */
                        CRYS_ECPKI_KG_FipsContext_t   *pFipsCtx       /*!< [in] Pointer to temporary buffer used in case FIPS certification if required. */
);

#ifdef __cplusplus
}
#endif

#endif


text:
local db = {}

function db.configurate(config)
    local api = {}

    local user = require('authman.model.user').model(config)
    local password = require('authman.model.password').model(config)
    local password_token = require('authman.model.password_token').model(config)
    local social = require('authman.model.social').model(config)
    local session = require('authman.model.session').model(config)
    local oauth_app = require('authman.model.oauth.app').model(config)
    local oauth_consumer = require('authman.model.oauth.consumer').model(config)
    local oauth_code = require('authman.model.oauth.code').model(config)
    local oauth_token = require('authman.model.oauth.token').model(config)
    local oauth_scope = require('authman.model.oauth.consumer.scope').model(config)
    local oauth_redirect = require('authman.model.oauth.consumer.redirect').model(config)

    function api.create_database()
        local user_space = box.schema.space.create(user.SPACE_NAME, {
            if_not_exists = true
        })
        user_space:create_index(user.PRIMARY_INDEX, {
            type = 'hash',
            parts = {user.ID, 'string'},
            if_not_exists = true
        })
        user_space:create_index(user.EMAIL_INDEX, {
            type = 'tree',
            unique = false,
            parts = {user.EMAIL, 'string', user.TYPE, 'unsigned'},
            if_not_exists = true
        })

        local password_space = box.schema.space.create(password.SPACE_NAME, {
            if_not_exists = true
        })
        password_space:create_index(password.PRIMARY_INDEX, {
            type = 'hash',
            parts = {password.ID, 'string'},
            if_not_exists = true
        })
        password_space:create_index(password.USER_ID_INDEX, {
            type = 'tree',
            unique = true,
            parts = {password.USER_ID, 'string'},
            if_not_exists = true
        })

        local reset_pwd_token_space = box.schema.space.create(password_token.SPACE_NAME, {
            if_not_exists = true
        })
        reset_pwd_token_space:create_index(password_token.PRIMARY_INDEX, {
            type = 'hash',
            parts = {password_token.USER_ID, 'string'},
            if_not_exists = true
        })

        local social_space = box.schema.space.create(social.SPACE_NAME, {
            if_not_exists = true
        })
        social_space:create_index(social.PRIMARY_INDEX, {
            type = 'hash',
            parts = {social.ID, 'string'},
            if_not_exists = true
        })
        social_space:create_index(social.USER_ID_INDEX, {
            type = 'tree',
            unique = true,
            parts = {social.USER_ID, 'string', social.PROVIDER, 'string'},
            if_not_exists = true
        })
        social_space:create_index(social.SOCIAL_INDEX, {
            type = 'hash',
            unique = true,
            parts = {social.SOCIAL_ID, 'string', social.PROVIDER, 'string'},
            if_not_exists = true
        })

        local session_space = box.schema.space.create(session.SPACE_NAME, {
            if_not_exists = true
        })
        session_space:create_index(session.PRIMARY_INDEX, {
            type = 'hash',
            parts = {session.ID, 'string'},
            if_not_exists = true
        })
        session_space:create_index(session.USER_ID_INDEX, {
            type = 'tree',
            parts = {session.USER_ID, 'string'},
            unique = false,
            if_not_exists = true
        })

        local app_space = box.schema.space.create(oauth_app.SPACE_NAME, {
            if_not_exists = true
        })
        app_space:create_index(oauth_app.PRIMARY_INDEX, {
            type = 'hash',
            parts = {oauth_app.ID, 'string'},
            if_not_exists = true
        })
        app_space:create_index(oauth_app.USER_ID_INDEX, {
            type = 'tree',
            unique = true,
            parts = {oauth_app.USER_ID, 'string', oauth_app.NAME, 'string'},
            if_not_exists = true
        })

        local oauth_consumer_space = box.schema.space.create(oauth_consumer.SPACE_NAME, {
            if_not_exists = true
        })

        oauth_consumer_space:create_index(oauth_consumer.PRIMARY_INDEX, {
            type = 'hash',
            parts = {oauth_consumer.ID, 'string'},
            if_not_exists = true
        })
        oauth_consumer_space:create_index(oauth_consumer.APP_ID_INDEX, {
            type = 'tree',
            unique = true,
            parts = {oauth_consumer.APP_ID, 'string'},
            if_not_exists = true
        })

        local oauth_code_space = box.schema.space.create(oauth_code.SPACE_NAME, {
            if_not_exists = true
        })

        oauth_code_space:create_index(oauth_code.PRIMARY_INDEX, {
            type = 'hash',
            parts = {oauth_code.CODE, 'string'},
            if_not_exists = true
        })
        oauth_code_space:create_index(oauth_code.CONSUMER_INDEX, {
            type = 'tree',
            unique = false,
            parts = {oauth_code.CONSUMER_KEY, 'string', oauth_code.RESOURCE_OWNER, 'string'},
            if_not_exists = true
        })

        local oauth_token_space = box.schema.space.create(oauth_token.SPACE_NAME, {
            if_not_exists = true
        })

        oauth_token_space:create_index(oauth_token.PRIMARY_INDEX, {
            type = 'hash',
            parts = {oauth_token.ACCESS_TOKEN, 'string'},
            if_not_exists = true
        })
        oauth_token_space:create_index(oauth_token.CONSUMER_INDEX, {
            type = 'tree',
            unique = false,
            parts = {oauth_token.CONSUMER_KEY, 'string', oauth_token.RESOURCE_OWNER, 'string'},
            if_not_exists = true
        })
        oauth_token_space:create_index(oauth_token.REFRESH_INDEX, {
            type = 'tree',
            unique = true,
            parts = {oauth_token.REFRESH_TOKEN, 'string'},
            if_not_exists = true
        })

        local oauth_scope_space = box.schema.space.create(oauth_scope.SPACE_NAME, {
            if_not_exists = true
        })

        oauth_scope_space:create_index(oauth_scope.PRIMARY_INDEX, {
            type = 'tree',
            unique = true,
            parts = {oauth_scope.CONSUMER_KEY, 'string', oauth_scope.USER_ID, 'string', oauth_scope.NAME, 'string'},
            if_not_exists = true
        })
        oauth_scope_space:create_index(oauth_scope.USER_ID_INDEX, {
            type = 'tree',
            unique = false,
            parts = {oauth_scope.USER_ID, 'string'},
            if_not_exists = true
        })

        local oauth_redirect_space = box.schema.space.create(oauth_redirect.SPACE_NAME, {
            if_not_exists = true
        })

        oauth_redirect_space:create_index(oauth_redirect.PRIMARY_INDEX, {
            type = 'tree',
            unique = true,
            parts = {oauth_redirect.CONSUMER_KEY, 'string', oauth_redirect.USER_ID, 'string'},
            if_not_exists = true
        })
        oauth_redirect_space:create_index(oauth_redirect.USER_ID_INDEX, {
            type = 'tree',
            unique = false,
            parts = {oauth_redirect.USER_ID, 'string'},
            if_not_exists = true
        })
    end

    function api.truncate_spaces()
        user.get_space():truncate()
        password_token.get_space():truncate()
        password.get_space():truncate()
        social.get_space():truncate()
        session.get_space():truncate()
        oauth_app.get_space():truncate()
        oauth_consumer.get_space():truncate()
        oauth_code.get_space():truncate()
        oauth_token.get_space():truncate()
        oauth_scope.get_space():truncate()
        oauth_redirect.get_space():truncate()
    end

    return api
end

return db


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cylindrocolla corticioides Sacc.

### Remarks
null


text:
<?php

namespace Doctrine\ODM\MongoDB;

use BadMethodCallException;
use Doctrine\MongoDB\CommandCursor as BaseCommandCursor;
use Doctrine\MongoDB\Iterator;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;

/**
 * Wrapper for the CommandCursor class.
 *
 * @since  1.1
 * @author alcaeus <alcaeus@alcaeus.org>
 */
class CommandCursor implements Iterator
{
    /**
     * The CommandCursor instance being wrapped.
     *
     * @var BaseCommandCursor
     */
    private $commandCursor;

    /**
     * @var UnitOfWork
     */
    private $unitOfWork;

    /**
     * @var ClassMetadata
     */
    private $class;

    /**
     * @param BaseCommandCursor $commandCursor The ComamndCursor instance being wrapped
     * @param UnitOfWork $unitOfWork
     * @param ClassMetadata $class The class to use for hydration or null if results should not be hydrated
     */
    public function __construct(BaseCommandCursor $commandCursor, UnitOfWork $unitOfWork, ClassMetadata $class = null)
    {
        $this->commandCursor = $commandCursor;
        $this->unitOfWork = $unitOfWork;
        $this->class = $class;
    }

    /**
     * Wrapper method for MongoCommandCursor::batchSize().
     *
     * @see http://php.net/manual/en/mongocommandcursor.batchsize.php
     * @param integer $num
     * @return self
     */
    public function batchSize($num)
    {
        $this->commandCursor->batchSize($num);

        return $this;
    }

    /**
     * Recreates the command cursor and counts its results.
     *
     * @see http://php.net/manual/en/countable.count.php
     * @return integer
     */
    public function count()
    {
        return $this->commandCursor->count();
    }

    /**
     * Wrapper method for MongoCommandCursor::current().
     *
     * @see http://php.net/manual/en/iterator.current.php
     * @see http://php.net/manual/en/mongocommandcursor.current.php
     * @return object|array|null
     */
    public function current()
    {
        return $this->hydrateDocument($this->commandCursor->current());
    }

    /**
     * Wrapper method for MongoCommandCursor::dead().
     *
     * @see http://php.net/manual/en/mongocommandcursor.dead.php
     * @return boolean
     */
    public function dead()
    {
        return $this->commandCursor->dead();
    }

    /**
     * Returns the MongoCommandCursor instance being wrapped.
     *
     * @return BaseCommandCursor
     */
    public function getBaseCursor()
    {
        return $this->commandCursor;
    }

    /**
     * Rewinds the cursor and returns its first result.
     *
     * @see Iterator::getSingleResult()
     * @return object|array|null
     */
    public function getSingleResult()
    {
        return $this->hydrateDocument($this->commandCursor->getSingleResult());
    }

    /**
     * @param array $document
     * @return array|object|null
     */
    private function hydrateDocument($document)
    {
        if ($document !== null && $this->class !== null) {
            return $this->unitOfWork->getOrCreateDocument($this->class->name, $document);
        }

        return $document;
    }

    /**
     * Wrapper method for MongoCommandCursor::info().
     *
     * @see http://php.net/manual/en/mongocommandcursor.info.php
     * @return array
     */
    public function info()
    {
        return $this->commandCursor->info();
    }

    /**
     * Wrapper method for MongoCommandCursor::key().
     *
     * @see http://php.net/manual/en/iterator.key.php
     * @see http://php.net/manual/en/mongocommandcursor.key.php
     * @return integer
     */
    public function key()
    {
        return $this->commandCursor->key();
    }

    /**
     * Wrapper method for MongoCommandCursor::next().
     *
     * @see http://php.net/manual/en/iterator.next.php
     * @see http://php.net/manual/en/mongocommandcursor.next.php
     */
    public function next()
    {
        $cursor = $this;

        $cursor->commandCursor->next();
    }

    /**
     * Wrapper method for MongoCommandCursor::rewind().
     *
     * @see http://php.net/manual/en/iterator.rewind.php
     * @see http://php.net/manual/en/mongocommandcursor.rewind.php
     * @return array
     */
    public function rewind()
    {
        return $this->commandCursor->rewind();
    }

    /**
     * Wrapper method for MongoCommandCursor::timeout().
     *
     * @see http://php.net/manual/en/mongocommandcursor.timeout.php
     * @param integer $ms
     * @return self
     * @throws BadMethodCallException if MongoCommandCursor::timeout() is not available
     */
    public function timeout($ms)
    {
        $this->commandCursor->timeout($ms);

        return $this;
    }

    /**
     * Return the cursor's results as an array.
     *
     * @see Iterator::toArray()
     * @return array
     */
    public function toArray()
    {
        return iterator_to_array($this);
    }

    /**
     * Wrapper method for MongoCommandCursor::valid().
     *
     * @see http://php.net/manual/en/iterator.valid.php
     * @see http://php.net/manual/en/mongocommandcursor.valid.php
     * @return boolean
     */
    public function valid()
    {
        return $this->commandCursor->valid();
    }
}


text:
<?php
require_once 'PHPUnit/Framework.php';
require_once dirname(__FILE__) . '/../PHPRtfLiteSampleTestCase.php';

/**
 * Created on 09.06.2010
 *
 * @author sz
 */
class ListsSampleTest extends PHPRtfLiteSampleTestCase
{

    private $_name = 'lists';

    public function test()
    {
        $this->processTest($this->_name . '.php');
    }

    protected function getSampleFile()
    {
        return $this->getSampleDir() . '/generated/' . $this->_name . '.rtf';
    }

}