text:
#include "pch.h"

#include "ShaderResourcesGL.hpp"

#include <unordered_set>

#include "RenderDeviceGLImpl.hpp"
#include "GLContextState.hpp"
#include "ShaderResourceVariableBase.hpp"
#include "Align.hpp"
#include "GLTypeConversions.hpp"

namespace Diligent
{

ShaderResourcesGL::ShaderResourcesGL(ShaderResourcesGL&& Program) noexcept :
    // clang-format off
    m_ShaderStages     {Program.m_ShaderStages         },
    m_UniformBuffers   {Program.m_UniformBuffers       },
    m_Textures         {Program.m_Textures             },
    m_Images           {Program.m_Images               },
    m_StorageBlocks    {Program.m_StorageBlocks        },
    m_NumUniformBuffers{Program.m_NumUniformBuffers    },
    m_NumTextures      {Program.m_NumTextures          },
    m_NumImages        {Program.m_NumImages            },
    m_NumStorageBlocks {Program.m_NumStorageBlocks     }
// clang-format on
{
    Program.m_UniformBuffers = nullptr;
    Program.m_Textures       = nullptr;
    Program.m_Images         = nullptr;
    Program.m_StorageBlocks  = nullptr;

    Program.m_NumUniformBuffers = 0;
    Program.m_NumTextures       = 0;
    Program.m_NumImages         = 0;
    Program.m_NumStorageBlocks  = 0;
}

inline void RemoveArrayBrackets(char* Str)
{
    auto* OpenBracketPtr = strchr(Str, '[');
    if (OpenBracketPtr != nullptr)
        *OpenBracketPtr = 0;
}

void ShaderResourcesGL::AllocateResources(std::vector<UniformBufferInfo>& UniformBlocks,
                                          std::vector<TextureInfo>&       Textures,
                                          std::vector<ImageInfo>&         Images,
                                          std::vector<StorageBlockInfo>&  StorageBlocks)
{
    VERIFY(m_UniformBuffers == nullptr, "Resources have already been allocated!");

    m_NumUniformBuffers = static_cast<Uint32>(UniformBlocks.size());
    m_NumTextures       = static_cast<Uint32>(Textures.size());
    m_NumImages         = static_cast<Uint32>(Images.size());
    m_NumStorageBlocks  = static_cast<Uint32>(StorageBlocks.size());

    size_t StringPoolDataSize = 0;
    for (const auto& ub : UniformBlocks)
    {
        StringPoolDataSize += strlen(ub.Name) + 1;
    }

    for (const auto& sam : Textures)
    {
        StringPoolDataSize += strlen(sam.Name) + 1;
    }

    for (const auto& img : Images)
    {
        StringPoolDataSize += strlen(img.Name) + 1;
    }

    for (const auto& sb : StorageBlocks)
    {
        StringPoolDataSize += strlen(sb.Name) + 1;
    }

    auto AlignedStringPoolDataSize = AlignUp(StringPoolDataSize, sizeof(void*));

    // clang-format off
    size_t TotalMemorySize =
        m_NumUniformBuffers * sizeof(UniformBufferInfo) +
        m_NumTextures       * sizeof(TextureInfo) +
        m_NumImages         * sizeof(ImageInfo) +
        m_NumStorageBlocks  * sizeof(StorageBlockInfo);
    // clang-format on

    if (TotalMemorySize == 0)
    {
        m_UniformBuffers = nullptr;
        m_Textures       = nullptr;
        m_Images         = nullptr;
        m_StorageBlocks  = nullptr;

        m_NumUniformBuffers = 0;
        m_NumTextures       = 0;
        m_NumImages         = 0;
        m_NumStorageBlocks  = 0;

        return;
    }

    TotalMemorySize += AlignedStringPoolDataSize * sizeof(Char);

    auto& MemAllocator = GetRawAllocator();
    void* RawMemory    = ALLOCATE_RAW(MemAllocator, "Memory buffer for ShaderResourcesGL", TotalMemorySize);

    // clang-format off
    m_UniformBuffers = reinterpret_cast<UniformBufferInfo*>(RawMemory);
    m_Textures       = reinterpret_cast<TextureInfo*>     (m_UniformBuffers + m_NumUniformBuffers);
    m_Images         = reinterpret_cast<ImageInfo*>       (m_Textures       + m_NumTextures);
    m_StorageBlocks  = reinterpret_cast<StorageBlockInfo*>(m_Images         + m_NumImages);
    void* EndOfResourceData =                              m_StorageBlocks + m_NumStorageBlocks;
    Char* StringPoolData = reinterpret_cast<Char*>(EndOfResourceData);
    // clang-format on

    // The pool is only needed to facilitate string allocation.
    StringPool TmpStringPool;
    TmpStringPool.AssignMemory(StringPoolData, StringPoolDataSize);

    for (Uint32 ub = 0; ub < m_NumUniformBuffers; ++ub)
    {
        auto& SrcUB = UniformBlocks[ub];
        new (m_UniformBuffers + ub) UniformBufferInfo{SrcUB, TmpStringPool};
    }

    for (Uint32 s = 0; s < m_NumTextures; ++s)
    {
        auto& SrcSam = Textures[s];
        new (m_Textures + s) TextureInfo{SrcSam, TmpStringPool};
    }

    for (Uint32 img = 0; img < m_NumImages; ++img)
    {
        auto& SrcImg = Images[img];
        new (m_Images + img) ImageInfo{SrcImg, TmpStringPool};
    }

    for (Uint32 sb = 0; sb < m_NumStorageBlocks; ++sb)
    {
        auto& SrcSB = StorageBlocks[sb];
        new (m_StorageBlocks + sb) StorageBlockInfo{SrcSB, TmpStringPool};
    }

    VERIFY_EXPR(TmpStringPool.GetRemainingSize() == 0);
}

ShaderResourcesGL::~ShaderResourcesGL()
{
    // clang-format off
    ProcessResources(
        [&](UniformBufferInfo& UB)
        {
            UB.~UniformBufferInfo();
        },
        [&](TextureInfo& Sam)
        {
            Sam.~TextureInfo();
        },
        [&](ImageInfo& Img)
        {
            Img.~ImageInfo();
        },
        [&](StorageBlockInfo& SB)
        {
            SB.~StorageBlockInfo();
        }
    );
    // clang-format on

    void* RawMemory = m_UniformBuffers;
    if (RawMemory != nullptr)
    {
        auto& MemAllocator = GetRawAllocator();
        MemAllocator.Free(RawMemory);
    }
}

void ShaderResourcesGL::LoadUniforms(SHADER_TYPE                           ShaderStages,
                                     PIPELINE_RESOURCE_FLAGS               SamplerResourceFlag,
                                     const GLObjectWrappers::GLProgramObj& GLProgram,
                                     GLContextState&                       State)
{
    VERIFY(SamplerResourceFlag == PIPELINE_RESOURCE_FLAG_NONE || SamplerResourceFlag == PIPELINE_RESOURCE_FLAG_COMBINED_SAMPLER,
           "Only NONE (for GLSL source) and COMBINED_SAMPLER (for HLSL source) are valid sampler resource flags");

    // Load uniforms to temporary arrays. We will then pack all variables into a single chunk of memory.
    std::vector<UniformBufferInfo> UniformBlocks;
    std::vector<TextureInfo>       Textures;
    std::vector<ImageInfo>         Images;
    std::vector<StorageBlockInfo>  StorageBlocks;
    std::unordered_set<String>     NamesPool;

    VERIFY(GLProgram != 0, "Null GL program");
    State.SetProgram(GLProgram);

    m_ShaderStages = ShaderStages;

    GLint numActiveUniforms = 0;
    glGetProgramiv(GLProgram, GL_ACTIVE_UNIFORMS, &numActiveUniforms);
    CHECK_GL_ERROR_AND_THROW("Unable to get the number of active uniforms\n");

    // Query the maximum name length of the active uniform (including null terminator)
    GLint activeUniformMaxLength = 0;
    glGetProgramiv(GLProgram, GL_ACTIVE_UNIFORM_MAX_LENGTH, &activeUniformMaxLength);
    CHECK_GL_ERROR_AND_THROW("Unable to get the maximum uniform name length\n");

    GLint numActiveUniformBlocks = 0;
    glGetProgramiv(GLProgram, GL_ACTIVE_UNIFORM_BLOCKS, &numActiveUniformBlocks);
    CHECK_GL_ERROR_AND_THROW("Unable to get the number of active uniform blocks\n");

    //
    // #### This parameter is currently unsupported by Intel OGL drivers.
    //
    // Query the maximum name length of the active uniform block (including null terminator)
    GLint activeUniformBlockMaxLength = 0;
    // On Intel driver, this call might fail:
    glGetProgramiv(GLProgram, GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH, &activeUniformBlockMaxLength);
    //CHECK_GL_ERROR_AND_THROW("Unable to get the maximum uniform block name length\n");
    if (glGetError() != GL_NO_ERROR)
    {
        LOG_WARNING_MESSAGE("Unable to get the maximum uniform block name length. Using 1024 as a workaround\n");
        activeUniformBlockMaxLength = 1024;
    }

    auto MaxNameLength = std::max(activeUniformMaxLength, activeUniformBlockMaxLength);

#if GL_ARB_program_interface_query
    GLint numActiveShaderStorageBlocks = 0;
    if (glGetProgramInterfaceiv)
    {
        glGetProgramInterfaceiv(GLProgram, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &numActiveShaderStorageBlocks);
        CHECK_GL_ERROR_AND_THROW("Unable to get the number of shader storage blocks blocks\n");

        // Query the maximum name length of the active shader storage block (including null terminator)
        GLint MaxShaderStorageBlockNameLen = 0;
        glGetProgramInterfaceiv(GLProgram, GL_SHADER_STORAGE_BLOCK, GL_MAX_NAME_LENGTH, &MaxShaderStorageBlockNameLen);
        CHECK_GL_ERROR_AND_THROW("Unable to get the maximum shader storage block name length\n");
        MaxNameLength = std::max(MaxNameLength, MaxShaderStorageBlockNameLen);
    }
#endif

    MaxNameLength = std::max(MaxNameLength, 512);
    std::vector<GLchar> Name(static_cast<size_t>(MaxNameLength) + 1);
    for (int i = 0; i < numActiveUniforms; i++)
    {
        GLenum dataType = 0;
        GLint  size     = 0;
        GLint  NameLen  = 0;
        // If one or more elements of an array are active, the name of the array is returned in 'name',
        // the type is returned in 'type', and the 'size' parameter returns the highest array element index used,
        // plus one, as determined by the compiler and/or linker.
        // Only one active uniform variable will be reported for a uniform array.
        // Uniform variables other than arrays will have a size of 1
        glGetActiveUniform(GLProgram, i, MaxNameLength, &NameLen, &size, &dataType, Name.data());
        CHECK_GL_ERROR_AND_THROW("Unable to get active uniform\n");
        VERIFY(NameLen < MaxNameLength && static_cast<size_t>(NameLen) == strlen(Name.data()), "Incorrect uniform name");
        VERIFY(size >= 1, "Size is expected to be at least 1");
        // Note that
        // glGetActiveUniform( program, index, bufSize, length, size, type, name );
        //
        // is equivalent to
        //
        // const enum props[] = { ARRAY_SIZE, TYPE };
        // glGetProgramResourceName( program, UNIFORM, index, bufSize, length, name );
        // glGetProgramResourceiv( program, GL_UNIFORM, index, 1, &props[0], 1, NULL, size );
        // glGetProgramResourceiv( program, GL_UNIFORM, index, 1, &props[1], 1, NULL, (int *)type );
        //
        // The latter is only available in GL 4.4 and GLES 3.1

        RESOURCE_DIMENSION ResDim;
        bool               IsMS;
        GLTextureTypeToResourceDim(dataType, ResDim, IsMS);

        switch (dataType)
        {
            case GL_SAMPLER_1D:
            case GL_SAMPLER_2D:
            case GL_SAMPLER_3D:
            case GL_SAMPLER_CUBE:
            case GL_SAMPLER_1D_SHADOW:
            case GL_SAMPLER_2D_SHADOW:

            case GL_SAMPLER_1D_ARRAY:
            case GL_SAMPLER_2D_ARRAY:
            case GL_SAMPLER_1D_ARRAY_SHADOW:
            case GL_SAMPLER_2D_ARRAY_SHADOW:
            case GL_SAMPLER_CUBE_SHADOW:

            case GL_SAMPLER_EXTERNAL_OES:

            case GL_INT_SAMPLER_1D:
            case GL_INT_SAMPLER_2D:
            case GL_INT_SAMPLER_3D:
            case GL_INT_SAMPLER_CUBE:
            case GL_INT_SAMPLER_1D_ARRAY:
            case GL_INT_SAMPLER_2D_ARRAY:
            case GL_UNSIGNED_INT_SAMPLER_1D:
            case GL_UNSIGNED_INT_SAMPLER_2D:
            case GL_UNSIGNED_INT_SAMPLER_3D:
            case GL_UNSIGNED_INT_SAMPLER_CUBE:
            case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY:
            case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:

            case GL_SAMPLER_CUBE_MAP_ARRAY:
            case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
            case GL_INT_SAMPLER_CUBE_MAP_ARRAY:
            case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY:

            case GL_SAMPLER_2D_MULTISAMPLE:
            case GL_INT_SAMPLER_2D_MULTISAMPLE:
            case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
            case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
            case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
            case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:

            case GL_SAMPLER_BUFFER:
            case GL_INT_SAMPLER_BUFFER:
            case GL_UNSIGNED_INT_SAMPLER_BUFFER:
            {
                const auto IsBuffer =
                    dataType == GL_SAMPLER_BUFFER ||
                    dataType == GL_INT_SAMPLER_BUFFER ||
                    dataType == GL_UNSIGNED_INT_SAMPLER_BUFFER;
                const auto ResourceType = IsBuffer ?
                    SHADER_RESOURCE_TYPE_BUFFER_SRV :
                    SHADER_RESOURCE_TYPE_TEXTURE_SRV;
                const auto ResourceFlags = IsBuffer ?
                    PIPELINE_RESOURCE_FLAG_FORMATTED_BUFFER :
                    SamplerResourceFlag // PIPELINE_RESOURCE_FLAG_NONE for HLSL source or
                                        // PIPELINE_RESOURCE_FLAG_COMBINED_SAMPLER for GLSL source
                    ;

                RemoveArrayBrackets(Name.data());

                Textures.emplace_back(
                    NamesPool.emplace(Name.data()).first->c_str(),
                    ShaderStages,
                    ResourceType,
                    ResourceFlags,
                    static_cast<Uint32>(size),
                    dataType,
                    ResDim,
                    IsMS //
                );
                break;
            }

#if GL_ARB_shader_image_load_store
            case GL_IMAGE_1D:
            case GL_IMAGE_2D:
            case GL_IMAGE_3D:
            case GL_IMAGE_2D_RECT:
            case GL_IMAGE_CUBE:
            case GL_IMAGE_BUFFER:
            case GL_IMAGE_1D_ARRAY:
            case GL_IMAGE_2D_ARRAY:
            case GL_IMAGE_CUBE_MAP_ARRAY:
            case GL_IMAGE_2D_MULTISAMPLE:
            case GL_IMAGE_2D_MULTISAMPLE_ARRAY:
            case GL_INT_IMAGE_1D:
            case GL_INT_IMAGE_2D:
            case GL_INT_IMAGE_3D:
            case GL_INT_IMAGE_2D_RECT:
            case GL_INT_IMAGE_CUBE:
            case GL_INT_IMAGE_BUFFER:
            case GL_INT_IMAGE_1D_ARRAY:
            case GL_INT_IMAGE_2D_ARRAY:
            case GL_INT_IMAGE_CUBE_MAP_ARRAY:
            case GL_INT_IMAGE_2D_MULTISAMPLE:
            case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
            case GL_UNSIGNED_INT_IMAGE_1D:
            case GL_UNSIGNED_INT_IMAGE_2D:
            case GL_UNSIGNED_INT_IMAGE_3D:
            case GL_UNSIGNED_INT_IMAGE_2D_RECT:
            case GL_UNSIGNED_INT_IMAGE_CUBE:
            case GL_UNSIGNED_INT_IMAGE_BUFFER:
            case GL_UNSIGNED_INT_IMAGE_1D_ARRAY:
            case GL_UNSIGNED_INT_IMAGE_2D_ARRAY:
            case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY:
            case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE:
            case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
            {
                const auto IsBuffer =
                    dataType == GL_IMAGE_BUFFER ||
                    dataType == GL_INT_IMAGE_BUFFER ||
                    dataType == GL_UNSIGNED_INT_IMAGE_BUFFER;
                const auto ResourceType = IsBuffer ?
                    SHADER_RESOURCE_TYPE_BUFFER_UAV :
                    SHADER_RESOURCE_TYPE_TEXTURE_UAV;
                const auto ResourceFlags = IsBuffer ?
                    PIPELINE_RESOURCE_FLAG_FORMATTED_BUFFER :
                    PIPELINE_RESOURCE_FLAG_NONE;

                RemoveArrayBrackets(Name.data());

                Images.emplace_back(
                    NamesPool.emplace(Name.data()).first->c_str(),
                    ShaderStages,
                    ResourceType,
                    ResourceFlags,
                    static_cast<Uint32>(size),
                    dataType,
                    ResDim,
                    IsMS //
                );
                break;
            }
#endif
            default:
                // Some other uniform type like scalar, matrix etc.
                break;
        }
    }

    for (int i = 0; i < numActiveUniformBlocks; i++)
    {
        // In contrast to shader uniforms, every element in uniform block array is enumerated individually
        GLsizei NameLen = 0;
        glGetActiveUniformBlockName(GLProgram, i, MaxNameLength, &NameLen, Name.data());
        CHECK_GL_ERROR_AND_THROW("Unable to get active uniform block name\n");
        VERIFY(NameLen < MaxNameLength && static_cast<size_t>(NameLen) == strlen(Name.data()), "Incorrect uniform block name");

        // glGetActiveUniformBlockName( program, uniformBlockIndex, bufSize, length, uniformBlockName );
        // is equivalent to
        // glGetProgramResourceName(program, GL_UNIFORM_BLOCK, uniformBlockIndex, bufSize, length, uniformBlockName);

        auto UniformBlockIndex = glGetUniformBlockIndex(GLProgram, Name.data());
        CHECK_GL_ERROR_AND_THROW("Unable to get active uniform block index\n");
        // glGetUniformBlockIndex( program, uniformBlockName );
        // is equivalent to
        // glGetProgramResourceIndex( program, GL_UNIFORM_BLOCK, uniformBlockName );

        bool IsNewBlock = true;

        GLint ArraySize      = 1;
        auto* OpenBracketPtr = strchr(Name.data(), '[');
        if (OpenBracketPtr != nullptr)
        {
            auto Ind        = atoi(OpenBracketPtr + 1);
            ArraySize       = std::max(ArraySize, Ind + 1);
            *OpenBracketPtr = 0;
            if (!UniformBlocks.empty())
            {
                // Look at previous uniform block to check if it is the same array
                auto& LastBlock = UniformBlocks.back();
                if (strcmp(LastBlock.Name, Name.data()) == 0)
                {
                    ArraySize = std::max(ArraySize, static_cast<GLint>(LastBlock.ArraySize));
                    VERIFY(UniformBlockIndex == LastBlock.UBIndex + Ind, "Uniform block indices are expected to be continuous");
                    LastBlock.ArraySize = ArraySize;
                    IsNewBlock          = false;
                }
                else
                {
#ifdef DILIGENT_DEBUG
                    for (const auto& ub : UniformBlocks)
                        VERIFY(strcmp(ub.Name, Name.data()) != 0, "Uniform block with the name '", ub.Name, "' has already been enumerated");
#endif
                }
            }
        }

        if (IsNewBlock)
        {
            UniformBlocks.emplace_back(
                NamesPool.emplace(Name.data()).first->c_str(),
                ShaderStages,
                SHADER_RESOURCE_TYPE_CONSTANT_BUFFER,
                static_cast<Uint32>(ArraySize),
                UniformBlockIndex //
            );
        }
    }

#if GL_ARB_shader_storage_buffer_object
    for (int i = 0; i < numActiveShaderStorageBlocks; ++i)
    {
        GLsizei Length = 0;
        glGetProgramResourceName(GLProgram, GL_SHADER_STORAGE_BLOCK, i, MaxNameLength, &Length, Name.data());
        CHECK_GL_ERROR_AND_THROW("Unable to get shader storage block name\n");
        VERIFY(Length < MaxNameLength && static_cast<size_t>(Length) == strlen(Name.data()), "Incorrect shader storage block name");

        auto SBIndex = glGetProgramResourceIndex(GLProgram, GL_SHADER_STORAGE_BLOCK, Name.data());
        CHECK_GL_ERROR_AND_THROW("Unable to get shader storage block index\n");

        bool  IsNewBlock     = true;
        Int32 ArraySize      = 1;
        auto* OpenBracketPtr = strchr(Name.data(), '[');
        if (OpenBracketPtr != nullptr)
        {
            auto Ind        = atoi(OpenBracketPtr + 1);
            ArraySize       = std::max(ArraySize, Ind + 1);
            *OpenBracketPtr = 0;
            if (!StorageBlocks.empty())
            {
                // Look at previous storage block to check if it is the same array
                auto& LastBlock = StorageBlocks.back();
                if (strcmp(LastBlock.Name, Name.data()) == 0)
                {
                    ArraySize = std::max(ArraySize, static_cast<GLint>(LastBlock.ArraySize));
                    VERIFY(static_cast<GLint>(SBIndex) == LastBlock.SBIndex + Ind, "Storage block indices are expected to be continuous");
                    LastBlock.ArraySize = ArraySize;
                    IsNewBlock          = false;
                }
                else
                {
#    ifdef DILIGENT_DEBUG
                    for (const auto& sb : StorageBlocks)
                        VERIFY(strcmp(sb.Name, Name.data()) != 0, "Storage block with the name \"", sb.Name, "\" has already been enumerated");
#    endif
                }
            }
        }

        if (IsNewBlock)
        {
            StorageBlocks.emplace_back(
                NamesPool.emplace(Name.data()).first->c_str(),
                ShaderStages,
                SHADER_RESOURCE_TYPE_BUFFER_UAV,
                static_cast<Uint32>(ArraySize),
                SBIndex //
            );
        }
    }
#endif

    State.SetProgram(GLObjectWrappers::GLProgramObj::Null());

    AllocateResources(UniformBlocks, Textures, Images, StorageBlocks);
}

ShaderResourceDesc ShaderResourcesGL::GetResourceDesc(Uint32 Index) const
{
    if (Index < m_NumUniformBuffers)
        return GetUniformBuffer(Index).GetResourceDesc();
    else
        Index -= m_NumUniformBuffers;

    if (Index < m_NumTextures)
        return GetTexture(Index).GetResourceDesc();
    else
        Index -= m_NumTextures;

    if (Index < m_NumImages)
        return GetImage(Index).GetResourceDesc();
    else
        Index -= m_NumImages;

    if (Index < m_NumStorageBlocks)
        return GetStorageBlock(Index).GetResourceDesc();
    else
        Index -= m_NumStorageBlocks;

    LOG_ERROR_MESSAGE("Resource index ", Index + GetVariableCount(), " is invalid");
    return ShaderResourceDesc{};
}

} // namespace Diligent


