text:
#include "config.h"
#include "core/frame/LocalFrame.h"

#include "bindings/core/v8/ScriptController.h"
#include "core/dom/DocumentType.h"
#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/InputMethodController.h"
#include "core/editing/SpellChecker.h"
#include "core/editing/htmlediting.h"
#include "core/editing/markup.h"
#include "core/events/Event.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/frame/EventHandlerRegistry.h"
#include "core/frame/FrameConsole.h"
#include "core/frame/FrameDestructionObserver.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLFrameElementBase.h"
#include "core/html/HTMLPlugInElement.h"
#include "core/inspector/ConsoleMessageStorage.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/page/Chrome.h"
#include "core/page/EventHandler.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/compositing/RenderLayerCompositor.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "platform/DragImage.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/text/TextStream.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/StdLibExtras.h"

namespace blink {

using namespace HTMLNames;

namespace {

struct ScopedFramePaintingState {
    ScopedFramePaintingState(LocalFrame* frame, Node* node)
        : frame(frame)
        , node(node)
        , paintBehavior(frame->view()->paintBehavior())
    {
        ASSERT(!node || node->renderer());
        if (node)
            node->renderer()->updateDragState(true);
    }

    ~ScopedFramePaintingState()
    {
        if (node && node->renderer())
            node->renderer()->updateDragState(false);
        frame->view()->setPaintBehavior(paintBehavior);
        frame->view()->setNodeToDraw(0);
    }

    LocalFrame* frame;
    Node* node;
    PaintBehavior paintBehavior;
};

inline float parentPageZoomFactor(LocalFrame* frame)
{
    Frame* parent = frame->tree().parent();
    if (!parent || !parent->isLocalFrame())
        return 1;
    return toLocalFrame(parent)->pageZoomFactor();
}

inline float parentTextZoomFactor(LocalFrame* frame)
{
    Frame* parent = frame->tree().parent();
    if (!parent || !parent->isLocalFrame())
        return 1;
    return toLocalFrame(parent)->textZoomFactor();
}

} // namespace

PassRefPtrWillBeRawPtr<LocalFrame> LocalFrame::create(FrameLoaderClient* client, FrameHost* host, FrameOwner* owner)
{
    RefPtrWillBeRawPtr<LocalFrame> frame = adoptRefWillBeNoop(new LocalFrame(client, host, owner));
    InspectorInstrumentation::frameAttachedToParent(frame.get());
    return frame.release();
}

void LocalFrame::setView(PassRefPtrWillBeRawPtr<FrameView> view)
{
    ASSERT(!m_view || m_view != view);
    detachView();

    // Prepare for destruction now, so any unload event handlers get run and the LocalDOMWindow is
    // notified. If we wait until the view is destroyed, then things won't be hooked up enough for
    // these calls to work.
    if (!view && document() && document()->isActive()) {
        // FIXME: We don't call willRemove here. Why is that OK?
        document()->prepareForDestruction();
    }

    eventHandler().clear();

    m_view = view;

    if (m_view && isMainFrame() && !settings()->pinchVirtualViewportEnabled())
        m_view->setVisibleContentScaleFactor(page()->pageScaleFactor());
}

void LocalFrame::createView(const IntSize& viewportSize, const Color& backgroundColor, bool transparent,
    ScrollbarMode horizontalScrollbarMode, bool horizontalLock,
    ScrollbarMode verticalScrollbarMode, bool verticalLock)
{
    ASSERT(this);
    ASSERT(page());

    bool isLocalRoot = this->isLocalRoot();

    if (isLocalRoot && view())
        view()->setParentVisible(false);

    setView(nullptr);

    RefPtrWillBeRawPtr<FrameView> frameView = nullptr;
    if (isLocalRoot) {
        frameView = FrameView::create(this, viewportSize);

        // The layout size is set by WebViewImpl to support @viewport
        frameView->setLayoutSizeFixedToFrameSize(false);
    } else {
        frameView = FrameView::create(this);
    }

    frameView->setScrollbarModes(horizontalScrollbarMode, verticalScrollbarMode, horizontalLock, verticalLock);

    setView(frameView);

    frameView->updateBackgroundRecursively(backgroundColor, transparent);

    if (isLocalRoot)
        frameView->setParentVisible(true);

    // FIXME: Not clear what the right thing for OOPI is here.
    if (ownerRenderer()) {
        HTMLFrameOwnerElement* owner = deprecatedLocalOwner();
        ASSERT(owner);
        // FIXME: OOPI might lead to us temporarily lying to a frame and telling it
        // that it's owned by a FrameOwner that knows nothing about it. If we're
        // lying to this frame, don't let it clobber the existing widget.
        if (owner->contentFrame() == this)
            owner->setWidget(frameView);
    }

    if (HTMLFrameOwnerElement* owner = deprecatedLocalOwner())
        view()->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
}

LocalFrame::~LocalFrame()
{
#if ENABLE(OILPAN)
    // Verify that the FrameView has been cleared as part of detaching
    // the frame owner.
    ASSERT(!m_view);
    // Oilpan: see setDOMWindow() comment why it is acceptable not to
    // mirror the non-Oilpan call below.
    //
    // Also, FrameDestructionObservers that live longer than this
    // frame object keep weak references to the frame; those will be
    // automatically cleared by the garbage collector. Hence, explicit
    // frameDestroyed() notifications aren't needed.
#else
    // FIXME: follow Oilpan and clear the FrameView and FrameLoader
    // during FrameOwner detachment instead, see LocalFrame::disconnectOwnerElement().
    setView(nullptr);
    m_loader.clear();
    setDOMWindow(nullptr);

    for (const auto& frameDestructionObserver : m_destructionObservers)
        frameDestructionObserver->frameDestroyed();
#endif
}

void LocalFrame::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
    visitor->trace(m_destructionObservers);
    visitor->trace(m_loader);
    visitor->trace(m_navigationScheduler);
    visitor->trace(m_view);
    visitor->trace(m_domWindow);
    visitor->trace(m_pagePopupOwner);
    visitor->trace(m_script);
    visitor->trace(m_editor);
    visitor->trace(m_spellChecker);
    visitor->trace(m_selection);
    visitor->trace(m_eventHandler);
    visitor->trace(m_console);
    visitor->trace(m_inputMethodController);
    visitor->registerWeakMembers<LocalFrame, &LocalFrame::clearWeakMembers>(this);
    HeapSupplementable<LocalFrame>::trace(visitor);
#endif
    Frame::trace(visitor);
}

LocalDOMWindow* LocalFrame::domWindow() const
{
    return m_domWindow.get();
}

void LocalFrame::navigate(Document& originDocument, const KURL& url, bool lockBackForwardList)
{
    m_navigationScheduler.scheduleLocationChange(&originDocument, url.string(), lockBackForwardList);
}

void LocalFrame::detach()
{
    // A lot of the following steps can result in the current frame being
    // detached, so protect a reference to it.
    RefPtrWillBeRawPtr<LocalFrame> protect(this);
    m_loader.stopAllLoaders();
    m_loader.closeURL();
    detachChildren();
    // stopAllLoaders() needs to be called after detachChildren(), because detachChildren()
    // will trigger the unload event handlers of any child frames, and those event
    // handlers might start a new subresource load in this frame.
    m_loader.stopAllLoaders();
    if (!client())
        return;
    m_loader.detach();
    setView(nullptr);
    willDetachFrameHost();
    // Notify ScriptController that the frame is closing, since its cleanup ends up calling
    // back to FrameLoaderClient via WindowProxy.
    script().clearForClose();
    InspectorInstrumentation::frameDetachedFromParent(this);
    Frame::detach();
#if ENABLE(OILPAN)
    // Clear the FrameLoader right here rather than during
    // finalization. Too late to access various heap objects at that
    // stage.
    loader().clear();
#endif
}

void LocalFrame::disconnectOwnerElement()
{
    if (owner()) {
        if (Document* document = this->document())
            document->topDocument().clearAXObjectCache();
#if ENABLE(OILPAN)
        // First give the plugin elements holding persisted,
        // renderer-less plugins the opportunity to dispose of them.
        for (const auto& pluginElement : m_pluginElements)
            pluginElement->disconnectContentFrame();
        m_pluginElements.clear();
#endif
    }
    Frame::disconnectOwnerElement();
}

void LocalFrame::addDestructionObserver(FrameDestructionObserver* observer)
{
    m_destructionObservers.add(observer);
}

void LocalFrame::removeDestructionObserver(FrameDestructionObserver* observer)
{
    m_destructionObservers.remove(observer);
}

void LocalFrame::willDetachFrameHost()
{

    for (const auto& frameDestructionObserver : m_destructionObservers)
        frameDestructionObserver->willDetachFrameHost();

    // FIXME: Page should take care of updating focus/scrolling instead of Frame.
    // FIXME: It's unclear as to why this is called more than once, but it is,
    // so page() could be null.
    if (page() && page()->focusController().focusedFrame() == this)
        page()->focusController().setFocusedFrame(nullptr);
    script().clearScriptObjects();

    if (page() && page()->scrollingCoordinator() && m_view)
        page()->scrollingCoordinator()->willDestroyScrollableArea(m_view.get());
}

void LocalFrame::setDOMWindow(PassRefPtrWillBeRawPtr<LocalDOMWindow> domWindow)
{
    // Oilpan: setDOMWindow() cannot be used when finalizing. Which
    // is acceptable as its actions are either not needed or handled
    // by other means --
    //
    //  - FrameDestructionObserver::willDetachFrameHost() will have
    //    signalled the Inspector frameWindowDiscarded() notifications.
    //    We assume that all LocalFrames are detached, where that notification
    //    will have been done.
    //
    //  - Calling LocalDOMWindow::reset() is not needed (called from
    //    Frame::setDOMWindow().) The Member references it clears will now
    //    die with the window. And the registered DOMWindowProperty instances that don't,
    //    only keep a weak reference to this frame, so there's no need to be
    //    explicitly notified that this frame is going away.
    if (m_domWindow && host()) {
        host()->consoleMessageStorage().frameWindowDiscarded(m_domWindow.get());
        InspectorInstrumentation::frameWindowDiscarded(this, m_domWindow.get());
    }
    if (domWindow)
        script().clearWindowProxy();

    if (m_domWindow)
        m_domWindow->reset();
    m_domWindow = domWindow;
}

Document* LocalFrame::document() const
{
    return m_domWindow ? m_domWindow->document() : 0;
}

void LocalFrame::setPagePopupOwner(Element& owner)
{
    m_pagePopupOwner = &owner;
}

RenderView* LocalFrame::contentRenderer() const
{
    return document() ? document()->renderView() : 0;
}

