text:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <exception>
#include <stdexcept>
#include <iomanip>
#include <limits>

#ifdef __WIN32__
// #include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#endif

#ifdef __WIN32__
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#include <unistd.h>
#endif

#include "protocol_v1.h"
#include "request.h"
#include "logger.h"
#include "utils.h"
#include "response.h"
#include "configuration.h"
#include "service/request_callback.h"

namespace org {
namespace labcrypto {
namespace hottentot {
namespace runtime {
  ProtocolV1::ProtocolV1(int remoteSocketFD)
    : Protocol(remoteSocketFD),
      isResponseComplete_(false),
      response_(0),
      readingLength_(0),
      readingCounter_(0),
      targetCounter_(0),
      currentState_(ReadingLengthState) {
  }
  ProtocolV1::~ProtocolV1() {
    if (response_) {
      delete response_;
    }
  }
  bool
  ProtocolV1::IsResponseComplete() {
    return isResponseComplete_;
  }
  Response*
  ProtocolV1::GetResponse() {
    return response_;
  }
  unsigned char*
  ProtocolV1::SerializeRequest(Request  &request,
                               uint32_t *length) {
    uint32_t actualLength = 0;
    actualLength += 1;  // Request type
    actualLength += 4;  // Service Id
    actualLength += 4;  // Method Id
    actualLength += 1;  // Number of arguments
    for (unsigned int i = 0; i < request.GetArgumentCount(); i++) {
      if (request.GetArgumentLength(i) < 128) {
        actualLength += 1;
        actualLength += request.GetArgumentLength(i);
      } else if (request.GetArgumentLength(i) < 256) {
        actualLength += 2;
        actualLength += request.GetArgumentLength(i);
      } else if (request.GetArgumentLength(i) < 256 * 256) {
        actualLength += 3;
        actualLength += request.GetArgumentLength(i);
      } else if (request.GetArgumentLength(i) < 256 * 256 * 256) {
        actualLength += 4;
        actualLength += request.GetArgumentLength(i);
#ifdef __CPPXX__
      } else if (request.GetArgumentLength(i) <= std::numeric_limits<uint32_t>::max()) {
#elif __WIN32__
      } else if (request.GetArgumentLength(i) <= _UI64_MAX) {
#endif
        actualLength += 5;
        actualLength += request.GetArgumentLength(i);
      }
    }
    *length = actualLength;
    unsigned char *data = new unsigned char[*length];
    unsigned int c = 0;
    data[c++] = request.GetType();
    uint32_t serviceId = request.GetServiceId();
    data[c++] = ((unsigned char *)&serviceId)[3];
    data[c++] = ((unsigned char *)&serviceId)[2];
    data[c++] = ((unsigned char *)&serviceId)[1];
    data[c++] = ((unsigned char *)&serviceId)[0];
    uint32_t methodId = request.GetMethodId();
    data[c++] = ((unsigned char *)&methodId)[3];
    data[c++] = ((unsigned char *)&methodId)[2];
    data[c++] = ((unsigned char *)&methodId)[1];
    data[c++] = ((unsigned char *)&methodId)[0];
    data[c++] = request.GetArgumentCount();
    for (unsigned int i = 0; i < request.GetArgumentCount(); i++) {
      if (request.GetArgumentLength(i) < 128) {
        data[c++] = request.GetArgumentLength(i);
      } else if (request.GetArgumentLength(i) < 256) {
        data[c++] = 0x81;
        data[c++] = request.GetArgumentLength(i);
      } else if (request.GetArgumentLength(i) < 256 * 256) {
        data[c++] = 0x82;
        data[c++] = request.GetArgumentLength(i) / 256;
        data[c++] = request.GetArgumentLength(i) % 256;
      } else if (request.GetArgumentLength(i) < 256 * 256 * 256) {
        data[c] = 0x83;
        data[c + 1] = request.GetArgumentLength(i) / (256 * 256);
        data[c + 2] = (request.GetArgumentLength(i) - data[c + 1] * 256 * 256) / 256;
        data[c + 3] = request.GetArgumentLength(i) % (256 * 256);
        c += 4;
#ifdef __CPPXX__
      } else if (request.GetArgumentLength(i) <= std::numeric_limits<uint32_t>::max()) {
#elif __WIN32__
      } else if (request.GetArgumentLength(i) <= _UI64_MAX) {
#endif
        data[c] = 0x84;
        data[c + 1] = request.GetArgumentLength(i) / (256 * 256 * 256);
        data[c + 2] = (request.GetArgumentLength(i) - data[c + 1] * 256 * 256 * 256) / (256 * 256);
        data[c + 3] = (request.GetArgumentLength(i) - data[c + 1] * 256 * 256 * 256 - data[c + 2] * 256 * 256) / 256;
        data[c + 4] = request.GetArgumentLength(i) % (256 * 256 * 256);
        c += 5;
      }
      unsigned char *argData = request.GetArgumentData(i);
      for (unsigned int j = 0; j < request.GetArgumentLength(i); j++) {
        data[c++] = argData[j];
      }
    }
    if (c != actualLength) {
      ::org::labcrypto::hottentot::runtime::Logger::GetError() <<
        "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
          "Inconsistency in request serialization process." << std::endl;
      exit(1);
    }
    return data;
  }
  unsigned char*
  ProtocolV1::SerializeResponse(Response &response,
                                uint32_t *length) {
    uint32_t actualLength = 0;
    actualLength += 1;  // Status Code
    if (response.GetDataLength() < 128) {
      actualLength += 1;
      actualLength += response.GetDataLength();
    } else if (response.GetDataLength() < 256) {
      actualLength += 2;
      actualLength += response.GetDataLength();
    } else if (response.GetDataLength() < 256 * 256) {
      actualLength += 3;
      actualLength += response.GetDataLength();
    } else if (response.GetDataLength() < 256 * 256 * 256) {
      actualLength += 4;
      actualLength += response.GetDataLength();
#ifdef __CPPXX__
      } else if (response.GetDataLength() <= std::numeric_limits<uint32_t>::max()) {
#elif __WIN32__
      } else if (response.GetDataLength() <= _UI64_MAX) {
#endif
      actualLength += 5;
      actualLength += response.GetDataLength();
    }
    *length = actualLength;
    unsigned char *data = new unsigned char[*length];
    unsigned int c = 0;
    data[c++] = response.GetStatusCode();
    if (response.GetDataLength() < 128) {
      data[c++] = response.GetDataLength();
    } else if (response.GetDataLength() < 256) {
      data[c++] = 0x81;
      data[c++] = response.GetDataLength();
    } else if (response.GetDataLength() < 256 * 256) {
      data[c++] = 0x82;
      data[c++] = response.GetDataLength() / 256;
      data[c++] = response.GetDataLength() % 256;
    } else if (response.GetDataLength() < 256 * 256 * 256) {
      data[c] = 0x83;
      data[c + 1] = response.GetDataLength() / (256 * 256);
      data[c + 2] = (response.GetDataLength() - data[c + 1] * 256 * 256) / 256;
      data[c + 3] = response.GetDataLength() % (256 * 256);
      c += 4;
#ifdef __CPPXX__
    } else if (response.GetDataLength() <= std::numeric_limits<uint32_t>::max()) {
#elif __WIN32__
    } else if (response.GetDataLength() <= _UI64_MAX) {
#endif
      data[c] = 0x84;
      data[c + 1] = response.GetDataLength() / (256 * 256 * 256);
      data[c + 2] = (response.GetDataLength() - data[c + 1] * 256 * 256 * 256) / (256 * 256);
      data[c + 3] = (response.GetDataLength() - data[c + 1] * 256 * 256 * 256 - data[c + 2] * 256 * 256) / 256;
      data[c + 4] = response.GetDataLength() % (256 * 256 * 256);
      c += 5;
    }
    unsigned char *argData = response.GetData();
    for (uint32_t i = 0; i < response.GetDataLength(); i++) {
      data[c++] = argData[i];
    }
    return data;
  }
  Request*
  ProtocolV1::DeserializeRequest(unsigned char  *data,
                                 uint32_t       dataLength) {
    uint32_t c = 0;
    Request *request = new Request;
    request->SetType((Request::RequestType)data[c++]);
    if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
          "Request Type: " << request->GetType() << std::endl;
    }
    uint32_t serviceId = 0;
    ((unsigned char *)(&serviceId))[3] = data[c++];
    ((unsigned char *)(&serviceId))[2] = data[c++];
    ((unsigned char *)(&serviceId))[1] = data[c++];
    ((unsigned char *)(&serviceId))[0] = data[c++];
    request->SetServiceId(serviceId);
    if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
          "Service Id: " << serviceId << std::endl;
    }
    uint32_t methodId = 0;
    ((unsigned char *)(&methodId))[3] = data[c++];
    ((unsigned char *)(&methodId))[2] = data[c++];
    ((unsigned char *)(&methodId))[1] = data[c++];
    ((unsigned char *)(&methodId))[0] = data[c++];
    request->SetMethodId(methodId);
    if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
          "Method Id: " << methodId << std::endl;
    }
    uint8_t argCount = data[c++];
    if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
          "Arg. Count: " << (uint8_t)argCount << std::endl;
    }
    for (unsigned int k = 0; k < (uint8_t)argCount; k++) {
      if (data[c] == 0x00) {
        request->AddArgument(0, 0);
        if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
          ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
            "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
              "Argument[" << k << "] Length: " << 0 << std::endl;
          ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
            "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
              "Argument has zero length." << std::endl;
        }
      } else {
        uint32_t argLength = 0;
        if ((data[c] & 0x80) == 0) {
          argLength = data[c];
          c++;
        } else if (data[c] == 0x81) {
          argLength = data[c + 1];
          c += 2;
        } else if (data[c] == 0x82) {
          argLength = data[c + 1] * 256 + data[c + 2];
          c += 3;
        } else if (data[c] == 0x83) {
          argLength = data[c + 1] * 256 * 256 + data[c + 2] * 256 + data[c + 3];
          c += 4;
        } else if (data[c] == 0x84) {
          argLength = data[c + 1] * 256 * 256 * 256 + data[c + 2] * 256 * 256 + data[c + 3] * 256 + data[c + 4];
          c += 5;
        }
        unsigned char *argData = new unsigned char[argLength];
        for (uint32_t i = 0; i < argLength; i++) {
          argData[i] = data[c++];
        }
        if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
          ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
            "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
              "Argument[" << k << "] Length: " << argLength << std::endl;
          ::org::labcrypto::hottentot::runtime::Utils::PrintArray("Argument Data", argData, argLength);
        }
        request->AddArgument(argData, argLength);
      }
    }
    return request;
  }
  Response*
  ProtocolV1::DeserializeResponse(unsigned char *data,
                                  uint32_t       dataLength) {
    Response *response = new Response;
    uint32_t c = 0;
    response->SetStatusCode(data[c++]);
    uint32_t resultLength = 0;
    if (data[c] == 0x00) {
      response->SetData(0);
      response->SetDataLength(0);
      if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
        ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
          "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
            "Response has zero length." << std::endl;
      }
      return response;
    } else {
      if ((data[c] & 0x80) == 0) {
        resultLength = data[c];
        c++;
      } else if (data[c] == 0x81) {
        resultLength = data[c + 1];
        c += 2;
      } else if (data[c] == 0x82) {
        resultLength = data[c + 1] * 256 + data[c + 2];
        c += 3;
      } else if (data[c] == 0x83) {
        resultLength = data[c + 1] * 256 * 256 + data[c + 2] * 256 + data[c + 3];
        c += 4;
      } else if (data[c] == 0x84) {
        resultLength = data[c + 1] * 256 * 256 * 256 + data[c + 2] * 256 * 256 + data[c + 3] * 256 + data[c + 4];
        c += 5;
      }
      unsigned char *resultData = new unsigned char[resultLength];
      for (uint32_t i = 0; i < resultLength; i++) {
        resultData[i] = data[c++];
      }
      response->SetData(resultData);
      response->SetDataLength(resultLength);
      if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
        ::org::labcrypto::hottentot::runtime::Utils::PrintArray("Response", resultData, resultLength);
      }
    }
    return response;
  }
  void
  ProtocolV1::ProcessDataForRequest(unsigned char *data,
                                    uint32_t       dataLength) {
    if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
          "We have data with length " << dataLength << " Bytes." << std::endl;
    }
    for (unsigned int i = 0; i < dataLength;) {
      if (currentState_ == ReadingLengthState) {
        if (readingCounter_ == 0) {
          readingBuffer_.clear();
          if ((data[i] & 0x80) == 0) {
            readingLength_ = data[i];
            readingCounter_ = 0;
            currentState_ = ReadingDataState;
            if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
              ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                  "Request length is " << readingLength_ << " Bytes." << std::endl;
            }
          } else {
            targetCounter_ = (data[i] & 0x0f);
            readingBuffer_.push_back(data[i]);
            readingCounter_++;
            if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
              ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                  "Length is more than 127." << std::endl;
            }
          }
        } else {
          if (readingCounter_ <= targetCounter_) {
            // Gathering length bytes
            readingBuffer_.push_back(data[i]);
            readingCounter_++;
          } else {
            uint32_t temp = 1;
            readingLength_ = 0;
            for (unsigned int c = targetCounter_; c > 0; c--) {
              readingLength_ += readingBuffer_[c] * temp;
              temp *= 256;
            }
            readingBuffer_.clear();
            readingCounter_ = 0;
            currentState_ = ReadingDataState;
            if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
              ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                  "Request length is " << readingLength_ << " Bytes." << std::endl;
            }
            // Variable 'i' shouldn't get incremented because no byte is processed here.
            i--;
          }
        }
      } else if (currentState_ == ReadingDataState) {
        if (readingCounter_ == 0) {
          readingBuffer_.clear();
          readingBuffer_.push_back(data[i]);
          readingCounter_++;
          // ::org::labcrypto::hottentot::runtime::Logger::GetOut() << ">>>>> " << readingCounter_ << " from " << targetCounter_ << " : " << (unsigned int)data[i] << std::endl;
          targetCounter_ = readingLength_;
          if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
            ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
              "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                "Preparing for reading the request body ..." << std::endl;
          }
        } else {
          if (readingCounter_ < targetCounter_) {
            // ::org::labcrypto::hottentot::runtime::Logger::GetOut() << "Reading request body : 0x" << std::hex << std::setfill('0') << std::setw(2) << (int)data[i] << " ..." << std::dec << std::endl;
            readingBuffer_.push_back(data[i]);
            readingCounter_++;
            // ::org::labcrypto::hottentot::runtime::Logger::GetOut() << ">>>>> " << readingCounter_ << " from " << targetCounter_ << " : " << (unsigned int)data[i] << std::endl;
            if (readingCounter_ == targetCounter_) {
              if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                  "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                    "We have read " << readingCounter_ << " Bytes of request body ..." << std::endl;
              }
              uint32_t requestLength = readingLength_;
              unsigned char *requestData = new unsigned char[requestLength];
              for (unsigned int c = 0; c < requestLength; c++) {
                requestData[c] = readingBuffer_[c];
              }
              readingBuffer_.clear();
              readingCounter_ = 0;
              currentState_ = ReadingLengthState;
              // Request deserialization
              if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                  "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                    "Deserializing request ..." << std::endl;
              }
              Request *request = DeserializeRequest(requestData, requestLength);
              if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                  "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                    "Deserialized." << std::endl;
              }
              if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                  "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                    "Calling callback ..." << std::endl;
              }
              Response *response = requestCallback_->OnRequest(this, *request);
              if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                  "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                    "Callback was successful." << std::endl;
              }
              if (response) {
                uint32_t responseSerializedLength = 0;
                unsigned char *responseSerializedData = SerializeResponse(*response, &responseSerializedLength);
                if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                  ::org::labcrypto::hottentot::runtime::Utils::PrintArray("Serialized response: ", responseSerializedData, responseSerializedLength);
                }
                uint32_t sendLength = 0;
                if (responseSerializedLength < 128) {
                  sendLength = 1 + responseSerializedLength;
                } else if (responseSerializedLength < 256) {
                  sendLength = 2 + responseSerializedLength;
                } else if (responseSerializedLength < 256 * 256) {
                  sendLength = 3 + responseSerializedLength;
                } else if (responseSerializedLength < 256 * 256 * 256) {
                  sendLength = 4 + responseSerializedLength;
#ifdef __CPPXX__
                } else if (responseSerializedLength <= std::numeric_limits<uint32_t>::max()) {
#elif __WIN32__
                } else if (responseSerializedLength <= _UI64_MAX) {
#endif
                  sendLength = 5 + responseSerializedLength;
                }
                unsigned char *sendData = new unsigned char[sendLength];
                uint32_t c = 0;
                if (responseSerializedLength < 128) {
                  sendData[c++] = responseSerializedLength;
                } else if (responseSerializedLength < 256) {
                  sendData[c++] = 0x81;
                  sendData[c++] = responseSerializedLength;
                } else if (responseSerializedLength < 256 * 256) {
                  sendData[c++] = 0x82;
                  sendData[c++] = responseSerializedLength / 256;
                  sendData[c++] = responseSerializedLength % 256;
                } else if (responseSerializedLength < 256 * 256 * 256) {
                  sendData[c] = 0x83;
                  sendData[c + 1] = responseSerializedLength / (256 * 256);
                  sendData[c + 2] = (responseSerializedLength - sendData[c + 1] * 256 * 256) / 256;
                  sendData[c + 3] = responseSerializedLength % (256 * 256);
                  c += 4;
#ifdef __CPPXX__
                } else if (responseSerializedLength <= std::numeric_limits<uint32_t>::max()) {
#elif __WIN32__
                } else if (responseSerializedLength <= _UI64_MAX) {
#endif
                  sendData[c] = 0x84;
                  sendData[c + 1] = responseSerializedLength / (256 * 256 * 256);
                  sendData[c + 2] = (responseSerializedLength - sendData[c + 1] * 256 * 256 * 256) / (256 * 256);
                  sendData[c + 3] = (responseSerializedLength - sendData[c + 1] * 256 * 256 * 256 - sendData[c + 2] * 256 * 256) / 256;
                  sendData[c + 4] = responseSerializedLength % (256 * 256 * 256);
                  c += 5;
                }
                for (unsigned int k = 0; k < responseSerializedLength; k++) {
                  sendData[c++] = responseSerializedData[k];
                }
                if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                  ::org::labcrypto::hottentot::runtime::Utils::PrintArray("Response2", sendData, sendLength);
                }
                if (sendLength > 0) {
#ifdef __UNIX__
                  try {
                    int result = write(remoteSocketFD_, sendData, sendLength * sizeof(unsigned char));
                    if (result <= 0) {
                      throw std::runtime_error("[" + Utils::GetCurrentUTCTimeString() + "]: Write to proxy failed.");
                    }
#else
                  try {
                    int result = send(remoteSocketFD_, (char *)sendData, sendLength * sizeof(unsigned char), 0);
                    if (result == SOCKET_ERROR) {
                      throw std::runtime_error("[" + Utils::GetCurrentUTCTimeString() + "]: Write to proxy failed.");
                    }
#endif
                  } catch (std::exception &e) {
                    ::org::labcrypto::hottentot::runtime::Logger::GetError() <<
                      "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                         e.what() << std::endl;
                  }
                }
                delete [] sendData;
                delete [] responseSerializedData;
                delete response;
              } else {
                ::org::labcrypto::hottentot::runtime::Logger::GetError() <<
                  "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                    "No handler is found." << std::endl;
              }
              delete request;
              delete [] requestData;
            }
          }
        }
      }
      i++;
    }
  }
  void
  ProtocolV1::ProcessDataForResponse(unsigned char *data,
                                     uint32_t       dataLength) {
    for (unsigned int i = 0; i < dataLength;) {
      if (currentState_ == ReadingLengthState) {
        if (readingCounter_ == 0) {
          if ((data[i] & 0x80) == 0) {
            isResponseComplete_ = false;
            readingLength_ = data[i];
            readingCounter_ = 0;
            currentState_ = ReadingDataState;
            if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
              ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                  "Response length is " << readingLength_ << " Bytes." << std::endl;
            }
          } else {
            targetCounter_ = (data[i] & 0x0f) + 1;
            readingBuffer_.clear();
            readingBuffer_.push_back(data[i]);
            readingCounter_++;
          }
        } else {
          if (readingCounter_ < targetCounter_) {
            readingBuffer_.push_back(data[i]);
            readingCounter_++;
          } else {
            uint32_t temp = 1;
            readingLength_ = 0;
            for (unsigned int c = targetCounter_ - 1; c > 0; c--) {
              readingLength_ += readingBuffer_[c] * temp;
              temp *= 256;
            }
            readingCounter_ = 0;
            currentState_ = ReadingDataState;
            if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
              ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
                "[" << Utils::GetCurrentUTCTimeString() << "]: " <<
                  "Response length is " << readingLength_ << " Bytes." << std::endl;
            }
            // Variable 'i' shouldn't get incremented because no byte is processed here.
            i--;
          }
        }
      } else if (currentState_ == ReadingDataState) {
        if (readingCounter_ == 0) {
          readingBuffer_.clear();
          readingBuffer_.push_back(data[i]);
          readingCounter_++;
          targetCounter_ = readingLength_;
        } else {
          if (readingCounter_ < targetCounter_) {
            if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
              // ::org::labcrypto::hottentot::runtime::Logger::GetOut() << "Reading response body : 0x" << std::hex << std::setfill('0') << std::setw(2) << (int)data[i] << " ..." << std::dec << std::endl;
            }
            readingBuffer_.push_back(data[i]);
            readingCounter_++;
            if (readingCounter_ == targetCounter_) {
              uint32_t responseLength = readingLength_;
              unsigned char *responseData = new unsigned char[responseLength];
              for (unsigned int c = 0; c < responseLength; c++) {
                responseData[c] = readingBuffer_[c];
              }
              if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
                ::org::labcrypto::hottentot::runtime::Utils::PrintArray("Response", responseData, responseLength);
              }
              response_ = DeserializeResponse(responseData, responseLength);
              readingBuffer_.clear();
              readingCounter_ = 0;
              currentState_ = ReadingLengthState;
              isResponseComplete_ = true;
              delete [] responseData;
            }
          }
        }
      }
      i++;
    }
  }
}
}
}
}


