text:
#include "config.h"

#if ENABLE(WEB_SOCKETS)

#include "WebSocketChannel.h"

#include "Blob.h"
#include "CookieJar.h"
#include "Document.h"
#include "FileError.h"
#include "FileReaderLoader.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "InspectorInstrumentation.h"
#include "Logging.h"
#include "Page.h"
#include "ProgressTracker.h"
#include "ScriptCallStack.h"
#include "ScriptExecutionContext.h"
#include "Settings.h"
#include "SocketStreamError.h"
#include "SocketStreamHandle.h"
#include "WebSocketChannelClient.h"
#include "WebSocketHandshake.h"

#include <wtf/ArrayBuffer.h>
#include <wtf/Deque.h>
#include <wtf/FastMalloc.h>
#include <wtf/HashMap.h>
#include <wtf/OwnPtr.h>
#include <wtf/PassOwnPtr.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringHash.h>
#include <wtf/text/WTFString.h>

using namespace std;

namespace WebCore {

const double TCPMaximumSegmentLifetime = 2 * 60.0;

WebSocketChannel::WebSocketChannel(Document* document, WebSocketChannelClient* client)
    : m_document(document)
    , m_client(client)
    , m_resumeTimer(this, &WebSocketChannel::resumeTimerFired)
    , m_suspended(false)
    , m_closing(false)
    , m_receivedClosingHandshake(false)
    , m_closingTimer(this, &WebSocketChannel::closingTimerFired)
    , m_closed(false)
    , m_shouldDiscardReceivedData(false)
    , m_unhandledBufferedAmount(0)
    , m_identifier(0)
    , m_hasContinuousFrame(false)
    , m_closeEventCode(CloseEventCodeAbnormalClosure)
    , m_outgoingFrameQueueStatus(OutgoingFrameQueueOpen)
#if ENABLE(BLOB)
    , m_blobLoaderStatus(BlobLoaderNotStarted)
#endif
{
    if (Page* page = m_document->page())
        m_identifier = page->progress()->createUniqueIdentifier();
}

WebSocketChannel::~WebSocketChannel()
{
}

void WebSocketChannel::connect(const KURL& url, const String& protocol)
{
    LOG(Network, "WebSocketChannel %p connect", this);
    ASSERT(!m_handle);
    ASSERT(!m_suspended);
    m_handshake = adoptPtr(new WebSocketHandshake(url, protocol, m_document));
    m_handshake->reset();
    if (m_deflateFramer.canDeflate())
        m_handshake->addExtensionProcessor(m_deflateFramer.createExtensionProcessor());
    if (m_identifier)
        InspectorInstrumentation::didCreateWebSocket(m_document, m_identifier, url, m_document->url());
    ref();
    m_handle = SocketStreamHandle::create(m_handshake->url(), this);
}

String WebSocketChannel::subprotocol()
{
    LOG(Network, "WebSocketChannel %p subprotocol", this);
    if (!m_handshake || m_handshake->mode() != WebSocketHandshake::Connected)
        return "";
    String serverProtocol = m_handshake->serverWebSocketProtocol();
    if (serverProtocol.isNull())
        return "";
    return serverProtocol;
}

String WebSocketChannel::extensions()
{
    LOG(Network, "WebSocketChannel %p extensions", this);
    if (!m_handshake || m_handshake->mode() != WebSocketHandshake::Connected)
        return "";
    String extensions = m_handshake->acceptedExtensions();
    if (extensions.isNull())
        return "";
    return extensions;
}

ThreadableWebSocketChannel::SendResult WebSocketChannel::send(const String& message)
{
    LOG(Network, "WebSocketChannel %p send %s", this, message.utf8().data());
    CString utf8 = message.utf8(String::StrictConversionReplacingUnpairedSurrogatesWithFFFD);
    enqueueTextFrame(utf8);
    // According to WebSocket API specification, WebSocket.send() should return void instead
    // of boolean. However, our implementation still returns boolean due to compatibility
    // concern (see bug 65850).
    // m_channel->send() may happen later, thus it's not always possible to know whether
    // the message has been sent to the socket successfully. In this case, we have no choice
    // but to return true.
    return ThreadableWebSocketChannel::SendSuccess;
}

ThreadableWebSocketChannel::SendResult WebSocketChannel::send(const ArrayBuffer& binaryData, unsigned byteOffset, unsigned byteLength)
{
    LOG(Network, "WebSocketChannel %p send arraybuffer %p %u %u", this, &binaryData, byteOffset, byteLength);
    enqueueRawFrame(WebSocketFrame::OpCodeBinary, static_cast<const char*>(binaryData.data()) + byteOffset, byteLength);
    return ThreadableWebSocketChannel::SendSuccess;
}

ThreadableWebSocketChannel::SendResult WebSocketChannel::send(const Blob& binaryData)
{
    LOG(Network, "WebSocketChannel %p send blob %s", this, binaryData.url().string().utf8().data());
    enqueueBlobFrame(WebSocketFrame::OpCodeBinary, binaryData);
    return ThreadableWebSocketChannel::SendSuccess;
}

bool WebSocketChannel::send(const char* data, int length)
{
    LOG(Network, "WebSocketChannel %p send binary %p (%dB)", this, data, length);
    enqueueRawFrame(WebSocketFrame::OpCodeBinary, data, length);
    return true;
}

unsigned long WebSocketChannel::bufferedAmount() const
{
    LOG(Network, "WebSocketChannel %p bufferedAmount", this);
    ASSERT(m_handle);
    ASSERT(!m_suspended);
    return m_handle->bufferedAmount();
}

void WebSocketChannel::close(int code, const String& reason)
{
    LOG(Network, "WebSocketChannel %p close", this);
    ASSERT(!m_suspended);
    if (!m_handle)
        return;
    startClosingHandshake(code, reason);
    if (m_closing && !m_closingTimer.isActive())
        m_closingTimer.startOneShot(2 * TCPMaximumSegmentLifetime);
}

void WebSocketChannel::fail(const String& reason)
{
    LOG(Network, "WebSocketChannel %p fail: %s", this, reason.utf8().data());
    ASSERT(!m_suspended);
    if (m_document) {
        InspectorInstrumentation::didReceiveWebSocketFrameError(m_document, m_identifier, reason);
        m_document->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, reason, m_handshake->clientOrigin());
    }

    // Hybi-10 specification explicitly states we must not continue to handle incoming data
    // once the WebSocket connection is failed (section 7.1.7).
    RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
    m_shouldDiscardReceivedData = true;
    if (!m_buffer.isEmpty())
        skipBuffer(m_buffer.size()); // Save memory.
    m_deflateFramer.didFail();
    m_hasContinuousFrame = false;
    m_continuousFrameData.clear();
    m_client->didReceiveMessageError();

    if (m_handle && !m_closed)
        m_handle->disconnect(); // Will call didClose().
}

void WebSocketChannel::disconnect()
{
    LOG(Network, "WebSocketChannel %p disconnect", this);
    if (m_identifier && m_document)
        InspectorInstrumentation::didCloseWebSocket(m_document, m_identifier);
    if (m_handshake)
        m_handshake->clearScriptExecutionContext();
    m_client = 0;
    m_document = 0;
    if (m_handle)
        m_handle->disconnect();
}

void WebSocketChannel::suspend()
{
    m_suspended = true;
}

void WebSocketChannel::resume()
{
    m_suspended = false;
    if ((!m_buffer.isEmpty() || m_closed) && m_client && !m_resumeTimer.isActive())
        m_resumeTimer.startOneShot(0);
}

void WebSocketChannel::willOpenSocketStream(SocketStreamHandle* handle)
{
    LOG(Network, "WebSocketChannel %p willOpensocketStream", this);
    ASSERT(handle);
    if (m_document->frame())
        m_document->frame()->loader()->client()->dispatchWillOpenSocketStream(handle);
}

void WebSocketChannel::didOpenSocketStream(SocketStreamHandle* handle)
{
    LOG(Network, "WebSocketChannel %p didOpenSocketStream", this);
    ASSERT(handle == m_handle);
    if (!m_document)
        return;
    if (m_identifier)
        InspectorInstrumentation::willSendWebSocketHandshakeRequest(m_document, m_identifier, *m_handshake->clientHandshakeRequest());
    CString handshakeMessage = m_handshake->clientHandshakeMessage();
    if (!handle->send(handshakeMessage.data(), handshakeMessage.length()))
        fail("Failed to send WebSocket handshake.");
}

void WebSocketChannel::didCloseSocketStream(SocketStreamHandle* handle)
{
    LOG(Network, "WebSocketChannel %p didCloseSocketStream", this);
    if (m_identifier && m_document)
        InspectorInstrumentation::didCloseWebSocket(m_document, m_identifier);
    ASSERT_UNUSED(handle, handle == m_handle || !m_handle);
    m_closed = true;
    if (m_closingTimer.isActive())
        m_closingTimer.stop();
    if (m_outgoingFrameQueueStatus != OutgoingFrameQueueClosed)
        abortOutgoingFrameQueue();
    if (m_handle) {
        m_unhandledBufferedAmount = m_handle->bufferedAmount();
        if (m_suspended)
            return;
        WebSocketChannelClient* client = m_client;
        m_client = 0;
        m_document = 0;
        m_handle = 0;
        if (client)
            client->didClose(m_unhandledBufferedAmount, m_receivedClosingHandshake ? WebSocketChannelClient::ClosingHandshakeComplete : WebSocketChannelClient::ClosingHandshakeIncomplete, m_closeEventCode, m_closeEventReason);
    }
    deref();
}