void LocalFrame::didChangeVisibilityState()
{
    if (document())
        document()->didChangeVisibilityState();

    WillBeHeapVector<RefPtrWillBeMember<LocalFrame> > childFrames;
    for (Frame* child = tree().firstChild(); child; child = child->tree().nextSibling()) {
        if (child->isLocalFrame())
            childFrames.append(toLocalFrame(child));
    }

    for (size_t i = 0; i < childFrames.size(); ++i)
        childFrames[i]->didChangeVisibilityState();
}

LocalFrame* LocalFrame::localFrameRoot()
{
    LocalFrame* curFrame = this;
    while (curFrame && curFrame->tree().parent() && curFrame->tree().parent()->isLocalFrame())
        curFrame = toLocalFrame(curFrame->tree().parent());

    return curFrame;
}

bool LocalFrame::inScope(TreeScope* scope) const
{
    ASSERT(scope);
    Document* doc = document();
    if (!doc)
        return false;
    // FIXME: This check is broken in for OOPI.
    HTMLFrameOwnerElement* owner = doc->ownerElement();
    if (!owner)
        return false;
    return owner->treeScope() == scope;
}

void LocalFrame::countObjectsNeedingLayout(unsigned& needsLayoutObjects, unsigned& totalObjects, bool& isPartial)
{
    RenderObject* root = view()->layoutRoot();
    isPartial = true;
    if (!root) {
        isPartial = false;
        root = contentRenderer();
    }

    needsLayoutObjects = 0;
    totalObjects = 0;

    for (RenderObject* o = root; o; o = o->nextInPreOrder(root)) {
        ++totalObjects;
        if (o->needsLayout())
            ++needsLayoutObjects;
    }
}

String LocalFrame::layerTreeAsText(LayerTreeFlags flags) const
{
    TextStream textStream;
    textStream << localLayerTreeAsText(flags);

    for (Frame* child = tree().firstChild(); child; child = child->tree().traverseNext(this)) {
        if (!child->isLocalFrame())
            continue;
        String childLayerTree = toLocalFrame(child)->localLayerTreeAsText(flags);
        if (!childLayerTree.length())
            continue;

        textStream << "\n\n--------\nFrame: '";
        textStream << child->tree().uniqueName();
        textStream << "'\n--------\n";
        textStream << childLayerTree;
    }

    return textStream.release();
}

void LocalFrame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio)
{
    // In setting printing, we should not validate resources already cached for the document.
    // See https://bugs.webkit.org/show_bug.cgi?id=43704
    ResourceCacheValidationSuppressor validationSuppressor(document()->fetcher());

    document()->setPrinting(printing);
    view()->adjustMediaTypeForPrinting(printing);

    document()->styleResolverChanged();
    if (shouldUsePrintingLayout()) {
        view()->forceLayoutForPagination(pageSize, originalPageSize, maximumShrinkRatio);
    } else {
        view()->forceLayout();
        view()->adjustViewSize();
    }

    // Subframes of the one we're printing don't lay out to the page size.
    for (RefPtrWillBeRawPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling()) {
        if (child->isLocalFrame())
            toLocalFrame(child.get())->setPrinting(printing, FloatSize(), FloatSize(), 0);
    }
}

bool LocalFrame::shouldUsePrintingLayout() const
{
    // Only top frame being printed should be fit to page size.
    // Subframes should be constrained by parents only.
    return document()->printing() && (!tree().parent() || !tree().parent()->isLocalFrame() || !toLocalFrame(tree().parent())->document()->printing());
}

FloatSize LocalFrame::resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize)
{
    FloatSize resultSize;
    if (!contentRenderer())
        return FloatSize();

    if (contentRenderer()->style()->isHorizontalWritingMode()) {
        ASSERT(fabs(originalSize.width()) > std::numeric_limits<float>::epsilon());
        float ratio = originalSize.height() / originalSize.width();
        resultSize.setWidth(floorf(expectedSize.width()));
        resultSize.setHeight(floorf(resultSize.width() * ratio));
    } else {
        ASSERT(fabs(originalSize.height()) > std::numeric_limits<float>::epsilon());
        float ratio = originalSize.width() / originalSize.height();
        resultSize.setHeight(floorf(expectedSize.height()));
        resultSize.setWidth(floorf(resultSize.height() * ratio));
    }
    return resultSize;
}

void LocalFrame::setPageZoomFactor(float factor)
{
    setPageAndTextZoomFactors(factor, m_textZoomFactor);
}

void LocalFrame::setTextZoomFactor(float factor)
{
    setPageAndTextZoomFactors(m_pageZoomFactor, factor);
}

void LocalFrame::setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor)
{
    if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor)
        return;

    Page* page = this->page();
    if (!page)
        return;

    Document* document = this->document();
    if (!document)
        return;

    // Respect SVGs zoomAndPan="disabled" property in standalone SVG documents.
    // FIXME: How to handle compound documents + zoomAndPan="disabled"? Needs SVG WG clarification.
    if (document->isSVGDocument()) {
        if (!document->accessSVGExtensions().zoomAndPanEnabled())
            return;
    }

    if (m_pageZoomFactor != pageZoomFactor) {
        if (FrameView* view = this->view()) {
            // Update the scroll position when doing a full page zoom, so the content stays in relatively the same position.
            LayoutPoint scrollPosition = view->scrollPosition();
            float percentDifference = (pageZoomFactor / m_pageZoomFactor);
            view->setScrollPosition(DoublePoint(scrollPosition.x() * percentDifference, scrollPosition.y() * percentDifference));
        }
    }

    m_pageZoomFactor = pageZoomFactor;
    m_textZoomFactor = textZoomFactor;

    for (RefPtrWillBeRawPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling()) {
        if (child->isLocalFrame())
            toLocalFrame(child.get())->setPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor);
    }

    document->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::Zoom));
    document->updateLayoutIgnorePendingStylesheets();
}

void LocalFrame::deviceOrPageScaleFactorChanged()
{
    document()->mediaQueryAffectingValueChanged();
    for (RefPtrWillBeRawPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling()) {
        if (child->isLocalFrame())
            toLocalFrame(child.get())->deviceOrPageScaleFactorChanged();
    }
}

double LocalFrame::devicePixelRatio() const
{
    if (!m_host)
        return 0;

    double ratio = m_host->deviceScaleFactor();
    ratio *= pageZoomFactor();
    return ratio;
}

String LocalFrame::documentTypeString() const
{
    if (DocumentType* doctype = document()->doctype())
        return createMarkup(doctype);

    return String();
}

PassOwnPtr<DragImage> LocalFrame::nodeImage(Node& node)
{
    if (!node.renderer())
        return nullptr;

    const ScopedFramePaintingState state(this, &node);

    m_view->updateLayoutAndStyleForPainting();

    m_view->setPaintBehavior(state.paintBehavior | PaintBehaviorFlattenCompositingLayers);

    m_view->setNodeToDraw(&node); // Enable special sub-tree drawing mode.

    // Document::updateLayout may have blown away the original RenderObject.
    RenderObject* renderer = node.renderer();
    if (!renderer)
        return nullptr;

    LayoutRect topLevelRect;
    IntRect paintingRect = pixelSnappedIntRect(renderer->paintingRootRect(topLevelRect));

    ASSERT(document()->isActive());
    float deviceScaleFactor = m_host->deviceScaleFactor();
    paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
    paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);

    OwnPtr<ImageBuffer> buffer = ImageBuffer::create(paintingRect.size());
    if (!buffer)
        return nullptr;
    buffer->context()->scale(deviceScaleFactor, deviceScaleFactor);
    buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
    buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));

    m_view->paintContents(buffer->context(), paintingRect);

    RefPtr<Image> image = buffer->copyImage();
    return DragImage::create(image.get(), renderer->shouldRespectImageOrientation(), deviceScaleFactor);
}

PassOwnPtr<DragImage> LocalFrame::dragImageForSelection()
{
    if (!selection().isRange())
        return nullptr;

    const ScopedFramePaintingState state(this, 0);
    m_view->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorFlattenCompositingLayers);
    m_view->updateLayoutAndStyleForPainting();

    IntRect paintingRect = enclosingIntRect(selection().bounds());

    ASSERT(document()->isActive());
    float deviceScaleFactor = m_host->deviceScaleFactor();
    paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
    paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);

    OwnPtr<ImageBuffer> buffer = ImageBuffer::create(paintingRect.size());
    if (!buffer)
        return nullptr;
    buffer->context()->scale(deviceScaleFactor, deviceScaleFactor);
    buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
    buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));

    m_view->paintContents(buffer->context(), paintingRect);

    RefPtr<Image> image = buffer->copyImage();
    return DragImage::create(image.get(), DoNotRespectImageOrientation, deviceScaleFactor);
}

String LocalFrame::selectedText() const
{
    return selection().selectedText();
}

String LocalFrame::selectedTextForClipboard() const
{
    return selection().selectedTextForClipboard();
}

VisiblePosition LocalFrame::visiblePositionForPoint(const IntPoint& framePoint)
{
    HitTestResult result = eventHandler().hitTestResultAtPoint(framePoint);
    Node* node = result.innerNonSharedNode();
    if (!node)
        return VisiblePosition();
    RenderObject* renderer = node->renderer();
    if (!renderer)
        return VisiblePosition();
    VisiblePosition visiblePos = VisiblePosition(renderer->positionForPoint(result.localPoint()));
    if (visiblePos.isNull())
        visiblePos = VisiblePosition(firstPositionInOrBeforeNode(node));
    return visiblePos;
}

Document* LocalFrame::documentAtPoint(const IntPoint& point)
{
    if (!view())
        return 0;

    IntPoint pt = view()->windowToContents(point);
    HitTestResult result = HitTestResult(pt);

    if (contentRenderer())
        result = eventHandler().hitTestResultAtPoint(pt, HitTestRequest::ReadOnly | HitTestRequest::Active);
    return result.innerNode() ? &result.innerNode()->document() : 0;
}

PassRefPtrWillBeRawPtr<Range> LocalFrame::rangeForPoint(const IntPoint& framePoint)
{
    VisiblePosition position = visiblePositionForPoint(framePoint);
    if (position.isNull())
        return nullptr;

    VisiblePosition previous = position.previous();
    if (previous.isNotNull()) {
        RefPtrWillBeRawPtr<Range> previousCharacterRange = makeRange(previous, position);
        LayoutRect rect = editor().firstRectForRange(previousCharacterRange.get());
        if (rect.contains(framePoint))
            return previousCharacterRange.release();
    }

    VisiblePosition next = position.next();
    if (RefPtrWillBeRawPtr<Range> nextCharacterRange = makeRange(position, next)) {
        LayoutRect rect = editor().firstRectForRange(nextCharacterRange.get());
        if (rect.contains(framePoint))
            return nextCharacterRange.release();
    }

    return nullptr;
}

