text:
#include "config.h"
#include "PluginView.h"

#include "BitmapImage.h"
#include "BitmapInfo.h"
#include "BridgeJSC.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Element.h"
#include "EventNames.h"
#include "FocusController.h"
#include "Frame.h"
#include "FrameLoadRequest.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLNames.h"
#include "HTMLPlugInElement.h"
#include "HostWindow.h"
#include "Image.h"
#include "JSDOMBinding.h"
#include "JSDOMWindow.h"
#include "KeyboardEvent.h"
#include "LocalWindowsContext.h"
#include "MIMETypeRegistry.h"
#include "MouseEvent.h"
#include "Page.h"
#include "PlatformMouseEvent.h"
#include "PluginDatabase.h"
#include "PluginDebug.h"
#include "PluginMainThreadScheduler.h"
#include "PluginMessageThrottlerWin.h"
#include "PluginPackage.h"
#include "RenderWidget.h"
#include "Settings.h"
#include "WebCoreInstanceHandle.h"
#include "c_instance.h"
#include "npruntime_impl.h"
#include "runtime_root.h"
#include <runtime/JSCJSValue.h>
#include <runtime/JSLock.h>
#include <wtf/ASCIICType.h>
#include <wtf/text/WTFString.h>
#include <wtf/win/GDIObject.h>

#if OS(WINCE)
#undef LOG_NPERROR
#define LOG_NPERROR(x)
#undef LOG_PLUGIN_NET_ERROR
#define LOG_PLUGIN_NET_ERROR()
#endif

#if USE(CAIRO)
#include "PlatformContextCairo.h"
#include <cairo-win32.h>
#endif

#if PLATFORM(GTK)
#include <gdk/gdkwin32.h>
#include <gtk/gtk.h>
#endif

static inline HWND windowHandleForPageClient(PlatformPageClient client)
{
#if PLATFORM(GTK)
    if (!client)
        return 0;
    if (GdkWindow* window = gtk_widget_get_window(client))
        return static_cast<HWND>(GDK_WINDOW_HWND(window));
    return 0;
#else
    return client;
#endif
}

using JSC::ExecState;
using JSC::JSLock;
using JSC::JSObject;

using std::min;

using namespace WTF;

namespace WebCore {

using namespace HTMLNames;

const LPCWSTR kWebPluginViewdowClassName = L"WebPluginView";
const LPCWSTR kWebPluginViewProperty = L"WebPluginViewProperty";

#if !OS(WINCE)
// The code used to hook BeginPaint/EndPaint originally came from
// <http://www.fengyuan.com/article/wmprint.html>.
// Copyright (C) 2000 by Feng Yuan (www.fengyuan.com).

static unsigned beginPaintSysCall;
static BYTE* beginPaint;

static unsigned endPaintSysCall;
static BYTE* endPaint;

typedef HDC (WINAPI *PtrBeginPaint)(HWND, PAINTSTRUCT*);
typedef BOOL (WINAPI *PtrEndPaint)(HWND, const PAINTSTRUCT*);

#if OS(WINDOWS) && CPU(X86_64) && COMPILER(MSVC)
extern "C" HDC __stdcall _HBeginPaint(HWND hWnd, LPPAINTSTRUCT lpPaint);
extern "C" BOOL __stdcall _HEndPaint(HWND hWnd, const PAINTSTRUCT* lpPaint);
#endif

HDC WINAPI PluginView::hookedBeginPaint(HWND hWnd, PAINTSTRUCT* lpPaint)
{
    PluginView* pluginView = reinterpret_cast<PluginView*>(GetProp(hWnd, kWebPluginViewProperty));
    if (pluginView && pluginView->m_wmPrintHDC) {
        // We're secretly handling WM_PRINTCLIENT, so set up the PAINTSTRUCT so
        // that the plugin will paint into the HDC we provide.
        memset(lpPaint, 0, sizeof(PAINTSTRUCT));
        lpPaint->hdc = pluginView->m_wmPrintHDC;
        GetClientRect(hWnd, &lpPaint->rcPaint);
        return pluginView->m_wmPrintHDC;
    }

#if COMPILER(GCC)
    HDC result;
    asm ("push    %2\n"
         "push    %3\n"
         "call    *%4\n"
         : "=a" (result)
         : "a" (beginPaintSysCall), "g" (lpPaint), "g" (hWnd), "m" (beginPaint)
         : "memory"
        );
    return result;
#elif defined(_M_IX86)
    // Call through to the original BeginPaint.
    __asm   mov     eax, beginPaintSysCall
    __asm   push    lpPaint
    __asm   push    hWnd
    __asm   call    beginPaint
#else
    return _HBeginPaint(hWnd, lpPaint);
#endif
}

BOOL WINAPI PluginView::hookedEndPaint(HWND hWnd, const PAINTSTRUCT* lpPaint)
{
    PluginView* pluginView = reinterpret_cast<PluginView*>(GetProp(hWnd, kWebPluginViewProperty));
    if (pluginView && pluginView->m_wmPrintHDC) {
        // We're secretly handling WM_PRINTCLIENT, so we don't have to do any
        // cleanup.
        return TRUE;
    }

#if COMPILER(GCC)
    BOOL result;
    asm ("push   %2\n"
         "push   %3\n"
         "call   *%4\n"
         : "=a" (result)
         : "a" (endPaintSysCall), "g" (lpPaint), "g" (hWnd), "m" (endPaint)
        );
    return result;
#elif defined (_M_IX86)
    // Call through to the original EndPaint.
    __asm   mov     eax, endPaintSysCall
    __asm   push    lpPaint
    __asm   push    hWnd
    __asm   call    endPaint
#else
    return _HEndPaint(hWnd, lpPaint);
#endif
}

static void hook(const char* module, const char* proc, unsigned& sysCallID, BYTE*& pProc, const void* pNewProc)
{
    // See <http://www.fengyuan.com/article/wmprint.html> for an explanation of
    // how this function works.

    HINSTANCE hMod = GetModuleHandleA(module);

    pProc = reinterpret_cast<BYTE*>(reinterpret_cast<ptrdiff_t>(GetProcAddress(hMod, proc)));

#if COMPILER(GCC) || defined(_M_IX86)
    if (pProc[0] != 0xB8)
        return;

    // FIXME: Should we be reading the bytes one-by-one instead of doing an
    // unaligned read?
    sysCallID = *reinterpret_cast<unsigned*>(pProc + 1);

    DWORD flOldProtect;
    if (!VirtualProtect(pProc, 5, PAGE_EXECUTE_READWRITE, &flOldProtect))
        return;

    pProc[0] = 0xE9;
    *reinterpret_cast<unsigned*>(pProc + 1) = reinterpret_cast<intptr_t>(pNewProc) - reinterpret_cast<intptr_t>(pProc + 5);

    pProc += 5;
#else
    /* Disassembly of BeginPaint()
    00000000779FC5B0 4C 8B D1         mov         r10,rcx
    00000000779FC5B3 B8 17 10 00 00   mov         eax,1017h
    00000000779FC5B8 0F 05            syscall
    00000000779FC5BA C3               ret
    00000000779FC5BB 90               nop
    00000000779FC5BC 90               nop
    00000000779FC5BD 90               nop
    00000000779FC5BE 90               nop
    00000000779FC5BF 90               nop
    00000000779FC5C0 90               nop
    00000000779FC5C1 90               nop
    00000000779FC5C2 90               nop
    00000000779FC5C3 90               nop
    */
    // Check for the signature as in the above disassembly
    DWORD guard = 0xB8D18B4C;
    if (*reinterpret_cast<DWORD*>(pProc) != guard)
        return;

    DWORD flOldProtect;
    VirtualProtect(pProc, 12, PAGE_EXECUTE_READWRITE, & flOldProtect);
    pProc[0] = 0x48;    // mov rax, this
    pProc[1] = 0xb8;
    *(__int64*)(pProc+2) = (__int64)pNewProc;
    pProc[10] = 0xff;   // jmp rax
    pProc[11] = 0xe0;
#endif
}

static void setUpOffscreenPaintingHooks(HDC (WINAPI*hookedBeginPaint)(HWND, PAINTSTRUCT*), BOOL (WINAPI*hookedEndPaint)(HWND, const PAINTSTRUCT*))
{
    static bool haveHooked = false;
    if (haveHooked)
        return;
    haveHooked = true;

    // Most (all?) windowed plugins don't seem to respond to WM_PRINTCLIENT, so
    // we hook into BeginPaint/EndPaint to allow their normal WM_PAINT handling
    // to draw into a given HDC. Note that this hooking affects the entire
    // process.
    hook("user32.dll", "BeginPaint", beginPaintSysCall, beginPaint, reinterpret_cast<const void *>(reinterpret_cast<ptrdiff_t>(hookedBeginPaint)));
    hook("user32.dll", "EndPaint", endPaintSysCall, endPaint, reinterpret_cast<const void *>(reinterpret_cast<ptrdiff_t>(hookedEndPaint)));

}
#endif

static bool registerPluginView()
{
    static bool haveRegisteredWindowClass = false;
    if (haveRegisteredWindowClass)
        return true;

    haveRegisteredWindowClass = true;

#if PLATFORM(GTK)
    WebCore::setInstanceHandle((HINSTANCE)(GetModuleHandle(0)));
#endif

    ASSERT(WebCore::instanceHandle());

#if OS(WINCE)
    WNDCLASS wcex = { 0 };
#else
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.hIconSm        = 0;
#endif

    wcex.style          = CS_DBLCLKS;
#if OS(WINCE)
    wcex.style          |= CS_PARENTDC;
#endif
    wcex.lpfnWndProc    = DefWindowProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = WebCore::instanceHandle();
    wcex.hIcon          = 0;
    wcex.hCursor        = LoadCursor(0, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)COLOR_WINDOW;
    wcex.lpszMenuName   = 0;
    wcex.lpszClassName  = kWebPluginViewdowClassName;

#if OS(WINCE)
    return !!RegisterClass(&wcex);
#else
    return !!RegisterClassEx(&wcex);
#endif
}

LRESULT CALLBACK PluginView::PluginViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PluginView* pluginView = reinterpret_cast<PluginView*>(GetProp(hWnd, kWebPluginViewProperty));

    return pluginView->wndProc(hWnd, message, wParam, lParam);
}

static bool isWindowsMessageUserGesture(UINT message)
{
    switch (message) {
        case WM_LBUTTONUP:
        case WM_MBUTTONUP:
        case WM_RBUTTONUP:
        case WM_KEYUP:
            return true;
        default:
            return false;
    }
}

static inline IntPoint contentsToNativeWindow(FrameView* view, const IntPoint& point)
{
    return view->contentsToWindow(point);
}

static inline IntRect contentsToNativeWindow(FrameView* view, const IntRect& rect)
{
    return view->contentsToWindow(rect);
}

