text:
#include "xenia/ui/d3d12/d3d12_immediate_drawer.h"

#include <cstring>
#include <memory>
#include <utility>
#include <vector>

#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/ui/d3d12/d3d12_context.h"
#include "xenia/ui/d3d12/d3d12_util.h"

namespace xe {
namespace ui {
namespace d3d12 {

// Generated with `xb buildshaders`.
namespace shaders {
#include "xenia/ui/shaders/bytecode/d3d12_5_1/immediate_ps.h"
#include "xenia/ui/shaders/bytecode/d3d12_5_1/immediate_vs.h"
}  // namespace shaders

D3D12ImmediateDrawer::D3D12ImmediateTexture::D3D12ImmediateTexture(
    uint32_t width, uint32_t height, ID3D12Resource* resource,
    SamplerIndex sampler_index, D3D12ImmediateDrawer* immediate_drawer,
    size_t immediate_drawer_index)
    : ImmediateTexture(width, height),
      resource_(resource),
      sampler_index_(sampler_index),
      immediate_drawer_(immediate_drawer),
      immediate_drawer_index_(immediate_drawer_index) {
  if (resource_) {
    resource_->AddRef();
  }
}

D3D12ImmediateDrawer::D3D12ImmediateTexture::~D3D12ImmediateTexture() {
  if (immediate_drawer_) {
    immediate_drawer_->OnImmediateTextureDestroyed(*this);
  }
  if (resource_) {
    resource_->Release();
  }
}

void D3D12ImmediateDrawer::D3D12ImmediateTexture::OnImmediateDrawerShutdown() {
  immediate_drawer_ = nullptr;
  // Lifetime is not managed anymore, so don't keep the resource either.
  util::ReleaseAndNull(resource_);
}

D3D12ImmediateDrawer::D3D12ImmediateDrawer(D3D12Context& graphics_context)
    : ImmediateDrawer(&graphics_context), context_(graphics_context) {}

D3D12ImmediateDrawer::~D3D12ImmediateDrawer() { Shutdown(); }

bool D3D12ImmediateDrawer::Initialize() {
  const D3D12Provider& provider = context_.GetD3D12Provider();
  ID3D12Device* device = provider.GetDevice();

  // Create the root signature.
  D3D12_ROOT_PARAMETER root_parameters[size_t(RootParameter::kCount)];
  D3D12_DESCRIPTOR_RANGE descriptor_range_texture, descriptor_range_sampler;
  {
    auto& root_parameter = root_parameters[size_t(RootParameter::kTexture)];
    root_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
    root_parameter.DescriptorTable.NumDescriptorRanges = 1;
    root_parameter.DescriptorTable.pDescriptorRanges =
        &descriptor_range_texture;
    descriptor_range_texture.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
    descriptor_range_texture.NumDescriptors = 1;
    descriptor_range_texture.BaseShaderRegister = 0;
    descriptor_range_texture.RegisterSpace = 0;
    descriptor_range_texture.OffsetInDescriptorsFromTableStart = 0;
    root_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  }
  {
    auto& root_parameter = root_parameters[size_t(RootParameter::kSampler)];
    root_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
    root_parameter.DescriptorTable.NumDescriptorRanges = 1;
    root_parameter.DescriptorTable.pDescriptorRanges =
        &descriptor_range_sampler;
    descriptor_range_sampler.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
    descriptor_range_sampler.NumDescriptors = 1;
    descriptor_range_sampler.BaseShaderRegister = 0;
    descriptor_range_sampler.RegisterSpace = 0;
    descriptor_range_sampler.OffsetInDescriptorsFromTableStart = 0;
    root_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  }
  {
    auto& root_parameter =
        root_parameters[size_t(RootParameter::kViewportSizeInv)];
    root_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
    root_parameter.Constants.ShaderRegister = 0;
    root_parameter.Constants.RegisterSpace = 0;
    root_parameter.Constants.Num32BitValues = 2;
    root_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  }
  D3D12_ROOT_SIGNATURE_DESC root_signature_desc;
  root_signature_desc.NumParameters = UINT(RootParameter::kCount);
  root_signature_desc.pParameters = root_parameters;
  root_signature_desc.NumStaticSamplers = 0;
  root_signature_desc.pStaticSamplers = nullptr;
  root_signature_desc.Flags =
      D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  root_signature_ = util::CreateRootSignature(provider, root_signature_desc);
  if (root_signature_ == nullptr) {
    XELOGE("Failed to create the Direct3D 12 immediate drawer root signature");
    Shutdown();
    return false;
  }

  // Create the pipelines.
  D3D12_GRAPHICS_PIPELINE_STATE_DESC pipeline_desc = {};
  pipeline_desc.pRootSignature = root_signature_;
  pipeline_desc.VS.pShaderBytecode = shaders::immediate_vs;
  pipeline_desc.VS.BytecodeLength = sizeof(shaders::immediate_vs);
  pipeline_desc.PS.pShaderBytecode = shaders::immediate_ps;
  pipeline_desc.PS.BytecodeLength = sizeof(shaders::immediate_ps);
  D3D12_RENDER_TARGET_BLEND_DESC& pipeline_blend_desc =
      pipeline_desc.BlendState.RenderTarget[0];
  pipeline_blend_desc.BlendEnable = TRUE;
  pipeline_blend_desc.SrcBlend = D3D12_BLEND_SRC_ALPHA;
  pipeline_blend_desc.DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  pipeline_blend_desc.BlendOp = D3D12_BLEND_OP_ADD;
  // Don't change alpha (always 1).
  pipeline_blend_desc.SrcBlendAlpha = D3D12_BLEND_ZERO;
  pipeline_blend_desc.DestBlendAlpha = D3D12_BLEND_ONE;
  pipeline_blend_desc.BlendOpAlpha = D3D12_BLEND_OP_ADD;
  pipeline_blend_desc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_RED |
                                              D3D12_COLOR_WRITE_ENABLE_GREEN |
                                              D3D12_COLOR_WRITE_ENABLE_BLUE;
  pipeline_desc.SampleMask = UINT_MAX;
  pipeline_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
  pipeline_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
  pipeline_desc.RasterizerState.FrontCounterClockwise = FALSE;
  pipeline_desc.RasterizerState.DepthClipEnable = TRUE;
  D3D12_INPUT_ELEMENT_DESC pipeline_input_elements[3] = {};
  pipeline_input_elements[0].SemanticName = "POSITION";
  pipeline_input_elements[0].Format = DXGI_FORMAT_R32G32_FLOAT;
  pipeline_input_elements[0].AlignedByteOffset = offsetof(ImmediateVertex, x);
  pipeline_input_elements[1].SemanticName = "TEXCOORD";
  pipeline_input_elements[1].Format = DXGI_FORMAT_R32G32_FLOAT;
  pipeline_input_elements[1].AlignedByteOffset = offsetof(ImmediateVertex, u);
  pipeline_input_elements[2].SemanticName = "COLOR";
  pipeline_input_elements[2].Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  pipeline_input_elements[2].AlignedByteOffset =
      offsetof(ImmediateVertex, color);
  pipeline_desc.InputLayout.pInputElementDescs = pipeline_input_elements;
  pipeline_desc.InputLayout.NumElements =
      UINT(xe::countof(pipeline_input_elements));
  pipeline_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  pipeline_desc.NumRenderTargets = 1;
  pipeline_desc.RTVFormats[0] = D3D12Context::kSwapChainFormat;
  pipeline_desc.SampleDesc.Count = 1;
  if (FAILED(device->CreateGraphicsPipelineState(
          &pipeline_desc, IID_PPV_ARGS(&pipeline_triangle_)))) {
    XELOGE(
        "Failed to create the Direct3D 12 immediate drawer triangle pipeline "
        "state");
    Shutdown();
    return false;
  }
  pipeline_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
  if (FAILED(device->CreateGraphicsPipelineState(
          &pipeline_desc, IID_PPV_ARGS(&pipeline_line_)))) {
    XELOGE(
        "Failed to create the Direct3D 12 immediate drawer line pipeline "
        "state");
    Shutdown();
    return false;
  }

  // Create the samplers.
  D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc;
  sampler_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
  sampler_heap_desc.NumDescriptors = UINT(SamplerIndex::kCount);
  sampler_heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  sampler_heap_desc.NodeMask = 0;
  if (FAILED(device->CreateDescriptorHeap(&sampler_heap_desc,
                                          IID_PPV_ARGS(&sampler_heap_)))) {
    XELOGE(
        "Failed to create the Direct3D 12 immediate drawer sampler descriptor "
        "heap");
    Shutdown();
    return false;
  }
  sampler_heap_cpu_start_ = sampler_heap_->GetCPUDescriptorHandleForHeapStart();
  sampler_heap_gpu_start_ = sampler_heap_->GetGPUDescriptorHandleForHeapStart();
  uint32_t sampler_size = provider.GetSamplerDescriptorSize();
  // Nearest neighbor, clamp.
  D3D12_SAMPLER_DESC sampler_desc = {};
  sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
  sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  sampler_desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  sampler_desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  sampler_desc.MaxAnisotropy = 1;
  D3D12_CPU_DESCRIPTOR_HANDLE sampler_handle;
  sampler_handle.ptr = sampler_heap_cpu_start_.ptr +
                       uint32_t(SamplerIndex::kNearestClamp) * sampler_size;
  device->CreateSampler(&sampler_desc, sampler_handle);
  // Bilinear, clamp.
  sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  sampler_handle.ptr = sampler_heap_cpu_start_.ptr +
                       uint32_t(SamplerIndex::kLinearClamp) * sampler_size;
  device->CreateSampler(&sampler_desc, sampler_handle);
  // Bilinear, repeat.
  sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  sampler_desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  sampler_desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  sampler_handle.ptr = sampler_heap_cpu_start_.ptr +
                       uint32_t(SamplerIndex::kLinearRepeat) * sampler_size;
  device->CreateSampler(&sampler_desc, sampler_handle);
  // Nearest neighbor, repeat.
  sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
  sampler_handle.ptr = sampler_heap_cpu_start_.ptr +
                       uint32_t(SamplerIndex::kNearestRepeat) * sampler_size;
  device->CreateSampler(&sampler_desc, sampler_handle);

  // Create pools for draws.
  vertex_buffer_pool_ = std::make_unique<D3D12UploadBufferPool>(provider);
  texture_descriptor_pool_ = std::make_unique<D3D12DescriptorHeapPool>(
      device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2048);

  // Reset the current state.
  current_command_list_ = nullptr;
  batch_open_ = false;

  return true;
}

void D3D12ImmediateDrawer::Shutdown() {
  for (auto& deleted_texture : textures_deleted_) {
    deleted_texture.first->Release();
  }
  textures_deleted_.clear();

  for (auto& texture_upload : texture_uploads_submitted_) {
    texture_upload.buffer->Release();
    texture_upload.texture->Release();
  }
  texture_uploads_submitted_.clear();

  for (auto& texture_upload : texture_uploads_pending_) {
    texture_upload.buffer->Release();
    texture_upload.texture->Release();
  }
  texture_uploads_pending_.clear();

  for (D3D12ImmediateTexture* texture : textures_) {
    texture->OnImmediateDrawerShutdown();
  }
  textures_.clear();

  texture_descriptor_pool_.reset();
  vertex_buffer_pool_.reset();

  util::ReleaseAndNull(sampler_heap_);

  util::ReleaseAndNull(pipeline_line_);
  util::ReleaseAndNull(pipeline_triangle_);

  util::ReleaseAndNull(root_signature_);
}

std::unique_ptr<ImmediateTexture> D3D12ImmediateDrawer::CreateTexture(
    uint32_t width, uint32_t height, ImmediateTextureFilter filter,
    bool is_repeated, const uint8_t* data) {
  const D3D12Provider& provider = context_.GetD3D12Provider();
  ID3D12Device* device = provider.GetDevice();
  D3D12_HEAP_FLAGS heap_flag_create_not_zeroed =
      provider.GetHeapFlagCreateNotZeroed();

  D3D12_RESOURCE_DESC resource_desc;
  resource_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  resource_desc.Alignment = 0;
  resource_desc.Width = width;
  resource_desc.Height = height;
  resource_desc.DepthOrArraySize = 1;
  resource_desc.MipLevels = 1;
  resource_desc.Format = D3D12ImmediateTexture::kFormat;
  resource_desc.SampleDesc.Count = 1;
  resource_desc.SampleDesc.Quality = 0;
  resource_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  resource_desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  ID3D12Resource* resource;
  if (SUCCEEDED(provider.GetDevice()->CreateCommittedResource(
          &util::kHeapPropertiesDefault, heap_flag_create_not_zeroed,
          &resource_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
          IID_PPV_ARGS(&resource)))) {
    // Create and fill the upload buffer.
    D3D12_PLACED_SUBRESOURCE_FOOTPRINT upload_footprint;
    UINT64 upload_size;
    device->GetCopyableFootprints(&resource_desc, 0, 1, 0, &upload_footprint,
                                  nullptr, nullptr, &upload_size);
    D3D12_RESOURCE_DESC upload_buffer_desc;
    util::FillBufferResourceDesc(upload_buffer_desc, upload_size,
                                 D3D12_RESOURCE_FLAG_NONE);
    ID3D12Resource* upload_buffer;
    if (SUCCEEDED(device->CreateCommittedResource(
            &util::kHeapPropertiesUpload, heap_flag_create_not_zeroed,
            &upload_buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
            IID_PPV_ARGS(&upload_buffer)))) {
      D3D12_RANGE upload_buffer_read_range;
      upload_buffer_read_range.Begin = 0;
      upload_buffer_read_range.End = 0;
      void* upload_buffer_mapping;
      if (SUCCEEDED(upload_buffer->Map(0, &upload_buffer_read_range,
                                       &upload_buffer_mapping))) {
        size_t data_row_length = sizeof(uint32_t) * width;
        if (data_row_length == upload_footprint.Footprint.RowPitch) {
          std::memcpy(upload_buffer_mapping, data, data_row_length * height);
        } else {
          uint8_t* upload_buffer_row =
              reinterpret_cast<uint8_t*>(upload_buffer_mapping) +
              upload_footprint.Offset;
          const uint8_t* data_row = data;
          for (uint32_t i = 0; i < height; ++i) {
            std::memcpy(upload_buffer_row, data_row, data_row_length);
            data_row += data_row_length;
            upload_buffer_row += upload_footprint.Footprint.RowPitch;
          }
        }
        upload_buffer->Unmap(0, nullptr);
        // Defer uploading and transition to the next draw.
        PendingTextureUpload& pending_upload =
            texture_uploads_pending_.emplace_back();
        // While the upload has not been yet completed, keep a reference to the
        // resource because its lifetime is not tied to that of the
        // ImmediateTexture (and thus to context's submissions) now.
        resource->AddRef();
        pending_upload.texture = resource;
        pending_upload.buffer = upload_buffer;
      } else {
        XELOGE(
            "Failed to map a Direct3D 12 upload buffer for a {}x{} texture for "
            "immediate drawing",
            width, height);
        upload_buffer->Release();
        resource->Release();
        resource = nullptr;
      }
    } else {
      XELOGE(
          "Failed to create a Direct3D 12 upload buffer for a {}x{} texture "
          "for immediate drawing",
          width, height);
      resource->Release();
      resource = nullptr;
    }
  } else {
    XELOGE("Failed to create a {}x{} Direct3D 12 texture for immediate drawing",
           width, height);
    resource = nullptr;
  }

  SamplerIndex sampler_index;
  if (filter == ImmediateTextureFilter::kLinear) {
    sampler_index =
        is_repeated ? SamplerIndex::kLinearRepeat : SamplerIndex::kLinearClamp;
  } else {
    sampler_index = is_repeated ? SamplerIndex::kNearestRepeat
                                : SamplerIndex::kNearestClamp;
  }

  // Manage by this immediate drawer if successfully created a resource.
  std::unique_ptr<D3D12ImmediateTexture> texture =
      std::make_unique<D3D12ImmediateTexture>(
          width, height, resource, sampler_index, resource ? this : nullptr,
          textures_.size());
  if (resource) {
    textures_.push_back(texture.get());
    // D3D12ImmediateTexture now holds a reference.
    resource->Release();
  }
  return std::move(texture);
}

void D3D12ImmediateDrawer::Begin(int render_target_width,
                                 int render_target_height) {
  assert_null(current_command_list_);
  assert_false(batch_open_);

  ID3D12Device* device = context_.GetD3D12Provider().GetDevice();

  // Use the compositing command list.
  current_command_list_ = context_.GetSwapCommandList();

  uint64_t completed_fence_value = context_.GetSwapCompletedFenceValue();

  // Release deleted textures.
  for (auto it = textures_deleted_.begin(); it != textures_deleted_.end();) {
    if (it->second > completed_fence_value) {
      ++it;
      continue;
    }
    it->first->Release();
    if (std::next(it) != textures_deleted_.end()) {
      *it = textures_deleted_.back();
    }
    textures_deleted_.pop_back();
  }

  // Release upload buffers for completed texture uploads.
  auto erase_uploads_end = texture_uploads_submitted_.begin();
  while (erase_uploads_end != texture_uploads_submitted_.end()) {
    if (erase_uploads_end->fence_value > completed_fence_value) {
      break;
    }
    erase_uploads_end->buffer->Release();
    // Release the texture reference held for uploading.
    erase_uploads_end->texture->Release();
    ++erase_uploads_end;
  }
  texture_uploads_submitted_.erase(texture_uploads_submitted_.begin(),
                                   erase_uploads_end);

  vertex_buffer_pool_->Reclaim(completed_fence_value);
  texture_descriptor_pool_->Reclaim(completed_fence_value);

  current_render_target_width_ = render_target_width;
  current_render_target_height_ = render_target_height;
  D3D12_VIEWPORT viewport;
  viewport.TopLeftX = 0.0f;
  viewport.TopLeftY = 0.0f;
  viewport.Width = float(render_target_width);
  viewport.Height = float(render_target_height);
  viewport.MinDepth = 0.0f;
  viewport.MaxDepth = 1.0f;
  current_command_list_->RSSetViewports(1, &viewport);

  current_command_list_->SetGraphicsRootSignature(root_signature_);
  float viewport_inv_size[2];
  viewport_inv_size[0] = 1.0f / viewport.Width;
  viewport_inv_size[1] = 1.0f / viewport.Height;
  current_command_list_->SetGraphicsRoot32BitConstants(
      UINT(RootParameter::kViewportSizeInv), 2, viewport_inv_size, 0);

  current_scissor_.left = 0;
  current_scissor_.top = 0;
  current_scissor_.right = 0;
  current_scissor_.bottom = 0;

  current_primitive_topology_ = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
  current_texture_ = nullptr;
  current_texture_descriptor_heap_index_ =
      D3D12DescriptorHeapPool::kHeapIndexInvalid;
  current_sampler_index_ = SamplerIndex::kInvalid;
}

void D3D12ImmediateDrawer::BeginDrawBatch(const ImmediateDrawBatch& batch) {
  assert_false(batch_open_);
  assert_not_null(current_command_list_);

  uint64_t current_fence_value = context_.GetSwapCurrentFenceValue();

  // Bind the vertices.
  D3D12_VERTEX_BUFFER_VIEW vertex_buffer_view;
  vertex_buffer_view.StrideInBytes = UINT(sizeof(ImmediateVertex));
  vertex_buffer_view.SizeInBytes =
      UINT(sizeof(ImmediateVertex)) * batch.vertex_count;
  void* vertex_buffer_mapping = vertex_buffer_pool_->Request(
      current_fence_value, vertex_buffer_view.SizeInBytes, sizeof(float),
      nullptr, nullptr, &vertex_buffer_view.BufferLocation);
  if (vertex_buffer_mapping == nullptr) {
    XELOGE("Failed to get a buffer for {} vertices in the immediate drawer",
           batch.vertex_count);
    return;
  }
  std::memcpy(vertex_buffer_mapping, batch.vertices,
              vertex_buffer_view.SizeInBytes);
  current_command_list_->IASetVertexBuffers(0, 1, &vertex_buffer_view);

  // Bind the indices.
  batch_has_index_buffer_ = batch.indices != nullptr;
  if (batch_has_index_buffer_) {
    D3D12_INDEX_BUFFER_VIEW index_buffer_view;
    index_buffer_view.SizeInBytes = UINT(sizeof(uint16_t)) * batch.index_count;
    index_buffer_view.Format = DXGI_FORMAT_R16_UINT;
    void* index_buffer_mapping = vertex_buffer_pool_->Request(
        current_fence_value, index_buffer_view.SizeInBytes, sizeof(uint16_t),
        nullptr, nullptr, &index_buffer_view.BufferLocation);
    if (index_buffer_mapping == nullptr) {
      XELOGE("Failed to get a buffer for {} indices in the immediate drawer",
             batch.index_count);
      return;
    }
    std::memcpy(index_buffer_mapping, batch.indices,
                index_buffer_view.SizeInBytes);
    current_command_list_->IASetIndexBuffer(&index_buffer_view);
  }

  batch_open_ = true;
}

void D3D12ImmediateDrawer::Draw(const ImmediateDraw& draw) {
  if (!batch_open_) {
    // Could be an error while obtaining the vertex and index buffers.
    return;
  }

  // Set the scissor rectangle if enabled.
  D3D12_RECT scissor;
  if (draw.scissor) {
    scissor.left = draw.scissor_rect[0];
    scissor.top = current_render_target_height_ -
                  (draw.scissor_rect[1] + draw.scissor_rect[3]);
    scissor.right = scissor.left + draw.scissor_rect[2];
    scissor.bottom = scissor.top + draw.scissor_rect[3];
  } else {
    scissor.left = 0;
    scissor.top = 0;
    scissor.right = current_render_target_width_;
    scissor.bottom = current_render_target_height_;
  }
  if (scissor.right <= scissor.left || scissor.bottom <= scissor.top) {
    // Nothing is visible (used as the default current_scissor_ value also).
    return;
  }
  if (current_scissor_.left != scissor.left ||
      current_scissor_.top != scissor.top ||
      current_scissor_.right != scissor.right ||
      current_scissor_.bottom != scissor.bottom) {
    current_scissor_ = scissor;
    current_command_list_->RSSetScissorRects(1, &scissor);
  }

  // Ensure texture data is available if any texture is loaded, upload all in a
  // batch, then transition all at once.
  UploadTextures();

  // Bind the texture. If this is the first draw in a frame, the descriptor heap
  // index will be invalid initially, and the texture will be bound regardless
  // of what's in current_texture_.
  uint64_t current_fence_value = context_.GetSwapCurrentFenceValue();
  auto texture = static_cast<D3D12ImmediateTexture*>(draw.texture);
  ID3D12Resource* texture_resource = texture ? texture->resource() : nullptr;
  bool bind_texture = current_texture_ != texture_resource;
  uint32_t texture_descriptor_index;
  uint64_t texture_heap_index = texture_descriptor_pool_->Request(
      current_fence_value, current_texture_descriptor_heap_index_,
      bind_texture ? 1 : 0, 1, texture_descriptor_index);
  if (texture_heap_index == D3D12DescriptorHeapPool::kHeapIndexInvalid) {
    return;
  }
  if (texture_resource) {
    texture->SetLastUsageFenceValue(current_fence_value);
  }
  if (current_texture_descriptor_heap_index_ != texture_heap_index) {
    current_texture_descriptor_heap_index_ = texture_heap_index;
    bind_texture = true;
    ID3D12DescriptorHeap* descriptor_heaps[] = {
        texture_descriptor_pool_->GetLastRequestHeap(), sampler_heap_};
    current_command_list_->SetDescriptorHeaps(2, descriptor_heaps);
  }

  const D3D12Provider& provider = context_.GetD3D12Provider();

  if (bind_texture) {
    current_texture_ = texture_resource;
    D3D12_SHADER_RESOURCE_VIEW_DESC texture_view_desc;
    texture_view_desc.Format = D3D12ImmediateTexture::kFormat;
    texture_view_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
    if (texture_resource) {
      texture_view_desc.Shader4ComponentMapping =
          D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
    } else {
      // No texture, solid color.
      texture_view_desc.Shader4ComponentMapping =
          D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(
              D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1,
              D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1,
              D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1,
              D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1);
    }
    texture_view_desc.Texture2D.MostDetailedMip = 0;
    texture_view_desc.Texture2D.MipLevels = 1;
    texture_view_desc.Texture2D.PlaneSlice = 0;
    texture_view_desc.Texture2D.ResourceMinLODClamp = 0.0f;
    provider.GetDevice()->CreateShaderResourceView(
        texture_resource, &texture_view_desc,
        provider.OffsetViewDescriptor(
            texture_descriptor_pool_->GetLastRequestHeapCPUStart(),
            texture_descriptor_index));
    current_command_list_->SetGraphicsRootDescriptorTable(
        UINT(RootParameter::kTexture),
        provider.OffsetViewDescriptor(
            texture_descriptor_pool_->GetLastRequestHeapGPUStart(),
            texture_descriptor_index));
  }

  // Bind the sampler. If the resource doesn't exist (solid color drawing), use
  // nearest-neighbor and clamp so fetching is simpler.
  SamplerIndex sampler_index =
      texture_resource ? texture->sampler_index() : SamplerIndex::kNearestClamp;
  if (current_sampler_index_ != sampler_index) {
    current_sampler_index_ = sampler_index;
    current_command_list_->SetGraphicsRootDescriptorTable(
        UINT(RootParameter::kSampler),
        provider.OffsetSamplerDescriptor(sampler_heap_gpu_start_,
                                         uint32_t(sampler_index)));
  }

  // Set the primitive type and the pipeline for it.
  D3D_PRIMITIVE_TOPOLOGY primitive_topology;
  ID3D12PipelineState* pipeline;
  switch (draw.primitive_type) {
    case ImmediatePrimitiveType::kLines:
      primitive_topology = D3D_PRIMITIVE_TOPOLOGY_LINELIST;
      pipeline = pipeline_line_;
      break;
    case ImmediatePrimitiveType::kTriangles:
      primitive_topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
      pipeline = pipeline_triangle_;
      break;
    default:
      assert_unhandled_case(draw.primitive_type);
      return;
  }
  if (current_primitive_topology_ != primitive_topology) {
    current_primitive_topology_ = primitive_topology;
    current_command_list_->IASetPrimitiveTopology(primitive_topology);
    current_command_list_->SetPipelineState(pipeline);
  }

  // Draw.
  if (batch_has_index_buffer_) {
    current_command_list_->DrawIndexedInstanced(
        draw.count, 1, draw.index_offset, draw.base_vertex, 0);
  } else {
    current_command_list_->DrawInstanced(draw.count, 1, draw.base_vertex, 0);
  }
}

void D3D12ImmediateDrawer::EndDrawBatch() { batch_open_ = false; }

void D3D12ImmediateDrawer::End() {
  assert_false(batch_open_);
  if (current_command_list_) {
    // Don't keep upload buffers forever if nothing was drawn in this frame.
    UploadTextures();
    current_command_list_ = nullptr;
  }
}

void D3D12ImmediateDrawer::OnImmediateTextureDestroyed(
    D3D12ImmediateTexture& texture) {
  // Remove from the texture list.
  size_t texture_index = texture.immediate_drawer_index();
  assert_true(texture_index != SIZE_MAX);
  D3D12ImmediateTexture*& texture_at_index = textures_[texture_index];
  texture_at_index = textures_.back();
  texture_at_index->SetImmediateDrawerIndex(texture_index);
  textures_.pop_back();

  // Queue for delayed release.
  ID3D12Resource* resource = texture.resource();
  uint64_t last_usage_fence_value = texture.last_usage_fence_value();
  if (resource &&
      last_usage_fence_value > context_.GetSwapCompletedFenceValue()) {
    resource->AddRef();
    textures_deleted_.push_back(
        std::make_pair(resource, last_usage_fence_value));
  }
}

void D3D12ImmediateDrawer::UploadTextures() {
  assert_not_null(current_command_list_);
  if (texture_uploads_pending_.empty()) {
    // Called often - don't initialize anything.
    return;
  }

  ID3D12Device* device = context_.GetD3D12Provider().GetDevice();
  uint64_t current_fence_value = context_.GetSwapCurrentFenceValue();

  // Copy all at once, then transition all at once (not interleaving copying and
  // pipeline barriers).
  std::vector<D3D12_RESOURCE_BARRIER> barriers;
  barriers.reserve(texture_uploads_pending_.size());
  for (const PendingTextureUpload& pending_upload : texture_uploads_pending_) {
    ID3D12Resource* texture = pending_upload.texture;

    D3D12_RESOURCE_DESC texture_desc = texture->GetDesc();
    D3D12_TEXTURE_COPY_LOCATION location_source, location_dest;
    location_source.pResource = pending_upload.buffer;
    location_source.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
    device->GetCopyableFootprints(&texture_desc, 0, 1, 0,
                                  &location_source.PlacedFootprint, nullptr,
                                  nullptr, nullptr);
    location_dest.pResource = texture;
    location_dest.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
    location_dest.SubresourceIndex = 0;
    current_command_list_->CopyTextureRegion(&location_dest, 0, 0, 0,
                                             &location_source, nullptr);

    D3D12_RESOURCE_BARRIER& barrier = barriers.emplace_back();
    barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
    barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
    barrier.Transition.pResource = texture;
    barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
    barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
    barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;

    SubmittedTextureUpload& submitted_upload =
        texture_uploads_submitted_.emplace_back();
    // Transfer the reference to the texture - need to keep it until the upload
    // is completed.
    submitted_upload.texture = texture;
    submitted_upload.buffer = pending_upload.buffer;
    submitted_upload.fence_value = current_fence_value;
  }
  texture_uploads_pending_.clear();
  assert_false(barriers.empty());
  current_command_list_->ResourceBarrier(UINT(barriers.size()),
                                         barriers.data());
}

}  // namespace d3d12
}  // namespace ui
}  // namespace xe


