text:
package org.vaadin.appbase.places.testobjects;

import org.vaadin.appbase.places.AbstractPlace;

public class PlaceTestClass extends AbstractPlace
{
  private StringBuilder activePathBuilder;

  public PlaceTestClass (String name)
  {
    this (name, null);
  }

  public PlaceTestClass (String name, StringBuilder activePathBuilder)
  {
    super (name);
    this.activePathBuilder = activePathBuilder;
  }

  @Override
  public void activate ()
  {
    if (activePathBuilder != null)
    {
      activePathBuilder.append (getName ()).append ("/");
    }
  }
}


text:
package org.activiti.engine.impl.db;

import org.activiti.engine.api.internal.Internal;

/**
 * Entities that are using revisions for optimistic locking, need to implement this interface.
 *

 */
@Internal
public interface HasRevision {

  void setRevision(int revision);

  int getRevision();

  int getRevisionNext();

}

redpajama_set_name: RedPajamaGithub


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/protobuf/type.proto

namespace Google\Protobuf;

/**
 * The syntax in which a protocol buffer element is defined.
 *
 * Protobuf enum Google\Protobuf\Syntax
 */
class Syntax
{
    /**
     * Syntax `proto2`.
     *
     * Generated from protobuf enum SYNTAX_PROTO2 = 0;
     */
    const SYNTAX_PROTO2 = 0;
    /**
     * Syntax `proto3`.
     *
     * Generated from protobuf enum SYNTAX_PROTO3 = 1;
     */
    const SYNTAX_PROTO3 = 1;
}


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

#include "bindings/core/v8/ScriptController.h"
#include "core/css/CSSComputedStyleDeclaration.h"
#include "core/css/CSSRuleList.h"
#include "core/css/DOMWindowCSS.h"
#include "core/css/MediaQueryList.h"
#include "core/css/MediaQueryMatcher.h"
#include "core/css/StyleMedia.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/DOMImplementation.h"
#include "core/dom/FrameRequestCallback.h"
#include "core/dom/SandboxFlags.h"
#include "core/editing/Editor.h"
#include "core/events/DOMWindowEventQueue.h"
#include "core/events/HashChangeEvent.h"
#include "core/events/MessageEvent.h"
#include "core/events/PageTransitionEvent.h"
#include "core/events/PopStateEvent.h"
#include "core/frame/BarProp.h"
#include "core/frame/Console.h"
#include "core/frame/EventHandlerRegistry.h"
#include "core/frame/FrameConsole.h"
#include "core/frame/FrameView.h"
#include "core/frame/History.h"
#include "core/frame/Navigator.h"
#include "core/frame/Screen.h"
#include "core/frame/ScrollToOptions.h"
#include "core/frame/Settings.h"
#include "core/frame/SuspendableTimer.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/input/EventHandler.h"
#include "core/inspector/ConsoleMessageStorage.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/loader/SinkDocument.h"
#include "core/loader/appcache/ApplicationCache.h"
#include "core/page/ChromeClient.h"
#include "core/page/CreateWindow.h"
#include "core/page/Page.h"
#include "core/page/WindowFeatures.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
#include "platform/EventDispatchForbiddenScope.h"
#include "public/platform/Platform.h"
#include "public/platform/WebFrameScheduler.h"
#include "public/platform/WebScreenInfo.h"

namespace blink {

LocalDOMWindow::WindowFrameObserver::WindowFrameObserver(LocalDOMWindow* window, LocalFrame& frame)
    : LocalFrameLifecycleObserver(&frame)
    , m_window(window)
{
}

PassOwnPtrWillBeRawPtr<LocalDOMWindow::WindowFrameObserver> LocalDOMWindow::WindowFrameObserver::create(LocalDOMWindow* window, LocalFrame& frame)
{
    return adoptPtrWillBeNoop(new WindowFrameObserver(window, frame));
}

#if !ENABLE(OILPAN)
LocalDOMWindow::WindowFrameObserver::~WindowFrameObserver()
{
}
#endif

DEFINE_TRACE(LocalDOMWindow::WindowFrameObserver)
{
    visitor->trace(m_window);
    LocalFrameLifecycleObserver::trace(visitor);
}

void LocalDOMWindow::WindowFrameObserver::willDetachFrameHost()
{
    m_window->willDetachFrameHost();
}

void LocalDOMWindow::WindowFrameObserver::contextDestroyed()
{
    m_window->frameDestroyed();
    LocalFrameLifecycleObserver::contextDestroyed();
}

class PostMessageTimer final : public NoBaseWillBeGarbageCollectedFinalized<PostMessageTimer>, public SuspendableTimer {
    WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(PostMessageTimer);
public:
    PostMessageTimer(LocalDOMWindow& window, PassRefPtrWillBeRawPtr<MessageEvent> event, PassRefPtrWillBeRawPtr<LocalDOMWindow> source, SecurityOrigin* targetOrigin, PassRefPtrWillBeRawPtr<ScriptCallStack> stackTrace, UserGestureToken* userGestureToken)
        : SuspendableTimer(window.document())
        , m_event(event)
        , m_window(&window)
        , m_targetOrigin(targetOrigin)
        , m_stackTrace(stackTrace)
        , m_userGestureToken(userGestureToken)
        , m_preventDestruction(false)
    {
        m_asyncOperationId = InspectorInstrumentation::traceAsyncOperationStarting(executionContext(), "postMessage");
    }

    PassRefPtrWillBeRawPtr<MessageEvent> event() const { return m_event.get(); }
    SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
    ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
    UserGestureToken* userGestureToken() const { return m_userGestureToken.get(); }
    void stop() override
    {
        SuspendableTimer::stop();

        if (!m_preventDestruction) {
            // Will destroy this object
            m_window->removePostMessageTimer(this);
        }
    }

    // Eager finalization is needed to promptly stop this timer object.
    // (see DOMTimer comment for more.)
    EAGERLY_FINALIZE();
    DEFINE_INLINE_VIRTUAL_TRACE()
    {
        visitor->trace(m_event);
        visitor->trace(m_window);
        visitor->trace(m_stackTrace);
        SuspendableTimer::trace(visitor);
    }

    WebTaskRunner* timerTaskRunner() override
    {
        return m_window->document()->timerTaskRunner();
    }

private:
    void fired() override
    {
        InspectorInstrumentationCookie cookie = InspectorInstrumentation::traceAsyncOperationCompletedCallbackStarting(executionContext(), m_asyncOperationId);
        // Prevent calls to stop triggered from the event handler to
        // kill this object.
        m_preventDestruction = true;
        m_window->postMessageTimerFired(this);
        // Will destroy this object
        m_window->removePostMessageTimer(this);
        InspectorInstrumentation::traceAsyncCallbackCompleted(cookie);
    }