text:
__author__ = "BOSS Team"

def strfix(msg):
  """
  Copies this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523011
  Constants out any characters that spew encoding errors
  """
  goodchars = {}
  try:
    return str(msg)
  except UnicodeEncodeError:
    res=''
    for i in list(msg):
      if i not in goodchars:
        try:
          str(i)
          goodchars[i] = i
        except UnicodeEncodeError:
          # format character as python string constant
          code = ord(i)
          t = None
          if code < 256:
            t ='\\x%02x' % code # 8-bit value
          elif code < 65536:
            t ='\\u%04x' % code # 16-bit value unicode
          else:
            t = '\\U%08x' % code # other values as 32-bit unicode
          goodchars[i] = t # or '.' for readability ;-)
      res += goodchars[i]
    return res

def write(msg):
  print strfix(msg)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <title>Code-O-Soccer 2017</title>

  <link rel="stylesheet" type="text/css" href="css/jquery.fullPage.css" />
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/skew.css" type="text/css" rel="stylesheet">
  <link href="css/terminal.css" type="text/css" rel="stylesheet">
  <link href="http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic,700italic" rel="stylesheet" type="text/css"/>
  <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">

In Association With

The Annual Techno-Management Fest of
 IIT Kharagpur

Code-O-Soccer&nbsp2017