text:
namespace Spritely.ReadModel.Mongo.Test
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using NUnit.Framework;

    public abstract class GetManyTestBase
    {
        protected ITestDatabase Database { get; set; }

        protected IReadOnlyList<StorageModel<TestModel, TestMetadata>> StorageModels { get; set; }

        protected IReadOnlyList<TestModel> TestModels { get; set; }

        protected string TestStorageName { get; set; }

        [Test]
        public void Gets_expected_results_from_database()
        {
            Database.AddTestModelsToDatabase(TestModels);

            var getTask = Database.ModelQueries.GetManyAsync(m => m.Name.StartsWith(TestStorageName));
            getTask.Wait();

            var results = getTask.Result.ToList();
            AssertResults.Match(results, TestModels);
        }

        [Test]
        public void Gets_expected_results_from_database_with_custom_metadata()
        {
            Database.AddStorageModelsToDatabase(StorageModels);

            var getTask = Database.StorageModelQueries.GetManyAsync(m => m.Model.Name.StartsWith(TestStorageName));
            getTask.Wait();

            var results = getTask.Result.ToList();
            AssertResults.Match(results, StorageModels);
        }

        [Test]
        public void Gets_expected_subset_results_from_database()
        {
            Database.AddTestModelsToDatabase(TestModels);

            var ids = TestModels.Skip(1).Take(3).Select(m => m.Id);
            var getTask = Database.ModelQueries.GetManyAsync(m => ids.Contains(m.Id));
            getTask.Wait();

            var results = getTask.Result.ToList();
            AssertResults.Match(results, TestModels.Skip(1).Take(3).ToList());
        }

        [Test]
        public void Gets_expected_subset_results_from_database_with_custom_metadata()
        {
            Database.AddStorageModelsToDatabase(StorageModels);

            var ids = StorageModels.Skip(1).Take(3).Select(m => m.Model.Id);
            var getTask = Database.StorageModelQueries.GetManyAsync(m => ids.Contains(m.Model.Id));
            getTask.Wait();

            var results = getTask.Result.ToList();
            AssertResults.Match(results, StorageModels.Skip(1).Take(3).ToList());
        }

        [Test]
        public void Gets_empty_results_with_querying_for_nonexistent_data()
        {
            Database.AddTestModelsToDatabase(TestModels);

            var getTask = Database.ModelQueries.GetManyAsync(m => m.Id == Guid.NewGuid());
            getTask.Wait();

            var results = getTask.Result.ToList();
            Assert.That(results, Is.Empty);
        }

        [Test]
        public void Gets_empty_results_with_querying_for_nonexistent_data_with_custom_metadata()
        {
            Database.AddStorageModelsToDatabase(StorageModels);

            var getTask = Database.StorageModelQueries.GetManyAsync(m => m.Model.Id == Guid.NewGuid());
            getTask.Wait();

            var results = getTask.Result.ToList();
            Assert.That(results, Is.Empty);
        }

        [Test]
        public void Throws_on_invalid_arguments()
        {
            Assert.That(
                () => Task.Run(() => Database.ModelQueries.GetManyAsync(null)).Wait(),
                Throws.TypeOf<AggregateException>().With.InnerException.TypeOf<ArgumentNullException>());
        }

        [Test]
        public void Throws_on_invalid_arguments_with_custom_metadata()
        {
            Assert.That(
                () => Task.Run(() => Database.StorageModelQueries.GetManyAsync(null)).Wait(),
                Throws.TypeOf<AggregateException>().With.InnerException.TypeOf<ArgumentNullException>());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.mobilesolutionworks.android.managedview;

/**
 * Created by yunarta on 30/5/14.
 */
public interface IObjectProvider
{
    void onPropertyChanged(String name, String property, String value);

    Object getProperty(String name, String property);
}


text:
namespace glraw
{

Converter::Converter()
:   m_format(GL_RGBA)
,   m_type(GL_UNSIGNED_BYTE)
{
}

Converter::~Converter()
{
}

QByteArray Converter::convert(QImage & image, AssetInformation & info)
{
    m_canvas.loadTextureFromImage(image);

    if (hasFragmentShader() && !m_canvas.process(m_fragmentShader, m_uniforms))
        return QByteArray();

    info.setProperty("format", QVariant(static_cast<int>(m_format)));
    info.setProperty("type", QVariant(static_cast<int>(m_type)));

    return m_canvas.imageFromTexture(m_format, m_type);
}

void Converter::setFormat(GLenum format)
{
    m_format = format;
}

void Converter::setType(GLenum type)
{
    m_type = type;
}

} // namespace glraw


text:
'use strict';

describe('Controller: AccountsCtrl', function () {

  // load the controller's module
  beforeEach(module('moneyWebClientApp'));

  var AccountsCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    AccountsCtrl = $controller('AccountsCtrl', {
      $scope: scope
      // place here mocked dependencies
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(AccountsCtrl.awesomeThings.length).toBe(3);
  });
});


text:
FROM docker.dever.cc/java/base:latest

MAINTAINER Rabin "https://github.com/shemic"

ENV SBT_HOME=/usr/local/sbt \
	SBT_VERSION=0.13.15
ENV PATH=$PATH:$SBT_HOME/bin

COPY repositories /root/repositories

RUN curl -O -L https://github.com/sbt/sbt/releases/download/v${SBT_VERSION}/sbt-${SBT_VERSION}.tgz && \
	tar -zxvf sbt-${SBT_VERSION}.tgz && \
	rm sbt-${SBT_VERSION}.tgz && \
	mv sbt ${SBT_HOME}

VOLUME ["/usr/local/sbt/conf"]


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>sap.ui.table - Test pages</title>

sap.ui.table - Test pages

Table

Main test page

OData V4

Scrolling with variable row heights and large data

Performance

Cell content alignment

Column width

Drag & Drop

Wide table with many columns

Multi labels and spans

Personalization with the sap.ui.table.TablePersoController

Synchronization

TreeTable

Main test page

OData V2

AnalyticalTable

Main test page


text:
enum {
	kGlyphForTabRight       = 0x21E5,
	kGlyphForTabLeft        = 0x21E4,
	kGlyphForCommand        = kCommandUnicode,
	kGlyphForOption         = kOptionUnicode,
	kGlyphForShift          = kShiftUnicode,
	kGlyphForControl        = kControlUnicode,
	kGlyphForReturn         = 0x2305,
	kGlyphForReturnR2L      = 0x21A9,
	kGlyphForDeleteLeft     = 0x232B,
	kGlyphForDeleteRight    = 0x2326,
	kGlyphForPadClear       = 0x2327,
    kGlyphForLeftArrow      = 0x2190,
	kGlyphForRightArrow     = 0x2192,
	kGlyphForUpArrow        = 0x2191,
	kGlyphForDownArrow      = 0x2193,
    kGlyphForPageDown       = 0x21DF,
	kGlyphForPageUp         = 0x21DE,
	kGlyphForNorthwestArrow = 0x2196,
	kGlyphForSoutheastArrow = 0x2198,
	kGlyphForEscape         = 0x238B,
	kGlyphForHelp           = 0x003F,
	kGlyphForUpArrowhead    = 0x2303,
};

enum {
	kKeyCodeForF1 = 122,
	kKeyCodeForF2 = 120,
	kKeyCodeForF3 = 99,
	kKeyCodeForF4 = 118,
	kKeyCodeForF5 = 96,
	kKeyCodeForF6 = 97,
	kKeyCodeForF7 = 98,
	kKeyCodeForF8 = 100,
	kKeyCodeForF9 = 101,
	kKeyCodeForF10 = 109,
	kKeyCodeForF11 = 103,
	kKeyCodeForF12 = 111,
	kKeyCodeForF13 = 105,
	kKeyCodeForF14 = 107,
	kKeyCodeForF15 = 113,
	kKeyCodeForF16 = 106,
	kKeyCodeForF17 = 64,
	kKeyCodeForF18 = 79,
	kKeyCodeForF19 = 80,
	kKeyCodeForSpace = 49,
	kKeyCodeForDeleteLeft = 51,
	kKeyCodeForDeleteRight = 117,
	kKeyCodeForPadClear = 71,
	kKeyCodeForLeftArrow = 123,
	kKeyCodeForRightArrow = 124,
	kKeyCodeForUpArrow = 126,
	kKeyCodeForDownArrow = 125,
	kKeyCodeForSoutheastArrow = 119,
	kKeyCodeForNorthwestArrow = 115,
	kKeyCodeForEscape = 53,
	kKeyCodeForPageDown = 121,
	kKeyCodeForPageUp = 116,
	kKeyCodeForReturnR2L = 36,
	kKeyCodeForReturn = 76,
	kKeyCodeForTabRight = 48,
	kKeyCodeForHelp = 114
};

@interface NUKeyboardUtils : NSObject

- (uint16_t) virtualKeyCodesForKey:(unichar)key;
- (NSString*) stringForKeyCode:(uint16_t)code;
- (NSString*) shortcutStringForKeyCode:(uint16_t)key withModifierFlags:(uint32_t)flags;

+ (NUKeyboardUtils*)sharedInstance;
+ (uint16_t) virtualKeyCodesForKey:(unichar)key;
+ (NSString*) stringForKeyCode:(uint16_t)code;
+ (NSString*) shortcutStringForKeyCode:(uint16_t)code withModifierFlags:(uint32_t)flags;
+ (id) keyboardUtils;

@end


text:
<?php

namespace Google\AdsApi\Dfp\Util\v201705;

use Google\AdsApi\Dfp\v201705\BooleanValue;
use Google\AdsApi\Dfp\v201705\Date;
use Google\AdsApi\Dfp\v201705\DateTime as DfpDateTime;
use Google\AdsApi\Dfp\v201705\DateTimeValue;
use Google\AdsApi\Dfp\v201705\DateValue;
use Google\AdsApi\Dfp\v201705\NumberValue;
use Google\AdsApi\Dfp\v201705\ResultSet;
use Google\AdsApi\Dfp\v201705\Row;
use Google\AdsApi\Dfp\v201705\SetValue;
use Google\AdsApi\Dfp\v201705\Targeting;
use Google\AdsApi\Dfp\v201705\TargetingValue;
use Google\AdsApi\Dfp\v201705\TextValue;
use Google\AdsApi\Dfp\v201705\Value;
use InvalidArgumentException;

/**
 * Static utility methods for working with PQL.
 */
class Pql {

  private function __construct() {}

  /**
   * Creates a PQL `Value` from the specified value.
   *
   * For example:
   *  - A `TextValue` for a value of type `string`.
   *  - A `BooleanValue` for type `bool`.
   *  - A `NumberValue` for type `float` or `int`.
   *  - A `DateTimeValue` for type DFP `DateTime`
   *  - A `DateValue` for type DFP `Date`
   *  - A `SetValue` for type `array`.
   *
   * If the specified value is already a PQL `Value`, the value is returned.
   *
   * @param mixed $value the value to convert to a PQL value
   * @return Value a PQL value of the appropriate type
   * @throws InvalidArgumentException if value cannot be converted
   */
  public static function createValue($value) {
    if ($value instanceof Value) {
      return $value;
    } else if (is_bool($value)) {
      return new BooleanValue($value);
    } else if (is_float($value) || is_int($value)) {
      return new NumberValue(strval($value));
    } else if (is_string($value)) {
      return new TextValue($value);
    } else if ($value instanceof DfpDateTime) {
      return new DateTimeValue($value);
    } else if ($value instanceof Date) {
      return new DateValue($value);
    } else if (is_array($value)) {
      $values = [];
      foreach ($value as $valueEntry) {
        $values[] = self::createValue($valueEntry);
      }
      $setValue = new SetValue();
      $setValue->setValues($values);
      return $setValue;
    } else if ($value instanceof Targeting) {
      return new TargetingValue($value);
    } else {
      throw new InvalidArgumentException(sprintf(
          'Unsupported value type [%s]',
          is_object($value) ? get_class($value) : gettype($value)
      ));
    }
  }

  /**
   * Creates a string from the Value.
   *
   * @param Value $value the value to convert
   * @return string the string representation of the value
   * @throws InvalidArgumentException if value cannot be converted
   */
  public static function toString(Value $value) {
    if ($value instanceof BooleanValue) {
      return $value->getValue() ? 'true' : 'false';
    } else if ($value instanceof NumberValue || $value instanceof TextValue) {
      return strval($value->getValue());
    } else if ($value instanceof DateTimeValue) {
      return $value->getValue() !== null
          ? DfpDateTimes::toDateTimeString($value->getValue()) : '';
    } else if ($value instanceof DateValue) {
      return DfpDates::toDateString($value->getValue());
    } else if ($value instanceof SetValue) {
      $pqlValues = $value->getValues();
      if ($pqlValues !== null) {
        $valuesAsStrings = [];
        foreach ($pqlValues as $pqlValue) {
          $valuesAsStrings[] = self::toString($pqlValue);
        }
        return implode(',', $valuesAsStrings);
      } else {
        return '';
      }
    } else {
      throw new InvalidArgumentException(
          sprintf('Unsupported value type [%s]', get_class($value)));
    }
  }

  /**
   * Gets the column labels for the result set.
   *
   * @param ResultSet $resultSet the result set to get the column labels for
   * @return string[] the string list of column labels
   */
  public static function getColumnLabels(ResultSet $resultSet) {
    $columnLabels = [];
    foreach ($resultSet->getColumnTypes() as $columnType) {
      $columnLabels[] = $columnType->getLabelName();
    }
    return $columnLabels;
  }

  /**
   * Gets the values in a row of the result set in the form of a string list.
   *
   * @param Row $row the row to get the values for
   * @return string[] the string list of row labels
   */
  public static function getRowStringValues(Row $row) {
    return array_map(['self', 'toString'], $row->getValues());
  }

  /**
   * Combines the first and second result sets, if and only if, the columns
   * of both result sets match.
   *
   * @throws InvalidArgumentException if the result sets to combine do not have
   *     identical column headers
   */
  public static function combineResultSets(ResultSet $first,
      ResultSet $second) {
    $firstColumns = self::getColumnLabels($first);
    $secondColumns = self::getColumnLabels($second);

    if ($firstColumns !== $secondColumns) {
      throw new InvalidArgumentException(sprintf('First result set columns '
          . '[%s] do not match second result set columns [%s]', implode(', ',
          $firstColumns), implode(', ', $secondColumns)));
    }

    $combinedRows = $first->getRows();
    if ($second->getRows() !== null) {
      $combinedRows = array_merge($combinedRows, $second->getRows());
    }

    return new ResultSet($first->getColumnTypes(), $combinedRows);
  }
}


text:
from touchdown.core import argument

from . import variable

class Integer(variable.Variable):

    resource_name = "integer"

    default = argument.Integer()
    min = argument.Integer()
    max = argument.Integer()

class Set(variable.Set):
    resource = Integer

    def to_lines(self, value):
        return [str(value)]

class Get(variable.Get):
    resource = Integer

    def from_lines(self, value):
        return int(value[0])

argument.Integer.register_adapter(Integer, variable.VariableAsString)


text:
'use strict';

import mongoose from 'mongoose';
import uuid from 'node-uuid';

/**
 * Generate a verification token using uuid v4.
 *
 * @returns {String} An uuid v4 token
 */
const generateToken = () => uuid.v4();

/**
 * Mongoose schema of verification token.
 *
 */
const verificationTokenSchema = new mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User',
          required: '{PATH} is required', },
  token: { type: String, default: generateToken },
  createdAt: { type: Date, default: Date.now, expires: 12 * 60 * 60 },
});