void WebSocketChannel::didReceiveSocketStreamData(SocketStreamHandle* handle, const char* data, int len)
{
    LOG(Network, "WebSocketChannel %p didReceiveSocketStreamData %d", this, len);
    RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
    ASSERT(handle == m_handle);
    if (!m_document) {
        return;
    }
    if (len <= 0) {
        handle->disconnect();
        return;
    }
    if (!m_client) {
        m_shouldDiscardReceivedData = true;
        handle->disconnect();
        return;
    }
    if (m_shouldDiscardReceivedData)
        return;
    if (!appendToBuffer(data, len)) {
        m_shouldDiscardReceivedData = true;
        fail("Ran out of memory while receiving WebSocket data.");
        return;
    }
    while (!m_suspended && m_client && !m_buffer.isEmpty())
        if (!processBuffer())
            break;
}

void WebSocketChannel::didUpdateBufferedAmount(SocketStreamHandle*, size_t bufferedAmount)
{
    if (m_client)
        m_client->didUpdateBufferedAmount(bufferedAmount);
}

void WebSocketChannel::didFailSocketStream(SocketStreamHandle* handle, const SocketStreamError& error)
{
    LOG(Network, "WebSocketChannel %p didFailSocketStream", this);
    ASSERT(handle == m_handle || !m_handle);
    if (m_document) {
        String message;
        if (error.isNull())
            message = "WebSocket network error";
        else if (error.localizedDescription().isNull())
            message = "WebSocket network error: error code " + String::number(error.errorCode());
        else
            message = "WebSocket network error: " + error.localizedDescription();
        String failingURL = error.failingURL();
        ASSERT(failingURL.isNull() || m_handshake->url().string() == failingURL);
        if (failingURL.isNull())
            failingURL = m_handshake->url().string();
        m_document->addConsoleMessage(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message, failingURL);
    }
    m_shouldDiscardReceivedData = true;
    handle->disconnect();
}

void WebSocketChannel::didReceiveAuthenticationChallenge(SocketStreamHandle*, const AuthenticationChallenge&)
{
}

void WebSocketChannel::didCancelAuthenticationChallenge(SocketStreamHandle*, const AuthenticationChallenge&)
{
}

#if ENABLE(BLOB)
void WebSocketChannel::didStartLoading()
{
    LOG(Network, "WebSocketChannel %p didStartLoading", this);
    ASSERT(m_blobLoader);
    ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
}

void WebSocketChannel::didReceiveData()
{
    LOG(Network, "WebSocketChannel %p didReceiveData", this);
    ASSERT(m_blobLoader);
    ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
}

void WebSocketChannel::didFinishLoading()
{
    LOG(Network, "WebSocketChannel %p didFinishLoading", this);
    ASSERT(m_blobLoader);
    ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
    m_blobLoaderStatus = BlobLoaderFinished;
    processOutgoingFrameQueue();
    deref();
}

void WebSocketChannel::didFail(int errorCode)
{
    LOG(Network, "WebSocketChannel %p didFail %d", this, errorCode);
    ASSERT(m_blobLoader);
    ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
    m_blobLoader.clear();
    m_blobLoaderStatus = BlobLoaderFailed;
    fail("Failed to load Blob: error code = " + String::number(errorCode)); // FIXME: Generate human-friendly reason message.
    deref();
}
#endif

bool WebSocketChannel::appendToBuffer(const char* data, size_t len)
{
    size_t newBufferSize = m_buffer.size() + len;
    if (newBufferSize < m_buffer.size()) {
        LOG(Network, "WebSocket buffer overflow (%lu+%lu)", static_cast<unsigned long>(m_buffer.size()), static_cast<unsigned long>(len));
        return false;
    }
    m_buffer.append(data, len);
    return true;
}

void WebSocketChannel::skipBuffer(size_t len)
{
    ASSERT(len <= m_buffer.size());
    memmove(m_buffer.data(), m_buffer.data() + len, m_buffer.size() - len);
    m_buffer.resize(m_buffer.size() - len);
}

bool WebSocketChannel::processBuffer()
{
    ASSERT(!m_suspended);
    ASSERT(m_client);
    ASSERT(!m_buffer.isEmpty());
    LOG(Network, "WebSocketChannel %p processBuffer %lu", this, static_cast<unsigned long>(m_buffer.size()));

    if (m_shouldDiscardReceivedData)
        return false;

    if (m_receivedClosingHandshake) {
        skipBuffer(m_buffer.size());
        return false;
    }

    RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.

    if (m_handshake->mode() == WebSocketHandshake::Incomplete) {
        int headerLength = m_handshake->readServerHandshake(m_buffer.data(), m_buffer.size());
        if (headerLength <= 0)
            return false;
        if (m_handshake->mode() == WebSocketHandshake::Connected) {
            if (m_identifier)
                InspectorInstrumentation::didReceiveWebSocketHandshakeResponse(m_document, m_identifier, m_handshake->serverHandshakeResponse());
            if (!m_handshake->serverSetCookie().isEmpty()) {
                if (cookiesEnabled(m_document)) {
                    ExceptionCode ec; // Exception (for sandboxed documents) ignored.
                    m_document->setCookie(m_handshake->serverSetCookie(), ec);
                }
            }
            // FIXME: handle set-cookie2.
            LOG(Network, "WebSocketChannel %p connected", this);
            skipBuffer(headerLength);
            m_client->didConnect();
            LOG(Network, "remaining in read buf %lu", static_cast<unsigned long>(m_buffer.size()));
            return !m_buffer.isEmpty();
        }
        ASSERT(m_handshake->mode() == WebSocketHandshake::Failed);
        LOG(Network, "WebSocketChannel %p connection failed", this);
        skipBuffer(headerLength);
        m_shouldDiscardReceivedData = true;
        fail(m_handshake->failureReason());
        return false;
    }
    if (m_handshake->mode() != WebSocketHandshake::Connected)
        return false;

    return processFrame();
}

void WebSocketChannel::resumeTimerFired(Timer<WebSocketChannel>* timer)
{
    ASSERT_UNUSED(timer, timer == &m_resumeTimer);

    RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
    while (!m_suspended && m_client && !m_buffer.isEmpty())
        if (!processBuffer())
            break;
    if (!m_suspended && m_client && m_closed && m_handle)
        didCloseSocketStream(m_handle.get());
}

void WebSocketChannel::startClosingHandshake(int code, const String& reason)
{
    LOG(Network, "WebSocketChannel %p closing %d %d", this, m_closing, m_receivedClosingHandshake);
    if (m_closing)
        return;
    ASSERT(m_handle);

    Vector<char> buf;
    if (!m_receivedClosingHandshake && code != CloseEventCodeNotSpecified) {
        unsigned char highByte = code >> 8;
        unsigned char lowByte = code;
        buf.append(static_cast<char>(highByte));
        buf.append(static_cast<char>(lowByte));
        buf.append(reason.utf8().data(), reason.utf8().length());
    }
    enqueueRawFrame(WebSocketFrame::OpCodeClose, buf.data(), buf.size());

    m_closing = true;
    if (m_client)
        m_client->didStartClosingHandshake();
}

void WebSocketChannel::closingTimerFired(Timer<WebSocketChannel>* timer)
{
    LOG(Network, "WebSocketChannel %p closing timer", this);
    ASSERT_UNUSED(timer, &m_closingTimer == timer);
    if (m_handle)
        m_handle->disconnect();
}