    RefPtrWillBeMember<MessageEvent> m_event;
    RawPtrWillBeMember<LocalDOMWindow> m_window;
    RefPtr<SecurityOrigin> m_targetOrigin;
    RefPtrWillBeMember<ScriptCallStack> m_stackTrace;
    RefPtr<UserGestureToken> m_userGestureToken;
    int m_asyncOperationId;
    bool m_preventDestruction;
};

static void updateSuddenTerminationStatus(LocalDOMWindow* domWindow, bool addedListener, FrameLoaderClient::SuddenTerminationDisablerType disablerType)
{
    Platform::current()->suddenTerminationChanged(!addedListener);
    if (domWindow->frame() && domWindow->frame()->loader().client())
        domWindow->frame()->loader().client()->suddenTerminationDisablerChanged(addedListener, disablerType);
}

using DOMWindowSet = WillBePersistentHeapHashCountedSet<RawPtrWillBeWeakMember<LocalDOMWindow>>;

static DOMWindowSet& windowsWithUnloadEventListeners()
{
    DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
    return windowsWithUnloadEventListeners;
}

static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
{
    DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
    return windowsWithBeforeUnloadEventListeners;
}

static void addUnloadEventListener(LocalDOMWindow* domWindow)
{
    DOMWindowSet& set = windowsWithUnloadEventListeners();
    if (set.isEmpty())
        updateSuddenTerminationStatus(domWindow, true, FrameLoaderClient::UnloadHandler);

    set.add(domWindow);
}

static void removeUnloadEventListener(LocalDOMWindow* domWindow)
{
    DOMWindowSet& set = windowsWithUnloadEventListeners();
    DOMWindowSet::iterator it = set.find(domWindow);
    if (it == set.end())
        return;
    set.remove(it);
    if (set.isEmpty())
        updateSuddenTerminationStatus(domWindow, false, FrameLoaderClient::UnloadHandler);
}

static void removeAllUnloadEventListeners(LocalDOMWindow* domWindow)
{
    DOMWindowSet& set = windowsWithUnloadEventListeners();
    DOMWindowSet::iterator it = set.find(domWindow);
    if (it == set.end())
        return;
    set.removeAll(it);
    if (set.isEmpty())
        updateSuddenTerminationStatus(domWindow, false, FrameLoaderClient::UnloadHandler);
}

static void addBeforeUnloadEventListener(LocalDOMWindow* domWindow)
{
    DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
    if (set.isEmpty())
        updateSuddenTerminationStatus(domWindow, true, FrameLoaderClient::BeforeUnloadHandler);

    set.add(domWindow);
}

static void removeBeforeUnloadEventListener(LocalDOMWindow* domWindow)
{
    DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
    DOMWindowSet::iterator it = set.find(domWindow);
    if (it == set.end())
        return;
    set.remove(it);
    if (set.isEmpty())
        updateSuddenTerminationStatus(domWindow, false, FrameLoaderClient::BeforeUnloadHandler);
}

static void removeAllBeforeUnloadEventListeners(LocalDOMWindow* domWindow)
{
    DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
    DOMWindowSet::iterator it = set.find(domWindow);
    if (it == set.end())
        return;
    set.removeAll(it);
    if (set.isEmpty())
        updateSuddenTerminationStatus(domWindow, false, FrameLoaderClient::BeforeUnloadHandler);
}

static bool allowsBeforeUnloadListeners(LocalDOMWindow* window)
{
    ASSERT_ARG(window, window);
    LocalFrame* frame = window->frame();
    if (!frame)
        return false;
    return frame->isMainFrame();
}

unsigned LocalDOMWindow::pendingUnloadEventListeners() const
{
    return windowsWithUnloadEventListeners().count(const_cast<LocalDOMWindow*>(this));
}

bool LocalDOMWindow::allowPopUp(LocalFrame& firstFrame)
{
    if (UserGestureIndicator::processingUserGesture())
        return true;

    Settings* settings = firstFrame.settings();
    return settings && settings->javaScriptCanOpenWindowsAutomatically();
}

bool LocalDOMWindow::allowPopUp()
{
    return frame() && allowPopUp(*frame());
}

LocalDOMWindow::LocalDOMWindow(LocalFrame& frame)
    : m_frameObserver(WindowFrameObserver::create(this, frame))
    , m_shouldPrintWhenFinishedLoading(false)
#if ENABLE(ASSERT)
    , m_hasBeenReset(false)
#endif
{
#if ENABLE(OILPAN)
    ThreadState::current()->registerPreFinalizer(this);
#endif
}

void LocalDOMWindow::clearDocument()
{
    if (!m_document)
        return;

    ASSERT(!m_document->isActive());

    // FIXME: This should be part of ActiveDOMObject shutdown
    clearEventQueue();

    m_document->clearDOMWindow();
    m_document = nullptr;
}

void LocalDOMWindow::clearEventQueue()
{
    if (!m_eventQueue)
        return;
    m_eventQueue->close();
    m_eventQueue.clear();
}

void LocalDOMWindow::acceptLanguagesChanged()
{
    if (m_navigator)
        m_navigator->setLanguagesChanged();

    dispatchEvent(Event::create(EventTypeNames::languagechange));
}

PassRefPtrWillBeRawPtr<Document> LocalDOMWindow::createDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
{
    RefPtrWillBeRawPtr<Document> document = nullptr;
    if (forceXHTML) {
        // This is a hack for XSLTProcessor. See XSLTProcessor::createDocumentFromSource().
        document = Document::create(init);
    } else {
        document = DOMImplementation::createDocument(mimeType, init, init.frame() ? init.frame()->inViewSourceMode() : false);
        if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
            document = SinkDocument::create(init);
    }

    return document.release();
}

PassRefPtrWillBeRawPtr<Document> LocalDOMWindow::installNewDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
{
    ASSERT(init.frame() == frame());

    clearDocument();

    m_document = createDocument(mimeType, init, forceXHTML);
    m_eventQueue = DOMWindowEventQueue::create(m_document.get());
    m_document->attach();

    if (!frame())
        return m_document;

    frame()->script().updateDocument();
    m_document->updateViewportDescription();

    if (frame()->page() && frame()->view()) {
        if (ScrollingCoordinator* scrollingCoordinator = frame()->page()->scrollingCoordinator()) {
            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(frame()->view(), HorizontalScrollbar);
            scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(frame()->view(), VerticalScrollbar);
            scrollingCoordinator->scrollableAreaScrollLayerDidChange(frame()->view());
        }
    }

    frame()->selection().updateSecureKeyboardEntryIfActive();
    return m_document;
}

EventQueue* LocalDOMWindow::eventQueue() const
{
    return m_eventQueue.get();
}

void LocalDOMWindow::enqueueWindowEvent(PassRefPtrWillBeRawPtr<Event> event)
{
    if (!m_eventQueue)
        return;
    event->setTarget(this);
    m_eventQueue->enqueueEvent(event);
}

void LocalDOMWindow::enqueueDocumentEvent(PassRefPtrWillBeRawPtr<Event> event)
{
    if (!m_eventQueue)
        return;
    event->setTarget(m_document.get());
    m_eventQueue->enqueueEvent(event);
}

void LocalDOMWindow::dispatchWindowLoadEvent()
{
    ASSERT(!EventDispatchForbiddenScope::isEventDispatchForbidden());
    dispatchLoadEvent();
}

void LocalDOMWindow::documentWasClosed()
{
    dispatchWindowLoadEvent();
    enqueuePageshowEvent(PageshowEventNotPersisted);
    if (m_pendingStateObject)
        enqueuePopstateEvent(m_pendingStateObject.release());
}

void LocalDOMWindow::enqueuePageshowEvent(PageshowEventPersistence persisted)
{
    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
    // As per spec pageshow must be triggered asynchronously.
    // However to be compatible with other browsers blink fires pageshow synchronously.
    dispatchEvent(PageTransitionEvent::create(EventTypeNames::pageshow, persisted), m_document.get());
}

void LocalDOMWindow::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
{
    enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
}

void LocalDOMWindow::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
{
    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
    dispatchEvent(PopStateEvent::create(stateObject, history()));
}

void LocalDOMWindow::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
{
    if (!frame())
        return;

    // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
    // defer firing of popstate until we're in the complete state.
    if (document()->isLoadCompleted())
        enqueuePopstateEvent(stateObject);
    else
        m_pendingStateObject = stateObject;
}

LocalDOMWindow::~LocalDOMWindow()
{
#if ENABLE(OILPAN)
    // Cleared when detaching document.
    ASSERT(!m_eventQueue);
#else
    ASSERT(m_hasBeenReset);
    ASSERT(m_document->isStopped());
    clearDocument();
#endif
}

void LocalDOMWindow::dispose()
{
    // Oilpan: should the LocalDOMWindow be GCed along with its LocalFrame without the
    // frame having first notified its observers of imminent destruction, the
    // LocalDOMWindow will not have had an opportunity to remove event listeners.
    //
    // Arrange for that removal to happen using a prefinalizer action. Making LocalDOMWindow
    // eager finalizable is problematic as other eagerly finalized objects may well
    // want to access their associated LocalDOMWindow from their destructors.
    //
    // (Non-Oilpan, LocalDOMWindow::reset() will always be invoked, the last opportunity
    // being via ~LocalFrame's setDOMWindow() call. Asserted for in the destructor.)
    if (!frame())
        return;

    removeAllEventListeners();
}

ExecutionContext* LocalDOMWindow::executionContext() const
{
    return m_document.get();
}

LocalDOMWindow* LocalDOMWindow::toDOMWindow()
{
    return this;
}

PassRefPtrWillBeRawPtr<MediaQueryList> LocalDOMWindow::matchMedia(const String& media)
{
    return document() ? document()->mediaQueryMatcher().matchMedia(media) : nullptr;
}

Page* LocalDOMWindow::page()
{
    return frame() ? frame()->page() : nullptr;
}

void LocalDOMWindow::willDetachFrameHost()
{
    frame()->host()->eventHandlerRegistry().didRemoveAllEventHandlers(*this);
    frame()->host()->consoleMessageStorage().frameWindowDiscarded(this);
    LocalDOMWindow::notifyContextDestroyed();
}

void LocalDOMWindow::frameDestroyed()
{
    willDestroyDocumentInFrame();
    resetLocation();
    m_properties.clear();
    removeAllEventListeners();
}

void LocalDOMWindow::willDestroyDocumentInFrame()
{
    for (const auto& domWindowProperty : m_properties)
        domWindowProperty->willDestroyGlobalObjectInFrame();
}

void LocalDOMWindow::willDetachDocumentFromFrame()
{
    for (const auto& domWindowProperty : m_properties)
        domWindowProperty->willDetachGlobalObjectFromFrame();
}

void LocalDOMWindow::registerProperty(DOMWindowProperty* property)
{
    m_properties.add(property);
}

void LocalDOMWindow::unregisterProperty(DOMWindowProperty* property)
{
    m_properties.remove(property);
}

void LocalDOMWindow::reset()
{
    m_frameObserver->contextDestroyed();

    m_screen = nullptr;
    m_history = nullptr;
    m_locationbar = nullptr;
    m_menubar = nullptr;
    m_personalbar = nullptr;
    m_scrollbars = nullptr;
    m_statusbar = nullptr;
    m_toolbar = nullptr;
    m_console = nullptr;
    m_navigator = nullptr;
    m_media = nullptr;
    m_applicationCache = nullptr;
#if ENABLE(ASSERT)
    m_hasBeenReset = true;
#endif

    LocalDOMWindow::notifyContextDestroyed();
}

void LocalDOMWindow::sendOrientationChangeEvent()
{
    ASSERT(RuntimeEnabledFeatures::orientationEventEnabled());
    ASSERT(frame()->isMainFrame());

    // Before dispatching the event, build a list of all frames in the page
    // to send the event to, to mitigate side effects from event handlers
    // potentially interfering with others.
    WillBeHeapVector<RefPtrWillBeMember<Frame>> frames;
    for (Frame* f = frame(); f; f = f->tree().traverseNext())
        frames.append(f);

    for (size_t i = 0; i < frames.size(); ++i) {
        if (!frames[i]->isLocalFrame())
            continue;
        toLocalFrame(frames[i].get())->localDOMWindow()->dispatchEvent(Event::create(EventTypeNames::orientationchange));
    }
}

int LocalDOMWindow::orientation() const
{
    ASSERT(RuntimeEnabledFeatures::orientationEventEnabled());

    if (!frame() || !frame()->host())
        return 0;

    int orientation = frame()->host()->chromeClient().screenInfo().orientationAngle;
    // For backward compatibility, we want to return a value in the range of
    // [-90; 180] instead of [0; 360[ because window.orientation used to behave
    // like that in WebKit (this is a WebKit proprietary API).
    if (orientation == 270)
        return -90;
    return orientation;
}

Screen* LocalDOMWindow::screen() const
{
    if (!m_screen)
        m_screen = Screen::create(frame());
    return m_screen.get();
}

History* LocalDOMWindow::history() const
{
    if (!m_history)
        m_history = History::create(frame());
    return m_history.get();
}

BarProp* LocalDOMWindow::locationbar() const
{
    if (!m_locationbar)
        m_locationbar = BarProp::create(frame(), BarProp::Locationbar);
    return m_locationbar.get();
}

BarProp* LocalDOMWindow::menubar() const
{
    if (!m_menubar)
        m_menubar = BarProp::create(frame(), BarProp::Menubar);
    return m_menubar.get();
}

BarProp* LocalDOMWindow::personalbar() const
{
    if (!m_personalbar)
        m_personalbar = BarProp::create(frame(), BarProp::Personalbar);
    return m_personalbar.get();
}

BarProp* LocalDOMWindow::scrollbars() const
{
    if (!m_scrollbars)
        m_scrollbars = BarProp::create(frame(), BarProp::Scrollbars);
    return m_scrollbars.get();
}

BarProp* LocalDOMWindow::statusbar() const
{
    if (!m_statusbar)
        m_statusbar = BarProp::create(frame(), BarProp::Statusbar);
    return m_statusbar.get();
}

BarProp* LocalDOMWindow::toolbar() const
{
    if (!m_toolbar)
        m_toolbar = BarProp::create(frame(), BarProp::Toolbar);
    return m_toolbar.get();
}

Console* LocalDOMWindow::console() const
{
    if (!m_console)
        m_console = Console::create(frame());
    return m_console.get();
}

FrameConsole* LocalDOMWindow::frameConsole() const
{
    if (!isCurrentlyDisplayedInFrame())
        return nullptr;
    return &frame()->console();
}

ApplicationCache* LocalDOMWindow::applicationCache() const
{
    if (!isCurrentlyDisplayedInFrame())
        return nullptr;
    if (!m_applicationCache)
        m_applicationCache = ApplicationCache::create(frame());
    return m_applicationCache.get();
}

Navigator* LocalDOMWindow::navigator() const
{
    if (!m_navigator)
        m_navigator = Navigator::create(frame());
    return m_navigator.get();
}

void LocalDOMWindow::schedulePostMessage(PassRefPtrWillBeRawPtr<MessageEvent> event, LocalDOMWindow* source, SecurityOrigin* target, PassRefPtrWillBeRawPtr<ScriptCallStack> stackTrace)
{
    // Schedule the message.
    OwnPtrWillBeRawPtr<PostMessageTimer> timer = adoptPtrWillBeNoop(new PostMessageTimer(*this, event, source, target, stackTrace, UserGestureIndicator::currentToken()));
    timer->startOneShot(0, BLINK_FROM_HERE);
    timer->suspendIfNeeded();
    m_postMessageTimers.add(timer.release());
}

void LocalDOMWindow::postMessageTimerFired(PostMessageTimer* timer)
{
    if (!isCurrentlyDisplayedInFrame()) {
        return;
    }

    RefPtrWillBeRawPtr<MessageEvent> event = timer->event();

    UserGestureIndicator gestureIndicator(timer->userGestureToken());

    event->entangleMessagePorts(document());
    dispatchMessageEventWithOriginCheck(timer->targetOrigin(), event, timer->stackTrace());
}

void LocalDOMWindow::removePostMessageTimer(PostMessageTimer* timer)
{
    m_postMessageTimers.remove(timer);
}

void LocalDOMWindow::dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtrWillBeRawPtr<Event> event, PassRefPtrWillBeRawPtr<ScriptCallStack> stackTrace)
{
    if (intendedTargetOrigin) {
        // Check target origin now since the target document may have changed since the timer was scheduled.
        if (!intendedTargetOrigin->isSameSchemeHostPortAndSuborigin(document()->securityOrigin())) {
            String message = ExceptionMessages::failedToExecute("postMessage", "DOMWindow", "The target origin provided ('" + intendedTargetOrigin->toString() + "') does not match the recipient window's origin ('" + document()->securityOrigin()->toString() + "').");
            RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message);
            consoleMessage->setCallStack(stackTrace);
            frameConsole()->addMessage(consoleMessage.release());
            return;
        }
    }

    dispatchEvent(event);
}