mongoose.model('VerificationToken', verificationTokenSchema);


text:
package com.tuplejump.calliope.server

import java.io._
import java.util.{ArrayList => JArrayList}

import jline.{ConsoleReader, History}
import org.apache.commons.lang.StringUtils
import org.apache.commons.logging.LogFactory
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.hive.cli.{CliDriver, CliSessionState, OptionsProcessor}
import org.apache.hadoop.hive.common.LogUtils.LogInitializationException
import org.apache.hadoop.hive.common.{HiveInterruptCallback, HiveInterruptUtils, LogUtils}
import org.apache.hadoop.hive.conf.HiveConf
import org.apache.hadoop.hive.ql.Driver
import org.apache.hadoop.hive.ql.exec.Utilities
import org.apache.hadoop.hive.ql.processors.{CommandProcessor, CommandProcessorFactory, SetProcessor}
import org.apache.hadoop.hive.ql.session.SessionState
import org.apache.hadoop.hive.shims.ShimLoader
import org.apache.spark.Logging
import org.apache.spark.sql.hive.CalliopeSQLDriver
import org.apache.thrift.transport.TSocket

import scala.collection.JavaConversions._

object CalliopeCLIDriver {
  private var prompt = "spark-sql"
  private var continuedPrompt = "".padTo(prompt.length, ' ')
  private var transport:TSocket = _