bool LocalFrame::isURLAllowed(const KURL& url) const
{
    // We allow one level of self-reference because some sites depend on that,
    // but we don't allow more than one.
    if (host()->subframeCount() >= FrameHost::maxNumberOfFrames)
        return false;
    bool foundSelfReference = false;
    for (const Frame* frame = this; frame; frame = frame->tree().parent()) {
        if (!frame->isLocalFrame())
            continue;
        if (equalIgnoringFragmentIdentifier(toLocalFrame(frame)->document()->url(), url)) {
            if (foundSelfReference)
                return false;
            foundSelfReference = true;
        }
    }
    return true;
}

bool LocalFrame::shouldReuseDefaultView(const KURL& url) const
{
    return loader().stateMachine()->isDisplayingInitialEmptyDocument() && document()->isSecureTransitionTo(url);
}

void LocalFrame::removeSpellingMarkersUnderWords(const Vector<String>& words)
{
    spellChecker().removeSpellingMarkersUnderWords(words);
}

#if ENABLE(OILPAN)
void LocalFrame::registerPluginElement(HTMLPlugInElement* plugin)
{
    m_pluginElements.add(plugin);
}

void LocalFrame::unregisterPluginElement(HTMLPlugInElement* plugin)
{
    ASSERT(m_pluginElements.contains(plugin));
    m_pluginElements.remove(plugin);
}

void LocalFrame::clearWeakMembers(Visitor* visitor)
{
    Vector<HTMLPlugInElement*> deadPlugins;
    for (const auto& pluginElement : m_pluginElements) {
        if (!visitor->isAlive(pluginElement)) {
            pluginElement->shouldDisposePlugin();
            deadPlugins.append(pluginElement);
        }
    }
    for (unsigned i = 0; i < deadPlugins.size(); ++i)
        m_pluginElements.remove(deadPlugins[i]);
}
#endif

String LocalFrame::localLayerTreeAsText(unsigned flags) const
{
    if (!contentRenderer())
        return String();

    return contentRenderer()->compositor()->layerTreeAsText(static_cast<LayerTreeFlags>(flags));
}

inline LocalFrame::LocalFrame(FrameLoaderClient* client, FrameHost* host, FrameOwner* owner)
    : Frame(client, host, owner)
    , m_loader(this)
    , m_navigationScheduler(this)
    , m_script(ScriptController::create(this))
    , m_editor(Editor::create(*this))
    , m_spellChecker(SpellChecker::create(*this))
    , m_selection(FrameSelection::create(this))
    , m_eventHandler(adoptPtrWillBeNoop(new EventHandler(this)))
    , m_console(FrameConsole::create(*this))
    , m_inputMethodController(InputMethodController::create(*this))
    , m_pageZoomFactor(parentPageZoomFactor(this))
    , m_textZoomFactor(parentTextZoomFactor(this))
    , m_inViewSourceMode(false)
{
}

void LocalFrame::detachView()
{
    // We detach the FrameView's custom scroll bars as early as
    // possible to prevent m_doc->detach() from messing with the view
    // such that its scroll bars won't be torn down.
    //
    // FIXME: We should revisit this.
    if (m_view)
        m_view->prepareForDetach();
}

} // namespace blink


text:
#include "webrtc/modules/video_coding/codecs/vp8/default_temporal_layers.h"

#include <stdlib.h>
#include <string.h>

#include <algorithm>
#include <vector>

#include "webrtc/base/checks.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/modules/video_coding/include/video_codec_interface.h"
#include "webrtc/modules/video_coding/codecs/vp8/include/vp8_common_types.h"

#include "vpx/vpx_encoder.h"
#include "vpx/vp8cx.h"

namespace webrtc {

TemporalLayers::FrameConfig::FrameConfig() {}

TemporalLayers::FrameConfig::FrameConfig(TemporalLayers::BufferFlags last,
                                         TemporalLayers::BufferFlags golden,
                                         TemporalLayers::BufferFlags arf)
    : FrameConfig(last, golden, arf, false) {}

TemporalLayers::FrameConfig::FrameConfig(TemporalLayers::BufferFlags last,
                                         TemporalLayers::BufferFlags golden,
                                         TemporalLayers::BufferFlags arf,
                                         FreezeEntropy)
    : FrameConfig(last, golden, arf, true) {}

TemporalLayers::FrameConfig::FrameConfig(TemporalLayers::BufferFlags last,
                                         TemporalLayers::BufferFlags golden,
                                         TemporalLayers::BufferFlags arf,
                                         bool freeze_entropy)
    : drop_frame(last == TemporalLayers::kNone &&
                 golden == TemporalLayers::kNone &&
                 arf == TemporalLayers::kNone),
      last_buffer_flags(last),
      golden_buffer_flags(golden),
      arf_buffer_flags(arf),
      freeze_entropy(freeze_entropy) {}

namespace {

std::vector<unsigned int> GetTemporalIds(size_t num_layers) {
  switch (num_layers) {
    case 1:
      // Temporal layer structure (single layer):
      // 0 0 0 0 ...
      return {0};
    case 2:
      // Temporal layer structure:
      //   1   1 ...
      // 0   0   ...
      return {0, 1};
    case 3:
      // Temporal layer structure:
      //   2   2   2   2 ...
      //     1       1   ...
      // 0       0       ...
      return {0, 2, 1, 2};
    case 4:
      // Temporal layer structure:
      //   3   3   3   3   3   3   3   3 ...
      //     2       2       2       2   ...
      //         1               1       ...
      // 0               0               ...
      return {0, 3, 2, 3, 1, 3, 2, 3};
    default:
      RTC_NOTREACHED();
      break;
  }
  RTC_NOTREACHED();
  return {0};
}

std::vector<bool> GetTemporalLayerSync(size_t num_layers) {
  switch (num_layers) {
    case 1:
      return {false};
    case 2:
      return {false, true, false, false, false, false, false, false};
    case 3:
      return {false, true, true, false, false, false, false, false};
    case 4:
      return {false, true, true,  true, true,  true, false, true,
              false, true, false, true, false, true, false, true};
    default:
      RTC_NOTREACHED();
      break;
  }
  RTC_NOTREACHED();
  return {false};
}

std::vector<TemporalLayers::FrameConfig> GetTemporalPattern(size_t num_layers) {
  // For indexing in the patterns described below (which temporal layers they
  // belong to), see the diagram above.
  // Layer sync is done similarly for all patterns (except single stream) and
  // happens every 8 frames:
  // TL1 layer syncs by periodically by only referencing TL0 ('last'), but still
  // updating 'golden', so it can be used as a reference by future TL1 frames.
  // TL2 layer syncs just before TL1 by only depending on TL0 (and not depending
  // on TL1's buffer before TL1 has layer synced).
  // TODO(pbos): Consider cyclically updating 'arf' (and 'golden' for 1TL) for
  // the base layer in 1-3TL instead of 'last' periodically on long intervals,
  // so that if scene changes occur (user walks between rooms or rotates webcam)
  // the 'arf' (or 'golden' respectively) is not stuck on a no-longer relevant
  // keyframe.
  switch (num_layers) {
    case 1:
      // All frames reference all buffers and the 'last' buffer is updated.
      return {TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kReference,
                                          TemporalLayers::kReference)};
    case 2:
      // All layers can reference but not update the 'alt' buffer, this means
      // that the 'alt' buffer reference is effectively the last keyframe.
      // TL0 also references and updates the 'last' buffer.
      // TL1 also references 'last' and references and updates 'golden'.
      return {TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kUpdate,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kUpdate,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kNone,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kNone,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kNone,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy)};
    case 3:
      // All layers can reference but not update the 'alt' buffer, this means
      // that the 'alt' buffer reference is effectively the last keyframe.
      // TL0 also references and updates the 'last' buffer.
      // TL1 also references 'last' and references and updates 'golden'.
      // TL2 references both 'last' and 'golden' but updates no buffer.
      return {TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kUpdate,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kNone,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kUpdate,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kNone,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kReference),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy)};
    case 4:
      // TL0 references and updates only the 'last' buffer.
      // TL1 references 'last' and updates and references 'golden'.
      // TL2 references 'last' and 'golden', and references and updates 'arf'.
      // TL3 references all buffers but update none of them.
      return {TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kNone,
                                          TemporalLayers::kNone),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kNone,
                                          TemporalLayers::kUpdate),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kUpdate,
                                          TemporalLayers::kNone),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kReference,
                                          TemporalLayers::kReferenceAndUpdate),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kNone,
                                          TemporalLayers::kNone),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kReference,
                                          TemporalLayers::kReferenceAndUpdate),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kReferenceAndUpdate,
                                          TemporalLayers::kNone),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy),
              TemporalLayers::FrameConfig(TemporalLayers::kReference,
                                          TemporalLayers::kReference,
                                          TemporalLayers::kReferenceAndUpdate),
              TemporalLayers::FrameConfig(
                  TemporalLayers::kReference, TemporalLayers::kReference,
                  TemporalLayers::kReference, TemporalLayers::kFreezeEntropy)};
    default:
      RTC_NOTREACHED();
      break;
  }
  RTC_NOTREACHED();
  return {TemporalLayers::FrameConfig(
      TemporalLayers::kNone, TemporalLayers::kNone, TemporalLayers::kNone)};
}

}  // namespace

DefaultTemporalLayers::DefaultTemporalLayers(int number_of_temporal_layers,
                                             uint8_t initial_tl0_pic_idx)
    : num_layers_(std::max(1, number_of_temporal_layers)),
      temporal_ids_(GetTemporalIds(num_layers_)),
      temporal_layer_sync_(GetTemporalLayerSync(num_layers_)),
      temporal_pattern_(GetTemporalPattern(num_layers_)),
      tl0_pic_idx_(initial_tl0_pic_idx),
      pattern_idx_(255),
      timestamp_(0),
      last_base_layer_sync_(false) {
  RTC_DCHECK_EQ(temporal_pattern_.size(), temporal_layer_sync_.size());
  RTC_CHECK_GE(kMaxTemporalStreams, number_of_temporal_layers);
  RTC_CHECK_GE(number_of_temporal_layers, 0);
  RTC_CHECK_LE(number_of_temporal_layers, 4);
  // pattern_idx_ wraps around temporal_pattern_.size, this is incorrect if
  // temporal_ids_ are ever longer. If this is no longer correct it needs to
  // wrap at max(temporal_ids_.size(), temporal_pattern_.size()).
  RTC_DCHECK_LE(temporal_ids_.size(), temporal_pattern_.size());
}