bool WebSocketChannel::processFrame()
{
    ASSERT(!m_buffer.isEmpty());

    WebSocketFrame frame;
    const char* frameEnd;
    String errorString;
    WebSocketFrame::ParseFrameResult result = WebSocketFrame::parseFrame(m_buffer.data(), m_buffer.size(), frame, frameEnd, errorString);
    if (result == WebSocketFrame::FrameIncomplete)
        return false;
    if (result == WebSocketFrame::FrameError) {
        fail(errorString);
        return false;
    }

    ASSERT(m_buffer.data() < frameEnd);
    ASSERT(frameEnd <= m_buffer.data() + m_buffer.size());

    OwnPtr<InflateResultHolder> inflateResult = m_deflateFramer.inflate(frame);
    if (!inflateResult->succeeded()) {
        fail(inflateResult->failureReason());
        return false;
    }

    // Validate the frame data.
    if (WebSocketFrame::isReservedOpCode(frame.opCode)) {
        fail("Unrecognized frame opcode: " + String::number(frame.opCode));
        return false;
    }

    if (frame.reserved2 || frame.reserved3) {
        fail("One or more reserved bits are on: reserved2 = " + String::number(frame.reserved2) + ", reserved3 = " + String::number(frame.reserved3));
        return false;
    }

    if (frame.masked) {
        fail("A server must not mask any frames that it sends to the client.");
        return false;
    }

    // All control frames must not be fragmented.
    if (WebSocketFrame::isControlOpCode(frame.opCode) && !frame.final) {
        fail("Received fragmented control frame: opcode = " + String::number(frame.opCode));
        return false;
    }

    // All control frames must have a payload of 125 bytes or less, which means the frame must not contain
    // the "extended payload length" field.
    if (WebSocketFrame::isControlOpCode(frame.opCode) && WebSocketFrame::needsExtendedLengthField(frame.payloadLength)) {
        fail("Received control frame having too long payload: " + String::number(frame.payloadLength) + " bytes");
        return false;
    }

    // A new data frame is received before the previous continuous frame finishes.
    // Note that control frames are allowed to come in the middle of continuous frames.
    if (m_hasContinuousFrame && frame.opCode != WebSocketFrame::OpCodeContinuation && !WebSocketFrame::isControlOpCode(frame.opCode)) {
        fail("Received new data frame but previous continuous frame is unfinished.");
        return false;
    }

    InspectorInstrumentation::didReceiveWebSocketFrame(m_document, m_identifier, frame);

    switch (frame.opCode) {
    case WebSocketFrame::OpCodeContinuation:
        // An unexpected continuation frame is received without any leading frame.
        if (!m_hasContinuousFrame) {
            fail("Received unexpected continuation frame.");
            return false;
        }
        m_continuousFrameData.append(frame.payload, frame.payloadLength);
        skipBuffer(frameEnd - m_buffer.data());
        if (frame.final) {
            // onmessage handler may eventually call the other methods of this channel,
            // so we should pretend that we have finished to read this frame and
            // make sure that the member variables are in a consistent state before
            // the handler is invoked.
            // Vector<char>::swap() is used here to clear m_continuousFrameData.
            OwnPtr<Vector<char> > continuousFrameData = adoptPtr(new Vector<char>);
            m_continuousFrameData.swap(*continuousFrameData);
            m_hasContinuousFrame = false;
            if (m_continuousFrameOpCode == WebSocketFrame::OpCodeText) {
                String message;
                if (continuousFrameData->size())
                    message = String::fromUTF8(continuousFrameData->data(), continuousFrameData->size());
                else
                    message = "";
                if (message.isNull())
                    fail("Could not decode a text frame as UTF-8.");
                else
                    m_client->didReceiveMessage(message);
            } else if (m_continuousFrameOpCode == WebSocketFrame::OpCodeBinary)
                m_client->didReceiveBinaryData(continuousFrameData.release());
        }
        break;

    case WebSocketFrame::OpCodeText:
        if (frame.final) {
            String message;
            if (frame.payloadLength)
                message = String::fromUTF8(frame.payload, frame.payloadLength);
            else
                message = "";
            skipBuffer(frameEnd - m_buffer.data());
            if (message.isNull())
                fail("Could not decode a text frame as UTF-8.");
            else
                m_client->didReceiveMessage(message);
        } else {
            m_hasContinuousFrame = true;
            m_continuousFrameOpCode = WebSocketFrame::OpCodeText;
            ASSERT(m_continuousFrameData.isEmpty());
            m_continuousFrameData.append(frame.payload, frame.payloadLength);
            skipBuffer(frameEnd - m_buffer.data());
        }
        break;

    case WebSocketFrame::OpCodeBinary:
        if (frame.final) {
            OwnPtr<Vector<char> > binaryData = adoptPtr(new Vector<char>(frame.payloadLength));
            memcpy(binaryData->data(), frame.payload, frame.payloadLength);
            skipBuffer(frameEnd - m_buffer.data());
            m_client->didReceiveBinaryData(binaryData.release());
        } else {
            m_hasContinuousFrame = true;
            m_continuousFrameOpCode = WebSocketFrame::OpCodeBinary;
            ASSERT(m_continuousFrameData.isEmpty());
            m_continuousFrameData.append(frame.payload, frame.payloadLength);
            skipBuffer(frameEnd - m_buffer.data());
        }
        break;

    case WebSocketFrame::OpCodeClose:
        if (!frame.payloadLength)
            m_closeEventCode = CloseEventCodeNoStatusRcvd;
        else if (frame.payloadLength == 1) {
            m_closeEventCode = CloseEventCodeAbnormalClosure;
            fail("Received a broken close frame containing an invalid size body.");
            return false;
        } else {
            unsigned char highByte = static_cast<unsigned char>(frame.payload[0]);
            unsigned char lowByte = static_cast<unsigned char>(frame.payload[1]);
            m_closeEventCode = highByte << 8 | lowByte;
            if (m_closeEventCode == CloseEventCodeNoStatusRcvd || m_closeEventCode == CloseEventCodeAbnormalClosure || m_closeEventCode == CloseEventCodeTLSHandshake) {
                m_closeEventCode = CloseEventCodeAbnormalClosure;
                fail("Received a broken close frame containing a reserved status code.");
                return false;
            }
        }
        if (frame.payloadLength >= 3)
            m_closeEventReason = String::fromUTF8(&frame.payload[2], frame.payloadLength - 2);
        else
            m_closeEventReason = "";
        skipBuffer(frameEnd - m_buffer.data());
        m_receivedClosingHandshake = true;
        startClosingHandshake(m_closeEventCode, m_closeEventReason);
        if (m_closing) {
            m_outgoingFrameQueueStatus = OutgoingFrameQueueClosing;
            processOutgoingFrameQueue();
        }
        break;

    case WebSocketFrame::OpCodePing:
        enqueueRawFrame(WebSocketFrame::OpCodePong, frame.payload, frame.payloadLength);
        skipBuffer(frameEnd - m_buffer.data());
        break;

    case WebSocketFrame::OpCodePong:
        // A server may send a pong in response to our ping, or an unsolicited pong which is not associated with
        // any specific ping. Either way, there's nothing to do on receipt of pong.
        skipBuffer(frameEnd - m_buffer.data());
        break;

    default:
        ASSERT_NOT_REACHED();
        skipBuffer(frameEnd - m_buffer.data());
        break;
    }

    return !m_buffer.isEmpty();
}

void WebSocketChannel::enqueueTextFrame(const CString& string)
{
    ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
    OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
    frame->opCode = WebSocketFrame::OpCodeText;
    frame->frameType = QueuedFrameTypeString;
    frame->stringData = string;
    m_outgoingFrameQueue.append(frame.release());
    processOutgoingFrameQueue();
}

void WebSocketChannel::enqueueRawFrame(WebSocketFrame::OpCode opCode, const char* data, size_t dataLength)
{
    ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
    OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
    frame->opCode = opCode;
    frame->frameType = QueuedFrameTypeVector;
    frame->vectorData.resize(dataLength);
    if (dataLength)
        memcpy(frame->vectorData.data(), data, dataLength);
    m_outgoingFrameQueue.append(frame.release());
    processOutgoingFrameQueue();
}

void WebSocketChannel::enqueueBlobFrame(WebSocketFrame::OpCode opCode, const Blob& blob)
{
    ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
    OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
    frame->opCode = opCode;
    frame->frameType = QueuedFrameTypeBlob;
    frame->blobData = Blob::create(blob.url(), blob.type(), blob.size());
    m_outgoingFrameQueue.append(frame.release());
    processOutgoingFrameQueue();
}

void WebSocketChannel::processOutgoingFrameQueue()
{
    if (m_outgoingFrameQueueStatus == OutgoingFrameQueueClosed)
        return;

    while (!m_outgoingFrameQueue.isEmpty()) {
        OwnPtr<QueuedFrame> frame = m_outgoingFrameQueue.takeFirst();
        switch (frame->frameType) {
        case QueuedFrameTypeString: {
            if (!sendFrame(frame->opCode, frame->stringData.data(), frame->stringData.length()))
                fail("Failed to send WebSocket frame.");
            break;
        }

        case QueuedFrameTypeVector:
            if (!sendFrame(frame->opCode, frame->vectorData.data(), frame->vectorData.size()))
                fail("Failed to send WebSocket frame.");
            break;

        case QueuedFrameTypeBlob: {
#if ENABLE(BLOB)
            switch (m_blobLoaderStatus) {
            case BlobLoaderNotStarted:
                ref(); // Will be derefed after didFinishLoading() or didFail().
                ASSERT(!m_blobLoader);
                m_blobLoader = adoptPtr(new FileReaderLoader(FileReaderLoader::ReadAsArrayBuffer, this));
                m_blobLoaderStatus = BlobLoaderStarted;
                m_blobLoader->start(m_document, frame->blobData.get());
                m_outgoingFrameQueue.prepend(frame.release());
                return;

            case BlobLoaderStarted:
            case BlobLoaderFailed:
                m_outgoingFrameQueue.prepend(frame.release());
                return;

            case BlobLoaderFinished: {
                RefPtr<ArrayBuffer> result = m_blobLoader->arrayBufferResult();
                m_blobLoader.clear();
                m_blobLoaderStatus = BlobLoaderNotStarted;
                if (!sendFrame(frame->opCode, static_cast<const char*>(result->data()), result->byteLength()))
                    fail("Failed to send WebSocket frame.");
                break;
            }
            }
#else
            fail("FileReader is not available. Could not send a Blob as WebSocket binary message.");
#endif
            break;
        }

        default:
            ASSERT_NOT_REACHED();
            break;
        }
    }

    ASSERT(m_outgoingFrameQueue.isEmpty());
    if (m_outgoingFrameQueueStatus == OutgoingFrameQueueClosing) {
        m_outgoingFrameQueueStatus = OutgoingFrameQueueClosed;
        m_handle->close();
    }
}

void WebSocketChannel::abortOutgoingFrameQueue()
{
    m_outgoingFrameQueue.clear();
    m_outgoingFrameQueueStatus = OutgoingFrameQueueClosed;
#if ENABLE(BLOB)
    if (m_blobLoaderStatus == BlobLoaderStarted) {
        m_blobLoader->cancel();
        didFail(FileError::ABORT_ERR);
    }
#endif
}

bool WebSocketChannel::sendFrame(WebSocketFrame::OpCode opCode, const char* data, size_t dataLength)
{
    ASSERT(m_handle);
    ASSERT(!m_suspended);

    WebSocketFrame frame(opCode, true, false, true, data, dataLength);
    InspectorInstrumentation::didSendWebSocketFrame(m_document, m_identifier, frame);

    OwnPtr<DeflateResultHolder> deflateResult = m_deflateFramer.deflate(frame);
    if (!deflateResult->succeeded()) {
        fail(deflateResult->failureReason());
        return false;
    }

    Vector<char> frameData;
    frame.makeFrameData(frameData);

    return m_handle->send(frameData.data(), frameData.size());
}

}  // namespace WebCore