  installSignalHandler()

  /**
   * Install an interrupt callback to cancel all Spark jobs. In Hive's CliDriver#processLine(),
   * a signal handler will invoke this registered callback if a Ctrl+C signal is detected while
   * a command is being processed by the current thread.
   */
  def installSignalHandler() {
    HiveInterruptUtils.add(new HiveInterruptCallback {
      override def interrupt() {
        // Handle remote execution mode
        if (CalliopeSQLEnv.sparkContext != null) {
          CalliopeSQLEnv.sparkContext.cancelAllJobs()
        } else {
          if (transport != null) {
            // Force closing of TCP connection upon session termination
            transport.getSocket.close()
          }
        }
      }
    })
  }

  def main(args: Array[String]) {
    val oproc = new OptionsProcessor()
    if (!oproc.process_stage1(args)) {
      System.exit(1)
    }

    // NOTE: It is critical to do this here so that log4j is reinitialized
    // before any of the other core hive classes are loaded
    var logInitFailed = false
    var logInitDetailMessage: String = null
    try {
      logInitDetailMessage = LogUtils.initHiveLog4j()
    } catch {
      case e: LogInitializationException =>
        logInitFailed = true
        logInitDetailMessage = e.getMessage
    }

    val sessionState = new CliSessionState(new HiveConf(classOf[SessionState]))

    sessionState.in = System.in
    try {
      sessionState.out = new PrintStream(System.out, true, "UTF-8")
      sessionState.info = new PrintStream(System.err, true, "UTF-8")
      sessionState.err = new PrintStream(System.err, true, "UTF-8")
    } catch {
      case e: UnsupportedEncodingException => System.exit(3)
    }

    if (!oproc.process_stage2(sessionState)) {
      System.exit(2)
    }

    if (!sessionState.getIsSilent) {
      if (logInitFailed) System.err.println(logInitDetailMessage)
      else SessionState.getConsole.printInfo(logInitDetailMessage)
    }

    // Set all properties specified via command line.
    val conf: HiveConf = sessionState.getConf
    sessionState.cmdProperties.entrySet().foreach { item: java.util.Map.Entry[Object, Object] =>
      conf.set(item.getKey.asInstanceOf[String], item.getValue.asInstanceOf[String])
      sessionState.getOverriddenConfigurations.put(
        item.getKey.asInstanceOf[String], item.getValue.asInstanceOf[String])
    }

    SessionState.start(sessionState)

    // Clean up after we exit
    Runtime.getRuntime.addShutdownHook(
      new Thread() {
        override def run() {
          CalliopeSQLEnv.stop()
        }
      }
    )

    // "-h" option has been passed, so connect to Hive thrift server.
    if (sessionState.getHost != null) {
      sessionState.connect()
      if (sessionState.isRemoteMode) {
        prompt = s"[${sessionState.getHost}:${sessionState.getPort}]" + prompt
        continuedPrompt = "".padTo(prompt.length, ' ')
      }
    }

    if (!sessionState.isRemoteMode && !ShimLoader.getHadoopShims.usesJobShell()) {
      // Hadoop-20 and above - we need to augment classpath using hiveconf
      // components.
      // See also: code in ExecDriver.java
      var loader = conf.getClassLoader
      val auxJars = HiveConf.getVar(conf, HiveConf.ConfVars.HIVEAUXJARS)
      if (StringUtils.isNotBlank(auxJars)) {
        loader = Utilities.addToClassPath(loader, StringUtils.split(auxJars, ","))
      }
      conf.setClassLoader(loader)
      Thread.currentThread().setContextClassLoader(loader)
    }

    val cli = new CalliopeCLIDriver
    cli.setHiveVariables(oproc.getHiveVariables)

    // TODO work around for set the log output to console, because the HiveContext
    // will set the output into an invalid buffer.
    sessionState.in = System.in
    try {
      sessionState.out = new PrintStream(System.out, true, "UTF-8")
      sessionState.info = new PrintStream(System.err, true, "UTF-8")
      sessionState.err = new PrintStream(System.err, true, "UTF-8")
    } catch {
      case e: UnsupportedEncodingException => System.exit(3)
    }

    // Execute -i init files (always in silent mode)
    cli.processInitFiles(sessionState)

    if (sessionState.execString != null) {
      System.exit(cli.processLine(sessionState.execString))
    }

    try {
      if (sessionState.fileName != null) {
        System.exit(cli.processFile(sessionState.fileName))
      }
    } catch {
      case e: FileNotFoundException =>
        System.err.println(s"Could not open input file for reading. (${e.getMessage})")
        System.exit(3)
    }

    val reader = new ConsoleReader()
    reader.setBellEnabled(false)
    // reader.setDebug(new PrintWriter(new FileWriter("writer.debug", true)))
    CliDriver.getCommandCompletor.foreach((e) => reader.addCompletor(e))

    val historyDirectory = System.getProperty("user.home")

    try {
      if (new File(historyDirectory).exists()) {
        val historyFile = historyDirectory + File.separator + ".hivehistory"
        reader.setHistory(new History(new File(historyFile)))
      } else {
        System.err.println("WARNING: Directory for Hive history file: " + historyDirectory +
                           " does not exist.   History will not be available during this session.")
      }
    } catch {
      case e: Exception =>
        System.err.println("WARNING: Encountered an error while trying to initialize Hive's " +
                           "history file.  History will not be available during this session.")
        System.err.println(e.getMessage)
    }

    val clientTransportTSocketField = classOf[CliSessionState].getDeclaredField("transport")
    clientTransportTSocketField.setAccessible(true)

    transport = clientTransportTSocketField.get(sessionState).asInstanceOf[TSocket]

    var ret = 0
    var prefix = ""
    val currentDB = ReflectionUtils.invokeStatic(classOf[CliDriver], "getFormattedDb",
      classOf[HiveConf] -> conf, classOf[CliSessionState] -> sessionState)

    def promptWithCurrentDB = s"$prompt$currentDB"
    def continuedPromptWithDBSpaces = continuedPrompt + ReflectionUtils.invokeStatic(
      classOf[CliDriver], "spacesForString", classOf[String] -> currentDB)

    var currentPrompt = promptWithCurrentDB
    var line = reader.readLine(currentPrompt + "> ")

    while (line != null) {
      if (prefix.nonEmpty) {
        prefix += '\n'
      }

      if (line.trim().endsWith(";") && !line.trim().endsWith("\\;")) {
        line = prefix + line
        ret = cli.processLine(line, true)
        prefix = ""
        currentPrompt = promptWithCurrentDB
      } else {
        prefix = prefix + line
        currentPrompt = continuedPromptWithDBSpaces
      }

      line = reader.readLine(currentPrompt + "> ")
    }

    sessionState.close()

    System.exit(ret)
  }
}