int DefaultTemporalLayers::GetTemporalLayerId(
    const TemporalLayers::FrameConfig& tl_config) const {
  RTC_DCHECK(!tl_config.drop_frame);
  return temporal_ids_[tl_config.pattern_idx % temporal_ids_.size()];
}

uint8_t DefaultTemporalLayers::Tl0PicIdx() const {
  return tl0_pic_idx_;
}

std::vector<uint32_t> DefaultTemporalLayers::OnRatesUpdated(
    int bitrate_kbps,
    int max_bitrate_kbps,
    int framerate) {
  std::vector<uint32_t> bitrates;
  for (size_t i = 0; i < num_layers_; ++i) {
    float layer_bitrate =
        bitrate_kbps * kVp8LayerRateAlloction[num_layers_ - 1][i];
    bitrates.push_back(static_cast<uint32_t>(layer_bitrate + 0.5));
  }
  new_bitrates_kbps_ = rtc::Optional<std::vector<uint32_t>>(bitrates);

  // Allocation table is of aggregates, transform to individual rates.
  uint32_t sum = 0;
  for (size_t i = 0; i < num_layers_; ++i) {
    uint32_t layer_bitrate = bitrates[i];
    RTC_DCHECK_LE(sum, bitrates[i]);
    bitrates[i] -= sum;
    sum = layer_bitrate;

    if (sum >= static_cast<uint32_t>(bitrate_kbps)) {
      // Sum adds up; any subsequent layers will be 0.
      bitrates.resize(i + 1);
      break;
    }
  }

  return bitrates;
}

bool DefaultTemporalLayers::UpdateConfiguration(vpx_codec_enc_cfg_t* cfg) {
  if (!new_bitrates_kbps_)
    return false;

  for (size_t i = 0; i < num_layers_; ++i) {
    cfg->ts_target_bitrate[i] = (*new_bitrates_kbps_)[i];
    // ..., 4, 2, 1
    cfg->ts_rate_decimator[i] = 1 << (num_layers_ - i - 1);
  }

  cfg->ts_number_layers = num_layers_;
  cfg->ts_periodicity = temporal_ids_.size();
  memcpy(cfg->ts_layer_id, &temporal_ids_[0],
         sizeof(unsigned int) * temporal_ids_.size());

  new_bitrates_kbps_ = rtc::Optional<std::vector<uint32_t>>();

  return true;
}

TemporalLayers::FrameConfig DefaultTemporalLayers::UpdateLayerConfig(
    uint32_t timestamp) {
  RTC_DCHECK_GT(num_layers_, 0);
  RTC_DCHECK_LT(0, temporal_pattern_.size());
  pattern_idx_ = (pattern_idx_ + 1) % temporal_pattern_.size();
  TemporalLayers::FrameConfig tl_config = temporal_pattern_[pattern_idx_];
  tl_config.pattern_idx = pattern_idx_;
  return tl_config;
}

void DefaultTemporalLayers::PopulateCodecSpecific(
    bool frame_is_keyframe,
    const TemporalLayers::FrameConfig& tl_config,
    CodecSpecificInfoVP8* vp8_info,
    uint32_t timestamp) {
  RTC_DCHECK_GT(num_layers_, 0);

  if (num_layers_ == 1) {
    vp8_info->temporalIdx = kNoTemporalIdx;
    vp8_info->layerSync = false;
    vp8_info->tl0PicIdx = kNoTl0PicIdx;
  } else {
    if (frame_is_keyframe) {
      vp8_info->temporalIdx = 0;
      vp8_info->layerSync = true;
    } else {
      vp8_info->temporalIdx = GetTemporalLayerId(tl_config);

      vp8_info->layerSync = temporal_layer_sync_[tl_config.pattern_idx %
                                                 temporal_layer_sync_.size()];
    }
    if (last_base_layer_sync_ && vp8_info->temporalIdx != 0) {
      // Regardless of pattern the frame after a base layer sync will always
      // be a layer sync.
      vp8_info->layerSync = true;
    }
    if (vp8_info->temporalIdx == 0 && timestamp != timestamp_) {
      timestamp_ = timestamp;
      tl0_pic_idx_++;
    }
    last_base_layer_sync_ = frame_is_keyframe;
    vp8_info->tl0PicIdx = tl0_pic_idx_;
  }
}

TemporalLayers* TemporalLayersFactory::Create(
    int simulcast_id,
    int temporal_layers,
    uint8_t initial_tl0_pic_idx) const {
  TemporalLayers* tl =
      new DefaultTemporalLayers(temporal_layers, initial_tl0_pic_idx);
  if (listener_)
    listener_->OnTemporalLayersCreated(simulcast_id, tl);
  return tl;
}

void TemporalLayersFactory::SetListener(TemporalLayersListener* listener) {
  listener_ = listener;
}

}  // namespace webrtc

redpajama_set_name: RedPajamaGithub


text:
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;

[assembly: AssemblyTitle("DM Jukebox for Windows")]
[assembly: AssemblyDescription("This is the UI frontend for DM Jukebox.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Joe Clapis")]
[assembly: AssemblyProduct("DM Jukebox")]
[assembly: AssemblyCopyright("Copyright © 2016 Joe Clapis. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None,
    ResourceDictionaryLocation.SourceAssembly
)]

[assembly: AssemblyVersion("0.1.*")]


text:
<?php

class validation{

    /*
    * @errors array
    */
    public $errors = array();

    /*
    * @the validation rules array
    */
    private $validation_rules = array();

    /*
     * @the sanitized values array
     */
    public $sanitized = array();

    /*
     * @the source
     */
    private $source = array();

    /**
     *
     * @the constructor, duh!
     *
     */
    public function __construct()
    {
    }

    /**
     *
     * @add the source
     *
     * @paccess public
     *
     * @param array $source
     *
     */
    public function addSource($source, $trim=false)
    {
        $this->source = $source;
    }

    /**
     *
     * @run the validation rules
     *
     * @access public
     *
     */
    public function run($var)
    {
        /*** set the vars ***/
        foreach( new ArrayIterator($this->validation_rules) as $var=>$opt)
        {
            if($opt['required'] == true)
            {
                $this->is_set($var);
            }

            /*** Trim whitespace from beginning and end of variable ***/
            if( array_key_exists('trim', $opt) && $opt['trim'] == true )
            {
                $this->source[$var] = trim( $this->source[$var] );
            }

            switch($opt['type'])
            {
                case 'email':
                    $this->validateEmail($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeEmail($var);
                    }
                    break;

                case 'url':
                    $this->validateUrl($var);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeUrl($var);
                    }
                    break;

                case 'numeric':
                    $this->validateNumeric($var, $opt['min'], $opt['max'], $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeNumeric($var);
                    }
                    break;

                case 'string':
                    $this->validateString($var, $opt['min'], $opt['max'], $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeString($var);
                    }
                break;

                case 'float':
                    $this->validateFloat($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeFloat($var);
                    }
                    break;

                case 'ipv4':
                    $this->validateIpv4($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeIpv4($var);
                    }
                    break;

                case 'ipv6':
                    $this->validateIpv6($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeIpv6($var);
                    }
                    break;

                case 'bool':
                    $this->validateBool($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitized[$var] = (bool) $this->source[$var];
                    }
                    break;
            }
        }
    }

    /**
     *
     * @add a rule to the validation rules array
     *
     * @access public
     *
     * @param string $varname The variable name
     *
     * @param string $type The type of variable
     *
     * @param bool $required If the field is required
     *
     * @param int $min The minimum length or range
     *
     * @param int $max the maximum length or range
     *
     */
    public function addRule($varname, $type, $required=false, $min=0, $max=0, $trim=false)
    {
        $this->validation_rules[$varname] = array('type'=>$type, 'required'=>$required, 'min'=>$min, 'max'=>$max, 'trim'=>$trim);
        /*** allow chaining ***/
        return $this;
    }

    /**
     *
     * @add multiple rules to teh validation rules array
     *
     * @access public
     *
     * @param array $rules_array The array of rules to add
     *
     */
    public function AddRules(array $rules_array)
    {
        $this->validation_rules = array_merge($this->validation_rules, $rules_array);
    }

    /**
     *
     * @Check if POST variable is set
     *
     * @access private
     *
     * @param string $var The POST variable to check
     *
     */
    private function is_set($var)
    {
        if(!isset($this->source[$var]))
        {
            $this->errors[$var] = $var . ' is not set';
        }
    }

    /**
     *
     * @validate an ipv4 IP address
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @param bool $required
     *
     */
    private function validateIpv4($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid IPv4';
        }
    }

    /**
     *
     * @validate an ipv6 IP address
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @param bool $required
     *
     */
    public function validateIpv6($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }

        if(filter_var($this->source[$var], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid IPv6';
        }
    }

    /**
     *
     * @validate a floating point number
     *
     * @access private
     *
     * @param $var The variable name
     *
     * @param bool $required
     */
    private function validateFloat($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_FLOAT) === false)
        {
            $this->errors[$var] = $var . ' is an invalid float';
        }
    }

    /**
     *
     * @validate a string
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @param int $min the minimum string length
     *
     * @param int $max The maximum string length
     *
     * @param bool $required
     *
     */
    private function validateString($var, $min=0, $max=0, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }

        if(isset($this->source[$var]))
        {
            if(strlen($this->source[$var]) < $min)
            {
                $this->errors[$var] = $var . ' is too short';
            }
            elseif(strlen($this->source[$var]) > $max)
            {
                $this->errors[$var] = $var . ' is too long';
            }
            elseif(!is_string($this->source[$var]))
            {
                $this->errors[$var] = $var . ' is invalid';
            }
        }
    }

    /**
     *
     * @validate an number
     *
     * @access private
     *
     * @param string $var the variable name
     *
     * @param int $min The minimum number range
     *
     * @param int $max The maximum number range
     *
     * @param bool $required
     *
     */
    private function validateNumeric($var, $min=0, $max=0, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max)))===FALSE)
        {
            $this->errors[$var] = $var . ' is an invalid number';
        }
    }

    /**
     *
     * @validate a url
     *
     * @access private
     *
      * @param string $var The variable name
     *
     * @param bool $required
     *
     */
    private function validateUrl($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_URL) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid URL';
        }
    }

    /**
     *
     * @validate an email address
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @param bool $required
     *
     */
    private function validateEmail($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_EMAIL) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid email address';
        }
    }

    /**
     * @validate a boolean
     *
     * @access private
     *
     * @param string $var the variable name
     *
     * @param bool $required
     *
     */
    private function validateBool($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        filter_var($this->source[$var], FILTER_VALIDATE_BOOLEAN);
        {
            $this->errors[$var] = $var . ' is Invalid';
        }
    }

    ########## SANITIZING METHODS ############

    /**
     *
     * @santize and email
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @return string
     *
     */
    public function sanitizeEmail($var)
    {
        $email = preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $this->source[$var] );
        $this->sanitized[$var] = (string) filter_var($email, FILTER_SANITIZE_EMAIL);
    }

    /**
     *
     * @sanitize a url
     *
     * @access private
     *
     * @param string $var The variable name
     *
     */
    private function sanitizeUrl($var)
    {
        $this->sanitized[$var] = (string) filter_var($this->source[$var],  FILTER_SANITIZE_URL);
    }

    /**
     *
     * @sanitize a numeric value
     *
     * @access private
     *
     * @param string $var The variable name
     *
     */
    private function sanitizeNumeric($var)
    {
        $this->sanitized[$var] = (int) filter_var($this->source[$var], FILTER_SANITIZE_NUMBER_INT);
    }

    /**
     *
     * @sanitize a string
     *
     * @access private
     *
     * @param string $var The variable name
     *
     */
    private function sanitizeString($var)
    {
        $this->sanitized[$var] = (string) filter_var($this->source[$var], FILTER_SANITIZE_STRING);
    }

} /*** end of class ***/