#endif  // ENABLE(WEB_SOCKETS)


text:
SCRIPT_DIR=`dirname $0` # so this script can be run from any directory

if [ "$2" == "" ]; then
  echo 1>&2 "Please specify the path to the keystore and the user ID to create a ticket for.  For example, $0 ./keystore1 12345"
  exit 1
fi
KEYSTORE=`pwd`/$1
USER_ID=$2

echo > $SCRIPT_DIR/props
echo "Ticketfile=logon_ticket_new.txt" >> $SCRIPT_DIR/props
echo "keystore=$KEYSTORE" >> $SCRIPT_DIR/props
echo "password=password" >> $SCRIPT_DIR/props
echo "user=$USER_ID" >> $SCRIPT_DIR/props
echo "client=client" >> $SCRIPT_DIR/props
echo "system=system" >> $SCRIPT_DIR/props
echo "defaultKeyAlias=mykey" >> $SCRIPT_DIR/props

OLD_DIR=`pwd`
cd $SCRIPT_DIR
# Hide the sentence Dies ist das Ticket so it's not confused with the contents
#   of the ticket.
# Convert + to ! because SAP does that to avoid having +'s being URLDecoded
#   and interpreted as spaces.
java -cp iaik_jce.jar:com.sap.security.api.jar:com.sap.security.core.jar com.sap.security.core.ticket.imp.Ticket create props | sed "s/Dies ist das Ticket://" | sed "s/+/!/g"
cd $OLD_DIR
rm -f $SCRIPT_DIR/logon_ticket_new.txt
rm -f $SCRIPT_DIR/props

redpajama_set_name: RedPajamaGithub


text:
<entry>
  <act classCode="ACT" moodCode="RQO" {{negationIndicator .EntrySection.Entry}}>
    <!-- Discharge Medication Entry -->
    <templateId root="2.16.840.1.113883.10.20.24.3.105" extension="2016-02-01"/>
    <id root="1.3.6.1.4.1.115" extension="{{.EntrySection.Entry.ObjectIdentifier.ID}}"/>
    <code code="75311-1"
          codeSystem="2.16.840.1.113883.6.1"
          codeSystemName="LOINC"
          displayName="Discharge medications"/>
    <statusCode code="active"/>
    <effectiveTime>
      <low {{valueOrNullFlavor .EntrySection.StartTime}}/>
    </effectiveTime>
    <entryRelationship typeCode="SUBJ">
      <substanceAdministration moodCode="EVN" classCode="SBADM">
        <!-- Medication Activity (consolidation) template -->
        <templateId root="2.16.840.1.113883.10.20.22.4.16" extension="2014-06-09"/>
        <!-- Medication, Active template -->
        <templateId root="2.16.840.1.113883.10.20.24.3.41" extension="2016-02-01"/>

        <id root="{{newRandom}}"/>
        <text>{{escape .EntrySection.Description}}</text>
        <statusCode code="active"/>
        <effectiveTime xsi:type="IVL_TS">
            <low {{valueOrNullFlavor .EntrySection.StartTime}}/>
            <high {{valueOrNullFlavor .EntrySection.EndTime}}/>
        </effectiveTime>
        {{if .EntrySection.HasSetAdministrationTiming}}
          <effectiveTime xsi:type="PIVL_TS" institutionSpecified="true" operator="A">
            <period value="{{.EntrySection.AdministrationTiming.Period.Value}}" unit="{{.EntrySection.AdministrationTiming.Period.Unit}}"/>
          </effectiveTime>
        {{end}}
        {{if .EntrySection.Route}}
        <!-- Attribute: route -->
          {{$vset := oidForCode .EntrySection.Route (index .MapDataCriteria.FieldOids "ROUTE")}}
          {{if ne $vset ""}}
            <routeCode code="{{.EntrySection.Route.Code}}" codeSystem="{{oidForCodeSystem .EntrySection.Route.CodeSystem}}" sdtc:valueSet="{{$vset}}"/>
          {{end}}
        {{end}}

        <!-- Attribute: dose -->
        {{if .EntrySection.HasSetDose}}
          <doseQuantity value="{{.EntrySection.Dose.Value}}"/>
        {{end}}

        {{if .EntrySection.ProductForm}}
        <administrationUnitCode code="{{.EntrySection.ProductForm.Code}}" codeSystem="{{.EntrySection.ProductForm.CodeSystem}}"/>
        {{end}}

        <consumable>
          <manufacturedProduct classCode="MANU">
            <!-- Medication Information (consolidation) template -->
            <templateId root="2.16.840.1.113883.10.20.22.4.23" extension="2014-06-09"/>
            <id root="{{newRandom}}"/>
            <manufacturedMaterial>
              {{template "_code.xml" generateCodeDisplay .EntrySection.Entry .EntrySection.Entry.Coded .MapDataCriteria "entryCode"}}
            </manufacturedMaterial>
            <manufacturerOrganization>
              <name>Medication Factory Inc.</name>
            </manufacturerOrganization>
          </manufacturedProduct>
        </consumable>
      </substanceAdministration>
    </entryRelationship>
    {{template "_reason.xml" .}}
  </act>
</entry>


text:
@echo OSR DDKBUILD.BAT V6.12 - OSR, Open Systems Resources, Inc.
@echo off
rem /////////////////////////////////////////////////////////////////////////////
rem //
rem //    This sofware is supplied for instructional purposes only.
rem //
rem //    OSR Open Systems Resources, Inc. (OSR) expressly disclaims any warranty
rem //    for this software.  THIS SOFTWARE IS PROVIDED  "AS IS" WITHOUT WARRANTY
rem //    OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION,
rem //    THE IMPLIED WARRANTIES OF MECHANTABILITY OR FITNESS FOR A PARTICULAR
rem //    PURPOSE.  THE ENTIRE RISK ARISING FROM THE USE OF THIS SOFTWARE REMAINS
rem //    WITH YOU.  OSR's entire liability and your exclusive remedy shall not
rem //    exceed the price paid for this material.  In no event shall OSR or its
rem //    suppliers be liable for any damages whatsoever (including, without
rem //    limitation, damages for loss of business profit, business interruption,
rem //    loss of business information, or any other pecuniary loss) arising out
rem //    of the use or inability to use this software, even if OSR has been
rem //    advised of the possibility of such damages.  Because some states/
rem //    jurisdictions do not allow the exclusion or limitation of liability for
rem //    consequential or incidental damages, the above limitation may not apply
rem //    to you.
rem //
rem //    OSR Open Systems Resources, Inc.
rem //    105 Route 101A Suite 19
rem //    Amherst, NH 03031  (603) 595-6500 FAX: (603) 595-6503
rem //    email bugs to: bugs@osr.com
rem //
rem //
rem //    MODULE:
rem //
rem //        ddkbuild.bat
rem //
rem //    ABSTRACT:
rem //
rem //      This file allows drivers to be build with visual studio and visual studio.net
rem //
rem //    AUTHOR(S):
rem //
rem //        OSR Open Systems Resources, Inc.
rem //
rem //    REVISION:   V6.12
rem //
rem //      Clean up batch procedure to make it easier to process.
rem //
rem //
rem //    REQUIREMENTS:  Environment variables that must be set.
rem //
rem //		NT4BASE - must be set up by user to point to NT4 DDK. (e.g. D:\NT4DDK )
rem //      W2KBASE - must be set up by user to point to W2K DDK  (e.g D:\Nt50DDK )
rem //      WXPBASE - must be set up by user to point to WXP DDK  (e.g D:\WINDDK\2600)
rem //      WNETBASE - must be set up by user to point to WNET DDK (e.g D:\WINDDK\1830)
rem //      WLHBASE  - must be set up by user to point to WNET DDK (e.g D:\WINDDK\5112)
rem //
rem //
rem //    COMMAND FORMAT:
rem //
rem //		ddkbuild -PLATFORM BUILDTYPE DIRECTORY [FLAGS] [-WDF] [-PREFAST]
rem //
rem //              PLATFORM is either
rem //                   WXP, WXP64, WXP2K - builds using WXP DDK
rem //                   W2K, W2K64,  - builds using W2k DDK
rem //                   WNET, WNET64, WNET2K, WNETXP, WNETXP64 - builds using WNET DDK
rem //                   WNETAMD64  for an AMD64/EM64T WNET build using the WNET DDK
rem //                   WLH, WLHNET, WLHNETX64, WLHNETI64, WLH2K, WLHXP - builds using WLH DDK
rem //                   WLHX64 for an AMD64/EM64T WNET build using the WLH DDK
rem //                   WLHI64 for IA64 use WLH DDK
rem //                   NT4  - build using NT4 DDK (NT4 is the default)
rem //              BUILDTYPE - free, checked, chk or fre
rem //				DIRECTORY is the path to the directory to be build.  It can be "."
rem //              FLAGS - build flags e.g. -cZ etc.
rem //              -WDF  - allows the user to perform a Windows Driver Framework build.
rem //                      this has been tested with the 01.00.5054 version of the
rem //                      framework.
rem //              -PREFAST - performs a prefast build, if prefast is available.
rem //
rem //	  BROWSE FILES:
rem //
rem //       This procedure supports the building of BROWSE files to be used by
rem //       Visual Studio 6 and by Visual Studio.Net  However, the BSCfiles created
rem //       by bscmake for the 2 studios are not compatible. When this command procedure
rem //       runs, it selects the first bscmake.exe found in the path.   So, make
rem //       sure that the correct bscmake.exe is in the path....
rem //
rem //       Note that if using Visual Studio.NET the .BSC must be added to the project
rem //       in order for the project to be browsed.
rem //
rem //    COMPILERS:
rem //
rem //        If you are building NT4 you should really
rem //        be using the VC 6 compiler.   Later versions of the DDK now contain the
rem //        compiler and the linker.  This procedure should use the correct compiler.
rem //
rem //    GENERAL COMMENTS:
rem //        This procedure has been cleaned up to be modular and easy to
rem //		  understand.
rem //
rem //		  As of the Server 2003 SP1 DDK ddkbuild now clears the
rem //        NO_BROWSE_FILE and NO_BINPLACE environment variables so that users
rem //        can use these features.
rem //
rem ///////////////////////////////////////////////////////////////////////////////