LRESULT
PluginView::wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    // <rdar://5711136> Sometimes Flash will call SetCapture before creating
    // a full-screen window and will not release it, which causes the
    // full-screen window to never receive mouse events. We set/release capture
    // on mouse down/up before sending the event to the plug-in to prevent that.
    switch (message) {
        case WM_LBUTTONDOWN:
        case WM_MBUTTONDOWN:
        case WM_RBUTTONDOWN:
            ::SetCapture(hWnd);
            break;
        case WM_LBUTTONUP:
        case WM_MBUTTONUP:
        case WM_RBUTTONUP:
            ::ReleaseCapture();
            break;
    }

    if (message == m_lastMessage &&
        m_plugin->quirks().contains(PluginQuirkDontCallWndProcForSameMessageRecursively) &&
        m_isCallingPluginWndProc)
        return 1;

    if (message == WM_USER + 1 &&
        m_plugin->quirks().contains(PluginQuirkThrottleWMUserPlusOneMessages)) {
        if (!m_messageThrottler)
            m_messageThrottler = adoptPtr(new PluginMessageThrottlerWin(this));

        m_messageThrottler->appendMessage(hWnd, message, wParam, lParam);
        return 0;
    }

    m_lastMessage = message;
    m_isCallingPluginWndProc = true;

    // If the plug-in doesn't explicitly support changing the pop-up state, we enable
    // popups for all user gestures.
    // Note that we need to pop the state in a timer, because the Flash plug-in
    // pops up windows in response to a posted message.
    if (m_plugin->pluginFuncs()->version < NPVERS_HAS_POPUPS_ENABLED_STATE &&
        isWindowsMessageUserGesture(message) && !m_popPopupsStateTimer.isActive()) {

        pushPopupsEnabledState(true);

        m_popPopupsStateTimer.startOneShot(0);
    }

#if !OS(WINCE)
    if (message == WM_PRINTCLIENT) {
        // Most (all?) windowed plugins don't respond to WM_PRINTCLIENT, so we
        // change the message to WM_PAINT and rely on our hooked versions of
        // BeginPaint/EndPaint to make the plugin draw into the given HDC.
        message = WM_PAINT;
        m_wmPrintHDC = reinterpret_cast<HDC>(wParam);
    }
#endif

    // Call the plug-in's window proc.
    LRESULT result = ::CallWindowProc(m_pluginWndProc, hWnd, message, wParam, lParam);

    m_wmPrintHDC = 0;

    m_isCallingPluginWndProc = false;

    return result;
}

void PluginView::updatePluginWidget()
{
    if (!parent())
        return;

    ASSERT(parent()->isFrameView());
    FrameView* frameView = toFrameView(parent());

    IntRect oldWindowRect = m_windowRect;
    IntRect oldClipRect = m_clipRect;

#if OS(WINCE)
    m_windowRect = frameView->contentsToWindow(frameRect());
#else
    m_windowRect = IntRect(frameView->contentsToWindow(frameRect().location()), frameRect().size());
#endif
    m_clipRect = windowClipRect();
    m_clipRect.move(-m_windowRect.x(), -m_windowRect.y());

    if (platformPluginWidget() && (!m_haveUpdatedPluginWidget || m_windowRect != oldWindowRect || m_clipRect != oldClipRect)) {

        setCallingPlugin(true);

        // To prevent flashes while scrolling, we disable drawing during the window
        // update process by clipping the window to the zero rect.

        bool clipToZeroRect = !m_plugin->quirks().contains(PluginQuirkDontClipToZeroRectWhenScrolling);

        if (clipToZeroRect) {
            auto rgn = adoptGDIObject(::CreateRectRgn(0, 0, 0, 0));
            ::SetWindowRgn(platformPluginWidget(), rgn.leak(), FALSE);
        } else {
            auto rgn = adoptGDIObject(::CreateRectRgn(m_clipRect.x(), m_clipRect.y(), m_clipRect.maxX(), m_clipRect.maxY()));
            ::SetWindowRgn(platformPluginWidget(), rgn.leak(), TRUE);
        }

        if (!m_haveUpdatedPluginWidget || m_windowRect != oldWindowRect)
            ::MoveWindow(platformPluginWidget(), m_windowRect.x(), m_windowRect.y(), m_windowRect.width(), m_windowRect.height(), TRUE);

        if (clipToZeroRect) {
            auto rgn = adoptGDIObject(::CreateRectRgn(m_clipRect.x(), m_clipRect.y(), m_clipRect.maxX(), m_clipRect.maxY()));
            ::SetWindowRgn(platformPluginWidget(), rgn.leak(), TRUE);
        }

        setCallingPlugin(false);

        m_haveUpdatedPluginWidget = true;
    }
}

void PluginView::setFocus(bool focused)
{
    if (focused && platformPluginWidget())
        SetFocus(platformPluginWidget());

    Widget::setFocus(focused);

    if (!m_plugin || m_isWindowed)
        return;

    NPEvent npEvent;

    npEvent.event = focused ? WM_SETFOCUS : WM_KILLFOCUS;
    npEvent.wParam = 0;
    npEvent.lParam = 0;

    dispatchNPEvent(npEvent);
}

void PluginView::show()
{
    setSelfVisible(true);

    if (isParentVisible() && platformPluginWidget())
        ShowWindow(platformPluginWidget(), SW_SHOWNA);

    Widget::show();
}

void PluginView::hide()
{
    setSelfVisible(false);

    if (isParentVisible() && platformPluginWidget())
        ShowWindow(platformPluginWidget(), SW_HIDE);

    Widget::hide();
}

bool PluginView::dispatchNPEvent(NPEvent& npEvent)
{
    if (!m_plugin->pluginFuncs()->event)
        return true;

    bool shouldPop = false;

    if (m_plugin->pluginFuncs()->version < NPVERS_HAS_POPUPS_ENABLED_STATE && isWindowsMessageUserGesture(npEvent.event)) {
        pushPopupsEnabledState(true);
        shouldPop = true;
    }

    JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM());
    setCallingPlugin(true);
    bool accepted = !m_plugin->pluginFuncs()->event(m_instance, &npEvent);
    setCallingPlugin(false);

    if (shouldPop)
        popPopupsEnabledState();

    return accepted;
}

void PluginView::paintIntoTransformedContext(HDC hdc)
{
    if (m_isWindowed) {
#if !OS(WINCE)
        SendMessage(platformPluginWidget(), WM_PRINTCLIENT, reinterpret_cast<WPARAM>(hdc), PRF_CLIENT | PRF_CHILDREN | PRF_OWNED);
#endif
        return;
    }

    m_npWindow.type = NPWindowTypeDrawable;
    m_npWindow.window = hdc;

    WINDOWPOS windowpos = { 0, 0, 0, 0, 0, 0, 0 };

    IntRect r = contentsToNativeWindow(toFrameView(parent()), frameRect());

    windowpos.x = r.x();
    windowpos.y = r.y();
    windowpos.cx = r.width();
    windowpos.cy = r.height();

    NPEvent npEvent;
    npEvent.event = WM_WINDOWPOSCHANGED;
    npEvent.lParam = reinterpret_cast<uintptr_t>(&windowpos);
    npEvent.wParam = 0;

    dispatchNPEvent(npEvent);

    setNPWindowRect(frameRect());

    npEvent.event = WM_PAINT;
    npEvent.wParam = reinterpret_cast<uintptr_t>(hdc);

    // This is supposed to be a pointer to the dirty rect, but it seems that the Flash plugin
    // ignores it so we just pass null.
    npEvent.lParam = 0;

    dispatchNPEvent(npEvent);
}

void PluginView::paintWindowedPluginIntoContext(GraphicsContext* context, const IntRect& rect)
{
#if !USE(WINGDI)
    ASSERT(m_isWindowed);
    ASSERT(context->shouldIncludeChildWindows());

    ASSERT(parent()->isFrameView());
    IntPoint locationInWindow = toFrameView(parent())->convertToContainingWindow(frameRect().location());

    LocalWindowsContext windowsContext(context, frameRect(), false);

#if USE(CAIRO)
    // Must flush drawings up to this point to the backing metafile, otherwise the
    // plugin region will be overwritten with any clear regions specified in the
    // cairo-controlled portions of the rendering.
    cairo_show_page(context->platformContext()->cr());
#endif

    HDC hdc = windowsContext.hdc();
    XFORM originalTransform;
    GetWorldTransform(hdc, &originalTransform);

    // The plugin expects the DC to be in client coordinates, so we translate
    // the DC to make that so.
    AffineTransform ctm = context->getCTM();
    ctm.translate(locationInWindow.x(), locationInWindow.y());
    XFORM transform = static_cast<XFORM>(ctm.toTransformationMatrix());

    SetWorldTransform(hdc, &transform);

    paintIntoTransformedContext(hdc);

    SetWorldTransform(hdc, &originalTransform);
#endif
}

void PluginView::paint(GraphicsContext* context, const IntRect& rect)
{
    if (!m_isStarted) {
        // Draw the "missing plugin" image
        paintMissingPluginIcon(context, rect);
        return;
    }

    if (context->paintingDisabled())
        return;

    // Ensure that we have called SetWindow before we try to paint.
    if (!m_haveCalledSetWindow)
        setNPWindowRect(frameRect());

    if (m_isWindowed) {
#if !USE(WINGDI)
        if (context->shouldIncludeChildWindows())
            paintWindowedPluginIntoContext(context, rect);
#endif
        return;
    }

    ASSERT(parent()->isFrameView());

    // In the GTK and Qt ports we draw in an offscreen buffer and don't want to use the window
    // coordinates.
#if PLATFORM(GTK)
    IntRect rectInWindow(rect);
    rectInWindow.intersect(frameRect());
#else
    IntRect rectInWindow = toFrameView(parent())->contentsToWindow(frameRect());
#endif
    LocalWindowsContext windowsContext(context, rectInWindow, m_isTransparent);

    // On Safari/Windows without transparency layers the GraphicsContext returns the HDC
    // of the window and the plugin expects that the passed in DC has window coordinates.
    // In the GTK and Qt ports we always draw in an offscreen buffer and therefore need
    // to preserve the translation set in getWindowsContext.
#if !PLATFORM(GTK) && !OS(WINCE)
    if (!context->isInTransparencyLayer()) {
        XFORM transform;
        GetWorldTransform(windowsContext.hdc(), &transform);
        transform.eDx = 0;
        transform.eDy = 0;
        SetWorldTransform(windowsContext.hdc(), &transform);
    }
#endif

    paintIntoTransformedContext(windowsContext.hdc());
}

void PluginView::handleKeyboardEvent(KeyboardEvent* event)
{
    ASSERT(m_plugin && !m_isWindowed);

    NPEvent npEvent;

    npEvent.wParam = event->keyCode();

    if (event->type() == eventNames().keydownEvent) {
        npEvent.event = WM_KEYDOWN;
        npEvent.lParam = 0;
    } else if (event->type() == eventNames().keypressEvent) {
        npEvent.event = WM_CHAR;
        npEvent.lParam = 0;
    } else if (event->type() == eventNames().keyupEvent) {
        npEvent.event = WM_KEYUP;
        npEvent.lParam = 0x8000;
    } else
        return;

    JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM());
    if (dispatchNPEvent(npEvent))
        event->setDefaultHandled();
}

#if !OS(WINCE)
extern bool ignoreNextSetCursor;
#endif