text:
<?
	class Jaime extends Lannister
	{
		public function sleepWith($other)
		{
			// Jaime wanna fuck Cersei in a weird tower
			// Jaime wanna fuck Sansa
			// Jaime refuse Tyrion
			if (is_a($other, 'Cersei'))
				echo ("With pleasure, but only in a tower in Winterfell, then.".PHP_EOL);
			else if (is_a($other, 'Sansa'))
				echo "Let's do this.".PHP_EOL;
			else if (is_a($other, 'Tyrion'))
				echo "Not event if I'm drunk !".PHP_EOL;
			else
				echo parent::sleepWith($other);
		}
		static public function doc(){ return "Ser Jaime Lannister is a knight of the Kingsguard."; }
		static public $verbose = False;
	}
?>

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Feddes Repert. 87(1-2): 146 (1976)

#### Original name
Camarosporium silenes-ponticae Manoliu & Mítítíuc

### Remarks
null


text:
describe('CorporaIndexController', function(){
  var createController, $controller, $scope, $rootScope, $httpBackend;

  beforeEach(module('linguine'));
  beforeEach(inject(function($injector){
    $rootScope = $injector.get('$rootScope');
    $scope = $rootScope.$new;
    $httpBackend = $injector.get('$httpBackend');
    $controller = $injector.get('$controller');
    createController = function(){
      return $controller('CorporaIndexController', {
        $scope: $scope
      });
    }
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('corpora', function(){
    it('should get the corpora', function(done){
      $httpBackend.expectGET('/api/corpora').respond(200, [
        {
          title: 'Thing',
          fileName: 'thing.txt',
          tags: ['something', 'or', 'other']
        },
        {
          title: 'Other Thing',
          fileName: 'other_thing.txt',
          tags: ['something', 'or', 'other']
        }
      ]);

      createController();
      $httpBackend.flush();
      expect($scope.corpora).to.have.length(2);
      done();
    });
  });
});


text:
{-# LANGUAGE TypeApplications #-}
module ProjectEuler.Problem20
  ( problem
  ) where

import Data.Char
import ProjectEuler.Types

problem :: Problem
problem = pureProblem 20 Solved result

result :: Int
result =
  sum . map digitToInt . show @Integer
  $ product [1..100]


text:
from load import main as main_load
from scrape import main as main_scrape
from transform import main as main_transform

def entrypoints():
    return {
        'scrape': main_scrape,
        'transform': main_transform,
        'load': main_load
    }


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

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

    <EditText android:id="@+id/splash_sign_in_dialog_username"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:paddingTop="20dp"
              android:layout_marginLeft="3dp"
              android:layout_marginRight="3dp"
              android:singleLine="true"
              android:hint="@string/splash_sign_in_dialog_username"
              android:inputType="text">
    </EditText>

    <EditText android:id="@+id/splash_sign_in_dialog_password"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:paddingTop="12dp"
              android:layout_marginLeft="3dp"
              android:layout_marginRight="3dp"
              android:singleLine="true"
              android:hint="@string/splash_sign_in_dialog_password"
              android:inputType="textPassword">
    </EditText>

</LinearLayout>


text:
  Directory Structure has been changed to gem style.
  A .gemspec has been created to allow the gemfication of the lib.
  This is the final version of the lib, no further changes will be made.
  In short, the RGSS3 MACL is now discontinued.

### V2.3.1 [24/07/2013]
  ADDED
    Ruthe: a import module similar to Lua's require, though it still requires
    a bit of back work to get working correctly.

### V2.3.0 [19/06/2013]
  CHANGE
    Surface::ANCHOR_* have changed slightly
      ANCHOR_CENTER refers not to the absolute center of a surface, but
      the Horizontal center position, use ANCHOR_MIDDLE_CENTER instead

### V2.2.4 [16/05/2013]
```
  CHANGE
    VERSION is now just 3 numbers, the last 3 seemed too extra

  FIXED
    gm-classes.rb
    gm-modules.rb
      Both where reloading the mixin/ source files instead of their respective
      gm-classes/ and gm-modules/

  MOVED
    lib/xpan/archijust.rb > lib/mixin/archijust.rb
      Always wondered why I didn't move it to the mixins instead of the
      Xpansion Lib
```

### V2.2.3.000 [11/05/2013]
```
  ADDED
    MACL::Mixin::Surface#anchor_*
    MACL::Mixin::Surface#set_anchor_*

  CHANGE
    MACL::Mixin::Surface#reanchor
      Now uses the anchor_* methods for calculation and setting

```

### V2.2.2.000 [05/05/2013]
```
  ADDED
    MACL::Pos2

```

### V2.2.1.000 [04/05/2013]
```
  ADDED
    MACL::Mixin::Archijust::uint_reader
    MACL::Mixin::Archijust::uint_writer
    MACL::Mixin::Archijust::uint_accessor
      Forces Incoming and Outgoing values to be greater than 0
```

### V2.2.0.000 [05/04/2013]
```
  ADDED
    MACL::Mixin::StackElement [lib/mixin/stackelement.rb]

```
### V2.1.5.000 [04/04/2013]
```
  CHANGE
    MACL::Vector* can now do math funcs with Arrays of the same size

```
### V2.1.4.000 [02/04/2013]
```
  BUGFIX
    MACL::Pos3

```
### V2.1.3.000 [01/04/2013]
```
  ADDED
    MACL::MatrixBase#to_a
    MACL::MatrixBase#hash
    MACL::MatrixBase#hash

  CHANGE
    MACL::MatrixBase is now Comparable, however this may be slow with large
    matrices

  REWRITE
    MACL::Vector*

  BUGFIX
    MACL::Vector*
      would StackError if compared, this has been fixed by implementing the #<=> method

    MACL::VectorList
      Was bricked due to missing arguments for super call

```
### V2.1.2.000 [30/03/2013]
```
  ADDED
    MACL::Grid3

  CHANGE
    MACL::Grid > MACL::Grid2

  ALIAS
    MACL::Grid2 as MACL::Grid

  UPDATE
    MACL::Grid2 [1.0.0]

  BUGFIX
    MACL::Cube#to_s
      to_s now uses the to_h instead of the missing to_hash method
```

### V2.1.1.000 [29/03/2013]
```
  ADDED
    MACL::MatrixBase#size alias of MACL::MatrixBase#datasize
    MACL::frame_rate
    MACL::Tween2
      Been longing to do a clean rewrite of Tween, and Tween2 solves that issue,
      its mostly an cosmetic change from the original, the code is much cleaner,
      and the usage is slighly different.

  CHANGE
    MACL::MatrixBase
      Parent class for Matrix

    MACL::Matrix extends MACL::MatrixBase
      Meta programming has been removed.

  FIXES
    Fixed FloatDomainError when using MACL::Easer::Back::InOut
```

### V2.1.0.000 [25/03/2013]
```
  MOVED
    MACL::Tween::Easer to MACL::Easer

  REWRITE
    MACL::Easer
      Easer has now been broken into smaller seperate files for easy management,
      and isolation.
      Easers are now seperate classes which can have instances with different
      properties with the same easing.
      This was done to allow configuration of Easers such as Elastic and Back
```

### V2.0.3.002 [24/03/2013]
```
  ADDED
    MACL::VectorList
      VectorList is a shorthand of the MACL::Matrix, utilizing only 1 dimension

  CHANGE
    Point* is now a subclass of Vector*i rather than an alias
```

### V2.0.3.001 [23/03/2013]
```
  ADDED
    CallbackError to MACL::Mixin::Callback
    MACL::Mixin::Callback::log
      Set this to any IO object, and all output will be routed.
      You can set individual logs by using the instances @callback_log or
      #callback_log=
    Vector*#normalize, Vector*#normalize!, Vector*#magnitude=
      #normalize will function properly only with 2 dimensional vectors
      currently

  RENAME
    Vector#degrees* to Vector#angle*
    Vector::from_polar to Vector::polar
    Vector*I to Vector*i
    Vector*F to Vector*f

  BUGFIX
    Interpolate#bezier now uses Vector2f instead of Vector2i
```

### V2.0.3.000 [22/03/2013]
```
  Renamed Numeric#unary > Numeric#signum
  Renamed Numeric#unary_inv > Numeric#signum_inv
```

### V2.0.2.001 [16/03/2013]
  Added Numeric#wall
  Added Archijust#bool_*

### V2.0.1.000 [??/03/2013]
```
  Added (lib/mixin/color-math.rb) MACL::Mixin::ColorMath
```

### V2.0.0.000


text:
layout: post
title: "New Subscription: Nourish Beauty Box + Get an Extra Box Free!"
description: ""
headline: "New Subscription: Nourish Beauty Box + Get an Extra Box Free!"
categories:
      - Subscriptions
      - Coupons
tags: [Nourish Beauty Box, Subscriptions, Coupons]
comments: true
mathjax: null
published: true
featured: false
type: photo
imagefeature: "NourishBeautyBox.png"
date: 2015-08-26 16:45:39 -08:00
---

Subscription: Nourish Beauty Box

Cost: $34.95/monthly.

Shipping: Free shipping Worldwide! Ships around the 25th of each month.

What's in the box: Nourish Beauty Box focuses on vegan, 100% cruelty-free, GMO-free & gluten-free beauty products. Their monthly boxes will contain 4 items; 3 Full Size bio-natural beauty products + 1 Limited-Edition canvas tote bag. Each box will also have a value of $70+!

Coupon: Use coupon code WHATSUPMAILBOX to get an Extra Box absolutely FREE to gift to friends & family or keep for yourself ;)

Note: Only 1 code can be used per household, and it expires 09/20/2015. Applicable only for the 1-month subscription option (not 3 or 6 months).

I've been waiting for a subscription like this to pop up! They're launching next month (September 2015) and I can't wait, so excited!

A box of natural beauty products that consists of 3 full-sized products plus a canvas tote, yes yes and YES!

Although there are other subscription boxes that cater to natural and organic beauty/skincare products, this has got to be the first in offering all full-sized products, yay!

Most of the other subs have been discontinued and the one that's still active has been quite disappointing lately by sending out old or expired products, yikes.

So it was a no brainer for me to instantly fall in love with this subscription and if you're like me - a natural beauty junkie - then I totally recommend for you to check them out and subscribe.

 Plus right now if you use the coupon code WHATSUPMAILBOX you'll get an extra box, yes TWO boxes, for the price of one. That's an awesome deal (!) and gives you more reason to try them out ;)

Stay tuned for my review next month of their launch box!  xoxo, Loretta


text:
Turtle Power
============

.. image:: https://travis-ci.org/AllTheWayDown/turtlepower.png?branch=master   :target: https://travis-ci.org/AllTheWayDown/turtlepower

A tool for making games and simulations with Turtles

PowerTurtle is an improved turtle object that provides some new methods, and is
designed to work in game loop as opposed to being driven from a prompt.

TurtleWorld provides a definition of a world and and an engine to manage and
move all the turtles in the world.

There are various example games and simulations that have been written using
turtlepower.

Status: very early development, lots changing

Installing
==========

Dependencies: system python, 2.7, 3.2 or 3.3

To install dev dependancies

.. code::

    pip install -r requirements.txt


text:
package dials.messages;

import dials.filter.FilterData;

public class FeatureStateRequestMessage extends ContextualMessage {

    private FilterData dynamicData;

    public FeatureStateRequestMessage(ContextualMessage message) {
        this(null, message);
    }

    public FeatureStateRequestMessage(FilterData dynamicData, ContextualMessage message) {
        super(message);
        this.dynamicData = dynamicData;
    }

    public FilterData getDynamicData() {
        return dynamicData;
    }
}


text:
using System;
using System.ComponentModel;
using System.Linq;

namespace BigBook
{
    /// <summary>
    /// Predicate extensions
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class PredicateExtensions
    {
        /// <summary>
        /// Adds the given values to the predicate set
        /// </summary>
        /// <typeparam name="T">Data type</typeparam>
        /// <param name="predicate">Predicate to add to</param>
        /// <param name="values">Values to add</param>
        /// <returns>The resulting predicate set</returns>
        public static Predicate<T>? AddToSet<T>(this Predicate<T> predicate, params T[] values)
        {
            if (predicate is null)
            {
                return null;
            }

            if (values is null || values.Length == 0)
            {
                return predicate;
            }

            return x => values.Contains(x) || predicate(x);
        }

        /// <summary>
        /// Treats the predicates as sets and does a cartesian product of them
        /// </summary>
        /// <typeparam name="T1">Type 1</typeparam>
        /// <typeparam name="T2">Type 2</typeparam>
        /// <param name="predicate1">Predicate 1</param>
        /// <param name="predicate2">Predicate 2</param>
        /// <returns>The cartesian product</returns>
        public static Func<T1, T2, bool>? CartesianProduct<T1, T2>(this Predicate<T1> predicate1, Predicate<T2> predicate2)
        {
            if (predicate1 is null || predicate2 is null)
            {
                return null;
            }

            return (x, y) => predicate1(x) && predicate2(y);
        }

        /// <summary>
        /// Treats the predicates as sets and does a difference
        /// </summary>
        /// <typeparam name="T">Data Type</typeparam>
        /// <param name="predicate1">Predicate 1</param>
        /// <param name="predicate2">Predicate 2</param>
        /// <returns>The difference of the two predicates</returns>
        public static Predicate<T>? Difference<T>(this Predicate<T> predicate1, Predicate<T> predicate2)
        {
            if (predicate1 is null)
            {
                return null;
            }

            if (predicate2 is null)
            {
                return predicate1;
            }

            return x => predicate1(x) ^ predicate2(x);
        }

        /// <summary>
        /// Treats predicates as sets and intersects them together
        /// </summary>
        /// <typeparam name="T">Data type</typeparam>
        /// <param name="predicate1">Predicate 1</param>
        /// <param name="predicate2">Predicate 2</param>
        /// <returns>The intersected predicate</returns>
        public static Predicate<T>? Intersect<T>(this Predicate<T> predicate1, Predicate<T> predicate2)
        {
            if (predicate1 is null || predicate2 is null)
            {
                return null;
            }

            return x => predicate1(x) && predicate2(x);
        }

        /// <summary>
        /// Treats predicates as sets and returns the relative complement
        /// </summary>
        /// <typeparam name="T">Data type</typeparam>
        /// <param name="predicate1">Predicate 1</param>
        /// <param name="predicate2">Predicate 2</param>
        /// <returns>The relative complement</returns>
        public static Predicate<T>? RelativeComplement<T>(this Predicate<T> predicate1, Predicate<T> predicate2)
        {
            if (predicate1 is null || predicate2 is null)
            {
                return null;
            }

            return x => predicate1(x) && !predicate2(x);
        }

        /// <summary>
        /// Removes the values from the predicate set
        /// </summary>
        /// <typeparam name="T">Data type</typeparam>
        /// <param name="predicate">Predicate</param>
        /// <param name="values">Values to remove</param>
        /// <returns>The resulting set</returns>
        public static Predicate<T>? RemoveFromSet<T>(this Predicate<T> predicate, params T[] values)
        {
            if (predicate is null)
            {
                return null;
            }

            if (values is null)
            {
                return predicate;
            }

            return x => !values.Contains(x) && predicate(x);
        }

        /// <summary>
        /// Treats predicates as sets and unions them together
        /// </summary>
        /// <typeparam name="T">Data type</typeparam>
        /// <param name="predicate1">Predicate 1</param>
        /// <param name="predicate2">Predicate 2</param>
        /// <returns>The unioned predicate</returns>
        public static Predicate<T> Union<T>(this Predicate<T> predicate1, Predicate<T> predicate2)
        {
            if (predicate1 is null)
            {
                return predicate2;
            }

            if (predicate2 is null)
            {
                return predicate1;
            }

            return x => predicate1(x) || predicate2(x);
        }
    }
}


text:
# marginalia [![Build Status](https://travis-ci.org/basecamp/marginalia.svg?branch=master)](https://travis-ci.org/basecamp/marginalia)

Attach comments to your ActiveRecord queries. By default, it adds the application, controller, and action names as a
comment at the end of each query.

This helps when searching log files for queries, and seeing where slow queries came from.

For example, once enabled, your logs will look like:

    Account Load (0.3ms)  SELECT `accounts`.* FROM `accounts`
    WHERE `accounts`.`queenbee_id` = 1234567890
    LIMIT 1
    /*application:BCX,controller:project_imports,action:show*/

You can also use these query comments along with a tool like [pt-query-digest](http://www.percona.com/doc/percona-toolkit/2.1/pt-query-digest.html#query-reviews)
to automate identification of controllers and actions that are hotspots for slow queries.

This gem was created at 37signals. You can read more about how we use it [on
our blog](http://37signals.com/svn/posts/3130-tech-note-mysql-query-comments-in-rails).

This has been tested and used in production with both the mysql and mysql2 gems,
tested on Rails 2.3.5 through 4.1.x. It has also been tested for sqlite3 and postgres.

Patches are welcome for other database adapters.

## Installation

### For Rails 3.x and 4.x:

    # Gemfile
    gem 'marginalia'

    # config/application.rb
    require 'marginalia/railtie'

### For Rails 2.x:

If using cached externals, add to your `config/externals.yml` file.

Or, if your prefer using `config.gem`, you can use:

    config.gem 'marginalia'

Finally, if bundled, you'll need to manually run the initialization step in an
initializer, e.g.:

    # Gemfile
    gem 'marginalia', :require => false

    #config/initializers/marginalia.rb
    require 'marginalia'
    Marginalia::Railtie.insert

### Customization
Optionally, you can set the application name shown in the log like so in an initializer (e.g. `config/initializers/marginalia.rb`):

    Marginalia.application_name = "BCX"

For Rails 3 applications, the name will default to your Rails application name.
For Rails 2 applications, "rails" is used as the default application name.

You can also configure the components of the comment that will be appended,
by setting `Marginalia::Comment.components`. By default, this is set to:

    Marginalia::Comment.components = [:application, :controller, :action]

Which results in a comment of
`application:#{application_name},controller:#{controller.name},action:#{action_name}`.

You can re-order or remove these components. You can also add additional
comment components of your desire by defining new module methods for
`Marginalia::Comment` which return a string. For example:

    module Marginalia
      module Comment
        def self.mycommentcomponent
          "TEST"
        end
      end
    end

    Marginalia::Comment.components = [:application, :mycommentcomponent]

Which will result in a comment like
`application:#{application_name},mycommentcomponent:TEST`
The calling controller is available to these methods via `@controller`.

Marginalia ships with `:application`, `:controller`, and `:action` enabled by
default. In addition, implementation is provided for:
  * `:line` (for file and line number calling query). :line supports
    a configuration by setting a regexp in `Marginalia::Comment.lines_to_ignore`
    to exclude parts of the stacktrace from inclusion in the line comment.
  * `:controller_with_namespace` to include the full classname (including namespace)
    of the controller.
  * `:job` to include the classname of the ActiveJob being performed.

Pull requests for other included comment components are welcome.

## Contributing

Start by bundling and creating the test database:

    bundle
    rake db:mysql:create
    rake db:postgresql:create

Then, running `rake` will run the tests on all the database adapters (`mysql`, `mysql2`, `postgresql` and `sqlite`):

    rake


text:
declare module 'color-hash' {
	interface Hasher {
		hex(text: string): string;
	}

	class ColorHash {
		public hex(text: string): string;
		public rgb(text: string): [number, number, number];
	}

	export = ColorHash;
}


text:
def mergeSpeechURL(first_csv, second_csv):
	import csv
	with open(first_csv, 'rU') as csv_1:

		#Add the first CSV to Merged CSV File
		for row in csv.reader(csv_1):
			with open('__merged_speechurls.csv','a') as f1: f1.write("{}\n".format(row[0]))

	with open(second_csv, 'rU') as csv_2:
		#Add the second CSV to Merged CSV File
		for row in csv.reader(csv_2):
			with open('__merged_speechurls.csv','a') as f1: f1.write("{}\n".format(row[0]))

	print "merging speech_urls files..."

#mergeSpeechURL("speechurls.csv", "speech_urls_current_data.csv")
mergeSpeechURL("speechurls.csv", "speech_urls_current_data.csv")


text:
<BODY>
Celestial mechanics
</BODY>


text:
this is student view.

Student 1
    <input type='text' ng-model='student1.response'>

Student 2
    <input type='text' ng-model='student2.response'>


text:
<?php

namespace Sylius\Bundle\VariableProductBundle\DependencyInjection;

use Sylius\Bundle\ResourceBundle\DependencyInjection\SyliusResourceExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;

/**
 * Sylius product catalog system container extension.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class SyliusVariableProductExtension extends SyliusResourceExtension implements PrependExtensionInterface
{
    protected $configFiles = array(
        'options',
        'variants',
        'prototypes',
    );

    /**
     * {@inheritdoc}
     */
    public function load(array $config, ContainerBuilder $container)
    {
        $this->configDir = __DIR__.'/../Resources/config/container';

        list(, $loader) = $this->configure($config, new Configuration(), $container, self::CONFIGURE_LOADER | self::CONFIGURE_PARAMETERS | self::CONFIGURE_VALIDATORS);

        $this->loadDatabaseDriver($container->getParameter('sylius_product.driver'), $loader);
    }

    /**
     * {@inheritdoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        if (!$container->hasExtension('sylius_product')) {
            return;
        }

        $container->prependExtensionConfig('sylius_product', array(
            'classes' => array(
                'product' => array(
                    'model' => 'Sylius\Bundle\VariableProductBundle\Model\VariableProduct',
                    'form'  => 'Sylius\Bundle\VariableProductBundle\Form\Type\VariableProductType'
                ),
                'prototype' => array(
                    'model' => 'Sylius\Bundle\VariableProductBundle\Model\Prototype',
                    'form'  => 'Sylius\Bundle\VariableProductBundle\Form\Type\PrototypeType'
                )
            ))
        );
    }
}