set scriptDebug=off
setlocal ENABLEEXTENSIONS

rem Check whether FINDSTR is available. It's used to show warnings etc.
findstr /? > NUL 2>&1 || echo "FINDSTR is a prerequisite but wasn't found!" && goto :EOF

@echo %scriptDebug%

rem //
rem // clear the error code variable
rem //
set error_code=0
set prefast_build=0
set BUILD_DEBUG=1
set VS_UNICODE_OUTPUT=
rem //
rem // determine what type of build is to be done.
rem //
if /I %1 EQU -NT4       goto NT4Build
if /I %1 EQU -WNET2K    goto WNET2KBuild
if /I %1 EQU -WNETXP    goto WNETXPBuild
if /I %1 EQU -WNETXP64  goto WNETXP64Build
if /I %1 EQU -WNET64    goto WNET64Build
if /I %1 EQU -WNETAMD64 goto WNETAMD64Build
if /I %1 EQU -WNET      goto WNETBuild
if /I %1 EQU -WXP64     goto WXP64Build
if /I %1 EQU -WXP       goto WXPBuild
if /I %1 EQU -WXP2K     goto WXP2KBuild
if /I %1 EQU -W2K64     goto W2K64Build
if /I %1 EQU -W2K       goto W2KBuild
if /I %1 EQU -WLH       goto WLHBuild
if /I %1 EQU -WLHX64    goto WLHX64Build
if /I %1 EQU -WLHI64    goto WLHI64Build
if /I %1 EQU -WLHNETX64 goto WLHNETX64Build
if /I %1 EQU -WLHNETI64 goto WLHNETI64Build
if /I %1 EQU -WLHXP     goto WLHXPBuild
if /I %1 EQU -WLH2K     goto WLH2KBuild
if /I %1 EQU -WLHNET    goto WLHNETBuild
set error_code=1
goto ErrUnKnownBuildType

rem //
rem // NT 4 Build
rem //
:NT4Build

@echo NT4 BUILD using NT4 DDK

set BASEDIR=%NT4BASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% "%MSDEVDIR%"
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WNET Windows 2000 Build using WNET DDK
rem //

:WNET2KBuild

@echo W2K BUILD using WNET DDK

set BASEDIR=%WNETBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% W2K %mode%
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WXP Build using WNET DDK
rem //
:WNETXPBuild

@echo WXP BUILD using WNET DDK

set BASEDIR=%WNETBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% WXP
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WXP 64 bit Build using WNET DDK
rem //
:WNETXP64Build

@echo WXP 64 BIT BUILD using WNET DDK

set BASEDIR=%WNETBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% 64 WXP
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WNET IA64 bit Build using WNET DDK
rem //
:WNET64Build

@echo WNET 64 BIT BUILD using WNET DDK

set BASEDIR=%WNETBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% 64 WNET
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WNET AMD64 bit Build using WNET DDK
rem //
:WNETAMD64Build

@echo WNET 64 BIT BUILD using WNET DDK

set BASEDIR=%WNETBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% AMD64 WNET
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WNET 32 BIT BUILD using WNET DDK
rem //
:WNETBuild

@echo WNET 32 BIT BUILD using WNET DDK

set BASEDIR=%WNETBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode%
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WXP 64 BIT BUILD using WXP DDK
rem //
:WXP64Build

@echo WXP 64 BIT BUILD using WXP DDK

set BASEDIR=%WXPBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% 64
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WXP 32 BIT BUILD using WXP DDK
rem //
:WXPBuild

@echo WXP 32 BIT BUILD using WXP DDK

set BASEDIR=%WXPBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode%
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // W2K 32 BIT BUILD using WXP DDK
rem //
:WXP2KBuild

@echo W2K 32 BIT BUILD using WXP DDK

set BASEDIR=%WXPBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\w2k\set2k.bat" %BASEDIR% %mode%
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // W2K 64 BIT BUILD using W2K DDK
rem //
:W2K64Build

@echo W2K 64 BIT BUILD using W2K DDK

set BASEDIR=%W2KBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv64.bat" %BASEDIR% %mode%
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // W2K 32 BIT BUILD using W2K DDK
rem //
:W2KBuild

@echo W2K 32 BIT BUILD using W2K DDK

set BASEDIR=%W2KBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode%
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WLH 32 BIT BUILD using WLH DDK
rem //
:WLHBuild
@echo WLH 32 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% WLH
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WLH X64 BIT BUILD using WLH DDK
rem //
:WLHX64Build

@echo WLH X64 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

call :DetectVistaWDK
pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% %OSR_AMD64FLAG% WLH
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WLH IA64 BIT BUILD using WLH DDK
rem //
:WLHI64Build

@echo WLH IA64 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% 64 WLH
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WNET X64 BIT BUILD using WLH DDK
rem //
:WLHNETX64Build

@echo WNET X64 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

call :DetectVistaWDK
pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% %OSR_AMD64FLAG% WNET
popd

goto RegularBuild

rem //
rem // WNET IA64 BIT BUILD using WLH DDK
rem //
:WLHNETI64Build

@echo WNET IA64 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% 64 WNET
popd

goto RegularBuild

rem //
rem // WXP 32 BIT BUILD using WLH DDK
rem //
:WLHXPBuild
@echo WLH 32 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% WXP
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // W2K 32 BIT BUILD using WLH DDK
rem //
:WLH2KBuild
@echo WLH 32 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetModeWLH2K %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% W2K
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // WNET 32 BIT BUILD using WLH DDK
rem //
:WLHNETBuild
@echo WLH 32 BIT BUILD using WLH DDK

set BASEDIR=%WLHBASE%

shift

if "%BASEDIR%"=="" goto ErrNoBASEDIR
call :MakeShort BASEDIR "%BASEDIR%"

set path=%BASEDIR%\bin;%path%

call :SetMode %1
if "%error_code%" NEQ "0" goto ErrBadMode

call :CheckTargets %2
if "%error_code%" NEQ "0" goto ErrNoDir

pushd .
call "%BASEDIR%\bin\setenv.bat" %BASEDIR% %mode% WNET
popd

@echo %scriptDebug%

goto RegularBuild

rem //
rem // All builds go here for the rest of the procedure.  Now,
rem // we are getting ready to call build.  The big problem
rem // here is to figure our the name of the buildxxx files being
rem // generated for the different platforms.
rem //

:RegularBuild

set NO_BROWSWER_FILE=
set NO_BINPLACE=

set mpFlag=-M
if "%BUILD_ALT_DIR%"=="" goto NT4

rem win2k sets this!
set W2kEXT=%BUILD_ALT_DIR%

set mpFlag=-MI

:NT4

if "%NUMBER_OF_PROCESSORS%"=="" set mpFlag=
if "%NUMBER_OF_PROCESSORS%"=="1" set mpFlag=

rem //
rem // Determine the settings of flags, WDF and PREFAST in other words
rem // what was set for %3 and beyond....
rem //
@echo build in directory %~2 with arguments %3 %4 %5 (basedir %BASEDIR%)

set buildDirectory=%~f2
call :MakeShort buildDirectory %buildDirectory%

cd /D %buildDirectory%
set bflags=-Ze
set bscFlags=""

:ContinueParsing
if "%3" == "" goto done
if "%3" == "/a" goto RebuildallFound
if "%3" == "-WDF" goto WDFFound
if "%3" == "-wdf" goto WDFFound
if "%3" == "-PREFAST" goto PrefastFound
if "%3" == "-prefast" goto PrefastFound
set bscFlags=/n
set bflags=%bflags% %3
shift
goto ContinueParsing

:WDFFound
shift
if "%BASEDIR%" == "%WLHBASE%" goto WDFOkay
if "%WDF_ROOT%" == "" goto errNoWdfRoot
pushd .
call "%WDF_ROOT%\set_wdf_env.cmd"
popd
:WDFOkay
set scriptDebug=on
goto ContinueParsing

:PrefastFound
shift
set prefast_build=1
goto ContinueParsing

:RebuildallFound
shift
set bscFlags=/n
set bflags=-cfeZ
goto ContinueParsing

:done

if EXIST build%W2kEXT%.err	 erase build%W2kEXT%.err
if EXIST build%W2kEXT%.wrn   erase build%W2kEXT%.wrn
if EXIST build%W2kEXT%.log	 erase build%W2kEXT%.log
if EXIST prefast%W2kEXT%.log erase prefast%W2kEXT%.log

if "%prefast_build%" NEQ "0" goto RunPrefastBuild
@echo run build %bflags% %mpFlag% for %mode% version in %buildDirectory%
pushd .
build  %bflags% %mpFlag%
goto BuildComplete