class CalliopeCLIDriver extends CliDriver with Logging {
  private val sessionState = SessionState.get().asInstanceOf[CliSessionState]

  private val LOG = LogFactory.getLog("CliDriver")

  private val console = new SessionState.LogHelper(LOG)

  private val conf: Configuration =
    if (sessionState != null) sessionState.getConf else new Configuration()

  // Force initializing SparkSQLEnv. This is put here but not object SparkSQLCliDriver
  // because the Hive unit tests do not go through the main() code path.
  if (!sessionState.isRemoteMode) {
    CalliopeSQLEnv.init()
  }

  override def processCmd(cmd: String): Int = {
    val cmd_trimmed: String = cmd.trim()
    val tokens: Array[String] = cmd_trimmed.split("\\s+")
    val cmd_1: String = cmd_trimmed.substring(tokens(0).length()).trim()
    if (cmd_trimmed.toLowerCase.equals("quit") ||
      cmd_trimmed.toLowerCase.equals("exit") ||
      tokens(0).equalsIgnoreCase("source") ||
      cmd_trimmed.startsWith("!") ||
      tokens(0).toLowerCase.equals("list") ||
      sessionState.isRemoteMode) {
      val start = System.currentTimeMillis()
      super.processCmd(cmd)
      val end = System.currentTimeMillis()
      val timeTaken: Double = (end - start) / 1000.0
      console.printInfo(s"Time taken: $timeTaken seconds")
      0
    } else {
      var ret = 0
      val hconf = conf.asInstanceOf[HiveConf]
      val proc: CommandProcessor = CommandProcessorFactory.get(tokens(0), hconf)

      if (proc != null) {
        if (proc.isInstanceOf[Driver] || proc.isInstanceOf[SetProcessor]) {
          val driver = new CalliopeSQLDriver

          driver.init()
          val out = sessionState.out
          val start:Long = System.currentTimeMillis()
          if (sessionState.getIsVerbose) {
            out.println(cmd)
          }

          val rc = driver.run(cmd)
          ret = rc.getResponseCode
          if (ret != 0) {
            console.printError(rc.getErrorMessage())
            driver.close()
            return ret
          }

          val res = new JArrayList[String]()

          if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_CLI_PRINT_HEADER)) {
            // Print the column names.
            Option(driver.getSchema.getFieldSchemas).map { fields =>
              out.println(fields.map(_.getName).mkString("\t"))
            }
          }

          try {
            while (!out.checkError() && driver.getResults(res)) {
              res.foreach(out.println)
              res.clear()
            }
          } catch {
            case e:IOException =>
              console.printError(
                s"""Failed with exception ${e.getClass.getName}: ${e.getMessage}
                   |${org.apache.hadoop.util.StringUtils.stringifyException(e)}
                 """.stripMargin)
              ret = 1
          }

          val cret = driver.close()
          if (ret == 0) {
            ret = cret
          }

          val end = System.currentTimeMillis()
          if (end > start) {
            val timeTaken:Double = (end - start) / 1000.0
            console.printInfo(s"Time taken: $timeTaken seconds", null)
          }

          // Destroy the driver to release all the locks.
          driver.destroy()
        } else {
          if (sessionState.getIsVerbose) {
            sessionState.out.println(tokens(0) + " " + cmd_1)
          }
          ret = proc.run(cmd_1).getResponseCode
        }
      }
      ret
    }
  }
}