Kharagpur RoboSoccer Students' Group

Home

Item1

Item2

Item3

Item4

Item5

About

                Code-O-Soccer is a coding competition conducted by Kharagpur RoboSoccer Students' Group. This is a first of its kind competition in India where soccer strategies brewing within one's mind are implemented on robots.

                The aim of the event is to introduce the concept of autonomous soccer playing robots to students and motivate them to create a challenging strategy using our API for a THREE BY THREE robot match.

[User]$

                      <input type="text" id="term-command"/>

What's in it for you?

Code-O-Soccer is one of a kind competetion in India. You can get a taste of what Simurosot in RoboWorld Cup is like. You get to battle your way up through the best in the country, under the supervision of the team that won Bronze in Mirosot 2015.

Additionally, there are prizes worth Rs. 50,000 up for grabs!

                  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
                    <line class="top" x1="0" y1="0" x2="900" y2="0"/>
                    <line class="left" x1="0" y1="460" x2="0" y2="-920"/>
                    <line class="bottom" x1="300" y1="460" x2="-600" y2="460"/>
                    <line class="right" x1="300" y1="0" x2="300" y2="1380"/>
                  </svg>

Who?

                  Participation is open to all programming and football enthusiasts. The event is about planning Soccer strategies and framing them in your codes. Interested people without the required coding skills can team up with coders!

                  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
                    <line class="top" x1="0" y1="0" x2="900" y2="0"/>
                    <line class="left" x1="0" y1="460" x2="0" y2="-920"/>
                    <line class="bottom" x1="300" y1="460" x2="-600" y2="460"/>
                    <line class="right" x1="300" y1="0" x2="300" y2="1380"/>
                  </svg>

Rules

                  Some easy do's and don'ts that are simpler to follow than those of a real soccer game! So don't dread them or tread over them. They are explained in the Tutorials section.

                  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
                    <line class="top" x1="0" y1="0" x2="900" y2="0"/>
                    <line class="left" x1="0" y1="460" x2="0" y2="-920"/>
                    <line class="bottom" x1="300" y1="460" x2="-600" y2="460"/>
                    <line class="right" x1="300" y1="0" x2="300" y2="1380"/>
                  </svg>

Judging

                  Your ranking will be up on the leader board. Your code will be up against that of your rival in a 3-on-3 RoboSoccer match. Good old knockout style tournament. Start coaching your bots already!

Skewed One Page Scroll

Just scroll down

Page 2

Nothing to do here, continue scrolling.

Page 3

The end is near, I promise!

Page 4

Ok, ok, just one more scroll!

Epic finale

                  Feel free to check
                  my other pens and follow me on
                  Twitter

About KRSSG:

It is a research group comprising of a bunch of ardent robotics technocrats from the Indian Institute of Technology, Kharagpur working together to build autonomous soccer-playing robots. The research objective of the group is to build and study cooperative multi-agent systems in highly dynamic adversarial environments. Our Aim is to participate in two International events FIRA and RoboCup.

Contact Us:

Link 1

Link 2

Link 3

Link 4

Social:

Link 1

Link 2

Link 3

Link 4


text:
package org.cleartk.corpus.genia.pos.util;

/**
 *

 * Copyright (c) 2007-2008, Regents of the University of Colorado

 * All rights reserved.
 */

public class Span {

  int begin;

  int end;

  public Span(int begin, int end) {
    this.begin = begin;
    this.end = end;
  }

  public int getBegin() {
    return begin;
  }

  public int getEnd() {
    return end;
  }

  public String toString() {
    return "" + begin + "|" + end;
  }
}


text:
require 'jsonpath'
require 'cgi'
require 'addressable/uri'