?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>dance</groupId>
  <artifactId>Distributed-Kit</artifactId>
  <versioning>
    <release>0.0.1</release>
    <versions>
      <version>0.0.1</version>
    </versions>
    <lastUpdated>20161130074033</lastUpdated>
  </versioning>
</metadata>


text:
<?php

namespace Tests\Unit\WindowsAzure\Common\Models;
use WindowsAzure\Common\Models\RetentionPolicy;
use Tests\Framework\TestResources;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Unit tests for class RetentionPolicy
 *
 * @category  Microsoft
 * @package   Tests\Unit\WindowsAzure
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.2_2016-04
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class RetentionPolicyTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers WindowsAzure\Common\Models\RetentionPolicy::create
     */
    public function testCreate()
    {
        // Setup
        $sample = TestResources::getServicePropertiesSample();
        $expectedEnabled = Utilities::toBoolean($sample['Logging']['RetentionPolicy']['Enabled']);
        $expectedDays = intval($sample['Logging']['RetentionPolicy']['Days']);

        // Test
        $actual = RetentionPolicy::create($sample['Logging']['RetentionPolicy']);

        // Assert
        $this->assertEquals($expectedEnabled, $actual->getEnabled());
        $this->assertEquals($expectedDays, $actual->getDays());
    }

    /**
     * @covers WindowsAzure\Common\Models\RetentionPolicy::getEnabled
     */
    public function testGetEnabled()
    {
        // Setup
        $sample = TestResources::getServicePropertiesSample();
        $retentionPolicy = new RetentionPolicy();
        $expected = Utilities::toBoolean($sample['Logging']['RetentionPolicy']['Enabled']);
        $retentionPolicy->setEnabled($expected);

        // Test
        $actual = $retentionPolicy->getEnabled();

        // Assert
        $this->assertEquals($expected, $actual);
    }

    /**
     * @covers WindowsAzure\Common\Models\RetentionPolicy::setEnabled
     */
    public function testSetEnabled()
    {
        // Setup
        $sample = TestResources::getServicePropertiesSample();
        $retentionPolicy = new RetentionPolicy();
        $expected = Utilities::toBoolean($sample['Logging']['RetentionPolicy']['Enabled']);

        // Test
        $retentionPolicy->setEnabled($expected);

        // Assert
        $actual = $retentionPolicy->getEnabled();
        $this->assertEquals($expected, $actual);
    }

    /**
     * @covers WindowsAzure\Common\Models\RetentionPolicy::getDays
     */
    public function testGetDays()
    {
        // Setup
        $sample = TestResources::getServicePropertiesSample();
        $retentionPolicy = new RetentionPolicy();
        $expected = intval($sample['Logging']['RetentionPolicy']['Days']);
        $retentionPolicy->setDays($expected);

        // Test
        $actual = $retentionPolicy->getDays();

        // Assert
        $this->assertEquals($expected, $actual);
    }

    /**
     * @covers WindowsAzure\Common\Models\RetentionPolicy::setDays
     */
    public function testSetDays()
    {
        // Setup
        $sample = TestResources::getServicePropertiesSample();
        $retentionPolicy = new RetentionPolicy();
        $expected = intval($sample['Logging']['RetentionPolicy']['Days']);

        // Test
        $retentionPolicy->setDays($expected);

        // Assert
        $actual = $retentionPolicy->getDays();
        $this->assertEquals($expected, $actual);
    }

    /**
     * @covers WindowsAzure\Common\Models\RetentionPolicy::toArray
     */
    public function testToArray()
    {
        // Setup
        $sample = TestResources::getServicePropertiesSample();
        $retentionPolicy = RetentionPolicy::create($sample['Logging']['RetentionPolicy']);
        $expected = array(
            'Enabled' => $sample['Logging']['RetentionPolicy']['Enabled'],
            'Days'    => $sample['Logging']['RetentionPolicy']['Days']
        );

        // Test
        $actual = $retentionPolicy->toArray();

        // Assert
        $this->assertEquals($expected, $actual);
    }

    /**
     * @covers WindowsAzure\Common\Models\RetentionPolicy::toArray
     */
    public function testToArrayWithoutDays()
    {
        // Setup
        $sample = TestResources::getServicePropertiesSample();
        $retentionPolicy = RetentionPolicy::create($sample['Logging']['RetentionPolicy']);
        $expected = array('Enabled' => $sample['Logging']['RetentionPolicy']['Enabled']);
        $retentionPolicy->setDays(null);

        // Test
        $actual = $retentionPolicy->toArray();

        // Assert
        $this->assertEquals($expected, $actual);
    }
}


text:
module CommonHelpers
  def limit_exceeded_exception(request = {})
    request_options = {
      :headers => {
        "Content-Type" => "application/json", "Authorization" => "OAuth 864b21f13485a7f2de49593f627213075e8eb046",
        "Host" => "api.gb1.brightbox.com:443", "Content-Length" => 71
      },
      :host => "api.gb1.brightbox.com", :mock => false, :path => "/1.0/servers",
      :port => "443", :query => nil, :scheme => "https",
      :expects => [202],
      :method => "POST",
      :body => "{\"image\":\"img-4gqhs\",\"server_type\":\"typ-qdiwq\",\"name\":\"medium servers\"}"
    }

    response = Excon::Response.new(
      :body => "{\"error_name\":\"account_limit_reached\",\"errors\":[\"Account limit reached, please contact support for more information\"]}",
      :status => 403,
      :headers => {
        "Date" => "Tue, 28 Jun 2011 08:07:21 GMT", "Server" => "Apache", "Cache-Control" => "no-cache", "Access-Control-Allow-Origin" => "*", "Access-Control-Allow-Headers" => "Authorization", "Content-Length" => "118", "Status" => "403", "Content-Type" => "application/json; charset=utf-8"
      }
    )

    Excon::Errors.status_error(request_options.merge(request), response)
  end
end


text:
#pragma once
#include <aws/mediaconvert/MediaConvert_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace MediaConvert
{
namespace Model
{
  enum class OutputGroupType
  {
    NOT_SET,
    HLS_GROUP_SETTINGS,
    DASH_ISO_GROUP_SETTINGS,
    FILE_GROUP_SETTINGS,
    MS_SMOOTH_GROUP_SETTINGS,
    CMAF_GROUP_SETTINGS
  };

namespace OutputGroupTypeMapper
{
AWS_MEDIACONVERT_API OutputGroupType GetOutputGroupTypeForName(const Aws::String& name);

AWS_MEDIACONVERT_API Aws::String GetNameForOutputGroupType(OutputGroupType value);
} // namespace OutputGroupTypeMapper
} // namespace Model
} // namespace MediaConvert
} // namespace Aws


text:
/*
   A small applet that shows multiple copies of the string "Java!"
   in random colors, at random locations, and in a number of fonts
   on a black background.  Strings are added one-by-one, then removed
   in the reverse order.  Then the process is repeated.

   David Eck
   Deparment of Mathematics and Computer Science
   Hobart and William Smith Colleges
   300 Pulteney Street
   Geneva, NY 14456
   eck@hws.edu

   This version of the applet is based on a generic animation applet
   defined in SimpleAnimationApplet.java.  (An earlier version was not.)
*/

import java.awt.*;

public class JavaPops extends SimpleAnimationApplet {

   static final String str = "Java!";   // the string to display
   static final int maxJavas = 20;      // number of instances of the string to be displayed

   Font[] fontList;          // various fonts to be used for displaying the string  (set up in init())
   FontMetrics[] fm;         // FontMetrics for each font in fontList

   int[] x, y;               // (x[i],y[i]) is position of i-th instance of string
   int[] font;               // font[i] is index in fontList[] of i-th instance of string
   Color[] color;            // color[i] is color used for i-th instance

   public void init() {

      setFrameCount(2*maxJavas);      // set up SimpleAnimationApplet variables
      setMillisecondsPerFrame(200);

      setBackground(Color.black);

      x = new int[maxJavas];
      y = new int[maxJavas];
      font = new int[maxJavas];
      color = new Color[maxJavas];

      fontList = new Font[5];   // create fonts for displaying the string
      fontList[0] = new Font("TimesRoman",Font.BOLD,24);
      fontList[1] = new Font("TimesRoman",Font.BOLD,42);
      fontList[2] = new Font("TimesRoman",Font.BOLD,60);
      fontList[3] = new Font("TimesRoman",Font.BOLD+Font.ITALIC,24);
      fontList[4] = new Font("TimesRoman",Font.BOLD+Font.ITALIC,42);

      fm = new FontMetrics[fontList.length];
      for (int i=0; i<fontList.length; i++) {
         fm[i] = getFontMetrics(fontList[i]);
      }

   }