void PluginView::handleMouseEvent(MouseEvent* event)
{
    ASSERT(m_plugin && !m_isWindowed);

    NPEvent npEvent;

    IntPoint p = contentsToNativeWindow(toFrameView(parent()), IntPoint(event->pageX(), event->pageY()));

    npEvent.lParam = MAKELPARAM(p.x(), p.y());
    npEvent.wParam = 0;

    if (event->ctrlKey())
        npEvent.wParam |= MK_CONTROL;
    if (event->shiftKey())
        npEvent.wParam |= MK_SHIFT;

    if (event->type() == eventNames().mousemoveEvent ||
        event->type() == eventNames().mouseoutEvent ||
        event->type() == eventNames().mouseoverEvent) {
        npEvent.event = WM_MOUSEMOVE;
        if (event->buttonDown())
            switch (event->button()) {
                case LeftButton:
                    npEvent.wParam |= MK_LBUTTON;
                    break;
                case MiddleButton:
                    npEvent.wParam |= MK_MBUTTON;
                    break;
                case RightButton:
                    npEvent.wParam |= MK_RBUTTON;
                break;
            }
    }
    else if (event->type() == eventNames().mousedownEvent) {
        focusPluginElement();
        switch (event->button()) {
            case 0:
                npEvent.event = WM_LBUTTONDOWN;
                break;
            case 1:
                npEvent.event = WM_MBUTTONDOWN;
                break;
            case 2:
                npEvent.event = WM_RBUTTONDOWN;
                break;
        }
    } else if (event->type() == eventNames().mouseupEvent) {
        switch (event->button()) {
            case 0:
                npEvent.event = WM_LBUTTONUP;
                break;
            case 1:
                npEvent.event = WM_MBUTTONUP;
                break;
            case 2:
                npEvent.event = WM_RBUTTONUP;
                break;
        }
    } else
        return;

    JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM());
    // FIXME: Consider back porting the http://webkit.org/b/58108 fix here.
    if (dispatchNPEvent(npEvent))
        event->setDefaultHandled();

#if !PLATFORM(GTK) && !OS(WINCE)
    // Currently, Widget::setCursor is always called after this function in EventHandler.cpp
    // and since we don't want that we set ignoreNextSetCursor to true here to prevent that.
    ignoreNextSetCursor = true;
    if (Page* page = m_parentFrame->page())
        page->chrome().client().setLastSetCursorToCurrentCursor();
#endif
}

void PluginView::setParent(ScrollView* parent)
{
    Widget::setParent(parent);

#if OS(WINCE)
    if (parent) {
        init();
        if (parent->isVisible())
            show();
        else
            hide();
    }
#else
    if (parent)
        init();
    else {
        if (!platformPluginWidget())
            return;

        // If the plug-in window or one of its children have the focus, we need to
        // clear it to prevent the web view window from being focused because that can
        // trigger a layout while the plugin element is being detached.
        HWND focusedWindow = ::GetFocus();
        if (platformPluginWidget() == focusedWindow || ::IsChild(platformPluginWidget(), focusedWindow))
            ::SetFocus(0);
    }
#endif
}

void PluginView::setParentVisible(bool visible)
{
    if (isParentVisible() == visible)
        return;

    Widget::setParentVisible(visible);

    if (isSelfVisible() && platformPluginWidget()) {
        if (visible)
            ShowWindow(platformPluginWidget(), SW_SHOWNA);
        else
            ShowWindow(platformPluginWidget(), SW_HIDE);
    }
}

void PluginView::setNPWindowRect(const IntRect& rect)
{
    if (!m_isStarted)
        return;

#if OS(WINCE)
    IntRect r = toFrameView(parent())->contentsToWindow(rect);
    m_npWindow.x = r.x();
    m_npWindow.y = r.y();

    m_npWindow.width = r.width();
    m_npWindow.height = r.height();

    m_npWindow.clipRect.right = r.width();
    m_npWindow.clipRect.bottom = r.height();
#else
    // In the GTK and Qt ports we draw in an offscreen buffer and don't want to use the window
    // coordinates.
# if PLATFORM(GTK)
    IntPoint p = rect.location();
# else
    IntPoint p = toFrameView(parent())->contentsToWindow(rect.location());
# endif
    m_npWindow.x = p.x();
    m_npWindow.y = p.y();

    m_npWindow.width = rect.width();
    m_npWindow.height = rect.height();

    m_npWindow.clipRect.right = rect.width();
    m_npWindow.clipRect.bottom = rect.height();
#endif
    m_npWindow.clipRect.left = 0;
    m_npWindow.clipRect.top = 0;

    if (m_plugin->pluginFuncs()->setwindow) {
        JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM());
        setCallingPlugin(true);
        m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow);
        setCallingPlugin(false);

        m_haveCalledSetWindow = true;

        if (!m_isWindowed)
            return;

        ASSERT(platformPluginWidget());

#if OS(WINCE)
        if (!m_pluginWndProc) {
            WNDPROC currentWndProc = (WNDPROC)GetWindowLong(platformPluginWidget(), GWL_WNDPROC);
            if (currentWndProc != PluginViewWndProc)
                m_pluginWndProc = (WNDPROC)SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)PluginViewWndProc);
        }
#else
        WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC);
        if (currentWndProc != PluginViewWndProc)
            m_pluginWndProc = (WNDPROC)SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)PluginViewWndProc);
#endif
    }
}

NPError PluginView::handlePostReadFile(Vector<char>& buffer, uint32_t len, const char* buf)
{
    String filename(buf, len);

    if (filename.startsWith("file:///"))
        filename = filename.substring(8);

    // Get file info
    WIN32_FILE_ATTRIBUTE_DATA attrs;
    if (GetFileAttributesExW(filename.charactersWithNullTermination().data(), GetFileExInfoStandard, &attrs) == 0)
        return NPERR_FILE_NOT_FOUND;

    if (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        return NPERR_FILE_NOT_FOUND;

    HANDLE fileHandle = CreateFileW(filename.charactersWithNullTermination().data(), FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

    if (fileHandle == INVALID_HANDLE_VALUE)
        return NPERR_FILE_NOT_FOUND;

    buffer.resize(attrs.nFileSizeLow);

    DWORD bytesRead;
    int retval = ReadFile(fileHandle, buffer.data(), attrs.nFileSizeLow, &bytesRead, 0);

    CloseHandle(fileHandle);

    if (retval == 0 || bytesRead != attrs.nFileSizeLow)
        return NPERR_FILE_NOT_FOUND;

    return NPERR_NO_ERROR;
}

bool PluginView::platformGetValueStatic(NPNVariable, void*, NPError*)
{
    return false;
}

bool PluginView::platformGetValue(NPNVariable variable, void* value, NPError* result)
{
    switch (variable) {
        case NPNVnetscapeWindow: {
            HWND* w = reinterpret_cast<HWND*>(value);
            *w = windowHandleForPageClient(parent() ? parent()->hostWindow()->platformPageClient() : 0);
            *result = NPERR_NO_ERROR;
            return true;
        }

        case NPNVSupportsWindowless: {
            NPBool* flag = reinterpret_cast<NPBool*>(value);
            *flag = TRUE;
            *result = NPERR_NO_ERROR;
            return true;
        }

    default:
        return false;
    }
}

void PluginView::invalidateRect(const IntRect& rect)
{
    if (m_isWindowed) {
        RECT invalidRect = { rect.x(), rect.y(), rect.maxX(), rect.maxY() };
        ::InvalidateRect(platformPluginWidget(), &invalidRect, false);
        return;
    }

    invalidateWindowlessPluginRect(rect);
}

void PluginView::invalidateRect(NPRect* rect)
{
    if (!rect) {
        invalidate();
        return;
    }

    IntRect r(rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top);

    if (m_isWindowed) {
        RECT invalidRect = { r.x(), r.y(), r.maxX(), r.maxY() };
        InvalidateRect(platformPluginWidget(), &invalidRect, FALSE);
    } else {
        if (m_plugin->quirks().contains(PluginQuirkThrottleInvalidate)) {
            m_invalidRects.append(r);
            if (!m_invalidateTimer.isActive())
                m_invalidateTimer.startOneShot(0.001);
        } else
            invalidateRect(r);
    }
}

void PluginView::invalidateRegion(NPRegion region)
{
    if (m_isWindowed)
        return;

    RECT r;

    if (GetRgnBox(region, &r) == 0) {
        invalidate();
        return;
    }

    IntRect rect(IntPoint(r.left, r.top), IntSize(r.right-r.left, r.bottom-r.top));
    invalidateRect(rect);
}

void PluginView::forceRedraw()
{
    if (m_isWindowed)
        ::UpdateWindow(platformPluginWidget());
    else
        ::UpdateWindow(windowHandleForPageClient(parent() ? parent()->hostWindow()->platformPageClient() : 0));
}

bool PluginView::platformStart()
{
    ASSERT(m_isStarted);
    ASSERT(m_status == PluginStatusLoadedSuccessfully);

    if (m_isWindowed) {
        registerPluginView();
#if !OS(WINCE)
        setUpOffscreenPaintingHooks(hookedBeginPaint, hookedEndPaint);
#endif

        DWORD flags = WS_CHILD;
        if (isSelfVisible())
            flags |= WS_VISIBLE;

        HWND parentWindowHandle = windowHandleForPageClient(m_parentFrame->view()->hostWindow()->platformPageClient());
        HWND window = ::CreateWindowEx(0, kWebPluginViewdowClassName, 0, flags,
                                       0, 0, 0, 0, parentWindowHandle, 0, WebCore::instanceHandle(), 0);

#if OS(WINDOWS) && PLATFORM(GTK)
        m_window = window;
#else
        setPlatformWidget(window);
#endif

        // Calling SetWindowLongPtrA here makes the window proc ASCII, which is required by at least
        // the Shockwave Director plug-in.
#if OS(WINDOWS) && CPU(X86_64)
        ::SetWindowLongPtrA(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)DefWindowProcA);
#elif OS(WINCE)
        ::SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)DefWindowProc);
#else
        ::SetWindowLongPtrA(platformPluginWidget(), GWL_WNDPROC, (LONG)DefWindowProcA);
#endif
        SetProp(platformPluginWidget(), kWebPluginViewProperty, this);

        m_npWindow.type = NPWindowTypeWindow;
        m_npWindow.window = platformPluginWidget();
    } else {
        m_npWindow.type = NPWindowTypeDrawable;
        m_npWindow.window = 0;
    }

    updatePluginWidget();

    if (!m_plugin->quirks().contains(PluginQuirkDeferFirstSetWindowCall))
        setNPWindowRect(frameRect());

    return true;
}

void PluginView::platformDestroy()
{
    if (!platformPluginWidget())
        return;

    DestroyWindow(platformPluginWidget());
    setPlatformPluginWidget(0);
}

PassRefPtr<Image> PluginView::snapshot()
{
#if !PLATFORM(GTK) && !USE(WINGDI)
    auto hdc = adoptGDIObject(::CreateCompatibleDC(0));

    if (!m_isWindowed) {
        // Enable world transforms.
        SetGraphicsMode(hdc.get(), GM_ADVANCED);

        XFORM transform;
        GetWorldTransform(hdc.get(), &transform);

        // Windowless plug-ins assume that they're drawing onto the view's DC.
        // Translate the context so that the plug-in draws at (0, 0).
        ASSERT(parent()->isFrameView());
        IntPoint position = toFrameView(parent())->contentsToWindow(frameRect()).location();
        transform.eDx = -position.x();
        transform.eDy = -position.y();
        SetWorldTransform(hdc.get(), &transform);
    }

    void* bits;
    BitmapInfo bmp = BitmapInfo::createBottomUp(frameRect().size());
    auto hbmp = adoptGDIObject(::CreateDIBSection(0, &bmp, DIB_RGB_COLORS, &bits, 0, 0));

    HBITMAP hbmpOld = static_cast<HBITMAP>(SelectObject(hdc.get(), hbmp.get()));

    paintIntoTransformedContext(hdc.get());

    SelectObject(hdc.get(), hbmpOld);

    return BitmapImage::create(hbmp.get());
#else
    return 0;
#endif
}

} // namespace WebCore