module Utils
  def self.unindent(s)
    s = s.gsub(/\t/, '  ').chomp
    min = ((s.split("\n").find {|l| l !~ /^\s*$/ })[/^\s+/, 0] || "").length
    if min > 0
      s.gsub(/^#{" " * min}/, "")
    else
      s
    end
  end

  def self.pretty_print(struct, indent = true)
    output = JSON.pretty_generate(struct)
    if indent
      output.gsub(/\n/i, "\n    ")
    else
      output
    end
  end

  def self.normalize_uri(uri)
    begin
      URI(uri)
    rescue URI::Error
      begin
        URI(uri.to_s.gsub(/[^\-_.!~*'()a-zA-Z\d;\/?:@&=+$,\[\]]+/) { |unsafe|
              unsafe.bytes.each_with_object(String.new) { |uc, s|
                s << sprintf('%%%02X', uc)
              }
            }.force_encoding(Encoding::US_ASCII))
      rescue URI::Error => e
        begin
          auri = Addressable::URI.parse(uri.to_s)
        rescue
          # Do not leak Addressable::URI::InvalidURIError which
          # callers might not expect.
          raise e
        else
          # Addressable::URI#normalize! modifies the query and
          # fragment components beyond escaping unsafe characters, so
          # avoid using it.  Otherwise `?a[]=%2F` would be normalized
          # as `?a%5B%5D=/`, for example.
          auri.site = auri.normalized_site
          auri.path = auri.normalized_path
          URI(auri.to_s)
        end
      end
    end
  end

  def self.interpolate_jsonpaths(value, data, options = {})
    if options[:leading_dollarsign_is_jsonpath] && value[0] == '$'
      Utils.values_at(data, value).first.to_s
    else
      value.gsub(/<[^>]+>/).each { |jsonpath|
        Utils.values_at(data, jsonpath[1..-2]).first.to_s
      }
    end
  end

  def self.recursively_interpolate_jsonpaths(struct, data, options = {})
    case struct
      when Hash
        struct.inject({}) {|memo, (key, value)| memo[key] = recursively_interpolate_jsonpaths(value, data, options); memo }
      when Array
        struct.map {|elem| recursively_interpolate_jsonpaths(elem, data, options) }
      when String
        interpolate_jsonpaths(struct, data, options)
      else
        struct
    end
  end

  def self.value_at(data, path)
    values_at(data, path).first
  end

  def self.values_at(data, path)
    if path =~ /\Aescape /
      path.gsub!(/\Aescape /, '')
      escape = true
    else
      escape = false
    end

    result = JsonPath.new(path).on(data.is_a?(String) ? data : data.to_json)
    if escape
      result.map {|r| CGI::escape r }
    else
      result
    end
  end

  # Output JSON that is ready for inclusion into HTML.  If you simply use to_json on an object, the
  # presence of </script> in the valid JSON can break the page and allow XSS attacks.
  # Optionally, pass `:skip_safe => true` to not call html_safe on the output.
  def self.jsonify(thing, options = {})
    json = thing.to_json.gsub('</', '<\/')
    if !options[:skip_safe]
      json.html_safe
    else
      json
    end
  end

  def self.pretty_jsonify(thing)
    JSON.pretty_generate(thing).gsub('</', '<\/')
  end

  class TupleSorter
    class SortableTuple
      attr_reader :array

      # The <=> method will call orders[n] to determine if the nth element
      # should be compared in descending order.
      def initialize(array, orders = [])
        @array = array
        @orders = orders
      end

      def <=> other
        other = other.array
        @array.each_with_index do |e, i|
          o = other[i]
          case cmp = e <=> o || e.to_s <=> o.to_s
          when 0
            next
          else
            return @orders[i] ? -cmp : cmp
          end
        end
        0
      end
    end

    class << self
      def sort!(array, orders = [])
        array.sort_by! do |e|
          SortableTuple.new(e, orders)
        end
      end
    end
  end

  def self.sort_tuples!(array, orders = [])
    TupleSorter.sort!(array, orders)
  end

  def self.parse_duration(string)
    return nil if string.blank?
    case string.strip
    when /\A(\d+)\.(\w+)\z/
      $1.to_i.send($2.to_s)
    when /\A(\d+)\z/
      $1.to_i
    else
      STDERR.puts "WARNING: Invalid duration format: '#{string.strip}'"
      nil
    end
  end

  def self.if_present(string, method)
    if string.present?
      string.send(method)
    else
      nil
    end
  end

  module HTMLTransformer
    SINGLE = 1
    MULTIPLE = 2
    COMMA_SEPARATED = 3
    SRCSET = 4

    URI_ATTRIBUTES = {
      'a' => { 'href' => SINGLE },
      'applet' => { 'archive' => COMMA_SEPARATED, 'codebase' => SINGLE },
      'area' => { 'href' => SINGLE },
      'audio' => { 'src' => SINGLE },
      'base' => { 'href' => SINGLE },
      'blockquote' => { 'cite' => SINGLE },
      'body' => { 'background' => SINGLE },
      'button' => { 'formaction' => SINGLE },
      'command' => { 'icon' => SINGLE },
      'del' => { 'cite' => SINGLE },
      'embed' => { 'src' => SINGLE },
      'form' => { 'action' => SINGLE },
      'frame' => { 'longdesc' => SINGLE, 'src' => SINGLE },
      'head' => { 'profile' => SINGLE },
      'html' => { 'manifest' => SINGLE },
      'iframe' => { 'longdesc' => SINGLE, 'src' => SINGLE },
      'img' => { 'longdesc' => SINGLE, 'src' => SINGLE, 'srcset' => SRCSET, 'usemap' => SINGLE },
      'input' => { 'formaction' => SINGLE, 'src' => SINGLE, 'usemap' => SINGLE },
      'ins' => { 'cite' => SINGLE },
      'link' => { 'href' => SINGLE },
      'object' => { 'archive' => MULTIPLE, 'classid' => SINGLE, 'codebase' => SINGLE, 'data' => SINGLE, 'usemap' => SINGLE },
      'q' => { 'cite' => SINGLE },
      'script' => { 'src' => SINGLE },
      'source' => { 'src' => SINGLE, 'srcset' => SRCSET },
      'video' => { 'poster' => SINGLE, 'src' => SINGLE },
    }

    URI_ELEMENTS_XPATH = '//*[%s]' % URI_ATTRIBUTES.keys.map { |name| "name()='#{name}'" }.join(' or ')

    module_function

    def transform(html, &block)
      block or raise ArgumentError, 'block must be given'

      case html
      when /\A\s*(?:<\?xml[\s?]|<!DOCTYPE\s)/i
        doc = Nokogiri.parse(html)
        yield doc
        doc.to_s
      when /\A\s*<(html|head|body)[\s>]/i
        # Libxml2 automatically adds DOCTYPE and <html>, so we need to
        # skip them.
        element_name = $1
        doc = Nokogiri::HTML::Document.parse(html)
        yield doc
        doc.at_xpath("//#{element_name}").xpath('self::node() | following-sibling::node()').to_s
      else
        doc = Nokogiri::HTML::Document.parse("<html><body>#{html}")
        yield doc
        doc.xpath("/html/body/node()").to_s
      end
    end

    def replace_uris(html, &block)
      block or raise ArgumentError, 'block must be given'

      transform(html) { |doc|
        doc.xpath(URI_ELEMENTS_XPATH).each { |element|
          uri_attrs = URI_ATTRIBUTES[element.name] or next
          uri_attrs.each { |name, format|
            attr = element.attribute(name) or next
            case format
            when SINGLE
              attr.value = block.call(attr.value.strip)
            when MULTIPLE
              attr.value = attr.value.gsub(/(\S+)/) { block.call($1) }
            when COMMA_SEPARATED, SRCSET
              attr.value = attr.value.gsub(/((?:\A|,)\s*)(\S+)/) { $1 + block.call($2) }
            end
          }
        }
      }
    end
  end

  def self.rebase_hrefs(html, base_uri)
    base_uri = normalize_uri(base_uri)
    HTMLTransformer.replace_uris(html) { |url|
      base_uri.merge(normalize_uri(url)).to_s
    }
  end
end


text:
Game::Game(
    sf::RenderWindow* window,
    const sf::VideoMode& mode,
    const string& title,
    const sf::ContextSettings& settings
) :
    window_(window),
    windowMode_(mode),
    windowTitle_(title),
    windowSettings_(settings),
    board_(8, 8, 5)
{
    //  initialise flags
    flags_["fullscreen"] = false;
    flags_["balls"] = false;
    flags_["path"] = false;
    flags_["fpv"] = true;
    flags_["guessing"] = false;
    flags_["running"] = true;
    flags_["shouldDismissMessageBox"] = false;
    flags_["hints"] = false;

    //  initialise world
    board_.setPlayerPosition(3);
    soundRenderer_.game = this;
    showWelcomeMessage();

    clock_.restart();
}

////////////////////////////////////////////////////////////////////////////////
void Game::showWelcomeMessage()
{
    stringstream stream;
    stream << "Welcome to ARDO!" << endl;
    stream << "This is a remake of the 1970's Boardgame" << endl;
    stream << "'BlackBox' or later 'ORDO'. Your goal is" << endl;
    stream << "to guess the five balls located some-" << endl;
    stream << "where on the board. But unlike the ori-" << endl;
    stream << "ginal game, you send beams of sound into" << endl;
    stream << "the field and have to listen carefully," << endl;
    stream << "in order to make out the balls, which" << endl;
    stream << "guide the sound along the board." << endl;
    stream << endl;
    stream << "Good luck!" << endl;
    stream << endl;
    stream << "PRESS ANY KEY TO CONTINUE" << endl;

    hud_.addMessageBox(Hud::Center, stream.str(), HudMessage::Permanent);
    flags_["shouldDismissMessageBox"] = true;
}

////////////////////////////////////////////////////////////////////////////////
void Game::update()
{
    const float dt = clock_.getElapsedTime().asSeconds();

    //  set guess orientation to player orientation
    if (renderer_.isFirstPerson()) {
        marker_.orientation = board_.getPlayerDirection();
    } else {
        marker_.orientation = Up;
    }

    //  update sound positions and play sounds
    Renderer::State state = renderer_.getPlayerState(board_);
    soundRenderer_.setListenerState(state);
    soundRenderer_.update(dt);

    clock_.restart();
}

////////////////////////////////////////////////////////////////////////////////
void Game::render()
{
    //  render everything
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    renderer_.setViewActive(board_);
    renderer_.drawBoard(board_);
    renderer_.drawPlayer(board_.getPlayerCenter());

    if (flags_["balls"]) {
        renderer_.drawBalls(board_.getBalls());
    }

    if (flags_["path"]) {
        renderer_.drawPath(board_.getPath(true));
    }

    if (flags_["guessing"]) {
        renderer_.drawGuesses(board_.getGuesses());
        renderer_.drawMarker(marker_.position);
    }

    hud_.draw(*window_);

    window_->display();
}

////////////////////////////////////////////////////////////////////////////////
void Game::shoot()
{
    shots_++;

    stringstream stream;
    stream << "PEW";

    if (flags_["hints"]) {
        stream << ". ";
    }

    //  get path
    const vector<vec2i> path = board_.getPath(false);

    //  keep track of points
    const vec2i& first = *path.begin();
    const vec2i& last = *prev(path.end());

    //  reflection
    if (first == last) {
        if (flags_["hints"]) stream << "REFLECT!";
        points_++;
    //  hit
    } else if (!board_.isBorder(last)) {
        if (flags_["hints"])stream << "HIT!";
        points_++;
    //  detour
    } else {
        if (flags_["hints"]) stream << "DETOUR!";
        points_ += 2;
    }

    hud_.addMessage(Hud::Center, stream.str(), 0.5f);
}

////////////////////////////////////////////////////////////////////////////////
void Game::guess()
{
    //  one can only submit if all balls are set ...
    if (board_.getNumGuesses() < board_.getNumBalls())
    {
        stringstream stream;
        stream << "YOU NEED " << board_.getNumBalls() << " GUESSED BALLS FOR SUBMISSION";

        hud_.addMessageBox(Hud::Center, stream.str(), HudMessage::Permanent);
        flags_["shouldDismissMessageBox"] = true;
    }
    //  ... which would be here
    else
    {
        const auto& guesses = board_.getGuesses();

        //  count correct guesses
        int correct = 0;

        for (const auto& guess : guesses) {
            if (board_.isBall(guess)) {
                correct++;
            }
        }

        //  account wrong guesses
        if (correct < board_.getNumBalls()) {
            hud_.addMessageBox(Hud::Center, "TRY AGAIN", 2.0f);
            points_ += 5 * (board_.getNumBalls() - correct);
        }
        //  all correct
        else
        {
            stringstream stream;
            stream << "BOOYA! NICELY DONE!" << endl;
            stream << "YOUR FINAL SCORE IS " << points_ << "." << endl;
            stream << "IT TOOK YOU " << shots_ << " SHOTS" << endl;
            stream << "TO START A NEW GAME, PRESS 'BACKSPACE'";

            hud_.addMessageBox(Hud::Center, stream.str(), HudMessage::Permanent);
            flags_["shouldDismissMessageBox"] = true;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
void Game::reset()
{
//    hud_.addMessageBox(Hud::Center, "STARTING NEW GAME", 2.0f);
    showWelcomeMessage();

    shots_ = 0;
    points_ = 0;

    board_.initBallsRandom(5);

    flags_["balls"] = false;
    flags_["path"] = false;
    flags_["guessing"] = false;
}

////////////////////////////////////////////////////////////////////////////////
void Game::toggleFullscreen()
{
    if (flags_["fullscreen"]) {
        window_->create(windowMode_, windowTitle_, sf::Style::Default, windowSettings_);
    } else {
        sf::VideoMode mode = sf::VideoMode::getFullscreenModes()[0];
        window_->create(mode, windowTitle_, sf::Style::Fullscreen, windowSettings_);
    }

    flags_["fullscreen"] = !flags_["fullscreen"];
}

////////////////////////////////////////////////////////////////////////////////
void Game::showHelp()
{
    stringstream stream;
    stream << "#KEYBOARD" << endl;
    stream << "PLAYER" << endl;
    stream << "  Left/Right:  Move Player" << endl;
    stream << "  Space:       Shoot" << endl;
    stream << "  I:           Activate/Deactivate Voice Input" << endl;
    stream << "  O:           Switch Synthetic/Recorded Sound" << endl;
    stream << "GUESSING" << endl;
    stream << "  G:           Enter/Leave Guess" << endl;
    stream << "  WASD:        Move Marker" << endl;
    stream << "  Up/Down:     Place/Remove Guess" << endl;
    stream << "  Enter:       Submit Guess" << endl;
    stream << "  R:           Remove All Guesses" << endl;
    stream << "VARIOUS" << endl;
    stream << "  Backspace:   Start New Game" << endl;
    stream << "  F:           Switch Fullscreen" << endl;
    stream << "  V:           Activate FP/Static Camera" << endl;
    stream << "  B:           Show/Hide Balls" << endl;
    stream << "  P:           Show/Hide Paths";

    hud_.addMessageBox(Hud::Center, stream.str(), 0.5f);
}

////////////////////////////////////////////////////////////////////////////////
void Game::handleEvents()
{
    //  process events
    sf::Event event;

    while (window_->pollEvent(event))
    {
        //  close window -> exit
        if (event.type == sf::Event::Closed) {
            window_->close();
            flags_["running"] = false;
        }

        //  handle keys
        if (event.type == sf::Event::KeyPressed) {
            handleKeyboardEvents(event);
        }

        //  resize viewport
        if (event.type == sf::Event::Resized) {
            glViewport(0, 0, event.size.width, event.size.height);
        }

//        if (event.type == sf::Event::JoystickButtonPressed)
//        {
//            switch (event.joystickButton.button)
//            {
//                case 11:
//                    marker_.move();
//                    break;
//
//                case 13:
//                    marker_.left();
//                    break;
//
//                case 12:
//                    marker_.back();
//                    break;
//
//                case 14:
//                    marker_.right();
//                    break;
//
//                case 0:
//                    board_.addGuess(marker_.position);
//                    break;
//
//                case 1:
//                    board_.removeGuess(marker_.position);
//                    break;
//
//                case 8:
//                    guess();
//                    break;
//
//                case 2:
//                    flags_["guessing"] = !flags_["guessing"];
//                    break;
//
//                case 9:
//                    flags_["fpv"] = !flags_["fpv"];
//                    renderer_.setViewType(flags_["fpv"]);
//                    break;
//
//                //  shoot
//                case :
//                    soundRenderer_.shoot();
//                    break;
//
//                    //  move player
//                case :
//                    board_.movePlayerRight();
//                    break;
//
//                case :
//                    board_.movePlayerLeft();
//                    break;
//
//                default:
//                    break;
//            }
//
//            cout << "joystick: " << event.joystickButton.joystickId;
//            cout << ", button: " << event.joystickButton.button << endl;
//        }
    }
}

////////////////////////////////////////////////////////////////////////////////
void Game::handleKeyboardEvents(const sf::Event& event)
{
    if (flags_["shouldDismissMessageBox"]) {
        flags_["shouldDismissMessageBox"] = false;
        hud_.dismissMessageBox(Hud::Center);
    }

    switch (event.key.code)
    {
        case sf::Keyboard::Slash:
            showHelp();
            break;

        case sf::Keyboard::H:
            hud_.addMessage(Hud::Right, "TOGGLE HINTS");
            flags_["hints"] = !flags_["hints"];
            break;

        case sf::Keyboard::BackSpace:
            reset();
            break;

        //  close on escape
        case sf::Keyboard::Escape:
            window_->close();
            flags_["running"] = false;
            break;

        //  move player
        case sf::Keyboard::Right:
            board_.movePlayerRight();
            break;

        case sf::Keyboard::Left:
            board_.movePlayerLeft();
            break;

        //  spawn new balls
        case sf::Keyboard::Num1:
            board_.initBallsRandom(5);
            break;

        //  reset guesses
        case sf::Keyboard::R:
            board_.clearGuesses();
            break;

        //  shoot
        case sf::Keyboard::Space:
            soundRenderer_.shoot();
            break;

        //  fullscreen
        case sf::Keyboard::F:
            toggleFullscreen();
            break;

        //  toggle input mode
        case sf::Keyboard::I:
            hud_.addMessage(Hud::Right, "TOGGLE INPUT MODE", 1.0f);
            soundRenderer_.toggleListening();
            break;

        //  balls
        case sf::Keyboard::B:
            flags_["balls"] = !flags_["balls"];
            break;

        //  guessing
        case sf::Keyboard::G:
            flags_["guessing"] = !flags_["guessing"];
            break;

        //  path
        case sf::Keyboard::P:
            flags_["path"] = !flags_["path"];
            break;

        //  first / third person view
        case sf::Keyboard::V:
            flags_["fpv"] = !flags_["fpv"];
            renderer_.setViewType(flags_["fpv"]);
            break;

        default:
            break;
    }

    if (flags_["guessing"]) {
        handleGuessingKeyboardEvents(event);
    }
}

////////////////////////////////////////////////////////////////////////////////
void Game::handleGuessingKeyboardEvents(const sf::Event &event)
{
    switch (event.key.code)
    {
        case sf::Keyboard::W:
            marker_.move();
            break;

        case sf::Keyboard::A:
            marker_.left();
            break;

        case sf::Keyboard::S:
            marker_.back();
            break;

        case sf::Keyboard::D:
            marker_.right();
            break;

        case sf::Keyboard::Down:
            board_.addGuess(marker_.position);
            break;

        case sf::Keyboard::Up:
            board_.removeGuess(marker_.position);
            break;

        case sf::Keyboard::Return:
            guess();
            break;

        default:
            break;
    }
}


text:
module Ad::PromotionsHelper
end


text:
module ActionView
  module Helpers
    module TextHelper
      # From Typo
      def nofollowify(text)
        text.gsub(/<\s*a\s*(.+?)>/i, '')
      end

      def textilize(text)
        RedCloth.new(text.to_s).to_html.gsub( /(.)\n(?!\Z| *([#*=]+(\s|$)|[{|]))/, "\\1
" ).gsub(%r{

}, '
')
      end

      def comment_to_html(body)
        nofollowify(sanitize(textilize(auto_link(body.dup).gsub(%r|(>https?://)(\S{50,50})(\S*)(<)|, '\1\2…\4'))))
      end

      # Make available to the String methods below
      module_function :pluralize, :truncate, :nofollowify, :auto_link, :textilize,
                      :auto_link_email_addresses, :auto_link_urls
      module_function :strip_links, :sanitize rescue nil
    end

    module SanitizeHelper
      module_function :strip_links, :sanitize rescue nil
    end
  end
end

class String
  unless method_defined?(:truncate)
    def truncate(length = 30, truncate_string = "...")
      ActionView::Helpers::TextHelper.truncate(self, :length => length, :omission => truncate_string)
    end
  end

  unless method_defined?(:pluralize)
    def pluralize(count = nil, plural = nil)
      count == 1 ? self : (plural || ActiveSupport::Inflector.pluralize(self))
    end
  end

  def strip_links
    ActionView::Helpers::SanitizeHelper.strip_links(self) rescue ActionView::Helpers::TextHelper.strip_links(self)
  end

  def unsmartify
    self.gsub(/'/, "'").gsub(/"/, '"').gsub(/"/, '"').gsub(/–/, "-").gsub(/…/, "...")
  end

  # From Typo:
  # Converts a post title to its-title-using-dashes
  # All special chars are stripped in the process
  #
  # options:
  #   :maxlen    - max length of the resulting string
  #   :keep_case - don't downcase the string
  def to_url(options = {})
    if options.is_a?(Fixnum)
      maxlen = options
      options = {}
    else
      maxlen = options[:maxlen]
    end

    result = self.strip
    result.downcase! unless options[:keep_case]

    # replace quotes by nothing
    result.gsub!(/['"]/, '')

    # Handle Danish chars
    result.gsub!(/æ/, 'ae')
    result.gsub!(/ø/, 'oe')
    result.gsub!(/å/, 'aa')
    result.gsub!(/Æ/, 'AE')
    result.gsub!(/Ø/, 'OE')
    result.gsub!(/Å/, 'AA')

    # Handle accented chars (is there a standardized way to do this?)
    result.gsub!(/[áä]/, 'a')
    result.gsub!(/[éë]/, 'e')
    result.gsub!(/[ÁÄ]/, 'A')
    result.gsub!(/[ÉË]/, 'E')

    # strip all non word chars
    result.gsub!(/[^a-zA-Z0-9_-]/, ' ')

    # replace all white space sections with a hyphen
    result.gsub!(/\ +/, '-')

    # trim hyphens
    result.gsub!(/(--+)/, '-')

    if maxlen && result.length > maxlen
      result = result[0..maxlen]
      result = result[0...maxlen] unless result.gsub!(/(.+)(-[^-]*)$/, '\1')
    end

    result.gsub!(/(-)$/, '')
    result.gsub!(/^(-)/, '')

    result
  end

  def flush_left
    indt = 0
    text = self.gsub(/\t/, '  ')
    if text =~ /^ /
      while text !~ /^ {#{indt}}\S/
        indt += 1
      end unless text.empty?
      if indt.nonzero?
        text.gsub!( /^ {#{indt}}/, '' )
      end
    end
    text
  end
end


text:
@import url(https://fonts.googleapis.com/css?family=Roboto:400,700,900);
* {
  font-family: 'Roboto', sans-serif;
}

html,
body {
  margin: 0px;
  padding: 0px;
}

body {
  background-image: url("https://diariodeunatelefila.files.wordpress.com/2014/12/promo-personajes-los-simpson.jpg");
  background-repeat: no-repeat;
}

header {
  display: flex;
  justify-content: center;
}
header h1 {
  font-size: 70px;
  font-weight: italic;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.box {
  display: flex;
  justify-content: center;
  background-color: #0288D1;
  width: 43%;
  height: 280px;
  border-radius: 12px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-direction: column;
}
.box .quote {
  margin-top: 15px;
}
.box .quote h3 {
  text-align: center;
}

.btns {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 15px;
}
.btns .btn {
  margin-left: 5px;
  margin-right: 5px;
}


text:
package org.zstack.compute.vm;

import org.zstack.core.config.GlobalConfig;
import org.zstack.core.config.GlobalConfigDefinition;
import org.zstack.core.config.GlobalConfigValidation;

@GlobalConfigDefinition
public class VmGlobalConfig {
    public static final String CATEGORY = "vm";

    @GlobalConfigValidation
    public static GlobalConfig DELETE_DATA_VOLUME_ON_VM_DESTROY = new GlobalConfig(CATEGORY, "dataVolume.deleteOnVmDestroy");
    @GlobalConfigValidation
    public static GlobalConfig UPDATE_INSTANCE_OFFERING_TO_NULL_WHEN_DELETING = new GlobalConfig(CATEGORY, "instanceOffering.setNullWhenDeleting");
    @GlobalConfigValidation(validValues = {"Direct","Delay", "Never"})
    public static GlobalConfig VM_DELETION_POLICY = new GlobalConfig(CATEGORY, "deletionPolicy");
    @GlobalConfigValidation(numberGreaterThan = 0)
    public static GlobalConfig VM_EXPUNGE_PERIOD = new GlobalConfig(CATEGORY, "expungePeriod");
    @GlobalConfigValidation(numberGreaterThan = 0)
    public static GlobalConfig VM_EXPUNGE_INTERVAL = new GlobalConfig(CATEGORY, "expungeInterval");
    @GlobalConfigValidation(validValues = {"true", "false"})
    public static GlobalConfig VM_CLEAN_TRAFFIC = new GlobalConfig(CATEGORY, "cleanTraffic");
    @GlobalConfigValidation(validValues = {"cirrus","vga", "qxl"})
    public static GlobalConfig VM_VIDEO_TYPE = new GlobalConfig(CATEGORY, "videoType");
    @GlobalConfigValidation
    public static GlobalConfig NUMA = new GlobalConfig(CATEGORY, "numa");
}


text:
/* global require, Notification */

(function () {

    var fs = require("fs");
    var toothrot = require("toothrot");
    var normalize = require("path").normalize;
    var format = require("vrep").format;
    var confirm = require("./src/confirm.js");

    var projectTemplate = document.querySelector("*[data-template-name=project]").innerHTML;
    var main = document.getElementById("main");
    var content = document.getElementById("content");

    main.addEventListener("click", function (event) {

        var target = event.target;
        var action = target.getAttribute("data-action");
        var path = target.getAttribute("data-project");

        if (action === "selectFolder") {
            selectDir(function (path) {

                var projectFile = readProjectFile(path);

                if (!projectFile) {
                    confirm(
                        "Create new project?",
                        "No project found in folder. Create new project here?",
                        function (yes) {
                            if (yes) {
                                createProject(path);
                            }
                        }
                    );
                }
                else {
                    importProject(path, projectFile);
                }
            });
        }
        else if (action === "build") {
            buildProject(path);
        }
        else if (action === "buildDesktop") {
            buildDesktopProject(path);
        }
        else if (action === "run") {
            runBrowser(path);
        }
    });

    function selectDir (then) {

        var dialog = require("electron").remote.dialog;

        dialog.showOpenDialog({
            properties: ["openDirectory"]
        }, processPaths);

        function processPaths (paths) {
            console.log("chosen path:", paths[0]);
            then(paths[0]);
        }
    }

    function readProjectFile (path) {

        var file = normalize(path + "/project.json");

        try {
            return JSON.parse("" + fs.readFileSync(file));
        }
        catch (error) {
            console.error(error);
            return false;
        }
    }

    function createProject (path) {

        toothrot.init(path, function () {

            var info = JSON.parse("" + fs.readFileSync(normalize(path + "/project.json")));

            addProject(path, info);
        });
    }

    function importProject (path, info) {
        addProject(path, info);
    }

    function addProject (path, info) {

        var data = loadProjectData();

        data[path] = {
            name: info.name,
            path: path,
            added: Date.now()
        };

        saveProjectData(data);

        updateProjectList();
    }

    function loadProjectData () {
        return JSON.parse(localStorage.getItem("toothrotProjects") || "{}");
    }

    function saveProjectData (data) {
        localStorage.setItem("toothrotProjects", JSON.stringify(data));
    }

    function updateProjectList () {

        var key;
        var data = loadProjectData();
        var text = "";

        for (key in data) {
            text += format(projectTemplate, {
                path: key,
                name: data[key].name
            });
        }

        content.innerHTML = text;
    }

    function buildProject (path, then) {

        then = then || function () {};

        toothrot.build(path, null, false, function () {

            var info = updateProjectInfo(path);

            updateProjectList();

            notify(
                info.name + " built successfully!",
                "The Toothrot Engine project '" + info.name +"' has been built " +
                "in " + path
            );

            then();
        });
    }

    function buildDesktopProject (path, then) {

        then = then || function () {};

        toothrot.build(path, null, true, function (error) {

            var info = updateProjectInfo(path);

            updateProjectList();

            if (error) {
                notify(
                    info.name + " cannot be built!",
                    error
                );
            }
            else {
                notify(
                    info.name + " built successfully!",
                    "The Toothrot Engine project built " +
                    "in:\n" + path
                );
            }

            then();
        });
    }

    function updateProjectInfo (path) {

        var file = normalize(path + "/project.json");
        var data = loadProjectData();
        var info = JSON.parse("" + fs.readFileSync(file));

        data[path].name = info.name;
        data[path].updated = Date.now();

        saveProjectData(data);

        return info;
    }

    function notify (title, message, timeout) {

        var notification = new Notification(title, {
            icon: "style/spanner-hammer.png",
            body: message
        });

        setTimeout(function () {
            notification.close();
        }, timeout || 4000);
    }

    function runBrowser (path) {
        buildProject(path, function () {

            var win = window.open(normalize("file://" + path + "/build/browser/index.html"));

            win.setSize(800, 600);
        });
    }

    updateProjectList();

}());


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Connect with your users and keep them coming back. Use any to improve your site. Use all if you're working towards a progressive web app.

{# wf_updated_on: 2016-09-09 #}
{# wf_published_on: 2015-09-08 #}

# Engage and Retain Users {: .page-title }

Connect with your users and keep them coming back. Use any to improve your
site. Use **all** if you're working towards a
[progressive web app](/web/progressive-web-apps/).

Foundational to many of these features is the [web app manifest](web-app-manifest/),
if your site doesn't have one, consider adding it. It's a simple file that let's
you:

* Control how your app appears to the user in areas where they would expect
to see apps (for example, the mobile home screen).
* Direct what the user can launch.
* Define its appearance at launch.

Add to home screen

    Web app install banners give you the ability to let your users quickly
    and seamlessly add your web app to their home screen, making it easy to
    launch and return to your app.

    Get Started

Web push notifications

    Web push notifications makes it easy to re-engage with users by
    showing relevant, timely, and contextual notifications, even when
    the browser is closed.

    Get Started

## Related resources

### Codelabs

[Your First Progressive Web App](/web/fundamentals/getting-started/codelabs/your-first-pwapp/)

This codelab walks you through creating your own Progressive Web App,
including the design considerations. It includes implementation details to
ensure that your app meets the key principles of a Progressive Web App.

[Your First Web Push Notification](/web/fundamentals/getting-started/codelabs/push-notifications/)

In this codelab, you learn how to add Push Notifications to web
applications. This enables you to re-engage users with breaking news and
information about new content. You'll also learn the basics of Service Workers.

### Chrome DevTools

* [Debug Progressive Web Apps](/web/tools/chrome-devtools/progressive-web-apps/)

### Udacity courses

[Progressive Web App Fundamentals](https://www.udacity.com/course/intro-to-progressive-web-apps--ud811)

In this course you'll get started working on your very first Progressive Web
App—a web app that takes advantage of many features that native
applications enjoy. You'll also get more experience in creating a web
app that works offline using Service Workers. Finally, you'll make your app
installable to the user's home screen with the Web App Manifest file.


text:
package com.evolvingstuff;

import java.util.Random;

public class EchoStateNetwork {
	EchoStateLiquid liquid;
	NeuralNetwork readout;

	public EchoStateNetwork(Random r, int input_dimension, int liquid_hidden_dimension, int readout_hidden_dimension, int output_dimension) throws Exception {
		liquid = new EchoStateLiquid(r, input_dimension, liquid_hidden_dimension);
		readout = NeuralNetwork.FactoryFeedForwardNeuralNetwork(r, liquid_hidden_dimension, readout_hidden_dimension, output_dimension, NeuronType.Sigmoid);
		liquid.Reset();
	}

	public void Reset() {
		liquid.Reset();
	}

	public double[] Next(double[] input, double[] target_output) throws Exception {
		double[] liquid_state = liquid.Next(input);
		double[] output = readout.Next(liquid_state, target_output);
		return output;
	}

	public double[] Next(double[] input) throws Exception {
		double[] liquid_state = liquid.Next(input);
		double[] output = readout.Next(liquid_state);
		return output;
	}

	public void ShowState() {
		liquid.ShowState();
	}

}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.messages = exports.ruleName = undefined;

exports.default = function (whitelist) {
  return function (root, result) {
    var validOptions = (0, _utils.validateOptions)(result, ruleName, {
      actual: whitelist,
      possible: [_lodash.isObject]
    });
    if (!validOptions) {
      return;
    }

    root.walkDecls(function (decl) {
      var prop = decl.prop;
      var value = decl.value;

      var unprefixedProp = _postcss.vendor.unprefixed(prop);

      var propWhitelist = (0, _lodash.find)(whitelist, function (list, propIdentifier) {
        return (0, _utils.matchesStringOrRegExp)(unprefixedProp, propIdentifier);
      });

      if (!propWhitelist) {
        return;
      }

      (0, _postcssValueParser2.default)(value).walk(function (node) {
        if (node.type === "string") {
          return;
        }

        var unit = _postcssValueParser2.default.unit(node.value).unit;

        if (!unit) {
          return;
        }
        if (propWhitelist.indexOf(unit) !== -1) {
          return;
        }

        (0, _utils.report)({
          message: messages.rejected(prop, unit),
          node: decl,
          index: (0, _utils.declarationValueIndex)(decl) + node.sourceIndex,
          result: result,
          ruleName: ruleName
        });
      });
    });
  };
};

var _postcss = require("postcss");

var _lodash = require("lodash");

var _postcssValueParser = require("postcss-value-parser");

var _postcssValueParser2 = _interopRequireDefault(_postcssValueParser);

var _utils = require("../../utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ruleName = exports.ruleName = "property-unit-whitelist";

var messages = exports.messages = (0, _utils.ruleMessages)(ruleName, {
  rejected: function rejected(p, u) {
    return "Unexpected unit \"" + u + "\" for property \"" + p + "\"";
  }
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HardToFind.BusinessObjects
{
    class CarProcessorBusinessObject
    {
    }
}


text:
function [ u, s ] = getSVDSpatialPatterns( obj, varargin )
% GETSVDSPATIALPATTERNS Get SVD spatial patterns and the corresponding
% singular values for  an nlsaModel object
%
% Modified 2016/01/03

[ u, s ] = getSpatialPatterns( getLinearMap( obj ), ...
                               varargin{ : } );


text:
<?xml version="1.0" encoding="us-ascii"?>
<AssetDeclaration xmlns="uri:ea.com:eala:asset" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xai="uri:ea.com:eala:asset:instance">
	<Tags></Tags>
	<Includes>
	</Includes>

	<GameObject
		id="MetaControlDummyMapRevealer"
		Side="Neutral"
		EditorSorting="UNIT"
		CommandSet="EmptyCommandSet"
		KindOf="UNSELECTABLE NO_COLLIDE IGNORE_FOR_VICTORY CANNOT_BE_DETECTED RESIST_EMP NOT_ON_RADAR AIRCRAFT"
		RadarPriority="NOT_ON_RADAR"
		EditorName="GenericCrateSpawner">
		<LocomotorSet
			Locomotor="MetaControlDummyLocomotor"
			Condition="NORMAL"
			Speed="1" />
		<DisplayName>GenericCrateSpawner</DisplayName>
		<ArmorSet
			Armor="NoArmor" />
		<Draws>
		</Draws>
		<Behaviors>
			<SlowDeath
				id="ModuleTag_Death"
				DestructionDelay="0s">
				<DieMuxData
					DeathTypes="ALL"
					DeathTypesForbidden="EXTRA_7"/>
			</SlowDeath>
			<SlowDeath
				id="ModuleTag_DeathExtra"
				DestructionDelay="0.2s">
				<DieMuxData
					DeathTypes="EXTRA_7" />
				<OCL
					Type="FINAL">
					<OCL>OCL_MetaControlDummyMapRevealerKiller</OCL>
				</OCL>
			</SlowDeath>
			<StealthDetectorUpdate
				id="ModuleTag_Detect"
				DetectionRange="15000.0" />
		    <RadarBehavior
				id="ModuleTag_RadarBehavior" />
			<InvisibilityUpdate
				id="ModuleTag_Invisibility"
				UpdatePeriod="1s"
				Options="STARTS_ACTIVE">
			</InvisibilityUpdate>
		</Behaviors>
		<AI>
			<AIUpdate
				id="ModuleTag_AI"
				AutoAcquireEnemiesWhenIdle="NO"
                AILuaEventsList="MapRevealerONEvent">
			</AIUpdate>
		</AI>
		<Body>
			<ActiveBody
				id="ModuleTag_Body"
				MaxHealth="999999.0" />
		</Body>
		<Geometry
			IsSmall="true">
			<Shape
				Type="CYLINDER"
				MajorRadius="1.0"
				Height="1.0"/>
		</Geometry>
		<VisionInfo
			VisionRange="0"
			ShroudClearingRange="15000" />
	</GameObject>

</AssetDeclaration>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.nattachai.walkingranger.BgroupActivity"
    tools:showIn="@layout/app_bar_bgroup">

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

        <Button
            android:id="@+id/joinG"
            android:text="Join Group"
            android:textSize="20dp"
            android:layout_width="200dp"
            android:layout_height="80dp"
            android:layout_weight="1" />

        <Button
            android:id="@+id/createG"
            android:text="Create Group"
            android:textSize="20dp"
            android:layout_width="200dp"
            android:layout_height="80dp"
            android:layout_weight="1" />

    </LinearLayout>

</RelativeLayout>


text:
namespace SignControl
{
    partial class ContentSimpleTextControl
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(3, 3);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(31, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Text:";
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(37, 0);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(176, 20);
            this.textBox1.TabIndex = 1;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(37, 26);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(89, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "Pick Color";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // ContentSimpleTextControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Name = "ContentSimpleTextControl";
            this.Size = new System.Drawing.Size(321, 78);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
    }
}


text:
import * as React from 'react';
import { Route, Switch } from 'react-router-dom';
import {
  useMatchMedia,
  useLocalStorage,
  useTheme,
  Button,
  Editor,
  Box,
  Icon,
  Link,
  List,
  ListItem,
  Tab,
  Tabs,
  Text,
  ThemeSwitcher,
  Tooltip,
  TypeTheme,
} from 'preshape';
import { Snake, SnakeViewer } from '@hhogg/snake';
import { ISolution } from '../Types';
import { CANVAS_SIZE } from '../config';
import { blank, manhattanDistance } from '../solutions';
import About from './About';
import Console from './Console';
import Controller from './Controller';
import Logo from './Logo';
import Scoreboard from './Scoreboard';
import Solutions from './Solutions';

import 'brace/mode/javascript';

const worker = new Worker('../../src/SnakeRunnerWorker.js');

export const RootContext = React.createContext<ISolution & {
  onSelect: (solution: ISolution) => void;
  theme: TypeTheme;
}>({
  content: '',
  name: '',
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  onSelect: () => {},
  theme: 'night',
});

export default () => {
  const [theme, setTheme ] = useLocalStorage<TypeTheme>('com.hogg.theme', 'night');
  const [editorState, setEditorState] = useLocalStorage<ISolution>('com.hogg.snake.editor', manhattanDistance);
  const [activeTab, setActiveTab] = React.useState<'game' | 'editor'>('game');
  const match = useMatchMedia(['1000px']);

  useTheme(theme);

  const onChange = (content: string) => {
    setEditorState({ ...editorState, content });
  };

  const onSelect = (solution: ISolution) => {
    setEditorState(solution);
  };

  const onReset = () => {
    setEditorState(blank);
  };

  const context = {
    ...editorState,
    onSelect,
    theme,
  };

  return (
    <RootContext.Provider value={ context }>
      <Box flex="vertical" grow>
        <Box
            alignChildrenVertical="middle"
            flex="horizontal"
            gap="x6"
            paddingHorizontal="x6"
            paddingVertical="x2">
          <Box
              alignChildrenVertical="middle"
              flex="horizontal"
              gap="x4"
              grow>
            <Box>
              <Logo height="32px" width="32px" />
            </Box>
          </Box>

          <Box>
            <List gap="x2">
              <ListItem separator="|">
                <Tooltip content="Solutions">
                  { (props) => (
                    <Link { ...props } display="block" to="/solutions">
                      <Icon name="Book" size="1.25rem" />
                    </Link>
                  ) }
                </Tooltip>
              </ListItem>

              <ListItem separator="|">
                <Tooltip content="About">
                  { (props) => (
                    <Link { ...props } display="block" to="/about">
                      <Icon name="Info" size="1.25rem" />
                    </Link>
                  ) }
                </Tooltip>
              </ListItem>

              <ListItem separator="|">
                <Tooltip content="Github">
                  { (props) => (
                    <Link { ...props } display="block" href="https://github.com/HHogg/snake" target="Snake" title="Snake">
                      <Icon name="Github" size="1.25rem" />
                    </Link>
                  ) }
                </Tooltip>
              </ListItem>

              <ListItem separator="|">
                <ThemeSwitcher
                    onChange={ setTheme }
                    theme={ theme } />
              </ListItem>
            </List>
          </Box>
        </Box>

        <Box>
          <Box borderColor="background-shade-3" borderSize="x1" />
        </Box>

        { !match('1000px') && (
          <Tabs margin="x2" paddingHorizontal="x6">
            <Tab
                active={ activeTab === 'game' }
                onClick={ () => setActiveTab('game') }>Game</Tab>
            <Tab
                active={ activeTab === 'editor' }
                onClick={ () => setActiveTab('editor') }>Editor</Tab>
          </Tabs>
        ) }

        <Box flex="horizontal" grow>
          { (match('1000px') || activeTab === 'game') && (
            <Box
                basis="0"
                flex="vertical"
                grow
                paddingHorizontal="x6"
                paddingVertical="x4">
              <Snake
                  solution={ editorState.content }
                  worker={ worker }
                  xLength={ CANVAS_SIZE }
                  yLength={ CANVAS_SIZE }>
                <Box
                    flex="horizontal"
                    gap="x4"
                    grow>
                  <Box
                      basis="0"
                      flex="vertical"
                      gap="x2"
                      grow>
                    <Box
                        basis="0"
                        flex="vertical"
                        grow
                        minHeight="20rem">
                      <SnakeViewer theme={ theme } />
                    </Box>

                    <Box flex="horizontal">
                      <Console />
                    </Box>

                    <Box>
                      <Scoreboard />
                    </Box>

                    <Box>
                      <Controller />
                    </Box>
                  </Box>
                </Box>
              </Snake>
            </Box>
          ) }

          { match('1000px') && (
            <Box borderColor="background-shade-3" borderSize="x1" />
          ) }

          { (match('1000px') || activeTab === 'editor') && (
            <Box
                basis="0"
                flex="vertical"
                gap="x6"
                grow
                paddingHorizontal="x6"
                paddingVertical="x4">
              <Box
                  alignChildrenVertical="middle"
                  flex="horizontal"
                  gap="x2">
                <Box basis="0" grow>
                  <Text ellipsis strong>{ editorState.name }</Text>
                </Box>

                <Box>
                  <Button
                      color="negative"
                      gap="x2"
                      onClick={ () => onReset() }>
                    <Box><Icon name="Delete" size="1rem" /></Box>
                    <Box>Clear</Box>
                  </Button>
                </Box>
              </Box>

              <Box flex="vertical" grow>
                <Editor
                    language="javascript"
                    onChange={ onChange }
                    value={ editorState.content } />
              </Box>
            </Box>
          ) }
        </Box>
      </Box>

      <Switch>
        <Route component={ About } path="/about" />
        <Route component={ Solutions } path="/solutions" />
      </Switch>
    </RootContext.Provider>
  );
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.zalando.stups</groupId>
        <artifactId>fullstop-aws-support</artifactId>
        <version>1.3.0-SNAPSHOT</version>
    </parent>

    <artifactId>fullstop-aws-client-support</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.zalando.stups</groupId>
            <artifactId>fullstop-logging</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-sts</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
        </dependency>

        <!-- TESTING -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-ec2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-cloudwatch</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
import pkgutil
import pkg_resources

from thumbor import __version__

class ErrorHandler(object):
    def __init__(self, config, client=None):
        import raven

        dsn = config.SENTRY_DSN_URL
        if not dsn:
            raise RuntimeError(
                "If you set USE_CUSTOM_ERROR_HANDLING to True, and you are using thumbor.error_handlers.sentry, " +
                "then you must specify the Sentry DSN using the SENTRY_DSN_URL configuration."
            )

        self.sentry = client or raven.Client(dsn)
        self.modules = self.get_modules()

    def get_modules(self):
        resolved = {}
        modules = [mod[1] for mod in tuple(pkgutil.iter_modules())]
        for module in modules:
            try:
                res_mod = pkg_resources.get_distribution(module)
                if res_mod is not None:
                    resolved[module] = res_mod.version
            except pkg_resources.DistributionNotFound:
                pass

        return resolved

    def handle_error(self, context, handler, exception):
        req = handler.request

        extra = {
            'thumbor-version': __version__
        }

        extra.update({
            'Headers': req.headers
        })

        cookies_header = extra.get('Headers', {}).get('Cookie', {})

        if isinstance(cookies_header, basestring):
            cookies = {}
            for cookie in cookies_header.split(';'):
                if not cookie:
                    continue
                values = cookie.strip().split('=')
                key, val = values[0], "".join(values[1:])
                cookies[key] = val
        else:
            cookies = cookies_header

        extra['Headers']['Cookie'] = cookies

        data = {
            'sentry.interfaces.Http': {
                'url': req.full_url(),
                'method': req.method,
                'data': req.arguments,
                'body': req.body,
                'query_string': req.query
            },
            'sentry.interfaces.User': {
                'ip': req.remote_ip,
            },
            'modules': self.modules
        }
        self.sentry.captureException(exception, extra=extra, data=data)


text:
<?php

namespace Sonata\PageBundle\Command;

use Sonata\PageBundle\CmsManager\CmsManagerInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Migrates the name setting of all blocks into a code setting.
 */
class RenderBlockCommand extends BaseCommand
{
    /**
     * {@inheritdoc}
     */
    public function configure()
    {
        $this->setName('sonata:page:render-block');
        $this->setDescription('Dump page information');
        $this->setHelp(
'Dump page information

Available manager:
 - sonata.page.cms.snapshot
 - sonata.page.cms.page
');

        $this->addArgument('manager', InputArgument::REQUIRED, 'The manager service id');
        $this->addArgument('page_id', InputArgument::REQUIRED, 'The page id');
        $this->addArgument('block_id', InputArgument::REQUIRED, 'The page id');
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $manager = $this->getContainer()->get($input->getArgument('manager'));

        if (!$manager instanceof CmsManagerInterface) {
            throw new \RuntimeException('The service does not implement the CmsManagerInterface');
        }

        $page = $manager->getPageById($input->getArgument('page_id'));

        $block = $manager->getBlock($input->getArgument('block_id'));

        if (!$block) {
            throw new \RuntimeException('Unable to find the related block');
        }

        $output->writeln('<info>Block Information</info>');
        $output->writeln(sprintf('  > Id: %d - type: %s - name: %s', $block->getId(), $block->getType(), $block->getName()));

        foreach ($block->getSettings() as $name => $value) {
            $output->writeln(sprintf('   >> %s: %s', $name, json_encode($value)));
        }

        $context = $this->getContainer()->get('sonata.block.context_manager')->get($block);

        $output->writeln("\n<info>BlockContext Information</info>");
        foreach ($context->getSettings() as $name => $value) {
            $output->writeln(sprintf('   >> %s: %s', $name, json_encode($value)));
        }

        $output->writeln("\n<info>Response Output</info>");

        // fake request
        $request = new Request();
        $this->getContainer()->enterScope('request');
        $this->getContainer()->set('request', $request, 'request');

        $output->writeln($this->getContainer()->get('sonata.block.renderer')->render($context));

        $this->getContainer()->leaveScope('request');
    }
}


text:
export BinomialTest, SignTest

## BINOMIAL TEST

immutable BinomialTest <: HypothesisTest
    p::Float64
    x::Int
    n::Int

    BinomialTest(x::Real, n::Real, p::Real=0.5) = new(p, x, n)
end

BinomialTest(x::AbstractVector{Bool}, p=0.5) =
    BinomialTest(sum(x), length(x), p)

"""
```julia
testname(::HypothesisTest)
```

Returns the string value. E.g. "Binomial test", "Sign Test"
"""
testname(::BinomialTest) = "Binomial test"
population_param_of_interest(x::BinomialTest) = ("Probability of success", x.p, x.x/x.n) # parameter of interest: name, value under h0, point estimate

function show_params(io::IO, x::BinomialTest, ident="")
    println(io, ident, "number of observations: $(x.n)")
    println(io, ident, "number of successes:    $(x.x)")
end

pvalue(x::BinomialTest; tail=:both) = pvalue(Binomial(x.n, x.p), x.x; tail=tail)

# Confidence interval

"""
```julia
function ci(x::HypothesisTest, alpha::Float64=0.05; tail=:both, method=:clopper_pearson)
```
Compute a confidence interval with coverage 1-alpha for multinomial proportions using one of the following methods. Possible values for method are:

Sison, Glaz intervals :sison_glaz (default):
Bootstrap intervals :bootstrap :
Quesenberry, Hurst intervals :quesenberry_hurst :
Gold intervals :gold (Asymptotic simultaneous intervals):
"""
function ci(x::BinomialTest, alpha::Float64=0.05; tail=:both, method=:clopper_pearson)
    check_alpha(alpha)

    if tail == :left
        (0.0, ci(x, alpha*2, method=method)[2])
    elseif tail == :right
        (ci(x, alpha*2, method=method)[1], 1.0)
    elseif tail == :both
        if method == :clopper_pearson
            ci_clopper_pearson(x, alpha)
        elseif method == :wald
            ci_wald(x, alpha)
        elseif method == :wilson
            ci_wilson(x, alpha)
        elseif method == :jeffrey
            ci_jeffrey(x, alpha)
        elseif method == :agresti_coull
            ci_agresti_coull(x, alpha)
        else
            throw(ArgumentError("method=$(method) is not implemented yet"))
        end
    else
        throw(ArgumentError("tail=$(tail) is invalid"))
    end
end

# Clopper-Pearson interval (confidence interval by inversion)
function ci_clopper_pearson(x::BinomialTest, alpha::Float64=0.05)
    (quantile(Beta(x.x, x.n - x.x + 1), alpha/2), quantile(Beta(x.x + 1, x.n - x.x), 1-alpha/2))
end

# Wald interval / normal approximation interval
function ci_wald(x::BinomialTest, alpha::Float64=0.05)
    μ = x.x / x.n
    σ = sqrt(μ*(1-μ)/x.n)
    (quantile(Normal(μ, σ), alpha/2), quantile(Normal(μ, σ), 1-alpha/2))
end

# Jeffreys interval
function ci_jeffrey(x::BinomialTest, alpha::Float64=0.05)
    (quantile(Beta(x.x + 1/2, x.n - x.x + 1/2), alpha/2), quantile(Beta(x.x + 1/2, x.n - x.x + 1/2), 1-alpha/2))
end

# Agresti-Coull interval
function ci_agresti_coull(x::BinomialTest, alpha::Float64=0.05)
    q = quantile(Normal(), 1-alpha/2)
    n = x.n + q^2
    μ = (x.x + q^2/2)/n
    σ = sqrt(μ*(1-μ)/n)
    (μ-q*σ, μ+q*σ)
end

# Wilson score interval
function ci_wilson(x::BinomialTest, alpha::Float64=0.05)
    q = quantile(Normal(), 1-alpha/2)
    p = x.x / x.n
    denominator = 1 + q^2/x.n
    μ = p + q^2/(2*x.n)
    μ /= denominator
    σ = sqrt(p*(1-p)/x.n + q^2/(4x.n^2))
    σ /= denominator
    (μ-q*σ, μ+q*σ)
end

## SIGN TEST

immutable SignTest <: HypothesisTest
    median::Float64
    x::Int
    n::Int
    data
end

SignTest{T<:Real}(x::AbstractVector{T}, median::Real=0) =
    SignTest(median, sum(x .> median), sum(x .!= median), sort(x))
SignTest{T<:Real, S<:Real}(x::AbstractVector{T}, y::AbstractVector{S}) = SignTest(x - y, 0.0)

testname(::SignTest) = "Sign Test"
population_param_of_interest(x::SignTest) = ("Median", x.median, median(x.data)) # parameter of interest: name, value under h0, point estimate

function show_params(io::IO, x::SignTest, ident="")
    text1 = "number of observations:"
    text2 = "observations larger than $(x.median): "
    maxlen = length(text2)

    println(io, ident, text1, repeat(" ", maxlen-length(text1)), x.n)
    println(io, ident, text2, x.x)
end

"""
```julia
pvalue(x::HypothesisTest; tail=:both)
```

Compute the p-value for a given significance test.

If tail is :both (default), then the p-value for the two-sided test is returned. If tail is :left or :right, then a one-sided test is performed.
"""
pvalue(x::SignTest; tail=:both) = pvalue(Binomial(x.n, 0.5), x.x; tail=tail)

"""
```julia
function ci(x::HypothesisTest, alpha::Float64=0.05; tail=:both)
```

Compute a confidence interval C with coverage 1-alpha.

If tail is :both (default), then a two-sided confidence interval is returned. If tail is :left or :right, then a one-sided confidence interval is returned
"""
@compat function ci(x::SignTest, alpha::Float64=0.05; tail=:both)
    check_alpha(alpha)

    if tail == :left
        q = Int(quantile(Binomial(x.n, 0.5), alpha))
        (x.data[q+1], x.median)
    elseif tail == :right
        q = Int(quantile(Binomial(x.n, 0.5), alpha))
        (x.median, x.data[end-q])
    elseif tail == :both
        q = Int(quantile(Binomial(x.n, 0.5), alpha/2))
        (x.data[q+1], x.data[end-q])
    else
        throw(ArgumentError("tail=$(tail) is invalid"))
    end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>patterns</groupId>
	<artifactId>patterns--configurable-implementation</artifactId>
	<version>1.0-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>commons-configuration</groupId>
			<artifactId>commons-configuration</artifactId>
			<version>1.10</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-dbutils</groupId>
			<artifactId>commons-dbutils</artifactId>
			<version>1.6</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.35</version>
		</dependency>
	</dependencies>

</project>


text:
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TaskManagement.Core;

namespace TaskManagement.Web.DIContainer
{
    public class EFModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType(typeof(TaskManagementContext)).As(typeof(IContext)).InstancePerLifetimeScope();
        }
    }
}


text:
javascript: (function() {

	var text = '';
	$('a.mw-changeslist-date').each(function(i, e) {
		text += mw.util.getParamValue('oldid', e.href) + '<br>';
	});

	var win = window.open('');
	win.document.body.innerHTML = text;

}
)();


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="template.app"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="TemplateApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TemplateActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>