text:
    <!-- jQuery -->
    <script src="<?php echo base_url('assets/vendor/jquery/jquery.min.js'); ?>"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="<?php echo base_url('assets/vendor/bootstrap/js/bootstrap.min.js'); ?>"></script>

    <!-- Metis Menu Plugin JavaScript -->
    <script src="<?php echo base_url('assets/vendor/metisMenu/metisMenu.min.js'); ?>"></script>

    <!-- Custom Theme JavaScript -->
    <script src="<?php echo base_url('assets/dist/js/sb-admin-2.js'); ?>"></script>

</body>

</html>


text:
namespace CGAL {

template <class R_>
class Segment_2 : public R_::Kernel_base::Segment_2
{
  typedef typename R_::RT                     RT;
  typedef typename R_::FT                     FT;
  typedef typename R_::Point_2                Point_2;
  typedef typename R_::Direction_2            Direction_2;
  typedef typename R_::Vector_2               Vector_2;
  typedef typename R_::Line_2                 Line_2;
  typedef typename R_::Aff_transformation_2   Aff_transformation_2;
  typedef typename R_::Kernel_base::Segment_2 RSegment_2;

  typedef Segment_2                           Self;
  CGAL_static_assertion((boost::is_same<Self, typename R_::Segment_2>::value));

public:

  typedef Dimension_tag<2>  Ambient_dimension;
  typedef Dimension_tag<1>  Feature_dimension;

  typedef RSegment_2 Rep;

  const Rep& rep() const
  {
    return *this;
  }

  Rep& rep()
  {
    return *this;
  }

  typedef  R_                               R;

  Segment_2() {}

  // conversion from implementation class object to interface class object
  Segment_2(const RSegment_2& s)
    : RSegment_2(s) {}

  Segment_2(const Point_2 &sp, const Point_2 &ep)
    :  RSegment_2(typename R::Construct_segment_2()(Return_base_tag(), sp,ep)) {}

  typename cpp11::result_of<typename R::Construct_source_2( Segment_2)>::type
  source() const
  {
    return R_().construct_source_2_object()(*this);
  }

  typename cpp11::result_of<typename R::Construct_target_2( Segment_2)>::type
  target() const
  {
    return R_().construct_target_2_object()(*this);
  }

  typename cpp11::result_of<typename R::Construct_source_2( Segment_2)>::type
  start() const
  {
    return source();
  }

  typename cpp11::result_of<typename R::Construct_target_2( Segment_2)>::type
  end() const
  {
    return target();
  }

  typename cpp11::result_of<typename R_::Construct_min_vertex_2(Segment_2)>::type
  min BOOST_PREVENT_MACRO_SUBSTITUTION() const;

  typename cpp11::result_of<typename R_::Construct_max_vertex_2( Segment_2)>::type
  max BOOST_PREVENT_MACRO_SUBSTITUTION () const;

  typename cpp11::result_of<typename R_::Construct_vertex_2( Segment_2, int)>::type
  vertex(int i) const;

  typename cpp11::result_of<typename R_::Construct_vertex_2( Segment_2, int)>::type
  point(int i) const;

  typename cpp11::result_of<typename R_::Construct_vertex_2( Segment_2, int)>::type
  operator[](int i) const;

  bool        is_horizontal() const;
  bool        is_vertical() const;
  bool        has_on(const Point_2 &p) const;
  bool        collinear_has_on(const Point_2 &p) const;
  FT          squared_length() const;

  bool        is_degenerate() const;

  Bbox_2      bbox() const
  {
    return R().construct_bbox_2_object()(*this);
  }

  bool
  operator==(const Segment_2 &s) const
  {
    return R().equal_2_object()(*this, s);
  }

  bool
  operator!=(const Segment_2 &s) const
  {
    return !(*this == s);
  }

  Direction_2
  direction() const
  {
    typename R::Construct_vector_2 construct_vector;
    return Direction_2( construct_vector( source(), target()));
  }

  Vector_2
  to_vector() const
  {
    typename R::Construct_vector_2 construct_vector;
    return construct_vector( source(), target());
  }

  Line_2
  supporting_line() const
  {
    typename R::Construct_line_2 construct_line;
    return construct_line(*this);
  }

  Segment_2
  opposite() const
  {
    return R().construct_opposite_segment_2_object()(*this);
  }

  Segment_2
  transform(const Aff_transformation_2 &t) const
  {
    return Segment_2(t.transform(source()), t.transform(target()));
  }
};

template < class R_ >
CGAL_KERNEL_INLINE
typename cpp11::result_of<typename R_::Construct_min_vertex_2( Segment_2<R_> )>::type
Segment_2<R_>::min BOOST_PREVENT_MACRO_SUBSTITUTION () const
{
  typename R_::Less_xy_2 less_xy;
  return less_xy(source(),target()) ? source() : target();
}

template < class R_ >
CGAL_KERNEL_INLINE
typename cpp11::result_of<typename R_::Construct_max_vertex_2( Segment_2<R_> )>::type
Segment_2<R_>::max BOOST_PREVENT_MACRO_SUBSTITUTION () const
{
  typename R_::Less_xy_2 less_xy;
  return less_xy(source(),target()) ? target() : source();
}

template < class R_ >
CGAL_KERNEL_INLINE
typename cpp11::result_of<typename R_::Construct_vertex_2( Segment_2<R_>, int )>::type
Segment_2<R_>::vertex(int i) const
{
  return (i%2 == 0) ? source() : target();
}

template < class R_ >
inline
typename cpp11::result_of<typename R_::Construct_vertex_2( Segment_2<R_>, int )>::type
Segment_2<R_>::point(int i) const
{
  return vertex(i);
}

template < class R_ >
inline
typename cpp11::result_of<typename R_::Construct_vertex_2( Segment_2<R_>, int )>::type
Segment_2<R_>::operator[](int i) const
{
  return vertex(i);
}

template < class R_ >
CGAL_KERNEL_INLINE
bool
Segment_2<R_>::is_horizontal() const
{
  return R_().equal_y_2_object()(source(), target());
}

template < class R_ >
CGAL_KERNEL_INLINE
bool
Segment_2<R_>::is_vertical() const
{
  return R_().equal_x_2_object()(source(), target());
}

template < class R_ >
CGAL_KERNEL_INLINE
bool
Segment_2<R_>::
has_on(const typename R_::Point_2 &p) const
{
  return R_().are_ordered_along_line_2_object()(source(),
					       p,
					       target());
}

template < class R_ >
inline
bool
Segment_2<R_>::
collinear_has_on(const typename R_::Point_2 &p) const
{
  return R_().collinear_has_on_2_object()
               (*this, p);
}

template < class R_ >
CGAL_KERNEL_INLINE
typename Segment_2<R_>::FT
Segment_2<R_>::squared_length() const
{
 return R_().compute_squared_length_2_object()(*this);
}

template < class R_ >
inline
bool
Segment_2<R_>::is_degenerate() const
{
  return R().is_degenerate_2_object()(*this);
}

template < class R >
std::ostream &
operator<<(std::ostream &os, const Segment_2<R> &s)
{
    switch(get_mode(os)) {
    case IO::ASCII :
        return os << s.source() << ' ' << s.target();
    case IO::BINARY :
        return os << s.source() << s.target();
    default:
        return os << "Segment_2(" << s.source() <<  ", " << s.target() << ")";
    }
}

template < class R >
std::istream &
operator>>(std::istream &is, Segment_2<R> &s)
{
    typename R::Point_2 p, q;

    is >> p >> q;

    if (is)
        s = Segment_2<R>(p, q);
    return is;
}

} //namespace CGAL

#endif //  CGAL_SEGMENT_2_H


text:
set schema 's';

-- Standard join filter case
explain plan for select lname,dname from emp,dept
where emp.deptno=dept.deptno and dept.dname='Marketing';

explain plan for select lname,dname from emp,dept
where emp.deptno=dept.deptno and dept.dname<'Development'
order by 1;

-- multiple dimension filter conditions
explain plan for select emp.lname, emp.fname, dname from emp,dept
where emp.deptno=dept.deptno and dept.dname='Accounting' and dept.locid in ('HQ','SF')
order by 1,2;

-- don't reference dept in the select list, should drop out
-- of select list
explain plan for select 1 from emp,dept
where emp.deptno=dept.deptno and dept.deptno=20
order by 1;

explain plan for select emp.fname from emp,dept
where emp.deptno=dept.deptno and dept.deptno<20
order by 1;

-- multiple dimension tables, filters on both
explain plan for select customers.lname, products.name, sales.price
from sales, products, customers
where customers.custid=sales.custid
and sales.prodid = products.prodid
and customers.lname < 'C'
and products.name >= 'Soap'
order by 1,2,3;

-- multiple dimension tables but filter on only one
explain plan for select customers.lname, products.name, sales.price
from sales, products, customers
where customers.custid=sales.custid
and sales.prodid = products.prodid
and customers.lname = 'Andrews'
order by 1,2,3;

-- multiple dimension tables, multiple filters
explain plan for select customers.lname, products.name, sales.price
from sales, products, customers
where customers.custid=sales.custid
and sales.prodid = products.prodid
and customers.lname < 'C'
and customers.fname > 'S'
order by 1,2,3;

explain plan for select customers.lname, products.name, sales.price
from sales, products, customers
where customers.custid=sales.custid
and sales.prodid = products.prodid
and customers.lname < 'C'
and customers.fname > 'S'
and sales.prodid < 10009
and products.name IN ('Soap', 'Juice', 'Soup', 'Microwave', 'Soda')
and products.price < 5.00
order by 1,2,3;

-- dimension tables not referenced in select list, should drop
-- out of join
explain plan for select sum(sales.price)
from sales, products, customers
where customers.custid=sales.custid
and sales.prodid = products.prodid
and customers.lname < 'C'
and customers.fname > 'S'
and sales.prodid < 10009
and products.name IN ('Soap', 'Juice', 'Soup', 'Microwave', 'Soda')
and products.price < 5.00;

explain plan for select sum(sales.price)
from sales
where custid in (select custid from customers where lname<'F' and fname>'D')
and prodid in (select prodid from products where name
IN ('Soap', 'Juice', 'Soup', 'Microwave', 'Soda'));