   public void drawFrame(Graphics g) {
         // A frame shows a number of randomly colored, sized, and positioned strings on
         // a black background.  For frame numbers 0 to maxJavas - 1, a new string is
         // added.  For frame numbers maxJavas to 2*maxJavas - 1, one of the strings is
         // removed.
      int width = getWidth();
      int height = getHeight();
      boolean ascending;  // true if a string is to be added in this frame
      ascending = getFrameNumber() < maxJavas;
      int javaCt;    // number of strings in this frame
      javaCt = (ascending? getFrameNumber() : 2*maxJavas - getFrameNumber() - 1);
      if (ascending) {  // add an instance of the string with random color, location, font
         font[javaCt] = (int)(fontList.length * Math.random());
         int strlen = fm[font[javaCt]].stringWidth(str);
         int strasc = fm[font[javaCt]].getAscent();
         int minx = -(strlen / 2);
         int miny = strasc / 2;
         int maxx = width + minx;
         int maxy = height + miny;
         x[javaCt] = (int)(minx + Math.random()*(maxx-minx));
         y[javaCt] = (int)(miny + Math.random()*(maxy-miny));
         color[javaCt] = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());
      }
      g.setColor(Color.black);  // start with a black background
      g.fillRect(0,0,width,height);
      for (int i = 0; i<javaCt; i++) {  // draw all the string instances
          g.setFont(fontList[font[i]]);
          g.setColor(color[i]);
          g.drawString(str,x[i],y[i]);
      }
   }

}  // end of applet


text:
import Language.MiniStg.Parser (parseStg)

main = do
        s <- getLine
        let t = parseStg s
        putStrLn . show $ t


text:
package io.restassured.examples.springmvc.controller;

import io.restassured.examples.springmvc.config.MainConfiguration;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MainConfiguration.class)
@WebAppConfiguration
public class WebAppContextWithMockMvcConfigurerITest {
    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Autowired
    private WebApplicationContext context;

    @Test public void
    web_app_context_setup_allows_passing_in_mock_mvc_configurers_using_the_dsl() {
        RestAssuredMockMvc.given().
                webAppContextSetup(context, springSecurity()).
                postProcessors(httpBasic("username", "password")).
                param("name", "Johan").
        when().
                get("/secured/greeting").
        then().
                statusCode(200).
                body("content", equalTo("Hello, Johan!")).
                expect(authenticated().withUsername("username"));
    }

    @Test public void
    web_app_context_setup_allows_passing_in_mock_mvc_configurers_statically() {
        RestAssuredMockMvc.webAppContextSetup(context, springSecurity());

        try {
            RestAssuredMockMvc.given().
                    postProcessors(httpBasic("username", "password")).
                    param("name", "Johan").
            when().
                    get("/secured/greeting").
            then().
                    statusCode(200).
                    body("content", equalTo("Hello, Johan!")).
                    expect(authenticated().withUsername("username"));
        } finally {
            RestAssuredMockMvc.reset();
        }
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Footer, FooterTab, Button, Text } from 'native-base';

export const FooterAction = ({ text, onPress }) => (
  <Footer>
    <FooterTab>
      <Button info onPress={onPress}>
        <Text>{text}</Text>
      </Button>
    </FooterTab>
  </Footer>
);

FooterAction.propTypes = {
  text: PropTypes.string.isRequired,
  onPress: PropTypes.func.isRequired,
}

export default FooterAction;


text:
package eu.dnetlib.iis.common.cache;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import eu.dnetlib.iis.common.FsShellPermissions;
import eu.dnetlib.iis.common.FsShellPermissions.Op;

/**
 * {@link FileSystem} based facade.
 *
 * @author mhorst
 *
 */
public class HadoopFileSystemFacade implements FileSystemFacade {

    private final FileSystem fs;

    // ------------------------------- CONSTRUCTORS ----------------------

    public HadoopFileSystemFacade(FileSystem fs) throws IOException {
        this.fs = fs;
    }

    // ------------------------------- LOGIC -----------------------------

    @Override
    public boolean exists(Path path) throws IOException {
        return fs.exists(path);
    }

    @Override
    public InputStream open(Path f) throws IOException {
        return fs.open(f);
    }

    @Override
    public OutputStream create(Path f, boolean overwrite) throws IOException {
        return fs.create(f, overwrite);
    }

    @Override
    public void changePermissions(Configuration config, Op op, boolean recursive, String group, String uri) {
        FsShellPermissions.changePermissions(this.fs, config, op, recursive, group, uri);

    }

}


text:
package io.pravega.controller.server.health;

import com.google.common.base.Preconditions;
import io.pravega.controller.server.bucket.BucketManager;
import io.pravega.shared.health.Health;
import io.pravega.shared.health.Status;
import io.pravega.shared.health.impl.AbstractHealthContributor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WatermarkingServiceHealthContributor extends AbstractHealthContributor {
    private final BucketManager watermarkingService;

    public WatermarkingServiceHealthContributor(String name, BucketManager watermarkingService) {
        super(name);
        this.watermarkingService = Preconditions.checkNotNull(watermarkingService, "watermarkingService");
    }

    @Override
    public Status doHealthCheck(Health.HealthBuilder builder) throws Exception {
        Status status = Status.DOWN;
        if (watermarkingService.isRunning()) {
            status = Status.NEW;
            if (watermarkingService.isHealthy()) {
                status = Status.UP;
            }
        }
        return status;
    }
}


text:
#ifndef DFGOSRExit_h
#define DFGOSRExit_h

#include <wtf/Platform.h>

#if ENABLE(DFG_JIT)

#include "CodeOrigin.h"
#include "DFGCommon.h"
#include "DFGExitProfile.h"
#include "DFGGPRInfo.h"
#include "DFGValueRecoveryOverride.h"
#include "MacroAssembler.h"
#include "MethodOfGettingAValueProfile.h"
#include "Operands.h"
#include "ValueProfile.h"
#include "ValueRecovery.h"
#include <wtf/Vector.h>

namespace JSC { namespace DFG {

class SpeculativeJIT;

// This enum describes the types of additional recovery that
// may need be performed should a speculation check fail.
enum SpeculationRecoveryType {
    SpeculativeAdd,
    BooleanSpeculationCheck
};

// === SpeculationRecovery ===
//
// This class provides additional information that may be associated with a
// speculation check - for example
class SpeculationRecovery {
public:
    SpeculationRecovery(SpeculationRecoveryType type, GPRReg dest, GPRReg src)
        : m_type(type)
        , m_dest(dest)
        , m_src(src)
    {
    }

    SpeculationRecoveryType type() { return m_type; }
    GPRReg dest() { return m_dest; }
    GPRReg src() { return m_src; }

private:
    // Indicates the type of additional recovery to be performed.
    SpeculationRecoveryType m_type;
    // different recovery types may required different additional information here.
    GPRReg m_dest;
    GPRReg m_src;
};

// === OSRExit ===
//
// This structure describes how to exit the speculative path by
// going into baseline code.
struct OSRExit {
    OSRExit(ExitKind, JSValueSource, MethodOfGettingAValueProfile, SpeculativeJIT*, unsigned streamIndex, unsigned recoveryIndex = 0);

    MacroAssemblerCodeRef m_code;

    JSValueSource m_jsValueSource;
    MethodOfGettingAValueProfile m_valueProfile;

    unsigned m_patchableCodeOffset;
    CodeOrigin m_codeOrigin;
    CodeOrigin m_codeOriginForExitProfile;

    unsigned m_recoveryIndex;
    unsigned m_watchpointIndex;

    ExitKind m_kind;
    uint32_t m_count;

    bool considerAddingAsFrequentExitSite(CodeBlock* profiledCodeBlock)
    {
        if (!m_count || !exitKindIsCountable(m_kind))
            return false;
        return considerAddingAsFrequentExitSiteSlow(profiledCodeBlock);
    }

    void setPatchableCodeOffset(MacroAssembler::PatchableJump);
    MacroAssembler::Jump getPatchableCodeOffsetAsJump() const;
    CodeLocationJump codeLocationForRepatch(CodeBlock*) const;
    void correctJump(LinkBuffer&);

    unsigned m_streamIndex;
    int m_lastSetOperand;

    RefPtr<ValueRecoveryOverride> m_valueRecoveryOverride;

private:
    bool considerAddingAsFrequentExitSiteSlow(CodeBlock* profiledCodeBlock);
};

struct SpeculationFailureDebugInfo {
    CodeBlock* codeBlock;
};

} } // namespace JSC::DFG

#endif // ENABLE(DFG_JIT)

#endif // DFGOSRExit_h


text:
namespace net {

class EpollServer;
class IPEndPoint;

namespace tools {
namespace test {

static const QuicConnectionId kTestConnectionId = 42;
static const int kTestPort = 123;
static const uint32 kInitialStreamFlowControlWindowForTest =
    32 * 1024;  // 32 KB
static const uint32 kInitialSessionFlowControlWindowForTest =
    64 * 1024;  // 64 KB

// Testing convenience method to construct a QuicAckFrame with |num_nack_ranges|
// nack ranges of width 1 packet, starting from |least_unacked|.
QuicAckFrame MakeAckFrameWithNackRanges(size_t num_nack_ranges,
                                        QuicPacketSequenceNumber least_unacked);

class MockConnection : public QuicConnection {
 public:
  // Uses a MockHelper, ConnectionId of 42, and 127.0.0.1:123.
  explicit MockConnection(bool is_server);

  // Uses a MockHelper, ConnectionId of 42.
  MockConnection(IPEndPoint address, bool is_server);

  // Uses a MockHelper, and 127.0.0.1:123
  MockConnection(QuicConnectionId connection_id, bool is_server);

  // Uses a Mock helper, ConnectionId of 42, and 127.0.0.1:123.
  MockConnection(bool is_server, const QuicVersionVector& supported_versions);

  virtual ~MockConnection();

  // If the constructor that uses a MockHelper has been used then this method
  // will advance the time of the MockClock.
  void AdvanceTime(QuicTime::Delta delta);

  MOCK_METHOD3(ProcessUdpPacket, void(const IPEndPoint& self_address,
                                      const IPEndPoint& peer_address,
                                      const QuicEncryptedPacket& packet));
  MOCK_METHOD1(SendConnectionClose, void(QuicErrorCode error));
  MOCK_METHOD2(SendConnectionCloseWithDetails, void(
      QuicErrorCode error,
      const std::string& details));
  MOCK_METHOD2(SendConnectionClosePacket, void(QuicErrorCode error,
                                               const std::string& details));
  MOCK_METHOD3(SendRstStream, void(QuicStreamId id,
                                   QuicRstStreamErrorCode error,
                                   QuicStreamOffset bytes_written));
  MOCK_METHOD3(SendGoAway, void(QuicErrorCode error,
                                QuicStreamId last_good_stream_id,
                                const std::string& reason));
  MOCK_METHOD1(SendBlocked, void(QuicStreamId id));
  MOCK_METHOD2(SendWindowUpdate, void(QuicStreamId id,
                                      QuicStreamOffset byte_offset));
  MOCK_METHOD0(OnCanWrite, void());
  MOCK_CONST_METHOD0(HasPendingWrites, bool());