:RunPrefastBuild
@echo run prefast build %bflags% %mpFlag% for %mode% version in %buildDirectory%
pushd .
prefast build  %bflags% %mpFlag%
if "%errorlevel%" GTR "0" set error_code=%errorlevel%
prefast list > prefast%W2kEXT%.log
goto BuildComplete

:BuildComplete
if "%errorlevel%" GTR "0" set error_code=%errorlevel%
popd

@echo %scriptDebug%

rem assume that the onscreen errors are complete!

@echo =============== build warnings ======================
if exist build%W2kEXT%.wrn findstr "warning[^.][DRCLU][0-9]*" build%W2kEXT%.log
if exist build%W2kEXT%.log findstr "error[^.][DRCLU][0-9]*" build%W2kEXT%.log

if "%prefast_build%" == "0" goto SkipPrefastWarnings
@echo =============== prefast warnings ======================
if exist prefast%W2kEXT%.log findstr "warning[^.][CLU]*" prefast%W2kEXT%.log
:SkipPrefastWarnings

@echo.
@echo.
@echo build complete

@echo building browse information files

if EXIST buildbrowse.cmd goto doBrowsescript

set sbrlist=sbrList.txt

if not EXIST sbrList%CPU%.txt goto sbrDefault

set sbrlist=sbrList%CPU%.txt

:sbrDefault

if not EXIST %sbrlist% goto end

if %bscFlags% == "" goto noBscFlags

bscmake %bscFlags% @%sbrlist%

goto end

:noBscFlags

bscmake @%sbrlist%

goto end

:doBrowsescript

call buildBrowse %mode%

goto end

rem //
rem //  SetMode
rem //
rem //  Subroutine to validate the mode of the build passed in.
rem //  it must be free, FREE, fre, FRE or checked, CHECKED,
rem //  chk, CHK.   Anything else is an error.
rem //
:SetMode
set mode=
for %%f in (free FREE fre FRE) do if %%f == %1 set mode=free
for %%f in (checked CHECKED chk CHK) do if %%f == %1 set mode=checked
if "%mode%" =="" set error_code=1
goto :EOF

rem //
rem //  SetModeWLH2K
rem //
rem //  Subroutine to validate the mode of the build passed in.
rem //  it must be free, FREE, fre, FRE or checked, CHECKED,
rem //  chk, CHK.   Anything else is an error.
rem //
:SetModeWLH2K
set mode=
for %%f in (free FREE fre FRE) do if %%f == %1 set mode=f
for %%f in (checked CHECKED chk CHK) do if %%f == %1 set mode=c
if "%mode%" =="" set error_code=1
goto :EOF

rem //
rem //  MakeShort
rem //
rem //  Subroutine to convert a long file path into a short (8.3)
rem //  file path for better compatibility with DDK tools.
rem //
:MakeShort
setlocal ENABLEEXTENSIONS
set PATH_SHORT=%~dpns2
set PATH_EXTSHORT=%~xs2
if not "" == "%PATH_EXTSHORT%" set PATH_EXTSHORT=%PATH_EXTSHORT:~0,4%
set PATH_SHORT=%PATH_SHORT%%PATH_EXTSHORT%
endlocal & set %~1=%PATH_SHORT%
goto :EOF

rem //
rem // CheckTargets
rem //
rem // Subroutine to validate that the target directory exists
rem // and that there is either a DIRS or SOURCES and MakeFile in
rem // it.
rem //
:CheckTargets
if "%1" NEQ "" goto CheckTargets1
set error_code=1
goto :EOF
:CheckTargets1
if exist %1 goto CheckTargets2
set error_code=1
goto :EOF
:CheckTargets2
if not exist %1\DIRS  goto CheckTargets3
set error_code=0
goto :EOF
:CheckTargets3
if exist %1\SOURCES  goto CheckTargets4
set error_code=2
goto :EOF
:CheckTargets4
if exist %1\MAKEFILE  goto CheckTargets5
set error_code=2
goto :EOF
:CheckTargets5
set error_code=0
goto :EOF

:DetectVistaWDK
setlocal ENABLEEXTENSIONS
rem // Newer flag (starting with W2K8) is default
set OSR_AMD64FLAG=x64
rem // The Vista WDK accepted *only* "AMD64", the newer W2K8 WDK accepts only "x64"
rem // We detect the older one by checking the setenv.bat for a certain string
findstr /C:"Windows Server Longhorn" "%BASEDIR%\bin\setenv.bat" > NUL 2>&1 && set OSR_AMD64FLAG=AMD64
endlocal & set OSR_AMD64FLAG=%OSR_AMD64FLAG%
goto :EOF

rem //
rem //  Error processing code.   Whenever we encounter an
rem //  error in the parameters, we come to one of the following
rem //  labels to output a decent error to help the user
rem //  understand what is wrong.
rem //

:ErrBadMode
@echo -
@echo ERROR: first param must be "checked", "free", "chk" or "fre"
set error_code=1
goto usage

:ErrNoBASEDIR
@echo -
@echo ERROR: NT4BASE, W2KBASE, WXPBASE, or WNETBASE environment variable not set.
@echo ERROR: Environment variable must be set by user according to DDK version installed.
set error_code=1
goto usage

:ErrUnKnownBuildType
@echo -
@echo ERROR: Unknown type of build.  Please recheck parameters.
set error_code=1
goto usage

:ErrNoDir
if "%error_code%" EQU "2" goto ErrNoTarget
@echo -
@echo ERROR: second parameter must be a valid directory
goto usage

:ErrNoTarget
@echo -
@echo ERROR: target directory must contain a SOURCES or DIRS file
goto usage

:errNoWdfRoot
@echo -
@echo ERROR: WDF_ROOT is not defined, are you using 00.01.5054 or later?
goto usage

rem //
rem // Usage output
rem //
:usage
@echo -
@echo -
@echo usage: ddkbuild [-W2K] "checked | free | chk | fre" "directory-to-build" [flags] [-WDF] [-PREFAST]
@echo        -W2K       indicates development system uses W2KBASE environment variable
@echo                   to locate the win2000 ddk
@echo        -W2K64     indicates development sytsem uses W2KBASE environment variable
@echo                   to locate the win2000 IA64 ddk
@echo        -WXP       to indicate WXP Build uses WXPBASE enviornment variable.
@echo        -WXP64     to indicate WXP IA64 bit build, uses WXPBASE
@echo        -WXP2K     to indicate Windows 2000 build using WXP ddk
@echo        -WNET      to indicate Windows .Net builds using WNET ddk
@echo        -WNET64    to indicate Windows .Net 64 bit builds using WNET DDK
@echo        -WNETXP    to indicate Windows XP builds suing WNET DDK
@echo        -WNETXP64  to indicate Windows XP 64 bit builds suing WNET DDK
@echo        -WNETAMD64 to indicate Windows .NET build for AMD64 using WNET DDK
@echo        -WNET2K    to indicate Windows 2000 builds using WNET DDK
@echo        -NT4       to indicate NT4 build using NT4 DDK.
@echo        -WLH       to indicate Windows LH builds using WLH DDK
@echo        -WLH2K     to indicate Windows 2K builds using WLH DDK
@echo        -WLHXP     to indicate Windows XP builds using WLH DDK
@echo        -WLHNET    to indicate Windows NET builds using WLH DDK
@echo        -WLHNETX64 to indicate Windows NET X64 builds using WLH DDK
@echo        -WLHNETI64 to indicate Windows NET IA64 builds using WLH DDK
@echo        -WLHX64    to indicate Windows LH X64 builds using WLH DDK
@echo        -WLHI64    to indicate Windows LH IA64 builds using WLH DDK
@echo         checked   indicates a checked build
@echo         free      indicates a free build
@echo         chk		indicates a checked build
@echo         fre		indicates a free build
@echo         directory path to build directory, try . (cwd)
@echo         flags     any random flags you think should be passed to build (try /a for clean)
@echo         -WDF      performs a WDF build
@echo         -PREFAST  preforms a PREFAST build
@echo -
@echo         ex: ddkbuild -NT4 checked . (for NT4 BUILD)
@echo         ex: ddkbuild -WXP64 chk .
@echo         ex: ddkbuild -WXP chk c:\projects\myproject
@echo         ex: ddkbuild -WNET64 chk .      (IA64 bit build)
@echo         ex: ddkbuild -WNETAMD64 chk .   (AMD64/EM64T bit build)
@echo         ex: ddkbuild -WNETXP chk . -cZ -WDF
@echo         ex: ddkbuild -WNETXP chk . -cZ -PREFAST
@echo -
@echo         In order for this procedure to work correctly for each platform, it requires
@echo         an environment variable to be set up for certain platforms.   The environment
@echo         variables are as follows:
@echo -
@echo         NT4BASE - You must set this up to do -NT4 builds
@echo         W2KBASE - You must set this up to do -W2K and -W2K64 builds
@echo         WXPBASE - You must set this up to do -WXP, -WXP64, -WXP2K builds
@echo         WNETBASE - You must set this up to do -WNET, -WNET64, -WNETXP, -WNETXP64,
@echo                    -WNETAMD64, and -WNET2K builds
@echo         WLHBASE  - You must set this to do any -WLH* builds
@echo -
@echo         WDF_ROOT must be set if attempting to do a WDF Build.
@echo -
@echo -
@echo   OSR DDKBUILD.BAT V6.12 - OSR, Open Systems Resources, Inc.
@echo     report any problems found to info@osr.com
@echo  -

rem goto end

:end

exit /b %error_code%

@echo ddkbuild complete


text:
import {Component} from "@angular/core";
import {NavController} from "ionic-angular";