text:
<?php

namespace Robot\Core\BaseClasses;

use Robot\Core\Contracts\IMessageTypes;
use Robot\Core\Contracts\IUserTypes;

class BaseUser implements IUserTypes
{
    protected $chat_id;
    function __construct($chat_id)
    {
        $this->chat_id = $chat_id;
    }

    function __get($name)
    {
        if($name=='chat_id')
        {
            return $this->chat_id;
        }
    }

    function send(IMessageTypes $message)
    {
        $message->sendTo($this);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*	$NetBSD: auth.h,v 1.15 2000/06/02 22:57:55 fvdl Exp $	*/

/*
 * Copyright (c) 2009, Sun Microsystems, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of Sun Microsystems, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *	from: @(#)auth.h 1.17 88/02/08 SMI
 *	from: @(#)auth.h	2.3 88/08/07 4.0 RPCSRC
 *	from: @(#)auth.h	1.43 	98/02/02 SMI
 * $FreeBSD: src/include/rpc/auth.h,v 1.20 2003/01/01 18:48:42 schweikh Exp $
 */

/*
 * auth.h, Authentication interface.
 *
 * Copyright (C) 1984, Sun Microsystems, Inc.
 *
 * The data structures are completely opaque to the client.  The client
 * is required to pass an AUTH * to routines that create rpc
 * "sessions".
 */

#ifndef _TIRPC_AUTH_H
#define  _TIRPC_AUTH_H

#include <rpc/xdr.h>
#include <rpc/clnt_stat.h>
#include <sys/socket.h>
#include <sys/types.h>

#define MAX_AUTH_BYTES	400
#define MAXNETNAMELEN	255	/* maximum length of network user's name */

/*
 *  Client side authentication/security data
 */

typedef struct sec_data {
	u_int	secmod;		/* security mode number e.g. in nfssec.conf */
	u_int	rpcflavor;	/* rpc flavors:AUTH_UNIX,AUTH_DES,RPCSEC_GSS */
	int	flags;		/* AUTH_F_xxx flags */
	caddr_t data;		/* opaque data per flavor */
} sec_data_t;

#ifdef _SYSCALL32_IMPL
struct sec_data32 {
	uint32_t secmod;	/* security mode number e.g. in nfssec.conf */
	uint32_t rpcflavor;	/* rpc flavors:AUTH_UNIX,AUTH_DES,RPCSEC_GSS */
	int32_t flags;		/* AUTH_F_xxx flags */
	caddr32_t data;		/* opaque data per flavor */
};
#endif /* _SYSCALL32_IMPL */

/*
 * AUTH_DES flavor specific data from sec_data opaque data field.
 * AUTH_KERB has the same structure.
 */
typedef struct des_clnt_data {
	struct netbuf	syncaddr;	/* time sync addr */
	struct knetconfig *knconf;	/* knetconfig info that associated */
					/* with the syncaddr. */
	char		*netname;	/* server's netname */
	int		netnamelen;	/* server's netname len */
} dh_k4_clntdata_t;

#ifdef _SYSCALL32_IMPL
struct des_clnt_data32 {
	struct netbuf32 syncaddr;	/* time sync addr */
	caddr32_t knconf;		/* knetconfig info that associated */
					/* with the syncaddr. */
	caddr32_t netname;		/* server's netname */
	int32_t netnamelen;		/* server's netname len */
};
#endif /* _SYSCALL32_IMPL */

/*
 * authentication/security specific flags
 */
#define AUTH_F_RPCTIMESYNC	0x001	/* use RPC to do time sync */
#define AUTH_F_TRYNONE		0x002	/* allow fall back to AUTH_NONE */

/*
 * Status returned from authentication check
 */
enum auth_stat {
	AUTH_OK=0,
	/*
	 * failed at  remote end
	 */
	AUTH_BADCRED=1,			/* bogus credentials (seal broken) */
	AUTH_REJECTEDCRED=2,		/* client should begin new session */
	AUTH_BADVERF=3,			/* bogus verifier (seal broken) */
	AUTH_REJECTEDVERF=4,		/* verifier expired or was replayed */
	AUTH_TOOWEAK=5,			/* rejected due to security reasons */
	/*
	 * failed locally
	*/
	AUTH_INVALIDRESP=6,		/* bogus response verifier */
	AUTH_FAILED=7,			/* some unknown reason */
	/*
	 * kerberos errors
	 */
	AUTH_KERB_GENERIC = 8,		/* kerberos generic error */
	AUTH_TIMEEXPIRE = 9,		/* time of credential expired */
	AUTH_TKT_FILE = 10,		/* something wrong with ticket file */
	AUTH_DECODE = 11,		/* can't decode authenticator */
	AUTH_NET_ADDR = 12,		/* wrong net address in ticket */
	/*
	 * RPCSEC_GSS errors
	 */
	RPCSEC_GSS_CREDPROBLEM = 13,
	RPCSEC_GSS_CTXPROBLEM = 14

};

typedef u_int32_t u_int32;	/* 32-bit unsigned integers */

union des_block {
	struct {
		u_int32_t high;
		u_int32_t low;
	} key;
	char c[8];
};
typedef union des_block des_block;
#ifdef __cplusplus
extern "C" {
#endif
extern bool_t xdr_des_block(XDR *, des_block *);
#ifdef __cplusplus
}
#endif

/*
 * Authentication info.  Opaque to client.
 */
struct opaque_auth {
	enum_t	oa_flavor;		/* flavor of auth */
	caddr_t	oa_base;		/* address of more auth stuff */
	u_int	oa_length;		/* not to exceed MAX_AUTH_BYTES */
};

/*
 * Auth handle, interface to client side authenticators.
 */
typedef struct __auth {
	struct	opaque_auth	ah_cred;
	struct	opaque_auth	ah_verf;
	union	des_block	ah_key;
	struct auth_ops {
		void	(*ah_nextverf) (struct __auth *);
		/* nextverf & serialize */
		int	(*ah_marshal) (struct __auth *, XDR *);
		/* validate verifier */
		int	(*ah_validate) (struct __auth *,
			    struct opaque_auth *);
		/* refresh credentials */
		int	(*ah_refresh) (struct __auth *, void *);
		/* destroy this structure */
		void	(*ah_destroy) (struct __auth *);
		/* encode data for wire */
		int     (*ah_wrap) (struct __auth *, XDR *, xdrproc_t, caddr_t);
		/* decode data for wire */
		int     (*ah_unwrap) (struct __auth *, XDR *, xdrproc_t, caddr_t);

	} *ah_ops;
	void *ah_private;
} AUTH;

/*
 * Authentication ops.
 * The ops and the auth handle provide the interface to the authenticators.
 *
 * AUTH	*auth;
 * XDR	*xdrs;
 * struct opaque_auth verf;
 */
#define AUTH_NEXTVERF(auth)		\
		((*((auth)->ah_ops->ah_nextverf))(auth))
#define auth_nextverf(auth)		\
		((*((auth)->ah_ops->ah_nextverf))(auth))

#define AUTH_MARSHALL(auth, xdrs)	\
		((*((auth)->ah_ops->ah_marshal))(auth, xdrs))
#define auth_marshall(auth, xdrs)	\
		((*((auth)->ah_ops->ah_marshal))(auth, xdrs))

#define AUTH_VALIDATE(auth, verfp)	\
		((*((auth)->ah_ops->ah_validate))((auth), verfp))
#define auth_validate(auth, verfp)	\
		((*((auth)->ah_ops->ah_validate))((auth), verfp))

#define AUTH_REFRESH(auth, msg)		\
		((*((auth)->ah_ops->ah_refresh))(auth, msg))
#define auth_refresh(auth, msg)		\
		((*((auth)->ah_ops->ah_refresh))(auth, msg))

#define AUTH_DESTROY(auth)		\
		((*((auth)->ah_ops->ah_destroy))(auth));
#define auth_destroy(auth)		\
		((*((auth)->ah_ops->ah_destroy))(auth));

#define AUTH_WRAP(auth, xdrs, xfunc, xwhere)            \
		((*((auth)->ah_ops->ah_wrap))(auth, xdrs, \
		xfunc, xwhere))
#define auth_wrap(auth, xdrs, xfunc, xwhere)            \
		((*((auth)->ah_ops->ah_wrap))(auth, xdrs, \
		xfunc, xwhere))

#define AUTH_UNWRAP(auth, xdrs, xfunc, xwhere)          \
		((*((auth)->ah_ops->ah_unwrap))(auth, xdrs, \
		xfunc, xwhere))
#define auth_unwrap(auth, xdrs, xfunc, xwhere)          \
		((*((auth)->ah_ops->ah_unwrap))(auth, xdrs, \
		xfunc, xwhere))

#ifdef __cplusplus
extern "C" {
#endif
extern struct opaque_auth _null_auth;
#ifdef __cplusplus
}
#endif

/*
 * Any style authentication.  These routines can be used by any
 * authentication style that does not use the wrap/unwrap functions.
 */
int authany_wrap(void), authany_unwrap(void);

/*
 * These are the various implementations of client side authenticators.
 */

/*
 * System style authentication
 * AUTH *authunix_create(machname, uid, gid, len, aup_gids)
 *	char *machname;
 *	int uid;
 *	int gid;
 *	int len;
 *	int *aup_gids;
 */
#ifdef __cplusplus
extern "C" {
#endif
extern AUTH *authunix_create(char *, uid_t, uid_t, int, uid_t *);
extern AUTH *authunix_create_default(void);	/* takes no parameters */
extern AUTH *authnone_create(void);		/* takes no parameters */
#ifdef __cplusplus
}
#endif
/*
 * DES style authentication
 * AUTH *authsecdes_create(servername, window, timehost, ckey)
 * 	char *servername;		- network name of server
 *	u_int window;			- time to live
 * 	const char *timehost;			- optional hostname to sync with
 * 	des_block *ckey;		- optional conversation key to use
 */
#ifdef __cplusplus
extern "C" {
#endif
extern AUTH *authdes_create (char *, u_int, struct sockaddr *, des_block *);
extern AUTH *authdes_pk_create (char *, netobj *, u_int,
				struct sockaddr *, des_block *);
extern AUTH *authdes_seccreate (const char *, const u_int, const  char *,
    const  des_block *);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
extern bool_t xdr_opaque_auth		(XDR *, struct opaque_auth *);
#ifdef __cplusplus
}
#endif

#define authsys_create(c,i1,i2,i3,ip) authunix_create((c),(i1),(i2),(i3),(ip))
#define authsys_create_default() authunix_create_default()

/*
 * Netname manipulation routines.
 */
#ifdef __cplusplus
extern "C" {
#endif
extern int getnetname(char *);
extern int host2netname(char *, const char *, const char *);
extern int user2netname(char *, const uid_t, const char *);
extern int netname2user(char *, uid_t *, gid_t *, int *, gid_t *);
extern int netname2host(char *, char *, const int);
extern void passwd2des ( char *, char * );
#ifdef __cplusplus
}
#endif

/*
 *
 * These routines interface to the keyserv daemon
 *
 */
#ifdef __cplusplus
extern "C" {
#endif
extern int key_decryptsession(const char *, des_block *);
extern int key_encryptsession(const char *, des_block *);
extern int key_gendes(des_block *);
extern int key_setsecret(const char *);
extern int key_secretkey_is_set(void);
#ifdef __cplusplus
}
#endif

/*
 * Publickey routines.
 */
#ifdef __cplusplus
extern "C" {
#endif
extern int getpublickey (const char *, char *);
extern int getpublicandprivatekey (char *, char *);
extern int getsecretkey (char *, char *, char *);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
struct svc_req;
struct rpc_msg;
enum auth_stat _svcauth_none (struct svc_req *, struct rpc_msg *);
enum auth_stat _svcauth_short (struct svc_req *, struct rpc_msg *);
enum auth_stat _svcauth_unix (struct svc_req *, struct rpc_msg *);
enum auth_stat _svcauth_gss (struct svc_req *, struct rpc_msg *, bool_t *);
#ifdef __cplusplus
}
#endif

#define AUTH_NONE	0		/* no authentication */
#define	AUTH_NULL	0		/* backward compatibility */
#define	AUTH_SYS	1		/* unix style (uid, gids) */
#define AUTH_UNIX	AUTH_SYS
#define	AUTH_SHORT	2		/* short hand unix style */
#define AUTH_DH		3		/* for Diffie-Hellman mechanism */
#define AUTH_DES	AUTH_DH		/* for backward compatibility */
#define AUTH_KERB	4		/* kerberos style */
#define RPCSEC_GSS	6		/* RPCSEC_GSS */

#endif /* !_TIRPC_AUTH_H */


text:
class UsersController < ApplicationController
  include UsersHelper
  def new
  end

  def create
    @user = User.new(user_params)
    if user_params[ :password ] == user_params[ :password_confirmation ]
      if @user.save
        session[:user_id] = @user.id
        redirect_to categories_path
      else
        @errors = @user.errors.full_messages
        render template: '/users/new'
      end
    else
      @user.save
      @errors = @user.errors.full_messages
      render template: '/users/new'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  def secret
  end

  def new_judge
    if check_tokens( params[:secret][:secret_key] )
      @token = params[:secret][:secret_key]
      render template: '/users/new_judge'
    else
      @error = 'Your token is either no longer valid or incorrect!'
      render template: '/users/secret'
    end
  end

  def create_judge
    token = params[ :user ][ :judge_token ]
    if check_tokens( token )
      @user = User.new( user_params )
      if @user.save
        @user.update_attributes( judge: true )
        update_token = Token.find_by( token: token )
        update_token.update_attributes( active: false )
        session[ :user_id ] = @user.id
        redirect_to root_path
      else
        @errors = @user.errors.full_messages
        render template: '/users/new_judge'
      end
    else
      redirect_to root_path
    end
  end

  def judges
    @judges=User.where(:judge => true)

  end

  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :judge, :judge_token, :organizer)
  end
end


text:
package org.zstack.test.storage.primary;

import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.cluster.ClusterInventory;
import org.zstack.header.host.HostInventory;
import org.zstack.header.message.MessageReply;
import org.zstack.header.simulator.storage.primary.SimulatorPrimaryStorageDetails;
import org.zstack.header.storage.primary.*;
import org.zstack.header.zone.ZoneInventory;
import org.zstack.test.*;
import org.zstack.utils.Utils;
import org.zstack.utils.data.SizeUnit;
import org.zstack.utils.logging.CLogger;

public class TestReturnPrimaryStorage {
    CLogger logger = Utils.getLogger(TestReturnPrimaryStorage.class);
    Api api;
    ComponentLoader loader;
    DatabaseFacade dbf;
    CloudBus bus;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        BeanConstructor con = new WebBeanConstructor();
        /* This loads spring application context */
        loader = con.addXml("PortalForUnitTest.xml").addXml("Simulator.xml")
                .addXml("PrimaryStorageManager.xml").addXml("ZoneManager.xml")
                .addXml("ClusterManager.xml").addXml("HostManager.xml").addXml("ConfigurationManager.xml").addXml("AccountManager.xml").build();
        dbf = loader.getComponent(DatabaseFacade.class);
        bus = loader.getComponent(CloudBus.class);
        api = new Api();
        api.startServer();
    }