  void ReallyProcessUdpPacket(const IPEndPoint& self_address,
                              const IPEndPoint& peer_address,
                              const QuicEncryptedPacket& packet) {
    return QuicConnection::ProcessUdpPacket(self_address, peer_address, packet);
  }

  virtual bool OnProtocolVersionMismatch(QuicVersion version) { return false; }

 private:
  scoped_ptr<QuicPacketWriter> writer_;
  scoped_ptr<QuicConnectionHelperInterface> helper_;

  DISALLOW_COPY_AND_ASSIGN(MockConnection);
};

class TestSession : public QuicSession {
 public:
  TestSession(QuicConnection* connection, const QuicConfig& config);
  virtual ~TestSession();

  MOCK_METHOD1(CreateIncomingDataStream, QuicDataStream*(QuicStreamId id));
  MOCK_METHOD0(CreateOutgoingDataStream, QuicDataStream*());

  void SetCryptoStream(QuicCryptoStream* stream);

  virtual QuicCryptoStream* GetCryptoStream() OVERRIDE;

 private:
  QuicCryptoStream* crypto_stream_;

  DISALLOW_COPY_AND_ASSIGN(TestSession);
};

class MockPacketWriter : public QuicPacketWriter {
 public:
  MockPacketWriter();
  virtual ~MockPacketWriter();

  MOCK_METHOD4(WritePacket,
               WriteResult(const char* buffer,
                           size_t buf_len,
                           const IPAddressNumber& self_address,
                           const IPEndPoint& peer_address));
  MOCK_CONST_METHOD0(IsWriteBlockedDataBuffered, bool());
  MOCK_CONST_METHOD0(IsWriteBlocked, bool());
  MOCK_METHOD0(SetWritable, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockPacketWriter);
};

class MockQuicServerSessionVisitor : public QuicServerSessionVisitor {
 public:
  MockQuicServerSessionVisitor();
  virtual ~MockQuicServerSessionVisitor();
  MOCK_METHOD2(OnConnectionClosed, void(QuicConnectionId connection_id,
                                        QuicErrorCode error));
  MOCK_METHOD1(OnWriteBlocked, void(QuicBlockedWriterInterface* writer));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockQuicServerSessionVisitor);
};

class MockAckNotifierDelegate : public QuicAckNotifier::DelegateInterface {
 public:
  MockAckNotifierDelegate();

  MOCK_METHOD5(OnAckNotification, void(int num_original_packets,
                                       int num_original_bytes,
                                       int num_retransmitted_packets,
                                       int num_retransmitted_bytes,
                                       QuicTime::Delta delta_largest_observed));

 protected:
  // Object is ref counted.
  virtual ~MockAckNotifierDelegate();

  DISALLOW_COPY_AND_ASSIGN(MockAckNotifierDelegate);
};

}  // namespace test
}  // namespace tools
}  // namespace net

#endif  // NET_TOOLS_QUIC_TEST_TOOLS_QUIC_TEST_UTILS_H_


text:
package immutableArrayBoard;

import java.util.function.Supplier;

import boardFeatures.Square;
import gamePlaying.Color;
import hashing.Hasher;
import lines.File;
import moves.Move;
import pieces.Piece;
import representation.Board;
import representation.BoardBuilder;
import representation.CastlingRights;
import representation.MoveGenerator;
import representation.MoveMaker;
import static support.Constructors.*;
import static support.UtilityFunctions.*;

/**
 * This is the most intuitive representation of a board. It holds a place for each square (at some index and some bit in the {@code board} array) and
 * the value at that square's place represents a piece. Furthermore, making a move to get to a new position will result in creating a new instance of
 * this class. Whether or not there's a more efficient implementation (such as bitboards), this one is the easiest to work with as a starting point.
 * @author matthewslesinski
 *
 */
public class ImmutableArrayBoard extends Board {

	/** How many bits from the little end the first castling right is, in the int that keeps track of rights */
	private static final int FIRST_CASTLING_RIGHT_BIT = 0;

	/** The index of the int that keeps track of rights */
	private static final int RIGHTS_INDEX = 8;

	/** The number of ints it takes to represent a board */
	private static final int ARRAY_SIZE = 12;

	/** The index of the int that stores the righter bits of the hashcode for this board */
	private static final int HASHCODE_INDEX_1 = 10;

	/** The index of the int that stores the lefter bits of the hashcode for this board */
	private static final int HASHCODE_INDEX_2 = 11;

	/** The number of bits in an int */
	private static final int INT_SIZE = 32;

	/** The index of the int that keeps track of the last move */
	private static final int LAST_MOVE_INDEX = 9;

	/** A bit mask that only has a 1 in the 9th bit. This is the same bit used to keep track of which color is to move */
	private static final int COLOR_MASK = 0x100;

	/** How many bits from the little end the en passant bits start */
	private static final int EN_PASSANT_INDEX = 4;

	/** A mask, meant to be applied to the en passant section of the rights int, that matches the bit that indicates en passant is possibly allowed */
	private static final int EN_PASSANT_PERMISSION_MASK = 0b1000;

	/** The log of the log of the number of pieces that can be represented by bits. */
	private static final int LOG_OF_LOG_OF_NUM_PIECES = 2;

	/** A bit mask that has ones in the same bits as the ones used to represent what en passant is allowed in the rights int*/
	private static final int ONES_IN_EN_PASSANT_BITS = 0b11110000;

	/** A bit mask that is succinctly just four ones */
	private static final int FOUR_ONES = 0b1111;

	/** A bit mask that only has a one in the same bit as the one used to keep track of if the king is in check */
	private static final int CHECK_MASK = 0x10000;

	/** The mask covering only the bits used for the fifty move rule count */
	private static final int FIFTY_MOVE_RULE_MASK = 0xFE00;

	/** The index for the fifty move rule count is kept */
	private static final int FIFTY_MOVE_RULE_INDEX = 9;

	/** Contains 1 in the bits that matter, in the int keeping track of rights, for determining equality between boards */
	private static final int EQUALITY_RIGHTS_MASK = 0b111111111;

	/**
	 * The array containing the pieces and other board information, and so the actual internal representation of this {@code Board}.
	 * The first 8 indices contain ints representing the file with that index. Each of those ints is divided into 8 groups of four bits.
	 * A piece can be encoded in 4 bits. So that's what's stored in each group of 4 bits: the piece stored at that square when indexing into
	 * the file to get the rank. The last index of the array holds the extra information about board state, such as who's to move. This int
	 * says what castling is potentially allowed, using the first four bits, now or in a deeper position from this one. It also uses the second 4 bits
	 * to say what file a pawn could take a pawn from through en passant, it uses the first bit of the next quarter of the int to say whose move it is,
	 * and it uses the next bit to say if it's in check. After the check bit, the next 7 bits are used to store how many plies it has been since an
	 * irreversible change in the board, as used by the 50 move draw rule. Everything except the check bit is calculated by the builder,
	 * but the check is set when calculating moves.
	 */
	private final int[] board;

	/** A reference to the previous board */
	private final Board previousBoard;

	/** Used to construct a move generator */
	private static final Supplier<MoveGenerator<ImmutableArrayBoard>> MOVE_GENERATOR_CONSTRUCTOR = ImmutableArrayMoveGenerator::new;

	private ImmutableArrayBoard(int[] board, Board previousBoard) {
		this.board = board;
		this.previousBoard = previousBoard;
		withCalculatedHash(previousBoard);
	}

	/**
	 * Records hashcode, a long, for this {@code Board}, based on the board preceding this one and the move used to get to this one
	 * @param previousBoardArg The {@code Board} preceding this one. Note the {@code Move} to get to this one is already stored in this board
	 */
	private void withCalculatedHash(Board previousBoardArg) {
		Hasher hasher = Hasher.getGlobalHasher();
		long code = previousBoardArg == null ? hasher.getHash(this) : hasher.getNextHash(previousBoardArg, lastMove());
		board[HASHCODE_INDEX_1] = (int) code;
		board[HASHCODE_INDEX_2] = (int) (code >>> INT_SIZE);
	}

	@Override
	public Piece getPieceAtSquare(Square square) {
		return Piece.getPieceByBits(getBitsAtSquare(square, board));
	}

	@Override
	public Color whoseMove() {
		return Color.getColor((board[RIGHTS_INDEX] & COLOR_MASK) == 0);
	}

	@Override
	public boolean canCastle(CastlingRights right) {
		return ((board[RIGHTS_INDEX] >>> (FIRST_CASTLING_RIGHT_BIT + right.ordinal())) & 1) == 1;
	}

	@Override
	public File enPassantCaptureFile() {
		int relevantInfo = board[RIGHTS_INDEX] >>> EN_PASSANT_INDEX;
		return (relevantInfo & EN_PASSANT_PERMISSION_MASK) != 0 ?
				File.getByIndex(relevantInfo & 0b111) : null;
	}

	@Override
	public int pliesSinceLastIrreversibleChange() {
		return (board[RIGHTS_INDEX] & FIFTY_MOVE_RULE_MASK) >>> FIFTY_MOVE_RULE_INDEX;
	}

	@Override
	public Move lastMove() {
		int compressed = board[LAST_MOVE_INDEX];
		return compressed == 0 ? null : MOVE_DECOMPRESSOR.apply(compressed);
	}

	@Override
	public long getHashCode() {
		return (((long) board[HASHCODE_INDEX_2]) << INT_SIZE) | board[HASHCODE_INDEX_1];
	}

	@Override
	public Board performMove(Move move) {
		MoveMaker<ImmutableArrayBoard> maker = new ImmutableArrayBoardMoveMaker();
		return maker.performMove(move, this);
	}

	@Override
	public Board getPreviousPosition() {
		return previousBoard;
	}

	@Override
	public boolean isInCheck() {
		if (legalMoves == null) {
			calculateMoves();
		}
		return (board[RIGHTS_INDEX] & CHECK_MASK) != 0;
	}

	@Override
	public void calculateMoves() {
		if (legalMoves == null) {
			MoveGenerator<ImmutableArrayBoard> generator = MOVE_GENERATOR_CONSTRUCTOR.get();
			legalMoves = generator.calculateMoves(this);
			setCheck(generator.isInCheck());
		} else {
			// TODO Log unexpected double call to calculateMoves
		}
	}

	@Override
	public int hashCode() {
		return board[HASHCODE_INDEX_1];
	}