/*
 Generated class for the LoginPage page.

 See http://ionicframework.com/docs/v2/components/#navigation for more info on
 Ionic pages and navigation.
 */
@Component({
  selector: 'page-setting',
  templateUrl: 'setting.html'
})
export class SettingPage {

  constructor(public nav: NavController) {
  }
}


text:
<?php

namespace NickMoline\Robots;

use NickMoline\Robots\Base as RobotsBase;
use PHPHtmlParser\Dom;

class Meta extends Status
{
    protected $userAgentAllowedLine = null;
    protected $globalAllowedLine = null;

    public static function createFromExisting(RobotsBase $existing, RobotsBase $robots = null)
    {
        if (!$robots) {
            $robots = new Meta();
        }

        $robots = Status::createFromExisting($existing, $robots);

        return $robots;
    }

    public function validate()
    {
        $dom = new Dom;
        $dom->load($this->contents);
        $metas = $dom->find('meta');

        foreach ($metas as $meta) {
            $this->processTagLine($meta);
        }

        if (!is_null($this->userAgentAllowed)) {
            $this->setAllowed($this->userAgentAllowed)
                 ->setReason($this->userAgentAllowedLine);
            return $this->userAgentAllowed;

        }

        if (!is_null($this->globalAllowed)) {
            $this->setAllowed($this->globalAllowed)
                 ->setReason($this->globalAllowedLine);

            return $this->globalAllowed;
        }

        if ($this->isAllowed()) {
            $this->setReason("No Meta Robots or Meta {$this->userAgent} Tag Present");
        }
        return $this->isAllowed();
    }

    private function lineAllowed($line)
    {
        $parts = preg_split("@[\s,]+@", strtolower($line));

        if (in_array("noindex", $parts)) {
            return false;
        }
        if (in_array("index", $parts)) {
            return true;
        }
        return null;
    }

    private function processTagLine($meta)
    {
        $name = $meta->getAttribute("name");
        if (!$name) return null;

        if (stristr($name, $this->userAgent)) {
            $content = $meta->getAttribute("content");
            $allowed = $this->lineAllowed($content);
            if (!is_null($allowed)) {
                $this->userAgentAllowed = $allowed;
                $this->userAgentLine = $meta->outerHtml;
                return $allowed;
            }
        }

        if (strtolower($name) == "robots") {
            $content = $meta->getAttribute("content");
            $allowed = $this->lineAllowed($content);
            if (!is_null($allowed)) {
                $this->globalAllowed = $allowed;
                $this->globalAllowedLine = $meta->outerHtml;
                return $allowed;
            }
        }

        return null;
    }
}


text:
package com.nobigsoftware.dfalex;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import backport.java.util.function.Consumer;

import static backport.java.util.function.BackportFuncs.forEach;

/**
 * Simple non-deterministic finite automaton (NFA) representation
 *

 * A set of {@link Matchable} patterns is converted to an NFA as an intermediate step toward
 * creating the DFA.
 *

 * You can also build an NFA directly with this class and convert it to a DFA with {@link
 * DfaBuilder#buildFromNfa(Nfa, int[], DfaAmbiguityResolver, com.nobigsoftware.util.BuilderCache)}.
 *

 * See NFA on
 * Wikipedia
 *
 * @param MATCHRESULT The type of result produce by matching a pattern.  This must be serializable
 *                    to support caching of built DFAs
 */
public class Nfa<MATCHRESULT> {
    private final ArrayList<List<NfaTransition>> m_stateTransitions = new ArrayList<>();
    private final ArrayList<List<Integer>> m_stateEpsilons = new ArrayList<>();
    private final ArrayList<MATCHRESULT> m_stateAccepts = new ArrayList<>();

    /**
     * Get the number of states in the NFA
     *
     * @return the total number of states that have been added with {@link #addState(Object)}
     */
    public int numStates() {
        return m_stateAccepts.size();
    }

    /**
     * Add a new state to the NFA
     *
     * @param accept if non-null, then the NFA will produce this result for any string that reaches
     *               the new state
     * @return the number of the new state
     */
    public int addState(MATCHRESULT accept) {
        int ret = m_stateAccepts.size();
        m_stateAccepts.add(accept);
        m_stateTransitions.add(null);
        m_stateEpsilons.add(null);
        assert (m_stateTransitions.size() == m_stateAccepts.size());
        assert (m_stateEpsilons.size() == m_stateAccepts.size());
        return ret;
    }

    /**
     * Add a transition to the NFA
     *

     * A new transition will be created from state <tt>from</tt> to state <tt>to</tt>
     * for all characters with code points in [from,to] (inclusive)
     *
     * @param from      the number of the state to transition from
     * @param to        the number of the state to transition to, for characters in the accepted
     *                  range
     * @param firstChar the first character in the accepted range
     * @param lastChar  the last character in the accepted range
     */
    public void addTransition(int from, int to, char firstChar, char lastChar) {
        List<NfaTransition> list = m_stateTransitions.get(from);
        if (list == null) {
            list = new ArrayList<>();
            m_stateTransitions.set(from, list);
        }
        list.add(new NfaTransition(firstChar, lastChar, to));
    }

    /**
     * Add an epsilon transition to the NFA
     *

     * An epsilon transition is created from state <tt>from</tt> to state <tt>to</tt>.
     *

     * This will cause any string that is accepted by <tt>to</tt> to be accepted by <tt>from</tt> as
     * well
     *
     * @param from the number of the state to transition from
     * @param to   the number of the state to transition to
     */
    public void addEpsilon(int from, int to) {
        List<Integer> list = m_stateEpsilons.get(from);
        if (list == null) {
            list = new ArrayList<Integer>();
            m_stateEpsilons.set(from, list);
        }
        list.add(to);
    }

    /**
     * Get the result attached to the given state
     *
     * @param state the state number
     * @return the result that was provided to {@link #addState(Object)} when the state was created
     */
    public MATCHRESULT getAccept(int state) {
        return m_stateAccepts.get(state);
    }

    /**
     * Check whether a state has any non-epsilon transitions or has a result attached
     *
     * @param state the state number
     * @return true if the state has any transitions or accepts
     */
    public boolean hasTransitionsOrAccepts(int state) {
        return (m_stateAccepts.get(state) != null || m_stateTransitions.get(state) != null);
    }

    /**
     * Get all the epsilon transitions from a state
     *
     * @param state the state number
     * @return An iterable over all transitions out of the given state
     */
    public Iterable<Integer> getStateEpsilons(int state) {
        List<Integer> list = m_stateEpsilons.get(state);
        List<Integer> emptyList = Collections.emptyList();
        return (list != null ? list : emptyList);
    }

    /**
     * Get all the non-epsilon transitions from a state
     *
     * @param state the state number
     * @return An iterable over all transitions out of the given state
     */
    public Iterable<NfaTransition> getStateTransitions(int state) {
        List<NfaTransition> list = m_stateTransitions.get(state);
        List<NfaTransition> emptyList = Collections.emptyList();
        return (list != null ? list : emptyList);
    }

    /**
     * Make modified state, if necessary, that doesn't match the empty string
     *

     * If <tt>state</tt> has a non-null result attached, or can reach such a state through
     * epsilon transitions, then a DFA made from that state would match the empty string.  In
     * that case a new NFA state will be created that matches all the same strings except
     * the empty string.
     *
     * @param state the number of the state to disemptify
     * @return If <tt>state</tt> matches the empty string, then a new state that does not match the
     * empty string is returned.  Otherwise <tt>state</tt> is returned.
     */
    public int Disemptify(final int state) {
        ArrayList<Integer> reachable = new ArrayList<>();

        //first find all epsilon-reachable states
        {
            Set<Integer> checkSet = new HashSet<>();
            reachable.add(state);
            checkSet.add(reachable.get(0)); //same Integer instance
            for (int i = 0; i < reachable.size(); ++i) {
                forStateEpsilons(reachable.get(i), num -> {
                    if (checkSet.add(num)) {
                        reachable.add(num);
                    }
                });
            }
        }

        //if none of them accept, then we're done
        for (int i = 0; ; ++i) {
            if (i >= reachable.size()) {
                return state;
            }
            if (getAccept(reachable.get(i)) != null) {
                break;
            }
        }

        //need to make a new disemptified state.  first get all transitions
        int newState = addState(null);
        Set<NfaTransition> transSet = new HashSet<>();
        for (Integer src : reachable) {
            forStateTransitions(src, trans -> {
                if (transSet.add(trans)) {
                    addTransition(newState, trans.m_stateNum, trans.m_firstChar, trans.m_lastChar);
                }
            });
        }
        return newState;
    }

    void forStateEpsilons(int state, Consumer<Integer> dest) {
        List<Integer> list = m_stateEpsilons.get(state);
        if (list != null) {
            forEach(list, dest);
        }
    }

    void forStateTransitions(int state, Consumer<NfaTransition> dest) {
        List<NfaTransition> list = m_stateTransitions.get(state);
        if (list != null) {
            forEach(list, dest);
        }
    }
}


text:
package org.zhenchao.oauth.entity;

public class Scope {
    private Integer id;

    private String name;

    private String description;

    private Integer level;

    private Integer type;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description == null ? null : description.trim();
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }
}


text:
package com.google.gxp.js;

import com.google.gxp.base.GxpClosure;

/**
 * Closure for content-type: text/javascript
 */
public interface JavascriptClosure extends GxpClosure {
}


text:
package us.eharning.atomun.mnemonic.spi.bip0039;

import com.google.common.base.Preconditions;
import com.tomgibara.bits.BitReader;
import com.tomgibara.bits.ByteArrayBitReader;

import javax.annotation.Nonnull;