    @After
    public void tearDown() throws Exception {
        api.stopServer();
    }

    @Test
    public void test() throws ApiSenderException, InterruptedException {
        long requiredSize = SizeUnit.GIGABYTE.toByte(10);
        SimulatorPrimaryStorageDetails sp = new SimulatorPrimaryStorageDetails();
        sp.setTotalCapacity(SizeUnit.TERABYTE.toByte(10));
        sp.setAvailableCapacity(sp.getTotalCapacity());
        sp.setUrl("nfs://simulator/primary/");
        PrimaryStorageInventory pinv = api.createSimulatoPrimaryStorage(1, sp).get(0);
        ZoneInventory zone = api.createZones(1).get(0);
        ClusterInventory cluster = api.createClusters(1, zone.getUuid()).get(0);
        HostInventory host = api.createHost(1, cluster.getUuid()).get(0);
        api.attachPrimaryStorage(cluster.getUuid(), pinv.getUuid());

        AllocatePrimaryStorageMsg msg = new AllocatePrimaryStorageMsg();
        msg.setRequiredHostUuid(host.getUuid());
        msg.setSize(requiredSize);
        msg.setServiceId(bus.makeLocalServiceId(PrimaryStorageConstant.SERVICE_ID));
        MessageReply reply = bus.call(msg);
        Assert.assertEquals(AllocatePrimaryStorageReply.class, reply.getClass());
        AllocatePrimaryStorageReply ar = (AllocatePrimaryStorageReply) reply;
        Assert.assertEquals(pinv.getUuid(), ar.getPrimaryStorageInventory().getUuid());

        IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
        imsg.setDiskSize(requiredSize);
        imsg.setPrimaryStorageUuid(pinv.getUuid());
        imsg.setServiceId(bus.makeLocalServiceId(PrimaryStorageConstant.SERVICE_ID));
        bus.send(imsg);
        Thread.sleep(2000);
        PrimaryStorageVO pvo = dbf.findByUuid(pinv.getUuid(), PrimaryStorageVO.class);
        Assert.assertEquals(pvo.getCapacity().getTotalCapacity(), pvo.getCapacity().getAvailableCapacity());
    }
}


text:
<?php
namespace works\action\api;

use works\action\BaseAction;

class TemplateAction extends BaseAction{}


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
    android:focusableInTouchMode="true"
    android:focusable="true"
    android:clickable="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:animateLayoutChanges="true"
            android:orientation="vertical">

            <FrameLayout
                android:id="@+id/frame_indent2"
                android:layout_width="match_parent"
                android:layout_height="5dp"
                android:visibility="gone"/>

        </LinearLayout>

        <!-- android:scaleType="fitXY" -->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/SOSRed">

            <TextView
                android:id="@+id/textView"
                style="@style/TextButton"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="@dimen/activity_horizontal_margin"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:paddingBottom="@dimen/c_padding"
                android:paddingTop="@dimen/st_padding"
                android:text="@string/password"
                android:textAppearance="?android:attr/textAppearanceLarge"/>

        </LinearLayout>

        <EditText
            android:id="@+id/edt_msg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="top"
            android:padding="@dimen/st_padding"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:phoneNumber="false"
            android:singleLine="true"
            android:password="true"
            android:inputType="textPassword" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/lock_with_password"
            android:id="@+id/fst_sos_lock" />

        <!-- Don't touch it. it's magic-->

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="bottom">

        <Button
            android:id="@+id/btn_save"
            style="@style/TextButton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/btn_sel"
            android:padding="@dimen/st_padding"
            android:singleLine="true"
            android:text="@string/btn_save" />
    </LinearLayout>

</LinearLayout>


text:
const debug = require('./../debug');

module.exports = (path) => debug(`studio/${path}`);


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace AppBundle\Component;

use JMS\DiExtraBundle\Annotation as DI;
use AppBundle\Entity\User;
use AppBundle\Entity\UserRepository;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
use Symfony\Component\Security\Core\Util\SecureRandom;

/**
 * @DI\Service("app.component.usermanager")
 */
class UserManager
{

    /**
     * @var UserPasswordEncoder
     */
    private $encoder;

    /**
     * @var SwiftMailer
     */
    private $mailer;

    /**
     * @DI\InjectParams({
     *     "encoder" = @DI\Inject("security.password_encoder"),
     *     "mailer" =  @DI\Inject("mailer")
     * })
     */
    public function __construct( UserPasswordEncoder $encoder, $mailer)
    {
        $this->encoder  = $encoder;
        $this->mailer = $mailer;
    }

    /**
     * Hash the users password
     * @param User $user
     */
    public function hashUserPassword(User $user)
    {
       $hashedPassword =  $this->encoder->encodePassword($user, $user->getPassword());
       $user->setPassword($hashedPassword);
    }