text:
=#
__precompile__()
module LowRankApprox
using FillArrays
using LinearAlgebra, SparseArrays, Random

import Base: convert,
             eltype, size, getindex, setindex!, copy,
             isreal, real, imag, Nothing, copyto!,
             +, -, *, /, \, ^, conj, conj!, promote_rule, similar, fill!,
             Matrix
import LinearAlgebra: BlasFloat, BlasInt, checksquare, chkstride1, rank

using FFTW
import FFTW: plan_r2r!, R2HC, r2rFFTWPlan, FFTWPlan
using Nullables
import LinearAlgebra: mul!, ldiv!, transpose, transpose!, axpy!, ishermitian, issymmetric,
            lmul!, rmul!, adjoint, adjoint!
import SparseArrays: sparse
ind2sub(dims, ind) = CartesianIndices(dims)[ind]
qrfact!(A) = qr!(A)

import FillArrays: AbstractFill

export

  # LowRankApprox.jl
  LRAOptions,

  # cur.jl
  AbstractCURPackedU, CURPackedU, HermitianCURPackedU, SymmetricCURPackedU,
  AbstractCUR, CUR, HermitianCUR, SymmetricCUR,
  curfact, curfact!, cur, cur!,

  # id.jl
  IDPackedV, ID, idfact, idfact!, id, id!,

  # linop.jl
  AbstractLinearOperator, AbstractMatOrLinOp,
  LinearOperator, HermitianLinearOperator,

  # matrixlib.jl
  matrixlib,

  # permute.jl
  PermutationMatrix, RowPermutation, ColumnPermutation,

  # pheig.jl
  HermitianPartialEigen, pheigfact, pheig, pheigvals,

  # pqr.jl
  PartialQRFactors, PartialQR, pqrfact, pqrfact!, pqr, pqr!,

  # prange.jl
  prange, prange!,

  # psvd.jl
  PartialSVD, psvdfact, psvd, psvdvals,

  # sketch.jl
  SketchMatrix, RandomGaussian, RandomSubset, SRFT, SparseRandomGaussian,
  sketch, sketchfact,

  # snorm.jl
  snorm, snormdiff,

  # trapezoidal.jl
  Trapezoidal, LowerTrapezoidal, UpperTrapezoidal,

  # aca.jl
  LowRankMatrix

# common

mutable struct LRAOptions
  atol::Float64
  maxdet_niter::Int
  maxdet_tol::Float64
  nb::Int
  pheig_orthtol::Float64
  pqrfact_retval::String
  rank::Int
  rtol::Float64
  sketch::Symbol
  sketch_randn_niter::Int
  sketchfact_adap::Bool
  sketchfact_randn_samp::Function
  sketchfact_srft_samp::Function
  sketchfact_sub_samp::Function
  snorm_niter::Int
  verb::Bool
end

function LRAOptions(::Type{T}; args...) where T
  opts = LRAOptions(
    0,                  # atol
    -1,                 # maxdet_niter
    -1,                 # maxdet_tol
    32,                 # nb
    sqrt(eps(real(T))), # pheig_orthtol
    "qr",               # pqrfact_retval
    -1,                 # rank
    5*eps(real(T)),     # rtol
    :randn,             # sketch
    0,                  # sketch_randn_niter
    true,               # sketchfact_adap
    n -> n + 8,         # sketchfact_randn_samp
    n -> n + 8,         # sketchfact_srft_samp
    n -> 4*n + 8,       # sketchfact_sub_samp
    32,                 # snorm_niter
    true,               # verb
  )
  for (key, value) in args
    setfield!(opts, key, value)
  end
  opts
end
LRAOptions(; args...) = LRAOptions(Float64; args...)

function copy(opts::LRAOptions; args...)
  opts_ = LRAOptions()
  for field in fieldnames(typeof(opts))
    setfield!(opts_, field, getfield(opts, field))
  end
  for (key, value) in args
    setfield!(opts_, key, value)
  end
  opts_
end

function chkopts!(opts::LRAOptions)
  opts.atol >= 0 || throw(ArgumentError("atol"))
  opts.nb > 0 || throw(ArgumentError("nb"))
  opts.pheig_orthtol >= 0 || throw(ArgumentError("pheig_orthtol"))
  opts.rtol >= 0 || throw(ArgumentError("rtol"))
  opts.sketch in (:none, :randn, :sprn, :srft, :sub) ||
    throw(ArgumentError("sketch"))
  opts.pqrfact_retval = lowercase(opts.pqrfact_retval)
end
function chkopts!(opts::LRAOptions, A)
  chkopts!(opts)
  if typeof(A) <: AbstractLinOp && opts.sketch != :randn
    warn("invalid sketch method; using \"randn\"")
    opts.sketch = :randn
  end
end

chktrans(trans::Symbol) = trans in (:n, :c) || throw(ArgumentError("trans"))

# source files

include("lapack.jl")
include("linop.jl")
include("matrixlib.jl")
include("permute.jl")
include("snorm.jl")
include("trapezoidal.jl")
include("util.jl")

include("cur.jl")
include("id.jl")
include("pheig.jl")
include("pqr.jl")
include("prange.jl")
include("psvd.jl")
include("sketch.jl")

include("lowrankmatrix.jl")

end  # module


text:
TakeHomeTest.WPF
================


text:
This project exists only for testing the AnnotationProcessor of the main
jeve project


text:
<!---

## What relative tasks can be? Why use json-schema?

### Meta programming

What is [generate-function](https://www.npmjs.com/package/generate-function)? How to write well-optimized functions?

- Templates
- Validators

### Goals

- keep structure and code clean

in is-my-json-schema-valid and jjv packages structure is - one file

- add architecture ability to set instantiate and randomize data
- fast validation
- normal speed generation

### Refactoring jjv

- splitted into files
- updated variable names

### Refactoring for generated function

investigate c++ inline functions

- is-my-json-valid implementation
- got a generated-function
- updated generated function with few methods - resolve, error, etc, cache - Maybe it is better to use some meta language for it?

### Optimized things

- Added Measured
- Describe All measurements

### Google Closure Advanced

- features
- what is used
- why still need optimizations

## TODO

### Todo Optimizations List

- generatedNonReffunctions 1377, generatedfunctionsUsed 3003 - make fn.if function, and transport scope/context/state to generate function
- update ref usage for non-ref inline functions - if a linke does not contain refs inside (can be easily checked by json.stringify), it should be a regular if-else consequence as well - Optimize small schemas (like in allOf example - don't generate function, althought return context)
- [if optimization](http://jsperf.com/ifs-vs-expression)?
- [killing optimization](http://habrahabr.ru/company/mailru/blog/273839/)

### General

- [asmjs compile step](http://ejohn.org/blog/asmjs-javascript-compile-target/)
- [compile with google closure or smth](https://www.npmjs.com/package/google-closure-compiler)
- $data
- add posibility to customize validators
- add nested tests
- add tests to [resolve](http://tools.ietf.org/html/draft-zyp-json-schema-04#section-7.2.4)

-->


text:
#include "../InputState_SteamController.h"
#include <assert.h>
/*
InputStateDigital_SteamController::InputStateDigital_SteamController( ControllerHandle_t activeControllerHandle, std::string action )
{
	static auto SC = SteamController();
	m_ActiveControllerHandle = activeControllerHandle;
	m_ActionHandle = SC->GetDigitalActionHandle( action.c_str() );
	assert( m_ActiveControllerHandle && m_ActionHandle );
}

bool InputStateDigital_SteamController::poll()
{
	static auto SC = SteamController();
	if ( m_ActionHandle != 0 )
	{
		ControllerDigitalActionData_t digitalData = SC->GetDigitalActionData( m_ActiveControllerHandle, m_ActionHandle );
		if ( digitalData.bActive )
			return digitalData.bState;
	}
	return false;
}

InputStateAnalog_SteamController::InputStateAnalog_SteamController( ControllerHandle_t activeControllerHandle, std::string action )
{
	static auto SC = SteamController();
	m_ActiveControllerHandle = activeControllerHandle;
	m_ActionHandle = SC->GetAnalogActionHandle( action.c_str() );
}

void InputStateAnalog_SteamController::poll( double & x, double & y )
{
	static auto SC = SteamController();
	if ( m_ActionHandle != 0 )
	{
		ControllerAnalogActionData_t analogData = SC->GetAnalogActionData( m_ActiveControllerHandle, m_ActionHandle );
		if ( analogData.bActive )
		{
			x = analogData.x;
			y = analogData.y;
		}
		else
		{
			x = 0;
			y = 0;
		}
	}
}
*/


text:
module EhXero
  module Mappers
    class Organisation
      extend Base

      class << self
        def fields_mapping
          {
            name: :name,
            phone_number: :phone
          }
        end
      end
    end
  end
end


text:
import gulp from 'gulp';
import plumber from 'gulp-plumber';
import jasmineBrowser from 'gulp-jasmine-browser';
import webpack from 'webpack-stream';

function testAssets(options = {}) {
  let webpackConfig = require('../config/webpack.config');
  webpackConfig = {...webpackConfig, ...options};
  return gulp.src('spec/**/*_spec.js')
    .pipe(plumber())
    .pipe(webpack(webpackConfig));
}

gulp.task('spec', function() {
  return testAssets({watch: false})
    .pipe(jasmineBrowser.specRunner({console: true}))
    .pipe(jasmineBrowser.headless());
});

gulp.task('jasmine', function() {
  const plugin = new (require('gulp-jasmine-browser/webpack/jasmine-plugin'))();
  return testAssets({plugins: [plugin]})
    .pipe(jasmineBrowser.specRunner())
    .pipe(jasmineBrowser.server());
});