	@Override
	public boolean equals(Object o) {
		if (o == null) {
			return false;
		}
		if (o == this) {
			return true;
		}
		if (!(o instanceof ImmutableArrayBoard)) {
			return false;
		}
		ImmutableArrayBoard that = (ImmutableArrayBoard) o;
		for (int index : getPrimitiveRange(0, RIGHTS_INDEX)) {
			if (this.board[index] != that.board[index]) {
				return false;
			}
		}
		return (this.board[RIGHTS_INDEX] & EQUALITY_RIGHTS_MASK) == (that.board[RIGHTS_INDEX] & EQUALITY_RIGHTS_MASK);
	}

	/**
	 * Unlike all the other board information, the bit keeping track of if the board is in check is
	 * set only when moves are calculated, instead of when the board is built. This sets that bit
	 * @param isInCheck The value to be represented in the bit: 1 if true, 0 if false
	 */
	private void setCheck(boolean isInCheck) {
		board[RIGHTS_INDEX] = setBitToBoolean(board[RIGHTS_INDEX], CHECK_MASK, isInCheck);
	}

	public static class Builder extends BoardBuilder<ImmutableArrayBoard> {

		private int[] board;
		private Board previousBoard = null;

		private Builder() {}

		/**
		 * Initializes the board based on another board
		 * @param boardContainer The {@code ImmutableArrayBoard} to base this one off of
		 * @return This builder
		 */
		public static Builder fromBoard(int[] board) {
			Builder builder = new Builder();
			builder.board = board.clone();
			builder.board[RIGHTS_INDEX] = (FOUR_ONES << FIRST_CASTLING_RIGHT_BIT) & board[RIGHTS_INDEX];
			return builder;
		}

		/**
		 * Initializes the board based on another board
		 * @param boardContainer The {@code ImmutableArrayBoard} to base this one off of
		 * @return This builder
		 */
		public static Builder fromBoard(ImmutableArrayBoard boardContainer) {
			return fromBoard(boardContainer.board);
		}

		/**
		 * Initializes the board based on an array of pieces. This does not set any rights except whose move.
		 * @param pieces The array of pieces to put on the board
		 * @param whoToMove Whose current move it is
		 * @return This builder
		 */
		public static Builder fromBoard(Piece[] pieces, Color whoToMove) {
			Builder builder = new Builder();
			builder.board = new int[ARRAY_SIZE];
			BoardBuilder.fromBoard(pieces, whoToMove, builder);
			return builder;
		}

		/**
		 * Produces an {@code ImmutableBoardBuilder} from a FEN string.
		 * @param fen: a FEN string representing the board.
		 * @return This builder
		 */
		public static Builder fromFen(String fen) {
			Builder builder = new Builder();
			builder.board = new int[ARRAY_SIZE];
			BoardBuilder.fromFen(fen, builder);
			return builder;
		}

		@Override
		public Builder withColorToMove(Color color) {
			setRightsByBitMask(COLOR_MASK, !color.isWhite());
			return this;
		}

		@Override
		public Builder withPieceAtSquare(Piece piece, Square square) {
			setPieceAtSquare(piece.getBitRepresentation(), square);
			return this;
		}

		@Override
		public Builder withCastlingRight(CastlingRights castlingRight, boolean enabled) {
			setRightsByBitMask(0x1 << (castlingRight.ordinal() + FIRST_CASTLING_RIGHT_BIT), enabled);
			return this;
		}

		@Override
		public Builder withEnPassant(File file) {
			setRightsByBitMask(file != null ?
					(file.getIndex() | EN_PASSANT_PERMISSION_MASK) << EN_PASSANT_INDEX : ONES_IN_EN_PASSANT_BITS,
					file != null);
			return this;
		}

		@Override
		public Builder withFiftyMoveRuleCount(int count) {
			setRightsByBitMask(FIFTY_MOVE_RULE_MASK & (count << FIFTY_MOVE_RULE_INDEX), true);
			return this;
		}

		@Override
		public Builder withPreviousBoardAndLastMove(Board previousBoardArg, Move move) {
			this.board[LAST_MOVE_INDEX] = move.compress();
			this.previousBoard = previousBoardArg;
			return this;
		}

		@Override
		public ImmutableArrayBoard build() {
			return new ImmutableArrayBoard(board, previousBoard);
		}

		/**
		 * Sets the rights for the board to have a certain value in all the bits set to 1 in a mask
		 * @param mask The mask
		 * @param orBoolean Whether the mask should be ORed, or the reverse of the mask should be ANDed, and in other words,
		 * the value for the bits to set
		 */
		private void setRightsByBitMask(int mask, boolean orBoolean) {
			board[RIGHTS_INDEX] = setBitToBoolean(board[RIGHTS_INDEX], mask, orBoolean);
		}

		/**
		 * Sets a bit representation of a piece at the bit placement for the given square
		 * @param pieceBits The bit representation of the piece
		 * @param square The square the piece is on
		 */
		private void setPieceAtSquare(int pieceBits, Square square) {
			int fileIndex = square.getFile().getIndex();
			// Get the index of the bit to set. The shifting is the same as multiplying by 4
			int indexInBitString = square.getRank().getIndex() << LOG_OF_LOG_OF_NUM_PIECES;
			// Get a mask to use to reset the value in the four bits at the desired index to 0s
			int reset = ~(FOUR_ONES << indexInBitString);
			// Get a mask to use to change the desired bits to the right value
			int change = pieceBits << indexInBitString;
			// Apply the change
			board[fileIndex] = (board[fileIndex] & reset) | change;
		}
	}

	/**
	 * Gets the bit representation of the piece at a square
	 * @param square The square to check
	 * @param board The board containing the piece
	 * @return The bit representation, where 0 is nothing, 1-6 is a white piece, and 7-12 is a black piece
	 */
	private static int getBitsAtSquare(Square square, int[] board) {
		return (board[square.getFile().getIndex()] >>> (square.getRank().getIndex() << LOG_OF_LOG_OF_NUM_PIECES)) & FOUR_ONES;
	}

	/**
	 * Returns a bit string that is the same as the original except all the bits that are set to 1 in the mask are set to {@code value},
	 * where true is the same as 1 and false is the same as 0.
	 *
	 * The way this works is by: if {@code orBoolean} is true, we want to set all the bits that are 1 in mask
	 * to 1 in the board, without touching the others, and if {@code orBoolean} is false, we want to set all the
	 * bits that are 0 in mask to 0 in the board, without touching the others. Therefore, if it's true, we just OR
	 * with the mask, but if it's false, we do the opposite, which is AND with the complement of the mask. In other
	 * words, the mask should have every bit be 0 except for the ones that we want to set, and we will set those bits
	 * to 1 if {@code orBoolean} is true, and to 0 if false.
	 * @param originalBitString The original bit string that the result should be an alteration from
	 * @param mask The mask with 1 only in the bits that should possibly be changed by this alteration
	 * @param value The boolean denoting if the bits to be changed should be set to 1
	 * @return The altered bit string
	 */
	private static int setBitToBoolean(int originalBitString, int mask, boolean value) {
		return value ? originalBitString | mask : (originalBitString & ~mask);
	}
}


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Application
 *
 * @property integer $id
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property integer $u_id
 * @property integer $p_id
 * @property integer $money
 * @property string $duration
 * @property string $content
 * @property boolean $has_portfolio
 * @property string $file_name
 * @property string $origin_name
 * @property string $choice
 * @property-read \App\Project $project
 * @property-read \App\User $user
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereUId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application wherePId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereMoney($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereDuration($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereContent($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereHasPortfolio($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereFileName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereOriginName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Application whereChoice($value)
 * @mixin \Eloquent
 */
class Application extends Model
{
    protected $fillable = [
        'p_id', 'u_id'
    ];

    public function project()
    {
        return $this->belongsTo('App\Project', 'p_id', 'id');
    }
    public function projectStep($step)
    {
        return $this->hasOne('App\Project', 'id', 'p_id')->where('step','=',$step);
    }
    public function projectArray($step)
    {
        $return = "";
            foreach($step as $eachStep){
            $return = $this->hasOne('App\Project', 'id', 'p_id')->orwhere('step','=',$eachStep);
        }
        return $return;
    }

    public function user()
    {
        return $this->belongsTo('App\User', 'u_id', 'id');
    }
}


text: Sample multitier PHP application used for PCF/PWS platform.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2018 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<!-- [START opencensus_pom] -->
<project>
  <modelVersion>4.0.0</modelVersion>
  <packaging>jar</packaging>
  <groupId>com.example</groupId>
  <artifactId>opencensus-samples</artifactId>
  <version>1.0</version>

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <opencensus.version>0.31.1</opencensus.version>
  </properties>

 <!--  Using libraries-bom to manage versions.
  See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>libraries-bom</artifactId>
        <version>26.1.4</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <!-- [START monitoring_opencensus_metrics_dependencies] -->
    <dependency>
      <groupId>io.opencensus</groupId>
      <artifactId>opencensus-api</artifactId>
      <version>${opencensus.version}</version>
    </dependency>
    <dependency>
      <groupId>io.opencensus</groupId>
      <artifactId>opencensus-impl</artifactId>
      <version>${opencensus.version}</version>
    </dependency>
    <dependency>
      <groupId>io.opencensus</groupId>
      <artifactId>opencensus-exporter-stats-stackdriver</artifactId>
      <version>${opencensus.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-core</artifactId>
    </dependency>
    <!-- [END monitoring_opencensus_metrics_dependencies] -->
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>com.example.opencensus.Quickstart</mainClass>
          <cleanupDaemonThreads>false</cleanupDaemonThreads>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
<!-- [END opencensus_pom] -->


text:
namespace ExampleApp
{
    namespace AppCamera
    {
        namespace SdkModel
        {
            class AppCameraSplinePlaybackWrapper : public IAppCamera
            {
            public:
                AppCameraSplinePlaybackWrapper(Eegeo::Camera::SplinePlayback::CameraSplinePlaybackController& splinePlaybackController,
                                               Eegeo::ITouchController& touchController);

                void Update(float dt);

                const Eegeo::Camera::CameraState GetCameraState() const;

                const Eegeo::Camera::RenderCamera GetRenderCamera() const;

                Eegeo::dv3 ComputeNonFlattenedCameraPosition() const;

                Eegeo::ITouchController& GetTouchController() const;

                Eegeo::Camera::SplinePlayback::CameraSplinePlaybackController& GetCameraSplinePlaybackController() const
                {
                    return m_splinePlaybackController;
                }

                float GetHeadingDegrees() const;

            private:
                Eegeo::Camera::SplinePlayback::CameraSplinePlaybackController& m_splinePlaybackController;
                Eegeo::ITouchController& m_touchController;
            };
        }
    }
}