    /**
     * Resets the users password, and returns the unhashed password
     * @param User $user
     * @return string
     */
    public function resetPassword(User $user)
    {
        $securityRandom = new SecureRandom();
        $password = $securityRandom->nextBytes(8);
        $user->setPassword($password);
        $this->hashUserPassword($user);
        return $password;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Lilloa 22: 553 (1951)

#### Original name
Hebeloma verruculosum Murrill

### Remarks
null


text:
package com.sample.app;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;

public class SecondActivity extends ActionBarActivity{
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        String result = getIntent().getStringExtra("result");
        tvResult = (TextView) findViewById(R.id.tvResult);
        tvResult.setText(result);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://www.knime.org/2008/09/XMLConfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.knime.org/2008/09/XMLConfig http://www.knime.org/XMLConfig_2008_09.xsd" key="settings.xml">
<entry key="node_file" type="xstring" value="settings.xml"/>
<config key="flow_stack"/>
<config key="internal_node_subsettings">
<entry key="memory_policy" type="xstring" value="CacheSmallInMemory"/>
</config>
<config key="model">
<entry key="classColumn" type="xstring" value="Col20"/>
<config key="positiveClass">
<entry key="datacell" type="xstring" value="org.knime.core.data.def.StringCell"/>
<config key="org.knime.core.data.def.StringCell">
<entry key="StringCell" type="xstring" value="1"/>
</config>
</config>
<config key="curves">
<entry key="array-size" type="xint" value="1"/>
<entry key="0" type="xstring" value="P (Col20=1)probability"/>
</config>
<entry key="maxPoints" type="xint" value="2000"/>
</config>
<config key="nodeAnnotation">
<entry key="text" type="xstring" value="score the model"/>
<entry key="bgcolor" type="xint" value="16777215"/>
<entry key="x-coordinate" type="xint" value="378"/>
<entry key="y-coordinate" type="xint" value="306"/>
<entry key="width" type="xint" value="101"/>
<entry key="height" type="xint" value="15"/>
<entry key="alignment" type="xstring" value="CENTER"/>
<config key="styles"/>
</config>
<entry key="customDescription" type="xstring" isnull="true" value=""/>
<entry key="state" type="xstring" value="IDLE"/>
<entry key="factory" type="xstring" value="org.knime.base.node.viz.roc.ROCNodeFactory"/>
<entry key="node-name" type="xstring" value="ROC Curve"/>
<entry key="node-bundle-name" type="xstring" value="KNIME Base Nodes"/>
<entry key="node-bundle-symbolic-name" type="xstring" value="org.knime.base"/>
<entry key="node-bundle-vendor" type="xstring" value="KNIME GmbH, Konstanz, Germany"/>
<entry key="node-bundle-version" type="xstring" value="2.11.2.0046096"/>
<config key="factory_settings"/>
<entry key="name" type="xstring" value="ROC Curve"/>
<entry key="hasContent" type="xboolean" value="false"/>
<entry key="isInactive" type="xboolean" value="false"/>
<config key="ports">
<config key="port_1">
<entry key="index" type="xint" value="1"/>
<entry key="port_dir_location" type="xstring" isnull="true" value=""/>
</config>
</config>
<config key="filestores">
<entry key="file_store_location" type="xstring" isnull="true" value=""/>
<entry key="file_store_id" type="xstring" isnull="true" value=""/>
</config>
</config>


text:
package org.jclouds.azurecompute.features;

import static com.google.common.collect.Iterables.transform;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

import org.jclouds.azurecompute.domain.AffinityGroup;
import org.jclouds.azurecompute.domain.Disk;
import org.jclouds.azurecompute.domain.Location;
import org.jclouds.azurecompute.domain.OSImage;
import org.jclouds.azurecompute.internal.AbstractAzureComputeApiLiveTest;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;

@Test(groups = "live", testName = "DiskApiLiveTest")
public class DiskApiLiveTest extends AbstractAzureComputeApiLiveTest {

   private ImmutableSet<String> locations;

   private ImmutableSet<String> images;

   private ImmutableSet<String> groups;

   @BeforeClass(groups = {"integration", "live"})
   @Override
   public void setup() {
      super.setup();

      locations = ImmutableSet.copyOf(transform(api.getLocationApi().list(),
              new Function<Location, String>() {

                 @Override
                 public String apply(final Location location) {
                    return location.name();
                 }
              }));
      images = ImmutableSet.copyOf(transform(api.getOSImageApi().list(), new Function<OSImage, String>() {

         @Override
         public String apply(final OSImage image) {
            return image.name();
         }
      }));
      groups = ImmutableSet.copyOf(transform(api.getAffinityGroupApi().list(), new Function<AffinityGroup, String>() {

         @Override
         public String apply(final AffinityGroup group) {
            return group.name();
         }
      }));
   }

   public void testList() {
      for (Disk disk : api().list()) {
         checkDisk(disk);
      }
   }

   // TODO testDeleteDisk, if we will need testCreateDisk
   private void checkDisk(Disk disk) {
      assertNotNull(disk.name(), "Name cannot be null for: " + disk);

      if (disk.attachedTo() != null) {
         // TODO: verify you can lookup the role
      }

      if (disk.logicalSizeInGB() != null) {
         assertTrue(disk.logicalSizeInGB() > 0, "LogicalSizeInGB should be positive, if set" + disk);
      }

      if (disk.mediaLink() != null) {
         assertTrue(ImmutableSet.of("http", "https").contains(disk.mediaLink().getScheme()),
                 "MediaLink should be an http(s) url" + disk);
      }

      if (disk.location() != null) {
         assertTrue(locations.contains(disk.location()), "Location not in " + locations + " :" + disk);
      }

      if (disk.sourceImage() != null) {
         assertTrue(images.contains(disk.sourceImage()), "SourceImage not in " + images + " :" + disk);
      }

      if (disk.affinityGroup() != null) {
         assertTrue(groups.contains(disk.affinityGroup()), "AffinityGroup not in " + groups + " :" + disk);
      }
   }

   private DiskApi api() {
      return api.getDiskApi();
   }
}


text:
> Play | Pause | Repeat

Loops is a first attempt at making a Single Page Web App (SPA) built using JS, Backbone and Flask (python).
Started as an experiment to learn HTML5 Audio it quickly turned into a music player with a slew of handy features like cross-browser support, keyboard shortcuts, playlist functionality and live display of artist and track info.
Loops can be used a replacement for your desktop music player if you're geeky enough to get it up and running. Future versions of this player will be packed with more features that will add support for large libraries.

## Dependancies
- Flask
- eyeD3 (for reading ID3 tags)

## Contributors
- [Prakhar Srivastav](https://github.com/prakhar1989)
- [Shashank Srivastav](https://github.com/shashankgroovy)

## Usage and Installation
- Step 0 - `pip install eyed3`
- Step 1 - Create a db of songs. Open the file `create_db.py` and change the
`songs_dir` to point to your music directory. Now run the script
``` python add_songs.py ```
If this has proceeded with no errors, you'll see a `loops.db` file in your
directory
- Step 2 - Deploy this app on a server of your choice and voila!

## Screenshots
![Image](https://dl.dropboxusercontent.com/u/9555677/loops/song3.png)
![Image](https://dl.dropboxusercontent.com/u/9555677/loops/song2.png)
![Image](https://dl.dropboxusercontent.com/u/9555677/loops/song1.png)


text:
using UnityEngine;
using System.Collections;

//sprint code

[RequireComponent (typeof(Holojam.Tools.Pairable))]
public class GestureListener : MonoBehaviour
{
	public float range = 9, speed = 0.45f;
	public float shakeAmount = 0.05f, shakeForce = 7;
	public float recordTime = 0.9f;
	public float cooldown = 1;
	public float lerpTime = 0.8f;

	[Space (8)]
	public Vector2 magnitudeRange = new Vector2 (0.1f, 0.45f);
	public float resultScale = 1;

	[Space (8)]
	public Transform table;
	public float tableSize = 0.45f;

	[Space (8)]
	public bool robotSynced = true;
	//
	public GestureTarget target;
	public float weight, mark;
	public bool recording = false;
	Vector3 initialPoint, startPosition, endPosition;

	Holojam.Tools.Pairable p;

	public GameObject robotCtrl;

	void Awake ()
	{
		if (!Holojam.Utility.IsMasterPC ())
			Destroy (this);
		p = GetComponent<Holojam.Tools.Pairable> ();
	}

	RaycastHit hit;

	void Update ()
	{
		if (!recording && Physics.Raycast (p.center, -transform.up, out hit, range)) {
			GestureTarget gt = hit.transform.GetComponent<GestureTarget> ();
			if (gt != null && !gt.locked && !gt.controlled) {
				if (target != null)
					ResetTarget (target);
				target = gt;
				gt.controllable = false;
				gt.locked = true;
				initialPoint = target.transform.position;
			}
		} else if (!recording && target != null) {
			target.controllable = true;
			ResetTarget (target);
		}

		if (target != null || recording) {
			weight += speed * Time.deltaTime;
			if (weight < 1) {
				target.transform.position = Vector3.Lerp (target.transform.position,
					initialPoint + Random.insideUnitSphere * shakeAmount,
					shakeForce * weight * Time.deltaTime
				);
			} else if (!recording) {
				target.transform.position = initialPoint;
				mark = Time.time;
				startPosition = p.center;
				recording = true;
				target.highlight = true;
			} else if (Time.time > mark + recordTime) {
				endPosition = p.center;
				ProcessGesture ();
				recording = false;
			}
		}

		//Debug
		Debug.DrawRay (p.center, -transform.up * range, Color.yellow);
	}

	void ProcessGesture ()
	{
		Transform targetRef = target.transform;
		ResetTarget (target, true);

		//Debug
		Debug.DrawRay (startPosition, Vector3.up, Color.blue, 4);
		Debug.DrawRay (endPosition, Vector3.up, Color.blue, 4);

		Vector3 direction = endPosition - startPosition;
		direction = new Vector3 (direction.x, 0, direction.z);
		if (direction.magnitude < magnitudeRange.x) {
			Debug.Log ("No gesture detected.");
			targetRef.GetComponent<GestureTarget> ().controllable = true; //uneeded
			return;
		}
		float strength = direction.magnitude / (magnitudeRange.y - magnitudeRange.x) + magnitudeRange.x; //broken
		strength = Mathf.Min (strength, 1) * resultScale;
		//print(direction.magnitude);

		direction = Vector3.Normalize (direction) * strength;

		//Debug
		Debug.DrawRay (initialPoint, direction, Color.magenta, 4);

		Vector3 exitPoint = initialPoint + direction;
		exitPoint = table.InverseTransformPoint (exitPoint);
		float x = exitPoint.x > tableSize ? tableSize : exitPoint.x < -tableSize ? -tableSize : exitPoint.x;
		float z = exitPoint.z > tableSize ? tableSize : exitPoint.z < -tableSize ? -tableSize : exitPoint.z;

		exitPoint = new Vector3 (x, exitPoint.y, z);
		exitPoint = table.TransformPoint (exitPoint);

		robotSynced = false;
		//tell robot to do something with exitPoint <-- position
		//make sure you set that to true when you're done
		robotCtrl.GetComponent<realBeerCtrl>().setDestination(exitPoint);

		//targetRef.position = exitPoint;
		StartCoroutine (LerpPosition (targetRef, exitPoint));
	}

	IEnumerator LerpPosition (Transform reference, Vector3 exit)
	{
		Vector3 start = reference.position;
		float startTime = Time.time;
		while (reference.position != exit) {
			reference.position = Vector3.Lerp (start, exit, (Time.time - startTime) / lerpTime);
			yield return null;
		}
	}

	void ResetTarget (GestureTarget gt, bool cool = false)
	{
		StartCoroutine (Reset (gt, cool));
	}

	IEnumerator Reset (GestureTarget gt, bool cool = false)
	{
		target = null;
		gt.highlight = false;
		weight = 0;
		if (cool) {
			print ("cool started");
			yield return new WaitForSeconds (cooldown);
			print ("cool ended");
			//robot
			gt.loading = true;
			while (!robotSynced)
				yield return null;
			gt.controllable = true;
		}
		gt.loading = false;
		gt.locked = false;
		gt = null;
	}
}


text:
package io.mycat.sqlengine;

public class SQLQueryResult<T> {
private final T result;
private final boolean success;

public SQLQueryResult(T result, boolean success) {
	super();
	this.result = result;
	this.success = success;
}
public T getResult() {
	return result;
}

public boolean isSuccess() {
	return success;
}

}


text:
package net.i2geo.onto.tasks;

import net.i2geo.onto.GeoSkillsAccess;
import net.i2geo.onto.parse.GeoSkillsParseListener;
import org.semanticweb.owl.model.*;
import org.semanticweb.owl.vocab.OWLRDFVocabulary;

import java.util.*;
import java.net.URI;

/**
 */
public class GeoSkillsParser {

    public GeoSkillsParser() {
        this(null);
    }

    public GeoSkillsParser(String urlToOntology) {
        if(urlToOntology==null)
            urlToOntology = GeoSkillsAccess.geoSkillsDevUrl;
        this.urlToOntology = urlToOntology;
    }

    public void setUrlToOntology(String url) {
        this.urlToOntology = url;
    }

    private String urlToOntology = null;
    GeoSkillsAccess access;

    public void runParser(GeoSkillsParseListener listener) throws Exception {

        this.access = new GeoSkillsAccess(urlToOntology);
        this.access.open();

        // first notify of IDs

        for(OWLClass cls: access.getDescendantClasses(access.getTopicClass())) {
            listener.thereIsItem(cls.getURI().toASCIIString(),
                    GeoSkillsParseListener.TYPE_TOPIC_CLASS);
        }
        for(OWLClass cls: access.getDescendantClasses(access.getCompetencyClass())) {
            listener.thereIsItem(cls.getURI().toASCIIString(),
                    GeoSkillsParseListener.TYPE_COMPETENCY_CLASS);
        }
        for(OWLIndividual i: access.getIndividualsOfClass(access.getTopicClass())) {
            listener.thereIsItem(i.getURI().toASCIIString(),
                    GeoSkillsParseListener.TYPE_TOPIC);
        }
        for(OWLIndividual i: access.getIndividualsOfClass(access.getCompetencyClass())) {
            listener.thereIsItem(i.getURI().toASCIIString(),
                    GeoSkillsParseListener.TYPE_COMPETENCY);
        }

        // then describe types

        Set<URI> alreadyDones = new HashSet<URI>();

        for(OWLClass i: access.getDescendantClasses(access.getTopicClass())) {
            if(alreadyDones.contains(i.getURI())) { System.err.println("Duplicate URI " + i.getURI()); continue; }
            alreadyDones.add(i.getURI());
            Set<String> parentTypes =
                access.toURIsList(i.getSuperClasses(access.getOnt()));
            listener.topicType(i.getURI().toASCIIString(), parentTypes,
                    readRDFLabels(access,i));
        }
        for(OWLClass i: access.getDescendantClasses(access.getCompetencyClass())) {
            if(alreadyDones.contains(i.getURI())) { System.err.println("Duplicate URI " + i.getURI()); continue; }
            alreadyDones.add(i.getURI());
            Set<String> parentTypes = access.toURIsList(i.getSuperClasses(access.getOnt()));
            listener.competencyType(i.getURI().toASCIIString(), parentTypes,
                    readRDFLabels(access,i));
        }

        // then describe individuals
        for(OWLIndividual i: access.getIndividualsOfClass(access.getTopicClass())) {
            if(alreadyDones.contains(i.getURI())) { System.err.println("Duplicate URI " + i.getURI()); continue; }
            alreadyDones.add(i.getURI());
            String uri = i.getURI().toASCIIString();
            Set<String> parentUris = access.toURIsList(i.getTypes(access.getOnt()));
            listener.topicDescription(uri,parentUris,makeNamesMap(i),new HereModificationData(i));
        }
        for(OWLIndividual i: access.getIndividualsOfClass(access.getCompetencyClass())) {
            if(alreadyDones.contains(i.getURI())) { System.err.println("Duplicate URI " + i.getURI()); continue; }
            alreadyDones.add(i.getURI());
            String uri = i.getURI().toASCIIString();
            Set<String> parentUris = access.toURIsList(i.getTypes(access.getOnt()));
            Set<OWLIndividual> s = i.getObjectPropertyValues(access.getOnt()).get(access.getOntologyPropertyOfName("hasTopic"));
            listener.competencyDescription(uri,parentUris,access.toURIsListIndiv(s),makeNamesMap(i),new HereModificationData(i));
        }
    }

    private NamesMap makeNamesMap(OWLIndividual i) {
        NamesMap namesMap = new NamesMap();
        Set<NameWithLanguage> alreadyDones = new HashSet<NameWithLanguage>();
        feedNamesInMap(access.getDefaultCommonNames(i),namesMap,alreadyDones,1.0f);
        feedNamesInMap(access.getCommonNames(i),namesMap,alreadyDones,0.9f);
        feedNamesInMap(access.getUnCommonNames(i),namesMap,alreadyDones,0.7f);
        feedNamesInMap(access.getRareNames(i),namesMap,alreadyDones,0.3f);
        feedNamesInMap(access.getFalseFriendNames(i),namesMap,alreadyDones,-1.0f);
        return namesMap;
    }

    private void feedNamesInMap(Map<String,Set<String>> omap, NamesMap namesMap, Set<NameWithLanguage> alreadyDones, float score) {
        for(Map.Entry<String,Set<String>> entry: omap.entrySet()) {
            if(entry==null) continue;
            String lang = GeoSkillsAccess.protectAgainstSubLanguage(entry.getKey());
            Set<GeoSkillsParseListener.NameWithFrequency> namesForLanguage = namesMap.map.get(lang);
            if(namesForLanguage==null) {
                namesForLanguage = new HashSet<GeoSkillsParseListener.NameWithFrequency>();
                namesMap.map.put(lang,namesForLanguage);
            }
            for(String s:entry.getValue()) {
                NameWithLanguage k = new NameWithLanguage(s,lang);
                if(alreadyDones.contains(k)) {// System.out.println("Removing duplicate name \"" + k.language + ": " + k.name);
                        continue;}
                alreadyDones.add(k);
                NameWithFrequencyImpl n = new NameWithFrequencyImpl();
                n.frequency = score;
                n.string = s;
                namesForLanguage.add(n);
            }
        }
    }

    private class HereModificationData implements GeoSkillsParseListener.ModificationData {
        HereModificationData(OWLIndividual i) {
            this.modificationDate = access.getModificationDate(i);
            this.creationDate = access.getCreationDate(i);
            this.modificationUserName = access.getModificationUserName(i);
            this.creationUserName = access.getCreationUserName(i);
        }
        private final Date modificationDate, creationDate;
        private final String modificationUserName, creationUserName;

        public Date getModificationDate() {
            return modificationDate;
        }

        public Date getCreationDate() {
            return creationDate;
        }

        public String getModificationUserName() {
            return modificationUserName;
        }

        public String getCreationUserName() {
            return creationUserName;
        }
    }

    public static class NamesMap implements GeoSkillsParseListener.NamesMap {
        public NamesMap(){}
        private Map<String,Set<GeoSkillsParseListener.NameWithFrequency>> map = new HashMap<String,Set<GeoSkillsParseListener.NameWithFrequency>>();
        public Iterator<String> getLanguages(){return map.keySet().iterator();}
        public Iterator<GeoSkillsParseListener.NameWithFrequency> getNames(String language)
            {return map.get(language).iterator(); }

    }

    private static class NameWithLanguage {
        private final String name;
        private final String language;
        private NameWithLanguage(String name, String language) {
            this.name = name;
            this.language = language;
        }

        public int hashCode() {
            return name.hashCode() + language.hashCode();
        }

        public boolean equals(Object o) {
            if(!(o instanceof NameWithLanguage)) return false;
            NameWithLanguage other = (NameWithLanguage) o;
            return other.language.equals(this.language) && other.name.equals(this.name);
        }
    }

    public static class NameWithFrequencyImpl implements GeoSkillsParseListener.NameWithFrequency {

        float frequency;
        String string;

        public float getFrequency() {return frequency;}
        public String getName() { return string; }
    }

    public static NamesMap readRDFLabels(GeoSkillsAccess access, OWLClass desc) {
        // TODO: this duplicates readRDFLabels(OWLEntity desc)
        NamesMap map = new NamesMap();
        for(OWLAnnotation annotation: desc.getAnnotations(access.getOnt())) {
            if(!OWLRDFVocabulary.RDFS_LABEL.getURI().equals(annotation.getAnnotationURI()))
                continue;
            OWLConstant constant = annotation.getAnnotationValueAsConstant();
            if(!constant.isTyped()) {
                OWLUntypedConstant label = constant.asOWLUntypedConstant();
                Set<GeoSkillsParseListener.NameWithFrequency> names = map.map.get(label.getLang());
                if(names==null) {
                    names = new HashSet<GeoSkillsParseListener.NameWithFrequency>();
                    map.map.put(label.getLang(),names);
                }
                NameWithFrequencyImpl name = new NameWithFrequencyImpl();
                name.frequency = 1.0f;
                name.string = label.getLiteral();
                names.add(name);
            }
        }
        return map;
    }
}


text:
#region License Agreement - READ THIS FIRST!!!

#endregion
using System;
using System.Collections;

namespace ircsharp
{
    /// <summary>
    /// Summary description for ChannelContainer.
    /// </summary>
    public class ChannelContainer : IRCBase, IEnumerable, IEnumerator
    {
        private ArrayList channels = new ArrayList();
        private ChannelListContainer channelList;
        private int _curr = -1;

		/// <summary>
		/// Occurs when the client has joined a channel, and all channel information has been retrieved (mode, topic and bans).
		/// </summary>
		/// <seealso cref="JoinCompleteEventArgs"/>
		/// <threadsafe instance="false"/>
		/// <remarks>When this event is fired by the Connection, it is fired in another thread then the original thread
		/// that created the class. Because of this you need to use the Invoke() method on your form if you're creating using Windows forms.</remarks>
		public event JoinCompleteEventHandler JoinComplete;

		/// <summary>
		/// Occurs when a user send an invitation (/INVITE) to join a channel.
		/// </summary>
		/// <seealso cref="InvitationEventArgs"/>
		/// <threadsafe instance="false"/>
		/// <remarks>When this event is fired by the Connection, it is fired in another thread then the original thread
		/// that created the class. Because of this you need to use the Invoke() method on your form if you're creating using Windows forms.</remarks>
		public event InvitationEventHandler Invitation;

		public event PartCompleteEventHandler PartComplete;

        internal ChannelContainer(ServerConnection creatorsCurrentConnection) : base(creatorsCurrentConnection)
        {
            channelList = new ChannelListContainer(creatorsCurrentConnection);
        }

        /// <summary>
        /// Gets the number of channels in the array.
        /// </summary>
        public int Count
        {
            get { return channels.Count; }
        }

        /// <summary>
        /// Gets a channel from its name.
        /// </summary>
        public Channel this[string ChannelName]
        {
            get { return GetChannel(ChannelName); }
        }

        /// <summary>
        /// Gets a channel from its array position.
        /// </summary>
        public Channel this[int Pos]
        {
            get { return GetChannel(Pos); }
        }

        /// <summary>
        /// Gtes a channel from its name.
        /// </summary>
        /// <param name="ChannelName">The channel name to find.</param>
        /// <returns>A channel.</returns>
        public Channel GetChannel(string ChannelName)
        {
            for (int x = 0; x < channels.Count; x++)
                if (((Channel)channels[x]).Name.ToLower() == ChannelName.ToLower())
                    return GetChannel(x);

            return null;
        }

        /// <summary>
        /// Gets a channel from its array position.
        /// </summary>
        /// <param name="Pos">The position in the array to return.</param>
        /// <returns>A channel.</returns>
        public Channel GetChannel(int Pos)
        {
            if (Pos >= 0 && Pos < channels.Count)
                return (Channel)channels[Pos];

            throw (new ArgumentOutOfRangeException("Pos", "Out of range"));
        }

        internal void AddChannel(Channel channel)
        {
            channels.Add(channel);
        }

        internal void RemoveChannel(string ChannelName)
        {
            for (int x = 0; x < channels.Count; x++)
                if (((Channel)channels[x]).Name.ToLower() == ChannelName.ToLower())
                    channels.RemoveAt(x);
        }

        /// <summary>
        /// Joins a channel.
        /// </summary>
        /// <param name="ChannelName">The name of the channel to join.</param>
        public void Join(string ChannelName)
        {
            base.CurrentConnection.SendData("JOIN " + ChannelName + "\r\n");
        }

        /// <summary>
        /// Joins a channel that requires a key to access.
        /// </summary>
        /// <param name="ChannelName">The name of the channel to join.</param>
        /// <param name="Key">The channel key to access the channel.</param>
        public void Join(string ChannelName, string Key)
        {
            base.CurrentConnection.SendData("JOIN " + ChannelName + " :" + Key + "\r\n");
        }

        internal void Clear()
        {
            while (channels.Count > 0)
            {
                ((Channel)channels[0]).Users.Clear();
                ((Channel)channels[0]).Bans.Clear();
                channels.RemoveAt(0);
            }
        }

        /// <summary>
        /// Gets an array of channels availible on the server.
        /// </summary>
        public ChannelListContainer List
        {
            get { return channelList; }
        }

        #region IsOnChannel
        /// <summary>
        /// Checks wheather the Connection is joined a specified channel.
        /// </summary>
        /// <param name="ChannelName">Channel to find.</param>
        /// <returns>Returns true if joined otherwise false.</returns>
        public bool IsOnChannel(string ChannelName)
        {
            for (int x = 0; x < channels.Count; x++)
                if (((Channel)channels[x]).Name.ToLower() == ChannelName.ToLower())
                    return true;
            return false;
        }

		internal bool IsUserOnAnyChannel(string Nick, string ExceptChannel)
		{
			foreach (Channel c in channels)
				if (!(ExceptChannel != null && c.Name.ToLower() == ExceptChannel.ToLower()))
					foreach (ChannelUser u in c.Users)
						if (u.User.Nick.ToLower() == Nick.ToLower())
							return true;
			return false;
		}

		internal bool IsUserOnAnyChannel(string Nick)
		{
			return IsUserOnAnyChannel(Nick, null);
		}
        #endregion

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            return this;
        }

        #endregion

        #region IEnumerator Members

        public object Current
        {
            get { return channels[_curr]; }
        }

        public bool MoveNext()
        {
            _curr++;
            if (_curr == channels.Count)
            {
                Reset();
                return false;
            }
            return true; ;
        }

        public void Reset()
        {
            _curr = -1;
        }

        #endregion

		internal void FireJoinCompleted(Channel channel)
		{
			if (this.JoinComplete != null)
				this.JoinComplete(base.CurrentConnection.Owner, new JoinCompleteEventArgs(channel));
		}

		internal void FirePartCompleted(Channel channel)
		{
			if (this.PartComplete != null)
				this.PartComplete(base.CurrentConnection.Owner, new PartCompleteEventArgs(channel));
		}

		internal void FireInvitation(User user, string channelName)
		{
			if (this.Invitation != null)
				this.Invitation(base.CurrentConnection.Owner, new InvitationEventArgs(user, channelName));
		}
	}
}


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'roomramify'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install roomramify

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it ( https://github.com/[my-github-username]/roomramify/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
import RoutingTable from './routing-table'
// eslint-disable-next-line no-unused-vars
import { Session } from 'neo4j-driver-core'

export default class Rediscovery {
  /**
   * @constructor
   * @param {object} routingContext
   */
  constructor (routingContext) {
    this._routingContext = routingContext
  }

  /**
   * Try to fetch new routing table from the given router.
   * @param {Session} session the session to use.
   * @param {string} database the database for which to lookup routing table.
   * @param {ServerAddress} routerAddress the URL of the router.
   * @param {string} impersonatedUser The impersonated user
   * @return {Promise<RoutingTable>} promise resolved with new routing table or null when connection error happened.
   */
  lookupRoutingTableOnRouter (session, database, routerAddress, impersonatedUser) {
    return session._acquireConnection(connection => {
      return this._requestRawRoutingTable(
        connection,
        session,
        database,
        routerAddress,
        impersonatedUser
      ).then(rawRoutingTable => {
        if (rawRoutingTable.isNull) {
          return null
        }
        return RoutingTable.fromRawRoutingTable(
          database,
          routerAddress,
          rawRoutingTable
        )
      })
    })
  }

  _requestRawRoutingTable (connection, session, database, routerAddress, impersonatedUser) {
    return new Promise((resolve, reject) => {
      connection.protocol().requestRoutingInformation({
        routingContext: this._routingContext,
        databaseName: database,
        impersonatedUser,
        sessionContext: {
          bookmarks: session._lastBookmarks,
          mode: session._mode,
          database: session._database,
          afterComplete: session._onComplete
        },
        onCompleted: resolve,
        onError: reject
      })
    })
  }
}


text:
.. meta::
    :author: Cask Data, Inc.
    :copyright: Copyright © 2015 Cask Data, Inc.

.. _included-apps-etl-plugins-batch-sources-s3:

====================
Batch Sources: S3
====================

.. rubric:: Description

Batch source to use Amazon S3 as a Source.

.. rubric:: Use Case

This source is used whenever you need to read from Amazon S3.
For example, you may want to read in log files from S3 every hour and then store
the logs in a TimePartitionedFileSet.

.. highlight:: xml

.. rubric:: Properties

**accessID:** Access ID of the Amazon S3 instance to connect to.

**accessKey:** Access Key of the Amazon S3 instance to connect to.

**path:** Path to file(s) to be read. If a directory is specified,
terminate the path name with a \'/\'.

**fileRegex:** Regex to filter out filenames in the path.

.. include:: ../time-filter.txt

**timeTable:** Name of the Table that keeps track of the last time files
were read in.

**inputFormatClass:** Name of the input format class, which must be a
subclass of FileInputFormat. Defaults to TextInputFormat.

**maxSplitSize:** Maximum split-size for each mapper in the MapReduce Job. Defaults to 128MB.

.. rubric:: Example

::

  {
    "name": "S3",
    "properties": {
      "accessKey": "key",
      "accessID": "ID",
      "path": "s3n://path/to/logs/",
      "fileRegex": "timefilter",
      "timeTable": "timeTable",
      "maxSplitSize": "1048576"
    }
  }

This example connects to Amazon S3 and reads in files found in the specified directory while
using the stateful ``timefilter``, which ensures that each file is read only once. The ``timefilter``
requires that files be named with either the convention "yy-MM-dd-HH..." (S3) or "...'.'yy-MM-dd-HH..."
(Cloudfront). The stateful metadata is stored in a table named 'timeTable'. With the maxSplitSize
set to 1MB, if the total size of the files being read is larger than 1MB, CDAP will
configure Hadoop to use one mapper per MB.


text:
using System.Text;

namespace Kaleidoscope.Analysis
{
	public sealed class RootTypeDeclare<T> : RootInstanceTypeDeclare where T : InstanceTypeDeclare
	{
		public readonly T Type;
		readonly string m_displayName;

		public override InstanceTypeDeclare InstanceType => Type;

		public RootTypeDeclare(Builder builder)
			: base(builder)
		{
			Type = builder.Type;

			var text = new StringBuilder();
			text.Append("[RootClassTypeDeclare] ");
			if (IsPublic) {
				text.Append("public ");
			}
			text.Append(Type.DisplayName);
			m_displayName = text.ToString();
		}

		public override string ToString()
		{
			return m_displayName;
		}

		public new sealed class Builder : RootInstanceTypeDeclare.Builder
		{
			public T Type;
		}
	}
}


text:
import React from 'react'
import styled from 'styled-components'
import { Link } from 'gatsby'

import {
  maxWidth,
  minWidth,
  PHONE,
  DESKTOP,
  SHORT_ANIMATION_DURATION,
} from '../../constants/measurements'
import { BLACK } from '../../constants/colors'
import { WORK_SANS } from '../../constants/fonts'
import {
  ABOUT_ROUTE,
  TEAM_ROUTE,
  PRODUCTS_ROUTE,
  RESOURCES_ROUTE,
  BLOG_ROUTE,
  APPLY_ROUTE,
} from '../../constants/routes'

interface ILinksProps {
  active: boolean
}

const LinksWrapper = styled.div<ILinksProps>`
  flex: 1;
  text-align: right;

  ${maxWidth(PHONE)} {
    flex: none;
    text-align: left;
    display: block;
    overflow: hidden;
    transition: max-height ${SHORT_ANIMATION_DURATION}ms ease,
      opacity ${SHORT_ANIMATION_DURATION}ms ease;
    max-height: ${({ active }) => (active ? '100vh' : '0')};
    opacity: ${({ active }) => (active ? '1' : '0')};
  }
`

const Spacer = styled.div<{}>`
  display: none;

  ${maxWidth(PHONE)} {
    display: block;
    width: 100%;
    height: 0.5rem;
  }
`

const StyledLink = styled(Link)<{}>`
  height: 2rem;
  line-height: 2rem;
  margin-left: 1rem;
  color: ${BLACK};
  opacity: 0.64;
  text-decoration: none;
  cursor: pointer;
  transition: opacity ${SHORT_ANIMATION_DURATION}ms ease;
  font-family: ${WORK_SANS};

  &:visited {
    color: ${BLACK};
  }

  &:hover,
  &:active {
    color: ${BLACK};
    opacity: 1;
    text-decoration: none;
  }

  ${minWidth(DESKTOP)} {
    margin-left: calc(1rem + 1.25vw);
  }

  ${maxWidth(PHONE)} {
    width: 100%;
    text-align: center;
    display: block;
    margin: 0.5rem 0;
    font-size: 1.2rem;
  }
`

const links: string[][] = [
  ['About', ABOUT_ROUTE],
  ['Team', TEAM_ROUTE],
  ['Products', PRODUCTS_ROUTE],
  ['Resources', RESOURCES_ROUTE],
  ['Blog', BLOG_ROUTE],
  ['Apply', APPLY_ROUTE],
]

export const Links = ({ active }: ILinksProps): React.ReactElement => (
  <LinksWrapper active={active}>
    <Spacer />
    {links.map(([text, link]) => (
      <StyledLink to={link} key={link}>
        {text}
      </StyledLink>
    ))}
  </LinksWrapper>
)


text:
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {browserHistory} from 'react-router';

export default(Comp) => {
    class AuthContainer extends Component {
        constructor(props) {
            super(props);

            this.checkAuth = this.checkAuth.bind(this);
        }

        componentWillMount() {
            this.checkAuth()
        }

        componentWillUpdate() {
            this.checkAuth()
        }

        checkAuth() {
            const {isLoggedIn} = this.props;

            if (!isLoggedIn) {
                browserHistory.push('/login');
            }
        }

        render() {
            const {props} = this;

            if (props.isLoggedIn) {
                return <Comp {...props}>{this.children}</Comp>;
            }

            return <div/>
        }
    }

    AuthContainer.propTypes = {
        isLoggedIn: PropTypes.bool.isRequired
    }

    const mapStateToProps = ({auth}) => {
        return {isLoggedIn: auth.isLoggedIn}
    }

    return connect(mapStateToProps)(AuthContainer);
}