DOMSelection* LocalDOMWindow::getSelection()
{
    if (!isCurrentlyDisplayedInFrame())
        return nullptr;

    return frame()->document()->getSelection();
}

Element* LocalDOMWindow::frameElement() const
{
    if (!frame())
        return nullptr;

    // The bindings security check should ensure we're same origin...
    return toHTMLFrameOwnerElement(frame()->owner());
}

void LocalDOMWindow::focus(ExecutionContext* context)
{
    if (!frame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    ASSERT(context);

    bool allowFocus = context->isWindowInteractionAllowed();
    if (allowFocus) {
        context->consumeWindowInteraction();
    } else {
        ASSERT(isMainThread());
        allowFocus = opener() && (opener() != this) && (toDocument(context)->domWindow() == opener());
    }

    // If we're a top level window, bring the window to the front.
    if (frame()->isMainFrame() && allowFocus)
        host->chromeClient().focus();

    frame()->eventHandler().focusDocumentView();
}

void LocalDOMWindow::blur()
{
}

void LocalDOMWindow::print()
{
    if (!frame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    if (frame()->document()->isSandboxed(SandboxModals)) {
        UseCounter::count(frame()->document(), UseCounter::DialogInSandboxedContext);
        if (RuntimeEnabledFeatures::sandboxBlocksModalsEnabled()) {
            frameConsole()->addMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Ignored call to 'print()'. The document is sandboxed, and the 'allow-modals' keyword is not set."));
            return;
        }
    }

    if (frame()->isLoading()) {
        m_shouldPrintWhenFinishedLoading = true;
        return;
    }
    m_shouldPrintWhenFinishedLoading = false;
    host->chromeClient().print(frame());
}

void LocalDOMWindow::stop()
{
    if (!frame())
        return;
    frame()->loader().stopAllLoaders();
}

void LocalDOMWindow::alert(const String& message)
{
    if (!frame())
        return;

    if (frame()->document()->isSandboxed(SandboxModals)) {
        UseCounter::count(frame()->document(), UseCounter::DialogInSandboxedContext);
        if (RuntimeEnabledFeatures::sandboxBlocksModalsEnabled()) {
            frameConsole()->addMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set."));
            return;
        }
    }

    frame()->document()->updateLayoutTreeIfNeeded();

    FrameHost* host = frame()->host();
    if (!host)
        return;

    host->chromeClient().openJavaScriptAlert(frame(), message);
}

bool LocalDOMWindow::confirm(const String& message)
{
    if (!frame())
        return false;

    if (frame()->document()->isSandboxed(SandboxModals)) {
        UseCounter::count(frame()->document(), UseCounter::DialogInSandboxedContext);
        if (RuntimeEnabledFeatures::sandboxBlocksModalsEnabled()) {
            frameConsole()->addMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Ignored call to 'confirm()'. The document is sandboxed, and the 'allow-modals' keyword is not set."));
            return false;
        }
    }

    frame()->document()->updateLayoutTreeIfNeeded();

    FrameHost* host = frame()->host();
    if (!host)
        return false;

    return host->chromeClient().openJavaScriptConfirm(frame(), message);
}

String LocalDOMWindow::prompt(const String& message, const String& defaultValue)
{
    if (!frame())
        return String();

    if (frame()->document()->isSandboxed(SandboxModals)) {
        UseCounter::count(frame()->document(), UseCounter::DialogInSandboxedContext);
        if (RuntimeEnabledFeatures::sandboxBlocksModalsEnabled()) {
            frameConsole()->addMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Ignored call to 'prompt()'. The document is sandboxed, and the 'allow-modals' keyword is not set."));
            return String();
        }
    }

    frame()->document()->updateLayoutTreeIfNeeded();

    FrameHost* host = frame()->host();
    if (!host)
        return String();

    String returnValue;
    if (host->chromeClient().openJavaScriptPrompt(frame(), message, defaultValue, returnValue))
        return returnValue;

    return String();
}

bool LocalDOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool wholeWord, bool /*searchInFrames*/, bool /*showDialog*/) const
{
    if (!isCurrentlyDisplayedInFrame())
        return false;

    // |frame()| can be destructed during |Editor::findString()| via
    // |Document::updateLayout()|, e.g. event handler removes a frame.
    RefPtrWillBeRawPtr<LocalFrame> protectFrame(frame());

    // FIXME (13016): Support searchInFrames and showDialog
    FindOptions options = (backwards ? Backwards : 0) | (caseSensitive ? 0 : CaseInsensitive) | (wrap ? WrapAround : 0) | (wholeWord ? WholeWord | AtWordStarts : 0);
    return frame()->editor().findString(string, options);
}

bool LocalDOMWindow::offscreenBuffering() const
{
    return true;
}

int LocalDOMWindow::outerHeight() const
{
    if (!frame())
        return 0;

    FrameHost* host = frame()->host();
    if (!host)
        return 0;

    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
        return lroundf(host->chromeClient().windowRect().height() * host->deviceScaleFactor());
    return host->chromeClient().windowRect().height();
}

int LocalDOMWindow::outerWidth() const
{
    if (!frame())
        return 0;

    FrameHost* host = frame()->host();
    if (!host)
        return 0;

    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
        return lroundf(host->chromeClient().windowRect().width() * host->deviceScaleFactor());
    return host->chromeClient().windowRect().width();
}

static FloatSize getViewportSize(LocalFrame* frame)
{
    FrameView* view = frame->view();
    if (!view)
        return FloatSize();

    FrameHost* host = frame->host();
    if (!host)
        return FloatSize();

    // The main frame's viewport size depends on the page scale. Since the
    // initial page scale depends on the content width and is set after a
    // layout, perform one now so queries during page load will use the up to
    // date viewport.
    if (host->settings().viewportEnabled() && frame->isMainFrame())
        frame->document()->updateLayoutIgnorePendingStylesheets();

    // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's layoutObject.
    if (Frame* parent = frame->tree().parent()) {
        if (parent && parent->isLocalFrame())
            toLocalFrame(parent)->document()->updateLayoutIgnorePendingStylesheets();
    }

    return frame->isMainFrame() && !host->settings().inertVisualViewport()
        ? host->visualViewport().visibleRect().size()
        : view->visibleContentRect(IncludeScrollbars).size();
}

int LocalDOMWindow::innerHeight() const
{
    if (!frame())
        return 0;

    FloatSize viewportSize = getViewportSize(frame());
    return adjustForAbsoluteZoom(expandedIntSize(viewportSize).height(), frame()->pageZoomFactor());
}

int LocalDOMWindow::innerWidth() const
{
    if (!frame())
        return 0;

    FloatSize viewportSize = getViewportSize(frame());
    return adjustForAbsoluteZoom(expandedIntSize(viewportSize).width(), frame()->pageZoomFactor());
}

int LocalDOMWindow::screenX() const
{
    if (!frame())
        return 0;

    FrameHost* host = frame()->host();
    if (!host)
        return 0;

    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
        return lroundf(host->chromeClient().windowRect().x() * host->deviceScaleFactor());
    return host->chromeClient().windowRect().x();
}

int LocalDOMWindow::screenY() const
{
    if (!frame())
        return 0;

    FrameHost* host = frame()->host();
    if (!host)
        return 0;

    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
        return lroundf(host->chromeClient().windowRect().y() * host->deviceScaleFactor());
    return host->chromeClient().windowRect().y();
}

double LocalDOMWindow::scrollX() const
{
    if (!frame())
        return 0;

    FrameView* view = frame()->view();
    if (!view)
        return 0;

    FrameHost* host = frame()->host();
    if (!host)
        return 0;

    frame()->document()->updateLayoutIgnorePendingStylesheets();

    ScrollableArea* viewport = host->settings().inertVisualViewport() ? view->layoutViewportScrollableArea() : view->scrollableArea();
    double viewportX = viewport->scrollPositionDouble().x();
    return adjustScrollForAbsoluteZoom(viewportX, frame()->pageZoomFactor());
}

double LocalDOMWindow::scrollY() const
{
    if (!frame())
        return 0;

    FrameView* view = frame()->view();
    if (!view)
        return 0;

    FrameHost* host = frame()->host();
    if (!host)
        return 0;

    frame()->document()->updateLayoutIgnorePendingStylesheets();

    ScrollableArea* viewport = host->settings().inertVisualViewport() ? view->layoutViewportScrollableArea() : view->scrollableArea();
    double viewportY = viewport->scrollPositionDouble().y();
    return adjustScrollForAbsoluteZoom(viewportY, frame()->pageZoomFactor());
}

const AtomicString& LocalDOMWindow::name() const
{
    if (!isCurrentlyDisplayedInFrame())
        return nullAtom;

    return frame()->tree().name();
}

void LocalDOMWindow::setName(const AtomicString& name)
{
    if (!isCurrentlyDisplayedInFrame())
        return;

    frame()->tree().setName(name);
    ASSERT(frame()->loader().client());
    frame()->loader().client()->didChangeName(name);
}

void LocalDOMWindow::setStatus(const String& string)
{
    m_status = string;

    if (!frame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    ASSERT(frame()->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
    host->chromeClient().setStatusbarText(m_status);
}

void LocalDOMWindow::setDefaultStatus(const String& string)
{
    m_defaultStatus = string;

    if (!frame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    ASSERT(frame()->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
    host->chromeClient().setStatusbarText(m_defaultStatus);
}

Document* LocalDOMWindow::document() const
{
    return m_document.get();
}

StyleMedia* LocalDOMWindow::styleMedia() const
{
    if (!m_media)
        m_media = StyleMedia::create(frame());
    return m_media.get();
}

PassRefPtrWillBeRawPtr<CSSStyleDeclaration> LocalDOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
{
    ASSERT(elt);
    return CSSComputedStyleDeclaration::create(elt, false, pseudoElt);
}

PassRefPtrWillBeRawPtr<CSSRuleList> LocalDOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement) const
{
    if (!element)
        return nullptr;

    if (!isCurrentlyDisplayedInFrame())
        return nullptr;

    unsigned colonStart = pseudoElement[0] == ':' ? (pseudoElement[1] == ':' ? 2 : 1) : 0;
    CSSSelector::PseudoType pseudoType = CSSSelector::parsePseudoType(AtomicString(pseudoElement.substring(colonStart)), false);
    if (pseudoType == CSSSelector::PseudoUnknown && !pseudoElement.isEmpty())
        return nullptr;

    unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
    PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
    element->document().updateLayoutTreeIfNeeded();
    return frame()->document()->ensureStyleResolver().pseudoCSSRulesForElement(element, pseudoId, rulesToInclude);
}

double LocalDOMWindow::devicePixelRatio() const
{
    if (!frame())
        return 0.0;

    return frame()->devicePixelRatio();
}

void LocalDOMWindow::scrollBy(double x, double y, ScrollBehavior scrollBehavior) const
{
    if (!isCurrentlyDisplayedInFrame())
        return;

    document()->updateLayoutIgnorePendingStylesheets();

    FrameView* view = frame()->view();
    if (!view)
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    x = ScrollableArea::normalizeNonFiniteScroll(x);
    y = ScrollableArea::normalizeNonFiniteScroll(y);

    ScrollableArea* viewport = host->settings().inertVisualViewport() ? view->layoutViewportScrollableArea() : view->scrollableArea();

    DoublePoint currentOffset = viewport->scrollPositionDouble();
    DoubleSize scaledDelta(x * frame()->pageZoomFactor(), y * frame()->pageZoomFactor());

    viewport->setScrollPosition(currentOffset + scaledDelta, ProgrammaticScroll, scrollBehavior);
}

void LocalDOMWindow::scrollBy(const ScrollToOptions& scrollToOptions) const
{
    double x = 0.0;
    double y = 0.0;
    if (scrollToOptions.hasLeft())
        x = scrollToOptions.left();
    if (scrollToOptions.hasTop())
        y = scrollToOptions.top();
    ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
    ScrollableArea::scrollBehaviorFromString(scrollToOptions.behavior(), scrollBehavior);
    scrollBy(x, y, scrollBehavior);
}

void LocalDOMWindow::scrollTo(double x, double y) const
{
    if (!isCurrentlyDisplayedInFrame())
        return;

    FrameView* view = frame()->view();
    if (!view)
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    x = ScrollableArea::normalizeNonFiniteScroll(x);
    y = ScrollableArea::normalizeNonFiniteScroll(y);

    // It is only necessary to have an up-to-date layout if the position may be clamped,
    // which is never the case for (0, 0).
    if (x || y)
        document()->updateLayoutIgnorePendingStylesheets();

    DoublePoint layoutPos(x * frame()->pageZoomFactor(), y * frame()->pageZoomFactor());
    ScrollableArea* viewport = host->settings().inertVisualViewport() ? view->layoutViewportScrollableArea() : view->scrollableArea();
    viewport->setScrollPosition(layoutPos, ProgrammaticScroll, ScrollBehaviorAuto);
}

void LocalDOMWindow::scrollTo(const ScrollToOptions& scrollToOptions) const
{
    if (!isCurrentlyDisplayedInFrame())
        return;

    FrameView* view = frame()->view();
    if (!view)
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    // It is only necessary to have an up-to-date layout if the position may be clamped,
    // which is never the case for (0, 0).
    if (!scrollToOptions.hasLeft()
        || !scrollToOptions.hasTop()
        || scrollToOptions.left()
        || scrollToOptions.top()) {
        document()->updateLayoutIgnorePendingStylesheets();
    }

    double scaledX = 0.0;
    double scaledY = 0.0;

    ScrollableArea* viewport = host->settings().inertVisualViewport() ? view->layoutViewportScrollableArea() : view->scrollableArea();

    DoublePoint currentOffset = viewport->scrollPositionDouble();
    scaledX = currentOffset.x();
    scaledY = currentOffset.y();

    if (scrollToOptions.hasLeft())
        scaledX = ScrollableArea::normalizeNonFiniteScroll(scrollToOptions.left()) * frame()->pageZoomFactor();

    if (scrollToOptions.hasTop())
        scaledY = ScrollableArea::normalizeNonFiniteScroll(scrollToOptions.top()) * frame()->pageZoomFactor();

    ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
    ScrollableArea::scrollBehaviorFromString(scrollToOptions.behavior(), scrollBehavior);

    viewport->setScrollPosition(DoublePoint(scaledX, scaledY), ProgrammaticScroll, scrollBehavior);
}

void LocalDOMWindow::moveBy(int x, int y) const
{
    if (!frame() || !frame()->isMainFrame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    IntRect windowRect = host->chromeClient().windowRect();
    windowRect.move(x, y);
    // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
    host->chromeClient().setWindowRectWithAdjustment(windowRect);
}

void LocalDOMWindow::moveTo(int x, int y) const
{
    if (!frame() || !frame()->isMainFrame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    IntRect windowRect = host->chromeClient().windowRect();
    windowRect.setLocation(IntPoint(x, y));
    // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
    host->chromeClient().setWindowRectWithAdjustment(windowRect);
}

void LocalDOMWindow::resizeBy(int x, int y) const
{
    if (!frame() || !frame()->isMainFrame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    IntRect fr = host->chromeClient().windowRect();
    IntSize dest = fr.size() + IntSize(x, y);
    IntRect update(fr.location(), dest);
    host->chromeClient().setWindowRectWithAdjustment(update);
}

void LocalDOMWindow::resizeTo(int width, int height) const
{
    if (!frame() || !frame()->isMainFrame())
        return;

    FrameHost* host = frame()->host();
    if (!host)
        return;

    IntRect fr = host->chromeClient().windowRect();
    IntSize dest = IntSize(width, height);
    IntRect update(fr.location(), dest);
    host->chromeClient().setWindowRectWithAdjustment(update);
}

int LocalDOMWindow::requestAnimationFrame(FrameRequestCallback* callback)
{
    callback->m_useLegacyTimeBase = false;
    if (Document* doc = document())
        return doc->requestAnimationFrame(callback);
    return 0;
}

int LocalDOMWindow::webkitRequestAnimationFrame(FrameRequestCallback* callback)
{
    callback->m_useLegacyTimeBase = true;
    if (Document* document = this->document())
        return document->requestAnimationFrame(callback);
    return 0;
}

void LocalDOMWindow::cancelAnimationFrame(int id)
{
    if (Document* document = this->document())
        document->cancelAnimationFrame(id);
}

int LocalDOMWindow::requestIdleCallback(IdleRequestCallback* callback, const IdleRequestOptions& options)
{
    if (Document* document = this->document())
        return document->requestIdleCallback(callback, options);
    return 0;
}

void LocalDOMWindow::cancelIdleCallback(int id)
{
    if (Document* document = this->document())
        document->cancelIdleCallback(id);
}

bool LocalDOMWindow::addEventListenerInternal(const AtomicString& eventType, PassRefPtrWillBeRawPtr<EventListener> prpListener, const EventListenerOptions& options)
{
    RefPtrWillBeRawPtr<EventListener> listener = prpListener;
    if (!EventTarget::addEventListenerInternal(eventType, listener, options))
        return false;

    if (frame() && frame()->host())
        frame()->host()->eventHandlerRegistry().didAddEventHandler(*this, eventType);

    if (Document* document = this->document()) {
        document->addListenerTypeIfNeeded(eventType);
    }

    notifyAddEventListener(this, eventType);

    if (eventType == EventTypeNames::unload) {
        UseCounter::count(document(), UseCounter::DocumentUnloadRegistered);
        addUnloadEventListener(this);
    } else if (eventType == EventTypeNames::beforeunload) {
        UseCounter::count(document(), UseCounter::DocumentBeforeUnloadRegistered);
        if (allowsBeforeUnloadListeners(this)) {
            // This is confusingly named. It doesn't actually add the listener. It just increments a count
            // so that we know we have listeners registered for the purposes of determining if we can
            // fast terminate the renderer process.
            addBeforeUnloadEventListener(this);
        } else {
            // Subframes return false from allowsBeforeUnloadListeners.
            UseCounter::count(document(), UseCounter::SubFrameBeforeUnloadRegistered);
        }
    }

    return true;
}

bool LocalDOMWindow::removeEventListenerInternal(const AtomicString& eventType, PassRefPtrWillBeRawPtr<EventListener> listener, const EventListenerOptions& options)
{
    if (!EventTarget::removeEventListenerInternal(eventType, listener, options))
        return false;

    if (frame() && frame()->host())
        frame()->host()->eventHandlerRegistry().didRemoveEventHandler(*this, eventType);

    notifyRemoveEventListener(this, eventType);

    if (eventType == EventTypeNames::unload) {
        removeUnloadEventListener(this);
    } else if (eventType == EventTypeNames::beforeunload && allowsBeforeUnloadListeners(this)) {
        removeBeforeUnloadEventListener(this);
    }

    return true;
}

void LocalDOMWindow::dispatchLoadEvent()
{
    RefPtrWillBeRawPtr<Event> loadEvent(Event::create(EventTypeNames::load));
    if (frame() && frame()->loader().documentLoader() && !frame()->loader().documentLoader()->timing().loadEventStart()) {
        // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
        // the event, so protect it to prevent writing the end time into freed memory.
        RefPtrWillBeRawPtr<DocumentLoader> documentLoader = frame()->loader().documentLoader();
        DocumentLoadTiming& timing = documentLoader->timing();
        timing.markLoadEventStart();
        dispatchEvent(loadEvent, document());
        timing.markLoadEventEnd();
    } else {
        dispatchEvent(loadEvent, document());
    }

    // For load events, send a separate load event to the enclosing frame only.
    // This is a DOM extension and is independent of bubbling/capturing rules of
    // the DOM.
    FrameOwner* owner = frame() ? frame()->owner() : nullptr;
    if (owner)
        owner->dispatchLoad();

    TRACE_EVENT_INSTANT1("devtools.timeline", "MarkLoad", TRACE_EVENT_SCOPE_THREAD, "data", InspectorMarkLoadEvent::data(frame()));
    InspectorInstrumentation::loadEventFired(frame());
}

bool LocalDOMWindow::dispatchEvent(PassRefPtrWillBeRawPtr<Event> prpEvent, PassRefPtrWillBeRawPtr<EventTarget> prpTarget)
{
    ASSERT(!EventDispatchForbiddenScope::isEventDispatchForbidden());

    RefPtrWillBeRawPtr<EventTarget> protect(this);
    RefPtrWillBeRawPtr<Event> event = prpEvent;

    event->setTrusted(true);
    event->setTarget(prpTarget ? prpTarget : this);
    event->setCurrentTarget(this);
    event->setEventPhase(Event::AT_TARGET);

    TRACE_EVENT1("devtools.timeline", "EventDispatch", "data", InspectorEventDispatchEvent::data(*event));
    return fireEventListeners(event.get());
}

void LocalDOMWindow::removeAllEventListeners()
{
    EventTarget::removeAllEventListeners();

    notifyRemoveAllEventListeners(this);
    if (frame() && frame()->host())
        frame()->host()->eventHandlerRegistry().didRemoveAllEventHandlers(*this);

    removeAllUnloadEventListeners(this);
    removeAllBeforeUnloadEventListeners(this);
}

void LocalDOMWindow::finishedLoading()
{
    if (m_shouldPrintWhenFinishedLoading) {
        m_shouldPrintWhenFinishedLoading = false;
        print();
    }
}

void LocalDOMWindow::printErrorMessage(const String& message)
{
    if (!isCurrentlyDisplayedInFrame())
        return;

    if (message.isEmpty())
        return;

    frameConsole()->addMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
}

PassRefPtrWillBeRawPtr<DOMWindow> LocalDOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
    LocalDOMWindow* callingWindow, LocalDOMWindow* enteredWindow)
{
    if (!isCurrentlyDisplayedInFrame())
        return nullptr;
    Document* activeDocument = callingWindow->document();
    if (!activeDocument)
        return nullptr;
    LocalFrame* firstFrame = enteredWindow->frame();
    if (!firstFrame)
        return nullptr;

    UseCounter::count(*activeDocument, UseCounter::DOMWindowOpen);
    if (!windowFeaturesString.isEmpty())
        UseCounter::count(*activeDocument, UseCounter::DOMWindowOpenFeatures);

    if (!enteredWindow->allowPopUp()) {
        // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
        // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
        if (frameName.isEmpty() || !frame()->tree().find(frameName))
            return nullptr;
    }

    // Get the target frame for the special cases of _top and _parent.
    // In those cases, we schedule a location change right now and return early.
    Frame* targetFrame = nullptr;
    if (frameName == "_top") {
        targetFrame = frame()->tree().top();
    } else if (frameName == "_parent") {
        if (Frame* parent = frame()->tree().parent())
            targetFrame = parent;
        else
            targetFrame = frame();
    }

    if (targetFrame) {
        if (!activeDocument->frame() || !activeDocument->frame()->canNavigate(*targetFrame))
            return nullptr;

        KURL completedURL = firstFrame->document()->completeURL(urlString);

        if (targetFrame->domWindow()->isInsecureScriptAccess(*callingWindow, completedURL))
            return targetFrame->domWindow();

        if (urlString.isEmpty())
            return targetFrame->domWindow();

        targetFrame->navigate(*activeDocument, completedURL, false, UserGestureStatus::None);
        return targetFrame->domWindow();
    }

    return createWindow(urlString, frameName, WindowFeatures(windowFeaturesString), *callingWindow, *firstFrame, *frame());
}

DEFINE_TRACE(LocalDOMWindow)
{
#if ENABLE(OILPAN)
    visitor->trace(m_frameObserver);
    visitor->trace(m_document);
    visitor->trace(m_properties);
    visitor->trace(m_screen);
    visitor->trace(m_history);
    visitor->trace(m_locationbar);
    visitor->trace(m_menubar);
    visitor->trace(m_personalbar);
    visitor->trace(m_scrollbars);
    visitor->trace(m_statusbar);
    visitor->trace(m_toolbar);
    visitor->trace(m_console);
    visitor->trace(m_navigator);
    visitor->trace(m_media);
    visitor->trace(m_applicationCache);
    visitor->trace(m_eventQueue);
    visitor->trace(m_postMessageTimers);
    HeapSupplementable<LocalDOMWindow>::trace(visitor);
#endif
    DOMWindow::trace(visitor);
    DOMWindowLifecycleNotifier::trace(visitor);
}

LocalFrame* LocalDOMWindow::frame() const
{
    // If the LocalDOMWindow still has a frame reference, that frame must point
    // back to this LocalDOMWindow: otherwise, it's easy to get into a situation
    // where script execution leaks between different LocalDOMWindows.
    if (m_frameObserver->frame())
        ASSERT_WITH_SECURITY_IMPLICATION(m_frameObserver->frame()->domWindow() == this);
    return m_frameObserver->frame();
}

} // namespace blink


text:
Public Class Brush

    Dim Secondes
    Dim Minutes
    Dim Closeit
    Dim NewPoint As New System.Drawing.Point
    Dim X, Y As Integer
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Panel1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseDown
        X = Control.MousePosition.X - Me.Location.X
        Y = Control.MousePosition.Y - Me.Location.Y
    End Sub

    Private Sub Panel1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseMove
        If e.Button = MouseButtons.Left Then
            NewPoint = Control.MousePosition
            NewPoint.Y -= (Y)
            NewPoint.X -= (X)
            Me.Location = NewPoint
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Timer1.Start()
        Timer3.Start()
        Button1.Hide()
        PictureBox1.Hide()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Secondes = Secondes + 1
        Minutes = 180 - Secondes
        Label1.Text = Minutes & " secondes restantes"
        If Secondes = 180 Then
            Label1.Hide()
            Label2.Text = "Tu as gagné(e) !"
            Timer1.Stop()
            Timer2.Start()
        End If
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        Closeit = Closeit + 1
        Timer3.Stop()
        If Closeit = 30 Then
            Aether.Show()
            Me.Close()
        End If
    End Sub

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
        Aether.Show()
        Me.Hide()
    End Sub

    Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
        If Minutes = "0" Then
            Dim ep = CreateObject("sapi.spvoice")
            ep.speak("Fini")
        End If
    End Sub
End Class


text:
package ru.emil.MassiveJurnal;

public class Main {
    public static void main(String[] args) {
        Start.start();
    }
}


text:
package com.cattong.sns.impl.facebook;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cattong.commons.LibException;
import com.cattong.commons.LibResultCode;
import com.cattong.commons.util.ParseUtil;
import com.cattong.commons.util.StringUtil;
import com.cattong.sns.entity.Status;

public class FacebookStatusAdapter {

	public static Status createStatus(String jsonString) throws LibException {
		try {
			JSONObject json = new JSONObject(jsonString);
			return createStatus(json);
		} catch (JSONException e) {
			throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
		}
	}

	public static List<Status> createStatusList(String jsonString)
			throws LibException {
		try {
			if (StringUtil.isEquals("{}", jsonString)
					|| StringUtil.isEquals("[]", jsonString)) {
				return new ArrayList<Status>(0);
			}
			JSONArray jsonArray = new JSONArray(jsonString);
			int length = jsonArray.length();
			List<Status> statuses = new ArrayList<Status>(length);
			for (int i = 0; i < length; i++) {
				statuses.add(createStatus(jsonArray.getJSONObject(i)));
			}
			return statuses;
		} catch (JSONException e) {
			throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
		}
	}

	public static Status createStatus(JSONObject json) throws LibException {
		if (json == null) {
			return null;
		}
		try {
			Status status = new Status();
			status.setId(ParseUtil.getRawString("id", json));
			status.setText(ParseUtil.getRawString("message", json));
			status.setUpdatedTime(ParseUtil.getDate("update_time", json, Facebook.DATE_FORMAT));
			if (json.has("comments")) {
				status.setCommentsCount(json.getJSONObject("comments").getJSONArray("data").length());
			}
			return status;
		} catch (ParseException e) {
			throw new LibException(LibResultCode.DATE_PARSE_ERROR, e);
		} catch (JSONException e) {
			throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
		}
	}

}


text:
package sw.cos226.eightpuzzle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.PriorityQueue;

public class Solver {
	private PriorityQueue<Node> minPQ = new PriorityQueue<Node>();
	private Node solution = null;

	/**
	 * Find a solution to the initial {@link Board} (using the A* algorithm)
	 *
	 * @param initial
	 */
	public Solver(Board initial) {
		minPQ.add(new Node(0, initial));
		solve();
	}

	/**
	 * Minimum number of moves to solve initial board
	 *
	 * @return -1 if no solution
	 */
	public int moves() {
		return solution.getMoves();
	}

	/**
	 * The main algorithm to slove the puzzle
	 *
	 */
	private void solve() {
		if(minPQ.peek().getBoard().isSolvable()) {
			Node temp = minPQ.poll();
			Node prevTemp = temp;
			Board tempBoard = temp.getBoard();
			while(!tempBoard.isGoal()) {
				for(Board neighbor : tempBoard.neighbors()) {
					if(!prevTemp.getBoard().equals(neighbor)) {
						minPQ.add(new Node(temp.getMoves() + 1, neighbor, temp));
					}
				}
				prevTemp = temp;
				temp = minPQ.poll();
				tempBoard = temp.getBoard();
				//System.out.println(tempBoard);
			}
			solution = temp;
		}
	}

	/**
	 * Sequence of boards in a shortest solution
	 *
	 * @return Empty collection if no solution
	 */
	public Iterable<Board> solution() {
		LinkedList<Board> solutionStack = new LinkedList<Board>();
		Node tsol = solution;
		while(tsol != null && tsol.getBoard() != null) {
			solutionStack.addFirst(tsol.getBoard());
			tsol = tsol.getPreviousNode();
		}

		return solutionStack;
	}

	public static void main(String[] args) {
		if (args.length != 1) {
	        System.err.println("Incorrect number of arguments.");
	        System.err.println("Usage: ./eightpuzzle.jar <puzzlefile.txt>");
	        System.exit(1);
		}

		int[][] blocks = null;
		try {
			BufferedReader in = new BufferedReader(new FileReader(new File(args[0])));
			Integer N = Integer.parseInt(in.readLine().trim());
			blocks = new int[N][N];
			String line = in.readLine();
			int i = 0;
			while (line != null && !line.trim().isEmpty()) {
				String[] stringLine = line.trim().split("\\s+");
				for (int j = 0; j < N; j++) {
					blocks[i][j] = Integer.parseInt(stringLine[j]);
				}
				i++;
				line = in.readLine();
			}
			in.close();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Board initial = new Board(blocks);
//		System.out.println(initial);
//		System.out.println("Hamming: " + initial.hamming());
//		System.out.println("Manhattan: " + initial.manhattan());
//		System.out.println("IsGoal: " + initial.isGoal());
//		for(Board b : initial.neighbors()) {
//			System.out.println(b);
//			System.out.println("Hamming: " + b.hamming());
//			System.out.println("Manhattan: " + b.manhattan());
//			System.out.println("IsGoal: " + b.isGoal());
//		}

		if (!initial.isSolvable()) {
			System.out.println("No solution possible");
		} else {
			Solver solver = new Solver(initial);
			System.out.println("Minimum number of moves = " + solver.moves());
			for (Board n : solver.solution()) {
				System.out.println(n);
			}
		}
	}
}


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

    <style name="AdapterPlaceWindow" parent="WrapContent.Vertical">
        <item name="android:padding">10dp</item>
    </style>

    <style name="AdapterPlaceWindowName" parent="WrapContent">
        <item name="android:layout_marginBottom">5dp</item>

        <item name="android:textSize">@dimen/subhead</item>
        <item name="android:textColor">@color/yellow</item>
    </style>

    <style name="AdapterPlaceWindowDate" parent="WrapContent">
        <item name="android:textSize">@dimen/caption</item>
        <item name="android:textColor">@color/black</item>
    </style>
</resources>


text:
package com.github.stephanenicolas.injectresource;

import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Movie;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import com.test.injectresource.R;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

/**
 * @author SNI
 */
@RunWith(InjectResourceTestRunner.class)
public class InjectResourceProcessorInViewTest {
  public static final int RESOURCE_ID_STRING = R.string.string1;
  public static final int RESOURCE_ID_INTEGER = R.integer.integer1;
  public static final int RESOURCE_ID_BOOLEAN = R.bool.bool1;
  public static final int RESOURCE_ID_STRING_ARRAY = R.array.array1;
  public static final int RESOURCE_ID_INTEGER_ARRAY = R.array.intarray1;
  public static final int RESOURCE_ID_MOVIE = R.raw.small;
  public static final int RESOURCE_ID_ANIMATION = android.R.anim.fade_in;
  public static final int RESOURCE_COLOR_STATE_LIST = R.color.colorlist;
  public static final String TAG = "TAG";

  @Test
  public void shouldInjectResource_simple() {
    TestActivity activity = Robolectric.buildActivity(TestActivity.class).create().get();
    assertThat(activity.view.string, is(Robolectric.application.getText(RESOURCE_ID_STRING)));
    assertThat(activity.view.intA,
        is(Robolectric.application.getResources().getInteger(RESOURCE_ID_INTEGER)));
    assertThat(activity.view.intB,
        is(Robolectric.application.getResources().getInteger(RESOURCE_ID_INTEGER)));
    assertThat(activity.view.boolA,
        is(Robolectric.application.getResources().getBoolean(RESOURCE_ID_BOOLEAN)));
    assertThat(activity.view.boolB,
        is(Robolectric.application.getResources().getBoolean(RESOURCE_ID_BOOLEAN)));
    assertThat(activity.view.arrayA,
        is(Robolectric.application.getResources().getStringArray(RESOURCE_ID_STRING_ARRAY)));
    assertThat(activity.view.arrayB,
        is(Robolectric.application.getResources().getIntArray(RESOURCE_ID_INTEGER_ARRAY)));
    assertNotNull(activity.view.anim);
    //doesn't work on Robolectric..
    //assertNotNull(activity.movie);
    assertNotNull(activity.view.colorStateList);
  }

  public static class TestActivity extends Activity {

    private TestView view;

    @Override protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      view = new TestView(this);
    }

    public static class TestView extends View {
      @InjectResource(RESOURCE_ID_STRING)
      protected String string;
      @InjectResource(RESOURCE_ID_INTEGER)
      protected int intA;
      @InjectResource(RESOURCE_ID_INTEGER)
      protected Integer intB;
      @InjectResource(RESOURCE_ID_BOOLEAN)
      protected boolean boolA;
      @InjectResource(RESOURCE_ID_BOOLEAN)
      protected Boolean boolB;
      @InjectResource(RESOURCE_ID_STRING_ARRAY)
      protected String[] arrayA;
      @InjectResource(RESOURCE_ID_INTEGER_ARRAY)
      protected int[] arrayB;
      @InjectResource(RESOURCE_ID_MOVIE)
      protected Movie movie;
      @InjectResource(RESOURCE_ID_ANIMATION)
      protected Animation anim;
      @InjectResource(RESOURCE_COLOR_STATE_LIST)
      protected ColorStateList colorStateList;

      public TestView(Context context) {
        super(context);
        onFinishInflate();
      }
    }
  }
}


text:
package io.druid.segment.loading;

import com.metamx.common.logger.Logger;
import io.druid.segment.IndexIO;
import io.druid.segment.QueryableIndex;

import java.io.File;
import java.io.IOException;

/**
 */
public class MMappedQueryableIndexFactory implements QueryableIndexFactory
{
  private static final Logger log = new Logger(MMappedQueryableIndexFactory.class);

  @Override
  public QueryableIndex factorize(File parentDir) throws SegmentLoadingException
  {
    try {
      return IndexIO.loadIndex(parentDir);
    }
    catch (IOException e) {
      throw new SegmentLoadingException(e, "%s", e.getMessage());
    }
  }
}


text:
function Demo() -- Gera uma sequencia randomicamente >:}
charset = "@#&ªº°0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" -- quais caracteres farão parte da sequencia
   local value = "" -- inicializa a string a ser gerada
      math.randomseed(os.time()) -- seed do random, melhor forma de ser realmente random.
      mindfuck = math.ceil((math.pi*(math.pow((math.sqrt(#charset)),(#charset/math.pow(math.pi,
                 (#charset/(math.pi*math.pi+(#charset/math.pi))))))/math.pow(math.pi, math.sqrt(#charset))))) -- hueBRHU3
      dawhat = (math.ceil(string.byte("k")*(#charset/(math.pow(math.pi, (math.pi-(#charset/string.byte("z")))))))) -- hueBRHU3

      for i = 1, math.random(mindfuck, dawhat) do
         rand = math.random(#charset)  -- tamanho do charset, no caso 71
         value = value .. string.sub(charset, rand, rand)
         --[[
            Mágica! value se une a uma substring do charset randomicamente gerada até a mesma letra.
            Se não fizesse assim ia ter q usar tabela e ia ficar muito grande)
            seria assim: value = "" .. charset, 2, 2 então value seria 1
         ]]--
      end
   return value
end

local function caesar(input, shift)
   input = input:gsub(" ", Demo()) -- procura por espaços e substitui pela string randomica
   return input:gsub("%a", function(x)
   --[[
      Retorna uma cópia do input em que todas as ocorrências da pattern "%a"
      (que no caso, representa todas as letras)
      são trocadas pelo 2º parâmetro (que no caso é uma função)
   ]]--

   local test = (x:lower() == x and string.byte('a') or string.byte('A'))
   --[[
      Funciona basciamente como o operador ternário em C: (a ? b : c).
      string.byte('x') retorna o código decimal do caractere.
      oq está escrito é: test = (if x == lower then true; else false) and 97 or 65
      se for true retorna o caractere 97, se não, retorna o caractere 65.
   ]]--

   local crypt = x:byte() - test  -- crypt = código decimal do caractere x - código decimal da variável test
   crypt = crypt + shift          -- crypt = crypt + variável shift
   crypt = crypt%26               -- funciona mesmo que crypt seja negativo. 26 = n de letras no alfabeto
   crypt = crypt + test           -- crypt = crypt + 97 se for lower ou 65 se for upper
   return string.char(crypt)
   --[[
      O que foi retornado?
      Simples padawan: texto = 'c', shift = 3
      test = 97
      crypt = 99 - 97
      crypt = 2 + 3
      crypt = 5%26
      crypt = 5 + 97
      ao final da função crypt estará valendo 102, que é o código deciaml de 'f', ou seja 'c' com shift de 3 vale 'f'
   ]]--
   end)
end

local function decrypt(input, shift)
   local decrypt =  caesar(input, -shift)
   --[[
      para descriptografar é só receber o texto criptografado e aplicar o shift negativo, no exemplo acima 102 - 3 = 99
      ou seja 'f' volta a valer 'c'
   ]]--
   return (decrypt:gsub(Demo(), function(text) return " " end)) -- substitui a string randomica pelo espaço novamente
end

-- Testando
do
   local input = "A rápida raposa pula por cima do cachorro preguiçoso"
   local shift = 3

   if type(input) == nil then
      print("Arruma essa frase bahianão.")
   elseif type(shift) ~= "number" then
      print("Shift tem q ser um número.")
   else
      local e = caesar(input, shift)
      local d = decrypt(e, shift)
      print("Texto Original:", input)
      print("Texto criptografado:", e)
      print("Texto descriptografado:", d)
   end
end


text:
'use strict';

/* eslint-disable no-console */

const q = require('q');
const options = require('commander');
const fs = require('fs');
const util = require('../lib/util');
const path = require('path');
const BigIp = require('../lib/bigIp');

const LOG_ID = 'setMasterKey.js';
const Logger = require('../lib/logger');
const cloudProviderFactory = require('../lib/cloudProviderFactory');
const BACKUP = require('../lib/sharedConstants').BACKUP;

(function run() {
    let logger;
    let bigIp;
    const runner = {
        run(argv) {
            const providerOptions = {};
            const loggerOptions = {};
            const tempUcsDir = `${BACKUP.UCS_LOCAL_TMP_DIRECTORY}/`;
            const DEFAULT_LOG_FILE = '/var/log/cloudlibs/setMasterKey.log';
            const PRIMARY_KEY_DIR = BACKUP.PRIMARY_KEY_DIR;
            const UNIT_KEY_DIR = BACKUP.UNIT_KEY_DIR;
            let cloudProvider;
            options
                .version('4.10.3')
                .option(
                    '--hostname <username>',
                    'Hostname for BIGIP device',
                    'localhost'
                )
                .option(
                    '--username <username>',
                    'Username to access BIGIP device',
                    'admin'
                )
                .option(
                    '--password <password>',
                    'Password to access BIGIP device',
                    'admin'
                )
                .option(
                    '--mgmtPort <port>',
                    'Managment port on BIGIP device',
                    '8443'
                )
                .option(
                    '--cloud <cloud_provider>',
                    'Cloud provider (aws | azure | etc.)'
                )
                .option(
                    '--provider-options <cloud_options>',
                    'Options specific to cloud_provider. Ex: param1:value1,param2:value2',
                    util.map,
                    providerOptions
                )
                .option(
                    '--log-level <level>',
                    'Log level (none, error, warn, info, verbose, debug, silly). Default is info.', 'info'
                )
                .option(
                    '-o, --output <file>',
                    `Log to file. Default is ${DEFAULT_LOG_FILE}`, DEFAULT_LOG_FILE
                )
                .parse(argv);

            /* eslint-enable max-len */
            loggerOptions.console = true;
            loggerOptions.logLevel = options.logLevel;
            loggerOptions.fileName = options.output;
            loggerOptions.module = module;
            if (loggerOptions.fileName) {
                const dirName = path.dirname(loggerOptions.fileName);
                if (!fs.existsSync(dirName)) {
                    fs.mkdirSync(dirName);
                }
            }
            logger = Logger.getLogger(loggerOptions);
            bigIp = new BigIp({ loggerOptions });
            util.setLoggerOptions(loggerOptions);
            logger.silly(LOG_ID, `Options: ${JSON.stringify(options)}`);
            logger.silly(LOG_ID, `Provider Options: ${JSON.stringify(providerOptions)}`);
            logger.info(LOG_ID, 'Starting setting master key....');
            return bigIp.init(
                options.hostname,
                options.username,
                options.password,
                {
                    port: options.mgmtPort
                }
            )
                .then(() => {
                    logger.info(LOG_ID, `Cloud Provider ${options.cloud}`);
                    cloudProvider = cloudProviderFactory.getCloudProvider(
                        options.cloud,
                        {
                            loggerOptions,
                            clOptions: options
                        }
                    );
                    logger.info(LOG_ID, 'Initializing cloud provider');
                    return util.tryUntil(
                        cloudProvider,
                        util.MEDIUM_RETRY,
                        cloudProvider.init,
                        [providerOptions]
                    );
                })
                .then(() => {
                    logger.silly(LOG_ID, `provider is configured for ${options.cloud} cloud`);
                    logger.silly(LOG_ID, 'Grabbing ucs from cloud storage');
                    return cloudProvider.getStoredUcs();
                })
                .then((ucsData) => {
                    if (ucsData) {
                        return util.writeUcsFile(`${tempUcsDir}temp.ucs`, ucsData);
                    }
                    return q.resolve(false);
                })
                .then((response) => {
                    if (!response) {
                        util.logAndExit('no ucs file available - skipping step for setting master key');
                        return Promise.reject(new Error('no ucs file available'));
                    }
                    logger.silly('stopping bigip to set master key');
                    return util.runShellCommand('bigstart stop');
                })
                .then(() => {
                    logger.silly(LOG_ID, 'bigstart stopped. untarring ucs');
                    fs.mkdirSync(`${tempUcsDir}ucsContent/`);
                    return util.runShellCommand(
                        `tar --warning=no-timestamp -xf ${tempUcsDir}temp.ucs -C ${tempUcsDir}ucsContent/`
                    );
                })
                .then(() => {
                    logger.silly(LOG_ID, 'untar success, reading key');
                    return util.readDataFromFile(`${tempUcsDir}ucsContent${PRIMARY_KEY_DIR}`);
                })
                .then((oldMasterKey) => {
                    logger.silly(LOG_ID, 'read success, writing key');
                    return util.writeDataToFile(oldMasterKey, PRIMARY_KEY_DIR);
                })
                .then(() => {
                    logger.silly(LOG_ID, 'wrote master key, reading unit key');
                    return util.readDataFromFile(`${tempUcsDir}ucsContent${UNIT_KEY_DIR}`);
                })
                .then((oldUnitKey) => {
                    logger.silly(LOG_ID, 'read unitkey success, writing unit key');
                    return util.writeDataToFile(oldUnitKey, UNIT_KEY_DIR);
                })
                .then(() => {
                    logger.silly(LOG_ID, 'wrote master key; calling bigstart restart');
                    return util.runShellCommand('bigstart start');
                })
                .then(() => {
                    return bigIp.ready();
                })
                .then(() => {
                    logger.info(LOG_ID, 'Master Key is configured; ' +
                        'Restarting dhclient to set mgmt ip address');
                    return util.runShellCommand('bigstart restart dhclient');
                })
                .then(() => {
                    return util.tryUntil(this, util.MEDIUM_RETRY, () => {
                        return util.runShellCommand('tmsh list sys management-ip')
                            .then((response) => {
                                logger.silly(`Response for Managemetn Ip: ${response}`);
                                if (response) {
                                    return Promise.resolve();
                                }
                                return Promise.reject(new Error('management ip is not configured on device'));
                            });
                    }, {});
                })
                .catch((err) => {
                    if (err.message === 'no ucs file available') {
                        process.exit(0);
                    }
                    logger.error(err.message);
                })
                .finally(() => {
                    if (fs.existsSync(tempUcsDir)) {
                        logger.silly(LOG_ID, 'cleaning up working directory');
                        return util.runShellCommand(`rm -rf ${tempUcsDir}`);
                    }
                    return Promise.resolve();
                });
        }
    };

    module.exports = runner;

    // If we're called from the command line, run
    // This allows for test code to call us as a module
    if (!module.parent) {
        runner.run(process.argv);
    }
}());


text:
package asw.intro.server.connector;

import asw.intro.service.Service;

import java.net.*;

import java.util.logging.Logger;

/* remote proxy lato server per il servizio */
public class ServiceServerProxy {
    private Service service;             // il vero servizio
    private int port;                    // porta per il servizio

	/* logger */
	private Logger logger = Logger.getLogger("asw.intro.server.connector");

	public ServiceServerProxy(Service service, int port) {
		logger.info("ServiceServerProxy: Created a new Remote Proxy for Service listening on port " + port);
        this.service = service;
        this.port = port;
    }

    public void run() {
		logger.info("Remote Proxy: Server started");
        try {
            /* crea la socket su cui ricevere le richieste */
            DatagramSocket socket = new DatagramSocket(this.port);
            socket.setSoTimeout(0);  // nessun timeout
            byte[] buffer = new byte[1000];
            while (true) {
                /* aspetta un datagramma di richiesta */
                DatagramPacket requestPacket =
                    new DatagramPacket(buffer, buffer.length);
                socket.receive(requestPacket);    // bloccante
                /* estrae l'invocazione dal datagramma di richiesta */
                String request = new String( requestPacket.getData(),
                		                     requestPacket.getOffset(),
                		                     requestPacket.getLength() );
        		logger.info("Server Proxy: received request: " + request);
                /* la richiesta ha la forma "operazione#parametro" */
                /* estrae operazione e parametro */
                String op = this.getOp(request);
                String arg = this.getParam(request);
                /* effettua l'invocazione del servizio e ottiene il risultato */
                String result = this.executeOperation(op, arg);
        		logger.info("Server Proxy: sending reply: " + result);

                /* crea il datagramma di risposta */
                /* la risposta ha la forma "risultato" */
                byte[] replyMessage = result.getBytes();
                DatagramPacket replyPacket =
                    new DatagramPacket( replyMessage, replyMessage.length,
                                        requestPacket.getAddress(),
                                        requestPacket.getPort() );
                /* invia il datagramma di risposta */
                socket.send(replyPacket);    // non bloccante
            }
        } catch(Exception e) {
        	e.printStackTrace();
        }
    }

    /* estrae l'operazione dalla richiesta */
    private String getOp(String request) {
        /* la richiesta ha la forma "operazione#parametro" */
        int sep = request.indexOf("#");
        String op = request.substring(0,sep);
        return op;
    }

    /* estrae il parametro dalla richiesta */
    private String getParam(String request) {
        /* la richiesta ha la forma "operazione#parametro" */
        int sep = request.indexOf("#");
        String arg = request.substring(sep+1);
        return arg;
    }

    /* gestisce la richiesta del servizio corretto al servente */
    private String executeOperation(String op, String arg) {
        String reply = null;

        if ( op.equals("alpha") ) {
    		logger.info("Server Proxy: calling alpha(" + arg + ")");
            reply = this.service.alpha(arg);
    		logger.info("Server Proxy: alpha(" + arg + ") ==> " + reply);
        }

        return reply;
    }

}


text:
import os
import ConfigParser
import grapeConfig
import option
import utility
import grapeGit as git

class AddSubproject(option.Option):
    """
        grape addSubproject
        Adds a new project to this workspace (such as a new library or a new test suite)

        Usage: grape-addSubproject  --name=<name> --prefix=<prefix> --url=<url> --branch=<branch>
                                    [--subtree [--squash | --nosquash] | --submodule | --nested]
                                    [--noverify]

        Options:
        --name=<name>       The name of the subproject.
        --prefix=<prefix>   Path to place the subproject in your current workspace. (Relative to the top level
                            directory in your workspace.)
        --url=<url>         The URL (SSH, HTTPS, or Relative URL) of the new project's repository.
        --branch=<branch>   The branch name of the subproject you want to add.
        --subtree           Add this subproject as a subtree. Default behavior if .grapeconfig.workspace.subprojectType
                            is subtree.
        --squash            For subtree projects, if --squash is used, will add <commit> as a squash merge.
                            This defaults to true if .grapeconfig.subtrees.mergePolicy is squash.
        --nosquash          For subtree projects, if --nosquash is used, will ensure full history of <branch> is merged
                            in.
        --submodule         Add this subproject as a submodule. Default behavior if
                            .grapeconfig.workspace.subprojectType is submodule.
        --nested            Add this subproject as a nested git project. While in the main repository, git will ignore
                            all activity in this subproject. GRAPE commands such as checkout, status, and commit will
                            act across all nested subprojects in much the same way as grape manages submodules.
        --noverify          Set to prevent grape from asking for user verification before adding the subproject.

    """
    def __init__(self):
        super(AddSubproject, self).__init__()
        self._key = "addSubproject"
        self._section = "Project Management"

    def description(self):
        return "Adds a new subproject (such as a library) as a subtree, submodule, or nested subproject. "

    @staticmethod
    def parseSubprojectType(config, args):
        projectType = config.get("workspace", "subprojectType").strip().lower()
        if args["--subtree"]:
            projectType = "subtree"
        if args["--submodule"]:
            projectType = "submodule"
        if args["--nested"]:
            projectType = "nested"
        # can happen with invalid type in .grapeconfig and no type specified at command line
        if projectType != "subtree" and projectType != "submodule" and projectType != "nested":
            utility.printMsg("Invalid subprojectType specified in .grapeconfig section [workspace].")
        return projectType

    def execute(self, args):
        name = args["--name"]
        prefix = args["--prefix"]
        url = args["--url"]
        fullurl = utility.parseSubprojectRemoteURL(url)
        branch = args["--branch"]
        config = grapeConfig.grapeConfig()
        projectType = self.parseSubprojectType(config, args)
        proceed = args["--noverify"]
        if projectType == "subtree":
            #  whether or not to squash
            squash = args["--squash"] or config.get("subtrees", "mergePolicy").strip().lower() == "squash"
            squash = squash and not args["--nosquash"]
            squash_arg = "--squash" if squash else ""
            # expand the URL
            if not proceed:
                proceed = utility.userInput("About to create a subtree called %s at path %s,\n"
                                            "cloned from %s at %s " % (name, prefix, fullurl, branch) +
                                            ("using a squash merge." if squash else "") + "\nProceed? [y/n]", "y")

            if proceed:
                os.chdir(utility.workspaceDir())
                git.subtree("add %s --prefix=%s %s %s" % (squash_arg, prefix, fullurl, branch))

                #update the configuration file
                current_cfg_names = config.get("subtrees", "names").split()
                if not current_cfg_names or current_cfg_names[0].lower() == "none":
                    config.set("subtrees", "names", name)
                else:
                    current_cfg_names.append(name)
                    config.set("subtrees", "names", ' '.join(current_cfg_names))

                section = "subtree-%s" % name
                config.add_section(section)
                config.set(section, "prefix", prefix)
                config.set(section, "remote", url)
                config.set(section, "topicPrefixMappings", "?:%s" % branch)
                with open(os.path.join(utility.workspaceDir(), ".grapeconfig"), "w") as f:
                    config.write(f)
                utility.printMsg("Successfully added subtree branch. \n"
                      "Updated .grapeconfig file. Review changes and then commit. ")
        elif projectType == "submodule":
            if not proceed:
                proceed = utility.userInput("about to add %s as a submodule at path %s,\n"
                                            "cloned from %s at branch %s.\nproceed? [y/n]" %
                                            (name, prefix, url, branch), "y")
            if proceed:
                git.submodule("add --name %s --branch %s %s %s" % (name, branch, url, prefix))
                print("Successfully added submodule %s at %s. Please review changes and commit." % (name, prefix))
        elif projectType == "nested":
            if not proceed:
                proceed = utility.userInput(" about to clone %s as a nested git repo at path %s,\n"
                                            "cloned from %s at branch %s.\nProceed? [y/n]" %
                                            (name, prefix, url, branch), 'y')
            if proceed:
                git.clone("%s %s" % (fullurl, prefix))
                ignorePath = os.path.join(git.baseDir(), ".gitignore")
                with open(ignorePath, 'a') as ignore:
                    ignore.writelines([prefix+'\n'])
                git.add(ignorePath)
                wsConfig = grapeConfig.workspaceConfig()
                currentSubprojects = wsConfig.getList("nestedProjects", "names")
                currentSubprojects.append(name)
                wsConfig.set("nestedProjects", "names", ' '.join(currentSubprojects))
                newSection = "nested-%s" % name
                wsConfig.ensureSection(newSection)
                wsConfig.set(newSection, "prefix", prefix)
                wsConfig.set(newSection, "url", url)
                configFileName = os.path.join(utility.workspaceDir(), ".grapeconfig")
                with open(os.path.join(configFileName), 'w') as f:
                    wsConfig.write(f)
                git.add(configFileName)
                git.commit("%s %s -m \"GRAPE: Added nested subproject %s\"" % (ignorePath, configFileName, prefix))
                # update the runtime config with the new workspace .grapeconfig's settings.
                grapeConfig.read()

                userConfig = grapeConfig.grapeUserConfig()
                userConfig.ensureSection(newSection)
                userConfig.set(newSection, "active", "True")
                grapeConfig.writeConfig(userConfig, os.path.join(utility.workspaceDir(), ".git", ".grapeuserconfig"))

        return True

    @staticmethod
    def activateNestedSubproject(subprojectName, userconfig):
        wsDir = utility.workspaceDir()
        config = grapeConfig.grapeConfig()
        prefix = config.get("nested-%s" % subprojectName, "prefix")
        url = config.get("nested-%s" % subprojectName, "url")
        fullurl = utility.parseSubprojectRemoteURL(url)
        section = "nested-%s" % subprojectName
        userconfig.ensureSection(section)
        currentlyActive = userconfig.getboolean(section, "active")
        if not currentlyActive:
            destDir = os.path.join(wsDir, prefix)
            if not (os.path.isdir(destDir) and os.listdir(destDir)):
                git.clone("%s %s" % (fullurl, prefix))
            elif '.git' in os.listdir(destDir):
                pass
            else:
                utility.printMsg("WARNING: inactive nested subproject %s has files but is not a git repo" % prefix)
                return False
        userconfig.set(section, "active", "True")
        grapeConfig.writeConfig(userconfig, os.path.join(wsDir, ".git", ".grapeuserconfig"))
        return True

    def setDefaultConfig(self, config):
        config.ensureSection("subtrees")
        config.ensureSection("workspace")
        config.ensureSection("nestedProjects")
        config.set("subtrees", "mergePolicy", "squash")
        config.set("workspace", "subprojectType", "subtree")
        config.set("nestedProjects", "names", "")