/**
 * Utility class for BIP0039 index generators.
 */
final class BIP0039MnemonicIndexGenerator {
    /**
     * Private constructor to indicate no instances should be created.
     */
    private BIP0039MnemonicIndexGenerator() {
    }

    /**
     * Take the input entropy and output an array of word indices.
     *
     * @param entropy
     *         generated entropy to process.
     *
     * @return array of integer indices into dictionary.
     */
    @Nonnull
    public static int[] generateIndices(@Nonnull byte[] entropy) {
        Preconditions.checkNotNull(entropy);
        byte[] joined = new byte[entropy.length + 256 / 8];

        System.arraycopy(entropy, 0, joined, 0, entropy.length);
        BIP0039MnemonicUtility.sha256digest(joined, 0, entropy.length, joined, entropy.length);

        /* Convert the length to bits for purpose of BIP0039 specification match-up */
        int entropyBitCount = entropy.length * 8;
        int checksumBitCount = entropyBitCount / 32;
        int totalBitCount = entropyBitCount + checksumBitCount;
        int mnemonicSentenceLength = totalBitCount / 11;

        BitReader bitReader = new ByteArrayBitReader(joined);

        int[] indexValues = new int[mnemonicSentenceLength];
        for (int i = 0; i < mnemonicSentenceLength; i++) {
            int index = bitReader.read(11);
            indexValues[i] = index;
        }
        return indexValues;
    }
}


text:
package lenka.example.com.testtask.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import lenka.example.com.testtask.R;
import lenka.example.com.testtask.activities.cameraActivity.CustomCameraActivity;
import lenka.example.com.testtask.adapters.ImageItemListAdapter;
import lenka.example.com.testtask.entities.POJO.ImageItem;

/**
 * Created by Lenka on 02.04.2016.
 */
public class CreatedPhotosFragment extends Fragment {

    ListView createdPhotosListView;
    ImageItemListAdapter adapter;

    public CreatedPhotosFragment() {
        createdPhotosListView = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View createdPhotosView = inflater.inflate(R.layout.created_photos_layout, container, false);
        createdPhotosListView = (ListView) createdPhotosView.findViewById(R.id.created_photos_listview);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        params.weight = 1.0f;
        createdPhotosView.setLayoutParams(params);
        updateList();
        return createdPhotosView;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateList();
    }

    private List<ImageItem> initListOfImages(){
        ArrayList<ImageItem> createdPhotosList = new ArrayList<>();
        File file = new File(this.getContext().getApplicationContext().getFilesDir(), CustomCameraActivity.PHOTOS_DIRECTORY_NAME);
        File[] files = file.listFiles();
        if(files != null){
            for(File f : files){ // loop and print all file
                createdPhotosList.add(new ImageItem(f.getName(), f));
            }
        }
        return createdPhotosList;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void updateList(){
        adapter = new ImageItemListAdapter(this.getContext().getApplicationContext(), initListOfImages());
        createdPhotosListView.setAdapter(adapter);
    }
}


text:
/

    /// This function internally calls registerResource API.
    void createResource()
    {
        std::string resourceURI = m_lightUri; //URI of the resource
        std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.

        EntityHandler cb = std::bind(&LightResource::entityHandler, this, PH::_1);

        // This will internally create and register the resource.
        OCStackResult result = OCPlatform::registerResource(m_resourceHandle, resourceURI,
                resourceTypeName, resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);

        if (OC_STACK_OK != result)
        {
            cout << "Resource creation was unsuccessful\n";
        }
        else
        {
            cout << "Resource URI : " << resourceURI << endl;
            cout << "\tResource Type Name : " << resourceTypeName << endl;
            cout << "\tResource Interface : " << DEFAULT_INTERFACE << endl;
            cout << "\tResource creation is successful with resource handle : " << m_resourceHandle
                    << endl;
        }
    }

    OCResourceHandle getHandle()
    {
        return m_resourceHandle;
    }

    // Puts representation.
    // Gets values from the representation and
    // updates the internal state
    void put(OCRepresentation& rep)
    {
        try
        {
            if (rep.getValue("power", m_power))
            {
                cout << "\t\t\t\t" << "power: " << m_power << endl;
            }
            else
            {
                cout << "\t\t\t\t" << "power not found in the representation" << endl;
            }
        }
        catch (exception& e)
        {
            cout << e.what() << endl;
        }

    }

    // Post representation.
    // Post can create new resource or simply act like put.
    // Gets values from the representation and
    // updates the internal state
    OCRepresentation post(OCRepresentation& rep)
    {
        put(rep);
        return get();
    }

    // gets the updated representation.
    // Updates the representation with latest internal state before
    // sending out.
    OCRepresentation get()
    {
        m_lightRep.setValue("power", m_power);

        return m_lightRep;
    }

    void addType(const std::string& type) const
    {
        OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
        if (OC_STACK_OK != result)
        {
            cout << "Binding TypeName to Resource was unsuccessful\n";
        }
    }

    void addInterface(const std::string& interface) const
    {
        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
        if (OC_STACK_OK != result)
        {
            cout << "Binding TypeName to Resource was unsuccessful\n";
        }
    }

private:
// This is just a sample implementation of entity handler.
// Entity handler can be implemented in several ways by the manufacturer
    OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
    {
        cout << "\tIn Server CPP entity handler:\n";
        OCEntityHandlerResult ehResult = OC_EH_ERROR;
        if (request)
        {
            // Get the request type and request flag
            std::string requestType = request->getRequestType();
            int requestFlag = request->getRequestHandlerFlag();

            if (requestFlag & RequestHandlerFlag::RequestFlag)
            {
                cout << "\t\trequestFlag : Request\n";
                auto pResponse = std::make_shared< OC::OCResourceResponse >();
                pResponse->setRequestHandle(request->getRequestHandle());
                pResponse->setResourceHandle(request->getResourceHandle());

                // If the request type is GET
                if (requestType == "GET")
                {
                    cout << "\t\t\trequestType : GET\n";
                    if (isSlowResponse) // Slow response case
                    {
                        static int startedThread = 0;
                        if (!startedThread)
                        {
                            std::thread t(handleSlowResponse, (void *) this, request);
                            startedThread = 1;
                            t.detach();
                        }
                        ehResult = OC_EH_SLOW;
                    }
                    else // normal response case.
                    {
                        pResponse->setErrorCode(200);
                        pResponse->setResponseResult(OC_EH_OK);
                        pResponse->setResourceRepresentation(get());
                        if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                        {
                            ehResult = OC_EH_OK;
                        }
                    }
                }
                else if (requestType == "PUT")
                {
                    cout << "\t\t\trequestType : PUT\n";
                    OCRepresentation rep = request->getResourceRepresentation();

                    // Do related operations related to PUT request
                    // Update the lightResource
                    put(rep);
                    pResponse->setErrorCode(200);
                    pResponse->setResponseResult(OC_EH_OK);
                    pResponse->setResourceRepresentation(get());
                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                    {
                        ehResult = OC_EH_OK;
                    }
                }
                else if (requestType == "POST")
                {
                    cout << "\t\t\trequestType : POST\n";

                    OCRepresentation rep = request->getResourceRepresentation();

                    // Do related operations related to POST request
                    OCRepresentation rep_post = post(rep);
                    pResponse->setResourceRepresentation(rep_post);
                    pResponse->setErrorCode(200);
                    if (rep_post.hasAttribute("createduri"))
                    {
                        pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
                        pResponse->setNewResourceUri(
                                rep_post.getValue< std::string >("createduri"));
                    }

                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                    {
                        ehResult = OC_EH_OK;
                    }
                }
                else if (requestType == "DELETE")
                {
                    // DELETE request operations
                }
            }
        }
        else
        {
            std::cout << "Request invalid" << std::endl;
        }

        return ehResult;
    }
};

void * handleSlowResponse(void *param, std::shared_ptr< OCResourceRequest > pRequest)
{
    // This function handles slow response case
    LightResource* lightPtr = (LightResource*) param;
    // Induce a case for slow response by using sleep
    std::cout << "SLOW response" << std::endl;
    sleep(10);

    auto pResponse = std::make_shared< OC::OCResourceResponse >();
    pResponse->setRequestHandle(pRequest->getRequestHandle());
    pResponse->setResourceHandle(pRequest->getResourceHandle());
    pResponse->setResourceRepresentation(lightPtr->get());
    pResponse->setErrorCode(200);
    pResponse->setResponseResult(OC_EH_OK);

    // Set the slow response flag back to false
    isSlowResponse = false;
    OCPlatform::sendResponse(pResponse);
    return NULL;
}

int main(int argc, char* argv[])
{
    // Create PlatformConfig object
    PlatformConfig cfg
    { OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0",
    // By setting to "0.0.0.0", it binds to all available interfaces
            0,// Uses randomly available port
            OC::QualityOfService::LowQos };

    OCPlatform::Configure(cfg);
    try
    {
        // Create the instance of the resource class
        // (in this case instance of class 'LightResource').
        LightResource myLight;

        // Invoke createResource function of class light.
        myLight.createResource();

        // A condition variable will free the mutex it is given, then do a non-
        // intensive block until 'notify' is called on it.  In this case, since we
        // don't ever call cv.notify, this should be a non-processor intensive version
        // of while(true);
        std::mutex blocker;
        std::condition_variable cv;
        std::unique_lock < std::mutex > lock(blocker);
        cv.wait(lock);
    }
    catch (OCException e)
    {
        //log(e.what());
    }

    // No explicit call to stop the platform.
    // When OCPlatform::destructor is invoked, internally we do platform cleanup

    return 0;
}