text:
//=============================================================================
//
// Render/HLSLGenerator.cpp
//
// Created by Max McGuire (max@unknownworlds.com)
// Copyright (c) 2013, Unknown Worlds Entertainment, Inc.
//
//=============================================================================

//#include "Engine/String.h"
//#include "Engine/Log.h"
#include "Engine.h"

#include "HLSLGenerator.h"
#include "HLSLParser.h"
#include "HLSLTree.h"

namespace M4
{

static const char* GetTypeName(const HLSLType& type)
{
    switch (type.baseType)
    {
    case HLSLBaseType_Void:         return "void";
    case HLSLBaseType_Float:        return "float";
    case HLSLBaseType_Float2:       return "float2";
    case HLSLBaseType_Float3:       return "float3";
    case HLSLBaseType_Float4:       return "float4";
	case HLSLBaseType_Float2x2:     return "float2x2";
    case HLSLBaseType_Float3x3:     return "float3x3";
    case HLSLBaseType_Float4x4:     return "float4x4";
    case HLSLBaseType_Float4x3:     return "float4x3";
    case HLSLBaseType_Float4x2:     return "float4x2";
    case HLSLBaseType_Half:        return "float";
    case HLSLBaseType_Half2:       return "float2";
    case HLSLBaseType_Half3:       return "float3";
    case HLSLBaseType_Half4:       return "float4";
    case HLSLBaseType_Half2x2:     return "float2x2";
    case HLSLBaseType_Half3x3:     return "float3x3";
    case HLSLBaseType_Half4x4:     return "float4x4";
    case HLSLBaseType_Half4x3:     return "float4x3";
    case HLSLBaseType_Half4x2:     return "float4x2";
    case HLSLBaseType_Bool:         return "bool";
	case HLSLBaseType_Bool2:        return "bool2";
	case HLSLBaseType_Bool3:        return "bool3";
	case HLSLBaseType_Bool4:        return "bool4";
    case HLSLBaseType_Int:          return "int";
    case HLSLBaseType_Int2:         return "int2";
    case HLSLBaseType_Int3:         return "int3";
    case HLSLBaseType_Int4:         return "int4";
    case HLSLBaseType_Uint:         return "uint";
    case HLSLBaseType_Uint2:        return "uint2";
    case HLSLBaseType_Uint3:        return "uint3";
    case HLSLBaseType_Uint4:        return "uint4";
    case HLSLBaseType_Texture:      return "texture";
    case HLSLBaseType_Sampler:      return "sampler";
    case HLSLBaseType_Sampler2D:    return "sampler2D";
    case HLSLBaseType_Sampler3D:    return "sampler3D";
    case HLSLBaseType_SamplerCube:  return "samplerCUBE";
    case HLSLBaseType_Sampler2DShadow:  return "sampler2DShadow";
    case HLSLBaseType_Sampler2DMS:  return "sampler2DMS";
    case HLSLBaseType_Sampler2DArray:    return "sampler2DArray";
    case HLSLBaseType_UserDefined:  return type.typeName;
    default: return "<unknown type>";
    }
}

static int GetFunctionArguments(HLSLFunctionCall* functionCall, HLSLExpression* expression[], int maxArguments)
{
    HLSLExpression* argument = functionCall->argument;
    int numArguments = 0;
    while (argument != NULL)
    {
        if (numArguments < maxArguments)
        {
            expression[numArguments] = argument;
        }
        argument = argument->nextExpression;
        ++numArguments;
    }
    return numArguments;
}

HLSLGenerator::HLSLGenerator()
{
    m_tree                          = NULL;
    m_entryName                     = NULL;
    m_legacy                        = false;
    m_target                        = Target_VertexShader;
    m_isInsideBuffer                = false;
    m_textureSampler2DStruct[0]     = 0;
    m_textureSampler2DCtor[0]       = 0;
    m_textureSampler3DStruct[0]     = 0;
    m_textureSampler3DCtor[0]       = 0;
    m_textureSamplerCubeStruct[0]   = 0;
    m_textureSamplerCubeCtor[0]     = 0;
    m_tex2DFunction[0]              = 0;
    m_tex2DProjFunction[0]          = 0;
    m_tex2DLodFunction[0]           = 0;
    m_tex2DBiasFunction[0]          = 0;
    m_tex2DGradFunction[0]          = 0;
    m_tex2DGatherFunction[0]        = 0;
    m_tex2DSizeFunction[0]          = 0;
    m_tex2DFetchFunction[0]         = 0;
    m_tex2DCmpFunction[0]           = 0;
    m_tex2DMSFetchFunction[0]       = 0;
    m_tex3DFunction[0]              = 0;
    m_tex3DLodFunction[0]           = 0;
    m_tex3DBiasFunction[0]          = 0;
    m_texCubeFunction[0]            = 0;
    m_texCubeLodFunction[0]         = 0;
    m_texCubeBiasFunction[0]        = 0;
}

// @@ We need a better way of doing semantic replacement:
// - Look at the function being generated.
// - Return semantic, semantics associated to fields of the return structure, or output arguments, or fields of structures associated to output arguments -> output semantic replacement.
// - Semantics associated input arguments or fields of the input arguments -> input semantic replacement.
static const char * TranslateSemantic(const char* semantic, bool output, HLSLGenerator::Target target)
{
    if (target == HLSLGenerator::Target_VertexShader)
    {
        if (output)
        {
            if (String_Equal("POSITION", semantic))     return "SV_Position";
        }
        else {
            if (String_Equal("INSTANCE_ID", semantic))  return "SV_InstanceID";
        }
    }
    else if (target == HLSLGenerator::Target_PixelShader)
    {
        if (output)
        {
            if (String_Equal("DEPTH", semantic))      return "SV_Depth";
            if (String_Equal("COLOR", semantic))      return "SV_Target";
            if (String_Equal("COLOR0", semantic))     return "SV_Target0";
            if (String_Equal("COLOR0_1", semantic))   return "SV_Target1";
            if (String_Equal("COLOR1", semantic))     return "SV_Target1";
            if (String_Equal("COLOR2", semantic))     return "SV_Target2";
            if (String_Equal("COLOR3", semantic))     return "SV_Target3";
        }
        else
        {
            if (String_Equal("VPOS", semantic))       return "SV_Position";
            if (String_Equal("VFACE", semantic))      return "SV_IsFrontFace";    // bool   @@ Should we do type replacement too?
        }
    }
    return NULL;
}

bool HLSLGenerator::Generate(HLSLTree* tree, Target target, const char* entryName, bool legacy)
{
    m_tree      = tree;
    m_entryName = entryName;
    m_target    = target;
    m_legacy    = legacy;
    m_isInsideBuffer = false;

    m_writer.Reset();

    // @@ Should we generate an entirely new copy of the tree so that we can modify it in place?
    if (!legacy)
    {
        HLSLFunction * function = tree->FindFunction(entryName);

        // Handle return value semantics
        if (function->semantic != NULL) {
            function->sv_semantic = TranslateSemantic(function->semantic, /*output=*/true, target);
        }
        if (function->returnType.baseType == HLSLBaseType_UserDefined) {
            HLSLStruct * s = tree->FindGlobalStruct(function->returnType.typeName);

			HLSLStructField * sv_fields = NULL;

			HLSLStructField * lastField = NULL;
            HLSLStructField * field = s->field;
            while (field) {
				HLSLStructField * nextField = field->nextField;

                if (field->semantic) {
					field->hidden = false;
                    field->sv_semantic = TranslateSemantic(field->semantic, /*output=*/true, target);

					// Fields with SV semantics are stored at the end to avoid linkage problems.
					if (field->sv_semantic != NULL) {
						// Unlink from last.
						if (lastField != NULL) lastField->nextField = nextField;
						else s->field = nextField;

						// Add to sv_fields.
						field->nextField = sv_fields;
						sv_fields = field;
					}
                }

				if (field != sv_fields) lastField = field;
                field = nextField;
            }

			// Append SV fields at the end.
			if (sv_fields != NULL) {
				if (lastField == NULL) {
					s->field = sv_fields;
				}
				else {
					ASSERT(lastField->nextField == NULL);
					lastField->nextField = sv_fields;
				}
			}
        }

        // Handle argument semantics.
        // @@ It would be nice to flag arguments that are used by the program and skip or hide the unused ones.
        HLSLArgument * argument = function->argument;
        while (argument) {
            bool output = argument->modifier == HLSLArgumentModifier_Out;
            if (argument->semantic) {
                argument->sv_semantic = TranslateSemantic(argument->semantic, output, target);
            }

            if (argument->type.baseType == HLSLBaseType_UserDefined) {
                HLSLStruct * s = tree->FindGlobalStruct(argument->type.typeName);

                HLSLStructField * field = s->field;
                while (field) {
                    if (field->semantic) {
						field->hidden = false;

						if (target == Target_PixelShader && !output && String_EqualNoCase(field->semantic, "POSITION")) {
							ASSERT(String_EqualNoCase(field->sv_semantic, "SV_Position"));
							field->hidden = true;
						}

                        field->sv_semantic = TranslateSemantic(field->semantic, output, target);
                    }

                    field = field->nextField;
                }
            }

            argument = argument->nextArgument;
        }
    }

    ChooseUniqueName("TextureSampler2D",            m_textureSampler2DStruct,   sizeof(m_textureSampler2DStruct));
    ChooseUniqueName("CreateTextureSampler2D",      m_textureSampler2DCtor,     sizeof(m_textureSampler2DCtor));
    ChooseUniqueName("TextureSampler2DShadow",      m_textureSampler2DShadowStruct, sizeof(m_textureSampler2DShadowStruct));
    ChooseUniqueName("CreateTextureSampler2DShadow",m_textureSampler2DShadowCtor,   sizeof(m_textureSampler2DShadowCtor));
    ChooseUniqueName("TextureSampler3D",            m_textureSampler3DStruct,   sizeof(m_textureSampler3DStruct));
    ChooseUniqueName("CreateTextureSampler3D",      m_textureSampler3DCtor,     sizeof(m_textureSampler3DCtor));
    ChooseUniqueName("TextureSamplerCube",          m_textureSamplerCubeStruct, sizeof(m_textureSamplerCubeStruct));
    ChooseUniqueName("CreateTextureSamplerCube",    m_textureSamplerCubeCtor,   sizeof(m_textureSamplerCubeCtor));
    ChooseUniqueName("tex2D",                       m_tex2DFunction,            sizeof(m_tex2DFunction));
    ChooseUniqueName("tex2Dproj",                   m_tex2DProjFunction,        sizeof(m_tex2DProjFunction));
    ChooseUniqueName("tex2Dlod",                    m_tex2DLodFunction,         sizeof(m_tex2DLodFunction));
    ChooseUniqueName("tex2Dbias",                   m_tex2DBiasFunction,        sizeof(m_tex2DBiasFunction));
    ChooseUniqueName("tex2Dgrad",                   m_tex2DGradFunction,        sizeof(m_tex2DGradFunction));
    ChooseUniqueName("tex2Dgather",                 m_tex2DGatherFunction,      sizeof(m_tex2DGatherFunction));
    ChooseUniqueName("tex2Dsize",                   m_tex2DSizeFunction,        sizeof(m_tex2DSizeFunction));
    ChooseUniqueName("tex2Dfetch",                  m_tex2DFetchFunction,       sizeof(m_tex2DFetchFunction));
    ChooseUniqueName("tex2Dcmp",                    m_tex2DCmpFunction,         sizeof(m_tex2DCmpFunction));
    ChooseUniqueName("tex2DMSfetch",                m_tex2DMSFetchFunction,     sizeof(m_tex2DMSFetchFunction));
    ChooseUniqueName("tex2DMSsize",                 m_tex2DMSSizeFunction,      sizeof(m_tex2DMSSizeFunction));
    ChooseUniqueName("tex3D",                       m_tex3DFunction,            sizeof(m_tex3DFunction));
    ChooseUniqueName("tex3Dlod",                    m_tex3DLodFunction,         sizeof(m_tex3DLodFunction));
    ChooseUniqueName("tex3Dbias",                   m_tex3DBiasFunction,        sizeof(m_tex3DBiasFunction));
    ChooseUniqueName("tex3Dsize",                   m_tex3DSizeFunction,        sizeof(m_tex3DSizeFunction));
    ChooseUniqueName("texCUBE",                     m_texCubeFunction,          sizeof(m_texCubeFunction));
    ChooseUniqueName("texCUBElod",                  m_texCubeLodFunction,       sizeof(m_texCubeLodFunction));
    ChooseUniqueName("texCUBEbias",                 m_texCubeBiasFunction,      sizeof(m_texCubeBiasFunction));
    ChooseUniqueName("texCUBEsize",                 m_texCubeSizeFunction,      sizeof(m_texCubeSizeFunction));

    if (!m_legacy)
    {
        // @@ Only emit code for sampler types that are actually used?

        m_writer.WriteLine(0, "struct %s {", m_textureSampler2DStruct);
        m_writer.WriteLine(1, "Texture2D    t;");
        m_writer.WriteLine(1, "SamplerState s;");
        m_writer.WriteLine(0, "};");

        m_writer.WriteLine(0, "struct %s {", m_textureSampler2DShadowStruct);
        m_writer.WriteLine(1, "Texture2D                t;");
        m_writer.WriteLine(1, "SamplerComparisonState   s;");
        m_writer.WriteLine(0, "};");

        m_writer.WriteLine(0, "struct %s {", m_textureSampler3DStruct);
        m_writer.WriteLine(1, "Texture3D    t;");
        m_writer.WriteLine(1, "SamplerState s;");
        m_writer.WriteLine(0, "};");

        m_writer.WriteLine(0, "struct %s {", m_textureSamplerCubeStruct);
        m_writer.WriteLine(1, "TextureCube  t;");
        m_writer.WriteLine(1, "SamplerState s;");
        m_writer.WriteLine(0, "};");

        m_writer.WriteLine(0, "%s %s(Texture2D t, SamplerState s) {", m_textureSampler2DStruct, m_textureSampler2DCtor);
        m_writer.WriteLine(1, "%s ts;", m_textureSampler2DStruct);
        m_writer.WriteLine(1, "ts.t = t; ts.s = s;");
        m_writer.WriteLine(1, "return ts;");
        m_writer.WriteLine(0, "}");

        m_writer.WriteLine(0, "%s %s(Texture2D t, SamplerComparisonState s) {", m_textureSampler2DShadowStruct, m_textureSampler2DShadowCtor);
        m_writer.WriteLine(1, "%s ts;", m_textureSampler2DShadowStruct);
        m_writer.WriteLine(1, "ts.t = t; ts.s = s;");
        m_writer.WriteLine(1, "return ts;");
        m_writer.WriteLine(0, "}");

        m_writer.WriteLine(0, "%s %s(Texture3D t, SamplerState s) {", m_textureSampler3DStruct, m_textureSampler3DCtor);
        m_writer.WriteLine(1, "%s ts;", m_textureSampler3DStruct);
        m_writer.WriteLine(1, "ts.t = t; ts.s = s;");
        m_writer.WriteLine(1, "return ts;");
        m_writer.WriteLine(0, "}");

        m_writer.WriteLine(0, "%s %s(TextureCube t, SamplerState s) {", m_textureSamplerCubeStruct, m_textureSamplerCubeCtor);
        m_writer.WriteLine(1, "%s ts;", m_textureSamplerCubeStruct);
        m_writer.WriteLine(1, "ts.t = t; ts.s = s;");
        m_writer.WriteLine(1, "return ts;");
        m_writer.WriteLine(0, "}");

        if (m_tree->GetContainsString("tex2D"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float2 texCoord) {", m_tex2DFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "return ts.t.Sample(ts.s, texCoord);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dproj"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord) {", m_tex2DProjFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "return ts.t.Sample(ts.s, texCoord.xy / texCoord.w);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dlod"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord, int2 offset=0) {", m_tex2DLodFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "return ts.t.SampleLevel(ts.s, texCoord.xy, texCoord.w, offset);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dbias"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord) {", m_tex2DBiasFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "return ts.t.SampleBias(ts.s, texCoord.xy, texCoord.w);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dgrad"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float2 texCoord, float2 ddx, float2 ddy) {", m_tex2DGradFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "return ts.t.SampleGrad(ts.s, texCoord.xy, ddx, ddy);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dgather"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float2 texCoord, int component, int2 offset=0) {", m_tex2DGatherFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "if(component == 0) return ts.t.GatherRed(ts.s, texCoord, offset);");
            m_writer.WriteLine(1, "if(component == 1) return ts.t.GatherGreen(ts.s, texCoord, offset);");
            m_writer.WriteLine(1, "if(component == 2) return ts.t.GatherBlue(ts.s, texCoord, offset);");
            m_writer.WriteLine(1, "return ts.t.GatherAlpha(ts.s, texCoord, offset);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dsize"))
        {
            m_writer.WriteLine(0, "int2 %s(%s ts) {", m_tex2DSizeFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "int2 size; ts.t.GetDimensions(size.x, size.y); return size;");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dfetch"))
        {
            m_writer.WriteLine(0, "int2 %s(%s ts, int3 texCoord) {", m_tex2DFetchFunction, m_textureSampler2DStruct);
            m_writer.WriteLine(1, "return ts.t.Load(texCoord.xyz);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2Dcmp"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord) {", m_tex2DCmpFunction, m_textureSampler2DShadowStruct);
            m_writer.WriteLine(1, "return ts.t.SampleCmpLevelZero(ts.s, texCoord.xy, texCoord.z);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2DMSfetch"))
        {
            m_writer.WriteLine(0, "float4 %s(Texture2DMS<float4> t, int2 texCoord, int sample) {", m_tex2DMSFetchFunction);
            m_writer.WriteLine(1, "return t.Load(texCoord, sample);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex2DMSsize"))
        {
            m_writer.WriteLine(0, "int3 %s(Texture2DMS<float4> t) {", m_tex2DMSSizeFunction);
            m_writer.WriteLine(1, "int3 size; t.GetDimensions(size.x, size.y, size.z); return size;");   // @@ Not tested, does this return the number of samples in the third argument?
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex3D"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float3 texCoord) {", m_tex3DFunction, m_textureSampler3DStruct);
            m_writer.WriteLine(1, "return ts.t.Sample(ts.s, texCoord);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex3Dlod"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord) {", m_tex3DLodFunction, m_textureSampler3DStruct);
            m_writer.WriteLine(1, "return ts.t.SampleLevel(ts.s, texCoord.xyz, texCoord.w);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex3Dbias"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord) {", m_tex3DBiasFunction, m_textureSampler3DStruct);
            m_writer.WriteLine(1, "return ts.t.SampleBias(ts.s, texCoord.xyz, texCoord.w);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("tex3Dsize"))
        {
            m_writer.WriteLine(0, "int3 %s(%s ts) {", m_tex3DSizeFunction, m_textureSampler3DStruct);
            m_writer.WriteLine(1, "int3 size; ts.t.GetDimensions(size.x, size.y, size.z); return size;");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("texCUBE"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float3 texCoord) {", m_texCubeFunction, m_textureSamplerCubeStruct);
            m_writer.WriteLine(1, "return ts.t.Sample(ts.s, texCoord);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("texCUBElod"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord) {", m_texCubeLodFunction, m_textureSamplerCubeStruct);
            m_writer.WriteLine(1, "return ts.t.SampleLevel(ts.s, texCoord.xyz, texCoord.w);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("texCUBEbias"))
        {
            m_writer.WriteLine(0, "float4 %s(%s ts, float4 texCoord) {", m_texCubeBiasFunction, m_textureSamplerCubeStruct);
            m_writer.WriteLine(1, "return ts.t.SampleBias(ts.s, texCoord.xyz, texCoord.w);");
            m_writer.WriteLine(0, "}");
        }
        if (m_tree->GetContainsString("texCUBEsize"))
        {
            m_writer.WriteLine(0, "int %s(%s ts) {", m_texCubeSizeFunction, m_textureSamplerCubeStruct);
            m_writer.WriteLine(1, "int size; ts.t.GetDimensions(size); return size;");   // @@ Not tested, does this return a single value?
            m_writer.WriteLine(0, "}");
        }
    }

    HLSLRoot* root = m_tree->GetRoot();
    OutputStatements(0, root->statement);

    m_tree = NULL;
    return true;
}

const char* HLSLGenerator::GetResult() const
{
    return m_writer.GetResult();
}

void HLSLGenerator::OutputExpressionList(HLSLExpression* expression)
{
    int numExpressions = 0;
    while (expression != NULL)
    {
        if (numExpressions > 0)
        {
            m_writer.Write(", ");
        }
        OutputExpression(expression);
        expression = expression->nextExpression;
        ++numExpressions;
    }
}

void HLSLGenerator::OutputExpression(HLSLExpression* expression)
{
    if (expression->nodeType == HLSLNodeType_IdentifierExpression)
    {
        HLSLIdentifierExpression* identifierExpression = static_cast<HLSLIdentifierExpression*>(expression);
        const char* name = identifierExpression->name;
        if (!m_legacy && IsSamplerType(identifierExpression->expressionType) && identifierExpression->global)
        {
            // @@ Handle generic sampler type.

            if (identifierExpression->expressionType.baseType == HLSLBaseType_Sampler2D)
            {
                m_writer.Write("%s(%s_texture, %s_sampler)", m_textureSampler2DCtor, name, name);
            }
            else if (identifierExpression->expressionType.baseType == HLSLBaseType_Sampler3D)
            {
                m_writer.Write("%s(%s_texture, %s_sampler)", m_textureSampler3DCtor, name, name);
            }
            else if (identifierExpression->expressionType.baseType == HLSLBaseType_SamplerCube)
            {
                m_writer.Write("%s(%s_texture, %s_sampler)", m_textureSamplerCubeCtor, name, name);
            }
            else if (identifierExpression->expressionType.baseType == HLSLBaseType_Sampler2DShadow)
            {
                m_writer.Write("%s(%s_texture, %s_sampler)", m_textureSampler2DShadowCtor, name, name);
            }
            else if (identifierExpression->expressionType.baseType == HLSLBaseType_Sampler2DMS)
            {
                m_writer.Write("%s", name);
            }
        }
        else
        {
            m_writer.Write("%s", name);
        }
    }
    else if (expression->nodeType == HLSLNodeType_CastingExpression)
    {
        HLSLCastingExpression* castingExpression = static_cast<HLSLCastingExpression*>(expression);
        m_writer.Write("(");
        OutputDeclaration(castingExpression->type, "");
        m_writer.Write(")(");
        OutputExpression(castingExpression->expression);
        m_writer.Write(")");
    }
    else if (expression->nodeType == HLSLNodeType_ConstructorExpression)
    {
        HLSLConstructorExpression* constructorExpression = static_cast<HLSLConstructorExpression*>(expression);
        m_writer.Write("%s(", GetTypeName(constructorExpression->type));
        OutputExpressionList(constructorExpression->argument);
        m_writer.Write(")");
    }
    else if (expression->nodeType == HLSLNodeType_LiteralExpression)
    {
        HLSLLiteralExpression* literalExpression = static_cast<HLSLLiteralExpression*>(expression);
        switch (literalExpression->type)
        {
        case HLSLBaseType_Half:
        case HLSLBaseType_Float:
            {
                // Don't use printf directly so that we don't use the system locale.
                char buffer[64];
                String_FormatFloat(buffer, sizeof(buffer), literalExpression->fValue);
                m_writer.Write("%s", buffer);
            }
            break;
        case HLSLBaseType_Int:
            m_writer.Write("%d", literalExpression->iValue);
            break;
        case HLSLBaseType_Bool:
            m_writer.Write("%s", literalExpression->bValue ? "true" : "false");
            break;
        default:
            ASSERT(0);
        }
    }
    else if (expression->nodeType == HLSLNodeType_UnaryExpression)
    {
        HLSLUnaryExpression* unaryExpression = static_cast<HLSLUnaryExpression*>(expression);
        const char* op = "?";
        bool pre = true;
        switch (unaryExpression->unaryOp)
        {
        case HLSLUnaryOp_Negative:      op = "-";  break;
        case HLSLUnaryOp_Positive:      op = "+";  break;
        case HLSLUnaryOp_Not:           op = "!";  break;
        case HLSLUnaryOp_PreIncrement:  op = "++"; break;
        case HLSLUnaryOp_PreDecrement:  op = "--"; break;
        case HLSLUnaryOp_PostIncrement: op = "++"; pre = false; break;
        case HLSLUnaryOp_PostDecrement: op = "--"; pre = false; break;
        case HLSLUnaryOp_BitNot:        op = "~";  break;
        }
        m_writer.Write("(");
        if (pre)
        {
            m_writer.Write("%s", op);
            OutputExpression(unaryExpression->expression);
        }
        else
        {
            OutputExpression(unaryExpression->expression);
            m_writer.Write("%s", op);
        }
        m_writer.Write(")");
    }
    else if (expression->nodeType == HLSLNodeType_BinaryExpression)
    {
        HLSLBinaryExpression* binaryExpression = static_cast<HLSLBinaryExpression*>(expression);
        m_writer.Write("(");
        OutputExpression(binaryExpression->expression1);
        const char* op = "?";
        switch (binaryExpression->binaryOp)
        {
        case HLSLBinaryOp_Add:          op = " + "; break;
        case HLSLBinaryOp_Sub:          op = " - "; break;
        case HLSLBinaryOp_Mul:          op = " * "; break;
        case HLSLBinaryOp_Div:          op = " / "; break;
        case HLSLBinaryOp_Less:         op = " < "; break;
        case HLSLBinaryOp_Greater:      op = " > "; break;
        case HLSLBinaryOp_LessEqual:    op = " <= "; break;
        case HLSLBinaryOp_GreaterEqual: op = " >= "; break;
        case HLSLBinaryOp_Equal:        op = " == "; break;
        case HLSLBinaryOp_NotEqual:     op = " != "; break;
        case HLSLBinaryOp_Assign:       op = " = "; break;
        case HLSLBinaryOp_AddAssign:    op = " += "; break;
        case HLSLBinaryOp_SubAssign:    op = " -= "; break;
        case HLSLBinaryOp_MulAssign:    op = " *= "; break;
        case HLSLBinaryOp_DivAssign:    op = " /= "; break;
        case HLSLBinaryOp_And:          op = " && "; break;
        case HLSLBinaryOp_Or:           op = " || "; break;
		case HLSLBinaryOp_BitAnd:       op = " & "; break;
        case HLSLBinaryOp_BitOr:        op = " | "; break;
        case HLSLBinaryOp_BitXor:       op = " ^ "; break;
        default:
            ASSERT(0);
        }
        m_writer.Write("%s", op);
        OutputExpression(binaryExpression->expression2);
        m_writer.Write(")");
    }
    else if (expression->nodeType == HLSLNodeType_ConditionalExpression)
    {
        HLSLConditionalExpression* conditionalExpression = static_cast<HLSLConditionalExpression*>(expression);
        m_writer.Write("((");
        OutputExpression(conditionalExpression->condition);
        m_writer.Write(")?(");
        OutputExpression(conditionalExpression->trueExpression);
        m_writer.Write("):(");
        OutputExpression(conditionalExpression->falseExpression);
        m_writer.Write("))");
    }
    else if (expression->nodeType == HLSLNodeType_MemberAccess)
    {
        HLSLMemberAccess* memberAccess = static_cast<HLSLMemberAccess*>(expression);
        m_writer.Write("(");
        OutputExpression(memberAccess->object);
        m_writer.Write(").%s", memberAccess->field);
    }
    else if (expression->nodeType == HLSLNodeType_ArrayAccess)
    {
        HLSLArrayAccess* arrayAccess = static_cast<HLSLArrayAccess*>(expression);
        OutputExpression(arrayAccess->array);
        m_writer.Write("[");
        OutputExpression(arrayAccess->index);
        m_writer.Write("]");
    }
    else if (expression->nodeType == HLSLNodeType_FunctionCall)
    {
        HLSLFunctionCall* functionCall = static_cast<HLSLFunctionCall*>(expression);
        const char* name = functionCall->function->name;
        if (!m_legacy)
        {
            if (String_Equal(name, "tex2D"))
            {
                name = m_tex2DFunction;
            }
            else if (String_Equal(name, "tex2Dproj"))
            {
                name = m_tex2DProjFunction;
            }
            else if (String_Equal(name, "tex2Dlod"))
            {
                name = m_tex2DLodFunction;
            }
            else if (String_Equal(name, "tex2Dbias"))
            {
                name = m_tex2DBiasFunction;
            }
            else if (String_Equal(name, "tex2Dgrad"))
            {
                name = m_tex2DGradFunction;
            }
            else if (String_Equal(name, "tex2Dgather"))
            {
                name = m_tex2DGatherFunction;
            }
            else if (String_Equal(name, "tex2Dsize"))
            {
                name = m_tex2DSizeFunction;
            }
            else if (String_Equal(name, "tex2Dfetch"))
            {
                name = m_tex2DFetchFunction;
            }
            else if (String_Equal(name, "tex2Dcmp"))
            {
                name = m_tex2DCmpFunction;
            }
            else if (String_Equal(name, "tex2DMSfetch"))
            {
                name = m_tex2DMSFetchFunction;
            }
            else if (String_Equal(name, "tex2DMSsize"))
            {
                name = m_tex2DMSSizeFunction;
            }
            else if (String_Equal(name, "tex3D"))
            {
                name = m_tex3DFunction;
            }
            else if (String_Equal(name, "tex3Dlod"))
            {
                name = m_tex3DLodFunction;
            }
            else if (String_Equal(name, "tex3Dbias"))
            {
                name = m_tex3DBiasFunction;
            }
            else if (String_Equal(name, "tex3Dsize"))
            {
                name = m_tex3DSizeFunction;
            }
            else if (String_Equal(name, "texCUBE"))
            {
                name = m_texCubeFunction;
            }
            else if (String_Equal(name, "texCUBElod"))
            {
                name = m_texCubeLodFunction;
            }
            else if (String_Equal(name, "texCUBEbias"))
            {
                name = m_texCubeBiasFunction;
            }
            else if (String_Equal(name, "texCUBEsize"))
            {
                name = m_texCubeSizeFunction;
            }
        }
        m_writer.Write("%s(", name);
        OutputExpressionList(functionCall->argument);
        m_writer.Write(")");
    }
    else
    {
        m_writer.Write("<unknown expression>");
    }
}

void HLSLGenerator::OutputArguments(HLSLArgument* argument)
{
    int numArgs = 0;
    while (argument != NULL)
    {
        if (numArgs > 0)
        {
            m_writer.Write(", ");
        }

        switch (argument->modifier)
        {
        case HLSLArgumentModifier_In:
            m_writer.Write("in ");
            break;
        case HLSLArgumentModifier_Out:
            m_writer.Write("out ");
            break;
        case HLSLArgumentModifier_Inout:
            m_writer.Write("inout ");
            break;
        case HLSLArgumentModifier_Uniform:
            m_writer.Write("uniform ");
            break;
        default:
            break;
        }

        const char * semantic = argument->sv_semantic ? argument->sv_semantic : argument->semantic;

        OutputDeclaration(argument->type, argument->name, semantic, /*registerName=*/NULL, argument->defaultValue);
        argument = argument->nextArgument;
        ++numArgs;
    }
}

static const char * GetAttributeName(HLSLAttributeType attributeType)
{
    if (attributeType == HLSLAttributeType_Unroll) return "unroll";
    if (attributeType == HLSLAttributeType_Branch) return "branch";
    if (attributeType == HLSLAttributeType_Flatten) return "flatten";
    return NULL;
}

void HLSLGenerator::OutputAttributes(int indent, HLSLAttribute* attribute)
{
    while (attribute != NULL)
    {
        const char * attributeName = GetAttributeName(attribute->attributeType);

        if (attributeName != NULL)
        {
            m_writer.WriteLineTagged(indent, attribute->fileName, attribute->line, "[%s]", attributeName);
        }

        attribute = attribute->nextAttribute;
    }
}

void HLSLGenerator::OutputStatements(int indent, HLSLStatement* statement)
{
    while (statement != NULL)
    {
        if (statement->hidden)
        {
            statement = statement->nextStatement;
            continue;
        }

        OutputAttributes(indent, statement->attributes);

        if (statement->nodeType == HLSLNodeType_Declaration)
        {
            HLSLDeclaration* declaration = static_cast<HLSLDeclaration*>(statement);
            m_writer.BeginLine(indent, declaration->fileName, declaration->line);
            OutputDeclaration(declaration);
            m_writer.EndLine(";");
        }
        else if (statement->nodeType == HLSLNodeType_Struct)
        {
            HLSLStruct* structure = static_cast<HLSLStruct*>(statement);
            m_writer.WriteLineTagged(indent, structure->fileName, structure->line, "struct %s {", structure->name);
            HLSLStructField* field = structure->field;
            while (field != NULL)
            {
                if (!field->hidden)
                {
                    m_writer.BeginLine(indent + 1, field->fileName, field->line);
                    const char * semantic = field->sv_semantic ? field->sv_semantic : field->semantic;
                    OutputDeclaration(field->type, field->name, semantic);
                    m_writer.Write(";");
                    m_writer.EndLine();
                }
                field = field->nextField;
            }
            m_writer.WriteLine(indent, "};");
        }
        else if (statement->nodeType == HLSLNodeType_Buffer)
        {
            HLSLBuffer* buffer = static_cast<HLSLBuffer*>(statement);
            HLSLDeclaration* field = buffer->field;

            if (!m_legacy)
            {
                m_writer.BeginLine(indent, buffer->fileName, buffer->line);
                m_writer.Write("cbuffer %s", buffer->name);
                if (buffer->registerName != NULL)
                {
                    m_writer.Write(" : register(%s)", buffer->registerName);
                }
                m_writer.EndLine(" {");
            }

            m_isInsideBuffer = true;

            while (field != NULL)
            {
                if (!field->hidden)
                {
                    m_writer.BeginLine(indent + 1, field->fileName, field->line);
                    OutputDeclaration(field->type, field->name, /*semantic=*/NULL, /*registerName*/field->registerName, field->assignment);
                    m_writer.Write(";");
                    m_writer.EndLine();
                }
                field = (HLSLDeclaration*)field->nextStatement;
            }

            m_isInsideBuffer = false;

            if (!m_legacy)
            {
                m_writer.WriteLine(indent, "};");
            }
        }
        else if (statement->nodeType == HLSLNodeType_Function)
        {
            HLSLFunction* function = static_cast<HLSLFunction*>(statement);

            // Use an alternate name for the function which is supposed to be entry point
            // so that we can supply our own function which will be the actual entry point.
            const char* functionName   = function->name;
            const char* returnTypeName = GetTypeName(function->returnType);

            m_writer.BeginLine(indent, function->fileName, function->line);
            m_writer.Write("%s %s(", returnTypeName, functionName);

            OutputArguments(function->argument);

            const char * semantic = function->sv_semantic ? function->sv_semantic : function->semantic;
            if (semantic != NULL)
            {
                m_writer.Write(") : %s {", semantic);
            }
            else
            {
                m_writer.Write(") {");
            }

            m_writer.EndLine();

            OutputStatements(indent + 1, function->statement);
            m_writer.WriteLine(indent, "};");
        }
        else if (statement->nodeType == HLSLNodeType_ExpressionStatement)
        {
            HLSLExpressionStatement* expressionStatement = static_cast<HLSLExpressionStatement*>(statement);
            m_writer.BeginLine(indent, statement->fileName, statement->line);
            OutputExpression(expressionStatement->expression);
            m_writer.EndLine(";");
        }
        else if (statement->nodeType == HLSLNodeType_ReturnStatement)
        {
            HLSLReturnStatement* returnStatement = static_cast<HLSLReturnStatement*>(statement);
            if (returnStatement->expression != NULL)
            {
                m_writer.BeginLine(indent, returnStatement->fileName, returnStatement->line);
                m_writer.Write("return ");
                OutputExpression(returnStatement->expression);
                m_writer.EndLine(";");
            }
            else
            {
                m_writer.WriteLineTagged(indent, returnStatement->fileName, returnStatement->line, "return;");
            }
        }
        else if (statement->nodeType == HLSLNodeType_DiscardStatement)
        {
            HLSLDiscardStatement* discardStatement = static_cast<HLSLDiscardStatement*>(statement);
            m_writer.WriteLineTagged(indent, discardStatement->fileName, discardStatement->line, "discard;");
        }
        else if (statement->nodeType == HLSLNodeType_BreakStatement)
        {
            HLSLBreakStatement* breakStatement = static_cast<HLSLBreakStatement*>(statement);
            m_writer.WriteLineTagged(indent, breakStatement->fileName, breakStatement->line, "break;");
        }
        else if (statement->nodeType == HLSLNodeType_ContinueStatement)
        {
            HLSLContinueStatement* continueStatement = static_cast<HLSLContinueStatement*>(statement);
            m_writer.WriteLineTagged(indent, continueStatement->fileName, continueStatement->line, "continue;");
        }
        else if (statement->nodeType == HLSLNodeType_IfStatement)
        {
            HLSLIfStatement* ifStatement = static_cast<HLSLIfStatement*>(statement);
            m_writer.BeginLine(indent, ifStatement->fileName, ifStatement->line);
            m_writer.Write("if (");
            OutputExpression(ifStatement->condition);
            m_writer.Write(") {");
            m_writer.EndLine();
            OutputStatements(indent + 1, ifStatement->statement);
            m_writer.WriteLine(indent, "}");
            if (ifStatement->elseStatement != NULL)
            {
                m_writer.WriteLine(indent, "else {");
                OutputStatements(indent + 1, ifStatement->elseStatement);
                m_writer.WriteLine(indent, "}");
            }
        }
        else if (statement->nodeType == HLSLNodeType_ForStatement)
        {
            HLSLForStatement* forStatement = static_cast<HLSLForStatement*>(statement);
            m_writer.BeginLine(indent, forStatement->fileName, forStatement->line);
            m_writer.Write("for (");
            OutputDeclaration(forStatement->initialization);
            m_writer.Write("; ");
            OutputExpression(forStatement->condition);
            m_writer.Write("; ");
            OutputExpression(forStatement->increment);
            m_writer.Write(") {");
            m_writer.EndLine();
            OutputStatements(indent + 1, forStatement->statement);
            m_writer.WriteLine(indent, "}");
        }
        else if (statement->nodeType == HLSLNodeType_BlockStatement)
        {
            HLSLBlockStatement* blockStatement = static_cast<HLSLBlockStatement*>(statement);
            m_writer.WriteLineTagged(indent, blockStatement->fileName, blockStatement->line, "{");
            OutputStatements(indent + 1, blockStatement->statement);
            m_writer.WriteLine(indent, "}");
        }
        else if (statement->nodeType == HLSLNodeType_Technique)
        {
            // Techniques are ignored.
        }
        else if (statement->nodeType == HLSLNodeType_Pipeline)
        {
            // Pipelines are ignored.
        }
        else
        {
            // Unhanded statement type.
            ASSERT(0);
        }

        statement = statement->nextStatement;
    }
}

void HLSLGenerator::OutputDeclaration(HLSLDeclaration* declaration)
{
    bool isSamplerType = IsSamplerType(declaration->type);

    if (!m_legacy && isSamplerType)
    {
        int reg = -1;
        if (declaration->registerName != NULL)
        {
            sscanf(declaration->registerName, "s%d", &reg);
        }

        const char* textureType = NULL;
        const char* samplerType = "SamplerState";
        // @@ Handle generic sampler type.

        if (declaration->type.baseType == HLSLBaseType_Sampler2D)
        {
            textureType = "Texture2D";
        }
        else if (declaration->type.baseType == HLSLBaseType_Sampler3D)
        {
            textureType = "Texture3D";
        }
        else if (declaration->type.baseType == HLSLBaseType_SamplerCube)
        {
            textureType = "TextureCube";
        }
        else if (declaration->type.baseType == HLSLBaseType_Sampler2DShadow)
        {
            textureType = "Texture2D";
            samplerType = "SamplerComparisonState";
        }
        else if (declaration->type.baseType == HLSLBaseType_Sampler2DMS)
        {
            textureType = "Texture2DMS<float4>";  // @@ Is template argument required?
            samplerType = NULL;
        }

        if (samplerType != NULL)
        {
            if (reg != -1)
            {
                m_writer.Write("%s %s_texture : register(t%d); %s %s_sampler : register(s%d)", textureType, declaration->name, reg, samplerType, declaration->name, reg);
            }
            else
            {
                m_writer.Write("%s %s_texture; %s %s_sampler", textureType, declaration->name, samplerType, declaration->name);
            }
        }
        else
        {
            if (reg != -1)
            {
                m_writer.Write("%s %s : register(t%d)", textureType, declaration->name, reg);
            }
            else
            {
                m_writer.Write("%s %s", textureType, declaration->name);
            }
        }
        return;
    }

    OutputDeclarationType(declaration->type);
    OutputDeclarationBody(declaration->type, declaration->name, declaration->semantic, declaration->registerName, declaration->assignment);
    declaration = declaration->nextDeclaration;

    while(declaration != NULL) {
        m_writer.Write(", ");
        OutputDeclarationBody(declaration->type, declaration->name, declaration->semantic, declaration->registerName, declaration->assignment);
        declaration = declaration->nextDeclaration;
    };
}

void HLSLGenerator::OutputDeclarationType(const HLSLType& type)
{
    const char* typeName = GetTypeName(type);
    if (!m_legacy)
    {
        if (type.baseType == HLSLBaseType_Sampler2D)
        {
            typeName = m_textureSampler2DStruct;
        }
        else if (type.baseType == HLSLBaseType_Sampler3D)
        {
            typeName = m_textureSampler3DStruct;
        }
        else if (type.baseType == HLSLBaseType_SamplerCube)
        {
            typeName = m_textureSamplerCubeStruct;
        }
        else if (type.baseType == HLSLBaseType_Sampler2DShadow)
        {
            typeName = m_textureSampler2DShadowStruct;
        }
        else if (type.baseType == HLSLBaseType_Sampler2DMS)
        {
            typeName = "Texture2DMS<float4>";
        }
    }

    if (type.flags & HLSLTypeFlag_Const)
    {
        m_writer.Write("const ");
    }
    if (type.flags & HLSLTypeFlag_Static)
    {
        m_writer.Write("static ");
    }

    // Interpolation modifiers.
    if (type.flags & HLSLTypeFlag_Centroid)
    {
        m_writer.Write("centroid ");
    }
    if (type.flags & HLSLTypeFlag_Linear)
    {
        m_writer.Write("linear ");
    }
    if (type.flags & HLSLTypeFlag_NoInterpolation)
    {
        m_writer.Write("nointerpolation ");
    }
    if (type.flags & HLSLTypeFlag_NoPerspective)
    {
        m_writer.Write("noperspective ");
    }
    if (type.flags & HLSLTypeFlag_Sample)   // @@ Only in shader model >= 4.1
    {
        m_writer.Write("sample ");
    }

    m_writer.Write("%s ", typeName);
}

void HLSLGenerator::OutputDeclarationBody(const HLSLType& type, const char* name, const char* semantic/*=NULL*/, const char* registerName/*=NULL*/, HLSLExpression * assignment/*=NULL*/)
{
    m_writer.Write("%s", name);

    if (type.array)
    {
        ASSERT(semantic == NULL);
        m_writer.Write("[");
        if (type.arraySize != NULL)
        {
            OutputExpression(type.arraySize);
        }
        m_writer.Write("]");
    }

    if (semantic != NULL)
    {
        m_writer.Write(" : %s", semantic);
    }

    if (registerName != NULL)
    {
        if (m_isInsideBuffer)
        {
            m_writer.Write(" : packoffset(%s)", registerName);
        }
        else
        {
            m_writer.Write(" : register(%s)", registerName);
        }
    }

    if (assignment != NULL && !IsSamplerType(type))
    {
        m_writer.Write(" = ");
        if (type.array)
        {
            m_writer.Write("{ ");
            OutputExpressionList(assignment);
            m_writer.Write(" }");
        }
        else
        {
            OutputExpression(assignment);
        }
    }
}

void HLSLGenerator::OutputDeclaration(const HLSLType& type, const char* name, const char* semantic/*=NULL*/, const char* registerName/*=NULL*/, HLSLExpression * assignment/*=NULL*/)
{
    OutputDeclarationType(type);
    OutputDeclarationBody(type, name, semantic, registerName, assignment);
}

bool HLSLGenerator::ChooseUniqueName(const char* base, char* dst, int dstLength) const
{
    // IC: Try without suffix first.
    String_Printf(dst, dstLength, "%s", base);
    if (!m_tree->GetContainsString(base))
    {
        return true;
    }

    for (int i = 1; i < 1024; ++i)
    {
        String_Printf(dst, dstLength, "%s%d", base, i);
        if (!m_tree->GetContainsString(dst))
        {
            return true;
        }
    }
    return false;
}

}


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../../resources/js-test.js"></script>
</head>
<body>
<script>
description('Test getting the port attribute of the URL in HTMLAnchorElement.');

var a = document.createElement('a');

debug("Default port is empty");
shouldBe("a.port", "''");

debug("Unspecified port should return empty string");
a.href = "http://example.com/";
shouldBe("a.port", "''");

debug("Empty port should be empty");
a.href = "http://example.com:/";
shouldBe("a.port", "''");
</script>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
#include "gazebo/transport/Node.hh"
#include "gazebo/transport/Publisher.hh"

#include "gazebo/common/Time.hh"

#include "gazebo/physics/World.hh"
#include "gazebo/physics/Collision.hh"
#include "gazebo/physics/Contact.hh"
#include "gazebo/physics/ContactManager.hh"

using namespace gazebo;
using namespace physics;

/////////////////////////////////////////////////
ContactManager::ContactManager()
{
  this->contactIndex = 0;
}

/////////////////////////////////////////////////
ContactManager::~ContactManager()
{
  this->Clear();
  this->node.reset();
  this->contactPub.reset();

  boost::unordered_map<std::string, ContactPublisher *>::iterator iter;
  for (iter = this->customContactPublishers.begin();
      iter != this->customContactPublishers.end(); ++iter)
  {
    if (iter->second)
    {
      iter->second->collisions.clear();
      iter->second->collisionNames.clear();
      iter->second->publisher.reset();
      delete iter->second;
      iter->second = NULL;
    }
  }
  this->customContactPublishers.clear();
}

/////////////////////////////////////////////////
void ContactManager::Init(WorldPtr _world)
{
  this->world = _world;

  this->node = transport::NodePtr(new transport::Node());
  this->node->Init(this->world->GetName());

  this->contactPub =
    this->node->Advertise<msgs::Contacts>("~/physics/contacts", 50);
}

/////////////////////////////////////////////////
Contact *ContactManager::NewContact(Collision *_collision1,
                                    Collision *_collision2,
                                    const common::Time &_time)
{
  Contact *result = NULL;

  if (!_collision1 || !_collision2)
    return result;

  // If no one is listening to the default topic, or there are no
  // custom contact publishers then don't create any contact information.
  // This is a signal to the Physics engine that it can skip the extra
  // processing necessary to get back contact information.

  std::vector<ContactPublisher *> publishers;
  boost::unordered_map<std::string, ContactPublisher *>::iterator iter;
  for (iter = this->customContactPublishers.begin();
      iter != this->customContactPublishers.end(); ++iter)
  {
    // A model can simply be loaded later, so convert ones that are not yet
    // found
    if (!iter->second->collisionNames.empty())
    {
      std::vector<std::string>::iterator it;
      for (it = iter->second->collisionNames.begin();
          it != iter->second->collisionNames.end();)
      {
        Collision *col = boost::dynamic_pointer_cast<Collision>(
            this->world->GetByName(*it)).get();
        if (!col)
        {
          ++it;
          continue;
        }
        else
          it = iter->second->collisionNames.erase(it);
        iter->second->collisions.insert(col);
      }
    }

    if (iter->second->collisions.find(_collision1) !=
        iter->second->collisions.end() ||
        iter->second->collisions.find(_collision2) !=
        iter->second->collisions.end())
    {
      publishers.push_back(iter->second);
    }
  }

  if (this->contactPub->HasConnections() || !publishers.empty())
  {
    // Get or create a contact feedback object.
    if (this->contactIndex < this->contacts.size())
      result = this->contacts[this->contactIndex++];
    else
    {
      result = new Contact();
      this->contacts.push_back(result);
      this->contactIndex = this->contacts.size();
    }
    for (unsigned int i = 0; i < publishers.size(); ++i)
    {
      publishers[i]->contacts.push_back(result);
    }
  }

  if (!result)
    return result;

  result->count = 0;
  result->collision1 = _collision1->GetScopedName();
  result->collision2 = _collision2->GetScopedName();
  result->collisionPtr1 = _collision1;
  result->collisionPtr2 = _collision2;
  result->time = _time;
  result->world = this->world;

  return result;
}

/////////////////////////////////////////////////
unsigned int ContactManager::GetContactCount() const
{
  return this->contactIndex;
}

/////////////////////////////////////////////////
Contact *ContactManager::GetContact(unsigned int _index) const
{
  if (_index < this->contactIndex)
    return this->contacts[_index];
  else
    return NULL;
}

/////////////////////////////////////////////////
const std::vector<Contact*> &ContactManager::GetContacts() const
{
  return this->contacts;
}

/////////////////////////////////////////////////
void ContactManager::ResetCount()
{
  this->contactIndex = 0;
}

/////////////////////////////////////////////////
void ContactManager::Clear()
{
  // Delete all the contacts.
  for (unsigned int i = 0; i < this->contacts.size(); ++i)
    delete this->contacts[i];

  this->contacts.clear();

  boost::unordered_map<std::string, ContactPublisher *>::iterator iter;
  for (iter = this->customContactPublishers.begin();
      iter != this->customContactPublishers.end(); ++iter)
    iter->second->contacts.clear();

  // Reset the contact count to zero.
  this->contactIndex = 0;
}

/////////////////////////////////////////////////
void ContactManager::PublishContacts()
{
//  if (this->contacts.size() == 0)
//    return;

  if (!this->contactPub)
  {
    gzerr << "ContactManager has not been initialized. "
          << "Unable to publish contacts.\n";
    return;
  }

  // publish to default topic, ~/physics/contacts
  msgs::Contacts msg;
  for (unsigned int i = 0; i < this->contactIndex; ++i)
  {
    if (this->contacts[i]->count == 0)
      continue;

    msgs::Contact *contactMsg = msg.add_contact();
    this->contacts[i]->FillMsg(*contactMsg);
  }

  msgs::Set(msg.mutable_time(), this->world->GetSimTime());
  this->contactPub->Publish(msg);

  // publish to other custom topics
  boost::unordered_map<std::string, ContactPublisher *>::iterator iter;
  for (iter = this->customContactPublishers.begin();
      iter != this->customContactPublishers.end(); ++iter)
  {
    ContactPublisher *contactPublisher = iter->second;
    msgs::Contacts msg2;
    for (unsigned int j = 0;
        j < contactPublisher->contacts.size(); ++j)
    {
      if (contactPublisher->contacts[j]->count == 0)
        continue;

      msgs::Contact *contactMsg = msg2.add_contact();
      contactPublisher->contacts[j]->FillMsg(*contactMsg);
    }
    msgs::Set(msg2.mutable_time(), this->world->GetSimTime());
    contactPublisher->publisher->Publish(msg2);
    contactPublisher->contacts.clear();
  }
}

/////////////////////////////////////////////////
std::string ContactManager::CreateFilter(const std::string &_name,
    const std::vector<std::string> &_collisions)
{
  if (_collisions.empty())
    return "";

  std::string name = _name;
  boost::replace_all(name, "::", "/");

  if (this->customContactPublishers.find(name) !=
    this->customContactPublishers.end())
  {
    gzerr << "Filter with the same name already exists! Aborting" << std::endl;
    return "";
  }

  // Contact sensors make use of this filter
  std::string topic = "~/" + name + "/contacts";

  transport::PublisherPtr pub =
    this->node->Advertise<msgs::Contacts>(topic);

  ContactPublisher *contactPublisher = new ContactPublisher;
  contactPublisher->publisher = pub;
  contactPublisher->collisionNames = _collisions;
  // convert collision names to pointers
  std::vector<std::string>::iterator iter;
  for (iter = contactPublisher->collisionNames.begin();
      iter != contactPublisher->collisionNames.end();)
  {
    Collision *col = boost::dynamic_pointer_cast<Collision>(
       this->world->GetByName(*iter)).get();
    if (!col)
    {
      ++iter;
      continue;
    }
    else
      iter = contactPublisher->collisionNames.erase(iter);
    contactPublisher->collisions.insert(col);
  }

  this->customContactPublishers[name] = contactPublisher;

  return topic;
}


text:
At the moment this is less of a wrapper and more of a program wrapped in a Go function that does what I'm looking for.

I plan on expanding this into a more useful wrapper over time.

## What is PocketSphinx?

[CMU Project Page](http://cmusphinx.sourceforge.net/)

In short, Sphinx and PocketSphinx are speech recognition toolkits.

## Dependencies

* pocketsphinx - on OS X I have only had luck with [this homebrew tap](https://github.com/watsonbox/homebrew-cmu-sphinx)


text:
using System.Linq;

namespace Umbraco.Core.Configuration.UmbracoSettings
{
    public static class ContentSectionExtensions
    {
        /// <summary>
        /// Determines if file extension is allowed for upload based on (optional) white list and black list
        /// held in settings.
        /// Allow upload if extension is whitelisted OR if there is no whitelist and extension is NOT blacklisted.
        /// </summary>
        public static bool IsFileAllowedForUpload(this IContentSection contentSection, string extension)
        {
            return contentSection.AllowedUploadFiles.Any(x => x.InvariantEquals(extension)) ||
                (contentSection.AllowedUploadFiles.Any() == false &&
                contentSection.DisallowedUploadFiles.Any(x => x.InvariantEquals(extension)) == false);
        }
    }
}


text:
//
//  HeaderPickerView.m
//  FRDStravaClientDemo
//
//  Created by Sebastien Windal on 5/15/14.
//  Copyright (c) 2014 Sebastien Windal. All rights reserved.
//

#import "HeaderPickerView.h"

@implementation HeaderPickerView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
"""
Utility functions for styles
"""

##########################################################################
## Imports
##########################################################################

import numpy as np

def find_text_color(base_color, dark_color="black", light_color="white", coef_choice=0):
    """
    Takes a background color and returns the appropriate light or dark text color.
    Users can specify the dark and light text color, or accept the defaults of 'black' and 'white'

    base_color: The color of the background. This must be
        specified in RGBA with values between 0 and 1 (note, this is the default
        return value format of a call to base_color = cmap(number) to get the
        color corresponding to a desired number). Note, the value of `A` in RGBA
        is not considered in determining light/dark.

    dark_color: Any valid matplotlib color value.
        Function will return this value if the text should be colored dark

    light_color: Any valid matplotlib color value.
        Function will return this value if thet text should be colored light.

    coef_choice: slightly different approaches to calculating brightness. Currently two options in
        a list, user can enter 0 or 1 as list index. 0 is default.
    """

    #Coefficients:
        # option 0: http://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx
        # option 1: http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
    coef_options = [np.array((.241, .691, .068, 0)),
                    np.array((.299, .587, .114, 0))
                    ]

    coefs= coef_options[coef_choice]
    rgb = np.array(base_color) * 255
    brightness = np.sqrt(np.dot(coefs, rgb**2))

    #Threshold from option 0 link; determined by trial and error.
    #base is light
    if brightness > 130:
        return dark_color
    return light_color


text:
import test from 'tape'
import {
  getUserInfo,
  getUserIMInfo,
  getGroupInfo,
  getChannelInfo,
  fetchToken,
} from 'utils'

test(`getChannelInfo
  should be a function`, (t) => {
  t.equal(typeof getChannelInfo, 'function', 'getChannelInfo is a function')
  t.end()
})

test(`getChannelInfo
  should find channel in a list of channels`, (t) => {
  const mockChannelList = {
    channels: [
      {
        id: 'U023BECGF',
        name: 'admins',
      },
    ],
  }
  const chanName = 'admins'
  getChannelInfo(mockChannelList, chanName).then((result) => {
    t.ok(result)
    t.equal(result.name, 'admins', 'Channel details is returned')
    t.end()
  })
})

test(`getChannelInfo
  should return an error if channel name does not exist`, (t) => {
  const mockChannelList = {
    channels: [
      {
        id: 'U023BECGF',
        name: 'admins',
      },
    ],
  }
  const chanName = 'Anonymous'
  getChannelInfo(mockChannelList, chanName)
    .then(t.fail)
    .catch((error) => {
      t.ok(error)
      t.equal(
        error,
        'ChannelName is invalid, please check and try again.',
        'Error message is returned.')
      t.end()
    })
})

test(`getGroupInfo
  should be a function`, (t) => {
  t.equal(typeof getGroupInfo, 'function', 'getGroupInfo is a function')
  t.end()
})

test(`getGroupInfo
  should find group in a list of groups`, (t) => {
  const mockGroupList = {
    groups: [
      {
        id: 'U023BECGF',
        name: 'admins',
      },
    ],
  }
  const groupName = 'admins'
  getGroupInfo(mockGroupList, groupName).then((result) => {
    t.ok(result)
    t.equal(result.name, 'admins', 'Groups details is returned')
    t.end()
  })
})

test(`getGroupInfo
  should return an error if groupname does not exist`, (t) => {
  const mockGroupList = {
    groups: [
      {
        id: 'U023BECGF',
        name: 'admins',
      },
    ],
  }
  const groupName = 'Anonymous'
  getGroupInfo(mockGroupList, groupName)
    .then(t.fail)
    .catch((error) => {
      t.ok(error)
      t.equal(
        error,
        'GroupName is invalid, please check and try again.',
        'Error message is returned.')
      t.end()
    })
})

test(`getUserInfo
  should be a function`, (t) => {
  t.equal(typeof getUserInfo, 'function', 'getUserInfo is a function')
  t.end()
})

test(`getUserIMInfo
  should be a function`, (t) => {
  t.equal(typeof getUserIMInfo, 'function', 'getUserIMInfo is a function')
  t.end()
})

test(`getUserInfo
  should find user in a list of users`, (t) => {
  const mockUserList = {
    members: [
      {
        id: 'U023BECGF',
        name: 'bobby',
      },
    ],
  }
  const username = 'bobby'
  getUserInfo(mockUserList, username).then((result) => {
    t.ok(result)
    t.equal(result.name, 'bobby', 'User details is returned')
    t.end()
  })
})

test(`getUserInfo
  should return an error if username does not exist`, (t) => {
  const mockUserList = {
    members: [
      {
        id: 'U023BECGF',
        name: 'bobby',
      },
    ],
  }
  const username = 'Anonymous'
  getUserInfo(mockUserList, username)
    .then(t.fail)
    .catch((error) => {
      t.ok(error)
      t.equal(
        error,
        'Username is invalid, please check and try again.',
        'Error message is returned.')
      t.end()
    })
})

test(`getUserIMInfo
  should find imInfo for a user`, (t) => {
  const mockUserList = {
    ims: [
      {
        user: 'USLACKBOT',
      },
      {
        user: 'U024BE7LH',
      },
    ],
  }
  const mockUserObj = {
    id: 'USLACKBOT',
    user: 'SLACKBOT',
  }
  getUserIMInfo(mockUserList, mockUserObj).then((result) => {
    t.ok(result)
    t.equal(result.user, 'USLACKBOT', 'User imInfo is fetch')
    t.end()
  })
})

test(`getUserIMInfo
  should return an error if username does not exist`, (t) => {
  const mockUserList = {
    ims: [
      {
        user: 'USLACKBOT',
      },
      {
        user: 'U024BE7LH',
      },
    ],
  }
  const mockUserObj = {
    id: 'INVALID',
    user: 'SLACKBOT',
  }
  getUserIMInfo(mockUserList, mockUserObj)
    .then(t.fail)
    .catch((error) => {
      t.ok(error)
      t.equal(
        error,
        `You do not have any IM history with this user:${mockUserObj.user}`,
        'Error message is returned.')
      t.end()
    })
})

test(`fetchToken
  should return token if passed in`, (t) => {
  const token = 'testingToken'
  const result = fetchToken(token)
  const message = 'Passed in token is returned'
  t.equal(token, result, message)
  t.end()
})

test(`fetchToken
  should fetch token from env var`, (t) => {
  const token = 'testingToken'
  // Store old value, so can be restored
  const oldEnvVar = process.env.SLACK_HISTORY_EXPORT_TOKEN
  process.env.SLACK_HISTORY_EXPORT_TOKEN = token
  const result = fetchToken()
  const message = 'Token is fetched from the set env variable'
  t.equal(token, result, message)
  // Restore old value
  process.env.SLACK_HISTORY_EXPORT_TOKEN = oldEnvVar
  t.end()
})


text:
package hudson.plugins.statusmonitor;

import hudson.Extension;
import hudson.model.*;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;

import javax.servlet.jsp.jstl.core.LoopTagStatus;
import java.util.ArrayList;
import java.util.List;

/**
 * Status Monitor, shows the configured Jobs in a single screen overview
 *
 * @author Daniel Galán y Martins
 */
@ExportedBean (defaultVisibility = 999)
@Extension
public class MonitorAction implements RootAction {
	private static final long serialVersionUID = 1L;

	private static final int COLUMNS = 2;

	public String getDisplayName() {
		// The Name on the Dashboard
		return "Status Monitor";
	}

	public String getIconFileName() {
		return MonitorDescriptor.ACTION_LOGO_MEDIUM;
	}

	public String getUrlName() {
		// The name of the URL path segment
		return "/monitor";
	}

	/**
	 * @return list projects that will be displayed
	 */
	private List<AbstractProject> getProjects() {
        List<AbstractProject> result = new ArrayList<AbstractProject>();
		List<TopLevelItem> topLevelItems = Hudson.getInstance().getItems();
        for (TopLevelItem topLevelItem : topLevelItems) {
            if (topLevelItem instanceof AbstractProject) {
                AbstractProject abstractProject = (AbstractProject) topLevelItem;
                if (abstractProject.getPublishersList().get(MonitorPublisher.DESCRIPTOR) != null) {
                        result.add(abstractProject);
                }
            }
        }

		return result;
	}

	public String getResult(AbstractProject project) {
		String result;
		if ((project.getLastCompletedBuild() != null) && (project.getLastCompletedBuild().getResult() != null)) {
			if (project.isDisabled()) {
				result = "DISABLED";
			}
			else {
				result = project.getLastCompletedBuild().getResult().toString();
			}
		}
		else {
			result = "NOT_BUILD";
		}
		return result;
	}

	private int getRows() {
		int size = getProjects().size();
		if (size <= 3) {
			return size;
		}
		return ((size % COLUMNS) == 0) ? (size / COLUMNS) : ((size + 1) / COLUMNS);
	}

	@Exported
	public double getRowsHeight() {
		return 100 / new Double(getRows());
	}

	@Exported
	public AbstractProject[][] getProjectsArray() {
		int rows = getRows();
		AbstractProject[][] result = new AbstractProject[rows][];
		List<AbstractProject> projects = getProjects();
		for (int i = 0; i < rows; i++) {
			AbstractProject[] row = result[i];
			if (row == null) {
				if (projects.size() <= 3) {
					row = new AbstractProject[1];
					row[0] = projects.get(i);
				}
				else {
					// last row and uneven
					if (((i + 1) == rows) && ((projects.size() % 2) != 0)) {
						row = new AbstractProject[1];
						row[0] = projects.get(i * COLUMNS);
					}
					else {
						row = new AbstractProject[COLUMNS];
						for (int j = 0; j < COLUMNS; j++) {
							row[j] = projects.get((i * COLUMNS) + j);
						}
					}
				}
				result[i] = row;
			}
		}
		return result;
	}

	@Exported
	public int getStyleId(LoopTagStatus varStatus, AbstractProject[][] projectsArray) {
		boolean lastLine = varStatus.isLast() && (projectsArray.length > 1) && (projectsArray[projectsArray.length - 1].length == 1);
		boolean oneDimenional = (projectsArray[0].length == 1);
		if (oneDimenional || lastLine) {
			return 1;
		}
		return 2;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- ATTENTION - THIS IS AN AUTOMATICALLY GENERATED FILE -->
<!-- Manual changes can cause severe problems and system instability -->
<!-- Apply manual changes only if you have received explicit instructions from Dynatrace Support -->
<dynatrace version="7.0.6.1013">
  <webuidashboard memento.version="7.0.6.1013">
    <metadata owner="admin" name="y_Production - [y] database impact by page" id="502cdff9-d637-4a6a-9221-da0e996c2bdf" modificationdate="1504647994182" sharemode="PUBLIC_SHARED" version="27" revision="b2d9846a-8efb-4b3b-98a6-8194fa56dc3a" />
  </webuidashboard>
</dynatrace>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Inbox2.Core.DataAccess.Reflection;
using Inbox2.Framework;

namespace Inbox2.Core.DataAccess
{
	public static class Migrate
	{
		public static void Up(Type targetType)
		{
			var map = Reflector.BuildMapFromType(targetType);

			if (TableExists(map.TableName))
				return;

			StringBuilder sql = new StringBuilder();
			sql.AppendFormat("CREATE TABLE \"{0}\"{1}", map.TableName, Environment.NewLine);
			sql.AppendLine("(");

			sql.AppendFormat("\t\"{0}\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, {1}",
				map.PrimaryKey.ColumName, Environment.NewLine);

			for (int i = 0; i < map.Columns.Count; i++)
			{
				var token = map.Columns[i];

				string dbType = "TEXT";

				if (token.SourceType == typeof (Int16)
				    || token.SourceType == typeof (Int32)
				    || token.SourceType == typeof (Int64))
				{
					dbType = "INTEGER";
				}

				sql.AppendFormat("\t\"{0}\" {1}{2}{3}",
					token.ColumName,
					dbType,
					i < map.Columns.Count -1 ? "," : "", // Skip comma for last column
					Environment.NewLine);
			}

			// Remove last comma
			sql.AppendLine(")");

			// Execute creation script for table
			ClientState.Current.DataService.ExecuteNonQuery(sql.ToString());
		}

		static bool TableExists(string tableName)
		{
			string sql = String.Format("select count(*) from sqlite_master where name='{0}'", tableName);

			return ClientState.Current.DataService.ExecuteScalar<int>(sql) > 0;
		}
	}
}


text:
#pragma config(Hubs, S1, HTMotor, HTServo, none, none)
#pragma config(Hubs, S2, HTMotor, none, none, none)
#pragma config(Hubs, S3, HTMotor, none, none, none)
#pragma config(Hubs, S4, HTMotor, none, none, none)
#pragma config(Motor, mtr_S1_C1_1, FR, tmotorTetrix, openLoop, reversed)
#pragma config(Motor, mtr_S1_C1_2, FL, tmotorTetrix, openLoop)
#pragma config(Motor, mtr_S2_C1_1, BR, tmotorTetrix, openLoop, reversed)
#pragma config(Motor, mtr_S2_C1_2, BL, tmotorTetrix, openLoop)
#pragma config(Motor, mtr_S3_C1_1, LIFTR, tmotorTetrix, openLoop)
#pragma config(Motor, mtr_S3_C1_2, LIFTL, tmotorTetrix, openLoop, reversed)
#pragma config(Motor, mtr_S4_C1_1, GUARDIANROLLER, tmotorTetrix, openLoop)
#pragma config(Motor, mtr_S4_C1_2, FLAGRAISER, tmotorTetrix, openLoop)
#pragma config(Servo,  srvo_S1_C2_1,    AB,                   tServoStandard)
#pragma config(Servo,  srvo_S1_C2_2,    servo2,               tServoNone)
#pragma config(Servo,  srvo_S1_C2_3,    servo3,               tServoNone)
#pragma config(Servo,  srvo_S1_C2_4,    servo4,               tServoNone)
#pragma config(Servo,  srvo_S1_C2_5,    servo5,               tServoNone)
#pragma config(Servo,  srvo_S1_C2_6,    servo6,               tServoNone)
/*Pragmas must be declared before anything, including comments.***************/
/*Any files including this one should have pragmas identical to these.********/

//File: RD-Lift.c
//Project: E-03-Rainbow Dash
//Creation Date: Oct 21, 2013
//
//Author: Brandon Sanders <brandon@mechakana.com>
//
//Special file that is run outside of the game to manually raise or lower
//Rainbow Dash's lift (it simply cannot be moved by hand).
//
//Confirmed to work on:
//Lego Mindstorms NXT
//
///////////////////////////////////////////////////////////////////////////////
//Copyright (c) 2013 Brandon Sanders <brandon@mechakana.com>
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
///////////////////////////////////////////////////////////////////////////////
//

//Function: initializeRobot////////////////////////////////////////////////////
//
//[initializeRobot] performs any tasks that your robot may need to do before
//                  the beginning of the autonomous segment of the robot game.
//
//[initializeRobot] will be left empty if no initialization code is
//                  required.
//
void initializeRobot()
{
	//Silence motors.
	motor[FR] = 0;
	motor[FL] = 0;
	motor[BR] = 0;
	motor[BL] = 0;
	motor[LIFTR] = 0;
	motor[LIFTL] = 0;
	motor[GUARDIANROLLER] = 0;
	motor[FLAGRAISER] = 0;

	//Have motors stall.
	bFloatDuringInactiveMotorPWM = false;
}

//Task: main///////////////////////////////////////////////////////////////////
//
//The following is the main code for the tele-op robot operation.  Customize
//as appropriate for your specific robot.
//
//At the end of the tele-op period, the FMS will automatically halt execution of
//the program.
//
task main()
{
	//Loop infinitely until the tele-op phase ends.
	while (true)
	{
		if (nNxtButtonPressed == 1)
		{
			motor[LIFTR] = 100;
			motor[LIFTL] = 100;
		}

		else if (nNxtButtonPressed == 2)
		{
			motor[LIFTR] = -100;
			motor[LIFTL] = -100;
		}

		else
		{
			motor[LIFTR] = 0;
			motor[LIFTL] = 0;
		}
	}
}


text:
package com.hack23.cia.web.impl.ui.application.web.listener;

import java.text.MessageFormat;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.event.AuthorizationFailureEvent;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;

import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.model.internal.application.system.impl.ApplicationOperationType;
import com.hack23.cia.service.api.ApplicationManager;
import com.hack23.cia.service.api.action.application.CreateApplicationEventRequest;
import com.hack23.cia.web.impl.ui.application.util.UserContextUtil;
import com.vaadin.server.Page;
import com.vaadin.ui.UI;

/**
 * The Class AuthorizationFailureEventListener.
 */
@Service
public final class AuthorizationFailureEventListener implements ApplicationListener<AuthorizationFailureEvent> {

	/** The Constant ACCESS_DENIED. */
	private static final String ACCESS_DENIED = "Access Denied";

	/** The Constant AUTHORITIES. */
	private static final String AUTHORITIES = "Authorities:";

	/** The Constant CRLF. */
	private static final String CRLF = "[\r\n]";

	/** The Constant CRLF_REPLACEMENT. */
	private static final String CRLF_REPLACEMENT = "";

	/** The Constant ERROR_MESSAGE_FORMAT. */
	private static final String ERROR_MESSAGE_FORMAT = "SECURITY:Url:{0} , Method{1} ,{2}{3}{4}{5} source:{6}";

	/**
	 * The Constant
	 * LOG_MSG_AUTHORIZATION_FAILURE_SESSION_ID_AUTHORITIES_REQUIRED_AUTHORITIES.
	 */
	private static final String LOG_MSG_AUTHORIZATION_FAILURE_SESSION_ID_AUTHORITIES_REQUIRED_AUTHORITIES = "SECURITY:Authorization Failure:: url : {} Method : {} SessionId :{} , Authorities : {} , RequiredAuthorities : {}";

	/** The Constant LOGGER. */
	private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationFailureEventListener.class);

	/** The Constant REQUIRED_AUTHORITIES. */
	private static final String REQUIRED_AUTHORITIES = " , RequiredAuthorities:";

	/** The application manager. */
	@Autowired
	private ApplicationManager applicationManager;

	/**
	 * Instantiates a new authorization failure event listener.
	 */
	public AuthorizationFailureEventListener() {
		super();
	}

	@Override
	public void onApplicationEvent(final AuthorizationFailureEvent authorizationFailureEvent) {

		final String sessionId = RequestContextHolder.currentRequestAttributes().getSessionId();

		final CreateApplicationEventRequest serviceRequest = new CreateApplicationEventRequest();
		serviceRequest.setSessionId(sessionId);

		serviceRequest.setEventGroup(ApplicationEventGroup.APPLICATION);
		serviceRequest.setApplicationOperation(ApplicationOperationType.AUTHORIZATION);

		serviceRequest.setUserId(UserContextUtil.getUserIdFromSecurityContext());

		final Page currentPageIfAny = Page.getCurrent();
		final String requestUrl = UserContextUtil.getRequestUrl(currentPageIfAny);
		final UI currentUiIfAny = UI.getCurrent();
		String methodInfo = "";

		if (currentPageIfAny != null && currentUiIfAny != null && currentUiIfAny.getNavigator() != null
				&& currentUiIfAny.getNavigator().getCurrentView() != null) {
			serviceRequest.setPage(currentUiIfAny.getNavigator().getCurrentView().getClass().getSimpleName());
			serviceRequest.setPageMode(currentPageIfAny.getUriFragment());
		}

		if (authorizationFailureEvent.getSource() instanceof final ReflectiveMethodInvocation methodInvocation) {
			if (methodInvocation.getThis() != null) {
				methodInfo = new StringBuilder().append(methodInvocation.getThis().getClass().getSimpleName())
						.append('.').append(methodInvocation.getMethod().getName()).toString();
			}
		}

		final Collection<? extends GrantedAuthority> authorities = authorizationFailureEvent.getAuthentication()
				.getAuthorities();
		final Collection<ConfigAttribute> configAttributes = authorizationFailureEvent.getConfigAttributes();

		serviceRequest.setErrorMessage(MessageFormat.format(ERROR_MESSAGE_FORMAT, requestUrl, methodInfo, AUTHORITIES,
				authorities, REQUIRED_AUTHORITIES, configAttributes, authorizationFailureEvent.getSource()));
		serviceRequest.setApplicationMessage(ACCESS_DENIED);

		applicationManager.service(serviceRequest);

		LOGGER.info(LOG_MSG_AUTHORIZATION_FAILURE_SESSION_ID_AUTHORITIES_REQUIRED_AUTHORITIES,
				requestUrl.replaceAll(CRLF, CRLF_REPLACEMENT), methodInfo.replaceAll(CRLF, CRLF_REPLACEMENT),
				sessionId.replaceAll(CRLF, CRLF_REPLACEMENT), authorities, configAttributes);
	}

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('model_login');
	}

	public function index()
	{

		$this->load->view('login');

	}

	public function login_user()
	{
		$this->load->library('form_validation');

		$this->form_validation->set_rules('email','Email Address','trim|required|min_length[10]|valid_email');
		$this->form_validation->set_rules('password','Password','trim|required|min_length[6]');

		if($this->form_validation->run() == FALSE)
		{
			$errors['errors'] = validation_errors();
			//echo "hello";
			$this->load->view('login',$errors);

		}

		else
		{

			$this->load->model('model_login');
			$result = $this->model_login->login_user();
			$role = $this->session->userdata('role');

			switch($result)
			{
				case 'logged_in':

					if($role=="super_admin")
					{
						redirect('/dashboard/');
					}
					else
					{
						redirect('/Home/');
					}
					break;

				case 'incorrect_password':
					$errors['errors'] ="Invalid Password. Please try again.";
					$this->load->view('login',$errors);
					break;

				case 'incorrect_email':
					$errors['errors'] ="Invalid Email. Please try again.";
					$this->load->view('login',$errors);
					break;

			}
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>Assimp: DefaultLogger.hpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Assimp
    v3.1.1 (June 2014)

Main Page

Related Pages

Namespaces

Classes

Files

File List

File Members

include

assimp

Classes |
Namespaces |
Macros

DefaultLogger.hpp File Reference

Classes

class  	Assimp::DefaultLogger

 	CPP-API: Primary logging facility of Assimp.  More...

Namespaces

  	Assimp

 	Assimp's CPP-API and all internal APIs.

Macros

#define 	ASSIMP_DEFAULT_LOG_NAME   "AssimpLog.txt"

 	default name of logfile  More...

Macro Definition Documentation

          #define ASSIMP_DEFAULT_LOG_NAME   "AssimpLog.txt"

default name of logfile

<address class="footer">
Generated on Wed Feb 18 2015 13:46:03 for Assimp by

 1.8.8
</address>


text:
package org.apache.spark.sql.execution

import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.{InternalRow, CatalystTypeConverters}
import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
import org.apache.spark.sql.catalyst.expressions.{Attribute, GenericMutableRow}
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Statistics}
import org.apache.spark.sql.sources.BaseRelation
import org.apache.spark.sql.types.DataType
import org.apache.spark.sql.{Row, SQLContext}

/**
 * :: DeveloperApi ::
 */
@DeveloperApi
object RDDConversions {
  def productToRowRdd[A <: Product](data: RDD[A], outputTypes: Seq[DataType]): RDD[InternalRow] = {
    data.mapPartitions { iterator =>
      val numColumns = outputTypes.length
      val mutableRow = new GenericMutableRow(numColumns)
      val converters = outputTypes.map(CatalystTypeConverters.createToCatalystConverter)
      iterator.map { r =>
        var i = 0
        while (i < numColumns) {
          mutableRow(i) = converters(i)(r.productElement(i))
          i += 1
        }

        mutableRow
      }
    }
  }

  /**
   * Convert the objects inside Row into the types Catalyst expected.
    * 将Row内的对象转换为预期的Catalyst类型
   */
  def rowToRowRdd(data: RDD[Row], outputTypes: Seq[DataType]): RDD[InternalRow] = {
    data.mapPartitions { iterator =>
      val numColumns = outputTypes.length
      val mutableRow = new GenericMutableRow(numColumns)
      val converters = outputTypes.map(CatalystTypeConverters.createToCatalystConverter)
      iterator.map { r =>
        var i = 0
        while (i < numColumns) {
          mutableRow(i) = converters(i)(r(i))
          i += 1
        }

        mutableRow
      }
    }
  }
}

/** Logical plan node for scanning data from an RDD.
  * 用于扫描RDD数据的逻辑计划节点*/
private[sql] case class LogicalRDD(
    output: Seq[Attribute],
    rdd: RDD[InternalRow])(sqlContext: SQLContext)
  extends LogicalPlan with MultiInstanceRelation {
  //Nil是一个空的List,::向队列的头部追加数据,创造新的列表
  override def children: Seq[LogicalPlan] = Nil

  override def newInstance(): LogicalRDD.this.type =
    LogicalRDD(output.map(_.newInstance()), rdd)(sqlContext).asInstanceOf[this.type]

  override def sameResult(plan: LogicalPlan): Boolean = plan match {
    case LogicalRDD(_, otherRDD) => rdd.id == otherRDD.id
    case _ => false
  }

  @transient override lazy val statistics: Statistics = Statistics(
    // TODO: Instead of returning a default value here, find a way to return a meaningful size
    // estimate for RDDs. See PR 1238 for more discussions.
    sizeInBytes = BigInt(sqlContext.conf.defaultSizeInBytes)
  )
}

/** Physical plan node for scanning data from an RDD.
  * 用于扫描来自RDD的数据的物理计划节点 */
private[sql] case class PhysicalRDD(
    output: Seq[Attribute],
    rdd: RDD[InternalRow],
    extraInformation: String) extends LeafNode {

  protected override def doExecute(): RDD[InternalRow] = rdd

  override def simpleString: String = "Scan " + extraInformation + output.mkString("[", ",", "]")
}

private[sql] object PhysicalRDD {
  def createFromDataSource(
      output: Seq[Attribute],
      rdd: RDD[InternalRow],
      relation: BaseRelation): PhysicalRDD = {
    PhysicalRDD(output, rdd, relation.toString)
  }
}

/** Logical plan node for scanning data from a local collection.
  * 用于扫描本地集合中的数据的逻辑计划节点*/
private[sql]
case class LogicalLocalTable(output: Seq[Attribute], rows: Seq[InternalRow])(sqlContext: SQLContext)
   extends LogicalPlan with MultiInstanceRelation {

  override def children: Seq[LogicalPlan] = Nil

  override def newInstance(): this.type =
    LogicalLocalTable(output.map(_.newInstance()), rows)(sqlContext).asInstanceOf[this.type]

  override def sameResult(plan: LogicalPlan): Boolean = plan match {
    case LogicalRDD(_, otherRDD) => rows == rows
    case _ => false
  }

  @transient override lazy val statistics: Statistics = Statistics(
    // TODO: Improve the statistics estimation.
    // This is made small enough so it can be broadcasted.
    sizeInBytes = sqlContext.conf.autoBroadcastJoinThreshold - 1
  )
}


text:
package ru.job4j2.strategy;

/**
 * Class Triangle.
 * @author vivanov
 * @version 1
 * @since 30.08.2017
 */

public class Triangle implements Shape {

    /**
     * Method pic - is used to build a shape picture.
     * @return result picture.
     */
    public String pic() {
        StringBuilder pic = new StringBuilder();
        pic.append("   +\n  +++\n +++++\n+++++++\n");
        return pic.toString();
    }
}


text:
package com.geth1b.coding.skills.lc;

/**
 *  [Reference URL]:  https://leetcode.com/problems/count-numbers-with-unique-digits/
 *      [Algorithm]:  DP / Math / Backtracking (#TODO)
 * [Data Structure]:  #TODO
 *      [Time BigO]:  O(n)
 *     [Space BigO]:  O(1)
 *
 * @author geth1b
 */
public class _357_CountNumbersWithUniqueDigits {

  // DP - n could recurse to n-1, ..., n=0 as base case
  //
  // O(n) time -- probably O(n) as it would be 0 after n > 9 (edge case)
  // O(1) space
  public int countNumbersWithUniqueDigits(int n) {
    if (n == 0) {
      return 1; // base case
    }
    int prev = 1;
    for (int i = 1; i <= n && i < 10; i++) { // no need to process n > 9 onwards; they are same as n = 9
      int curr = countUniqueWithLength(i);
      curr += prev; // include length < i
      prev = curr; // switch value for next iteration
    }
    return prev;
  }

  private int countUniqueWithLength(int k) { // k >= 1 here
    int result = 9; // first digit cannot be 0
    int x = 9;
    while (k-- > 1) {
      result *= x--;
    }
    return result;
  }

}


text:
using CDDotMe.Models;
using Microsoft.EntityFrameworkCore;

namespace CDDotMe.Data
{
    public class PortfolioContext : DbContext
    {
        public PortfolioContext(DbContextOptions<PortfolioContext> options) : base(options) { }

        public DbSet<Project> Projects { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Project>().ToTable("Project");
        }
    }
}


text:
using System;
using System.Web;

namespace AlchemyAPI
{

	///
	/// Enumeration that specifies what to extract from the text.
	/// Multiple extractions are specified via a bitmask.
	///
	/// e.g.
	/// If you want to get title, author, and taxonomy, it would look like:
	/// Extract::Title | Extract::Author | Extract::Taxonomy
	///
	public enum CombinedExtract
	{
		PageImage = 0x1,
		Entity = 0x2,
		Keyword = 0x4,
		Title = 0x8,
		Author = 0x10,
		Taxonomy = 0x20,
		Concept = 0x40,
		Relation = 0x80,
		DocSentiment = 0x100
	};

	public class AlchemyAPI_CombinedDataParams : AlchemyAPI_BaseParams
	{
		private PageImageMode? _imageMode;
		private CombinedExtract _extract;
		private string _jsonpCallback;
		private bool? _disambiguateEntities;
		private bool? _includeLinkedData;
		private bool? _coreference;
		private bool? _quotations;
		private bool? _sentiment;
		private bool? _showSourceText;
		private int? _maxRetrieve;
		private string _baseUrl;

		public CombinedExtract Extractions {
		get {
			return _extract;
		}
		set {
			_extract = value;
		}
		}
		public PageImageMode? ImageMode {
		get { return _imageMode; }
		set { _imageMode = value; }
		}

		public string JsonPCallback {
		get { return _jsonpCallback; }
		set { _jsonpCallback = value; }
		}

		public bool? DisambiguateEntities {
		get { return _disambiguateEntities; }
		set { _disambiguateEntities = value; }
		}

		public bool? IncludeLinkedData {
		get { return _includeLinkedData; }
		set { _includeLinkedData = value; }
		}

		public bool? Coreference {
		get { return _coreference; }
		set { _coreference = value; }
		}

		public bool? Quotations {
		get { return _quotations; }
		set { _quotations = value; }
		}

		public bool? Sentiment {
		get { return _sentiment; }
		set { _sentiment = value; }
		}

		public bool? ShowSourceText {
		get { return _showSourceText; }
		set { _showSourceText = value; }
		}

		public int? MaxRetrieve {
		get { return _maxRetrieve; }
		set { _maxRetrieve = value; }
		}

		public string BaseURL {
		get { return _baseUrl; }
		set { _baseUrl = value; }
		}

		public bool isExtracting (CombinedExtract type)
		{
			return (_extract & type) == type;
		}
		public AlchemyAPI_CombinedDataParams setExtraction(CombinedExtract type, bool doExtraction)
		{
			if (doExtraction)
				_extract |= type;
			else
				_extract &= ~type;
			return this;
		}

		public override string getParameterString ()
		{
			string retString = base.getParameterString ();

			retString += "&extract=" + getExtractionString();

			if (_imageMode != null)
				retString += "&extractMode=" + PageImageModeHelper.ToString(_imageMode.Value);

			if (_jsonpCallback != null)
				retString += "&jsonp=" + _jsonpCallback;

			if (_disambiguateEntities != null)
				retString += "&disambiguate=" + encodeBool(_disambiguateEntities);

			if (_includeLinkedData != null)
				retString += "&linkedData=" + encodeBool(_includeLinkedData);

			if (_coreference != null)
				retString += "&coreference=" + encodeBool(_coreference);

			if (_quotations != null)
				retString += "&quotations=" + encodeBool(_quotations);

			if (_sentiment != null)
				retString += "&sentiment=" + encodeBool(_sentiment);

			if (_showSourceText != null)
				retString += "&showSourceText=" + encodeBool(_showSourceText);

			if (_maxRetrieve != null)
				retString += "&maxRetrieve=" + _maxRetrieve;

			if (_baseUrl != null)
				retString += "&baseUrl=" + _baseUrl;

			return retString;
		}

		private string getExtractionString()
		{
			string ret = string.Empty;
			if (isExtracting(CombinedExtract.PageImage))
				ret += "page-image,";
			if (isExtracting(CombinedExtract.Entity))
				ret += "entity,";
			if (isExtracting(CombinedExtract.Keyword))
				ret += "keyword,";
			if (isExtracting(CombinedExtract.Title))
				ret += "title,";
			if (isExtracting(CombinedExtract.Author))
				ret += "author,";
			if (isExtracting(CombinedExtract.Taxonomy))
				ret += "taxonomy,";
			if (isExtracting(CombinedExtract.Concept))
				ret += "concept,";
			if (isExtracting(CombinedExtract.Relation))
				ret += "relation,";
			if (isExtracting(CombinedExtract.DocSentiment))
				ret += "doc-sentiment";

			// Trim the trailing comma
			if (ret.EndsWith(","))
				ret = ret.Remove(ret.Length - 1);

			if (ret.Length == 0)
				throw new ArgumentException("At least one extraction must be specified.");

			return ret;
		}
	}
}


text:
package org.kuali.kfs.module.ar.document.validation.event;

import org.kuali.kfs.module.ar.businessobject.CustomerCreditMemoDetail;
import org.kuali.kfs.module.ar.document.validation.RecalculateCustomerCreditMemoDetailRule;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.document.TransactionalDocument;
import org.kuali.rice.krad.rules.rule.BusinessRule;

public class RecalculateCustomerCreditMemoDetailEvent extends CustomerCreditMemoDetailEventBase {

    protected CustomerCreditMemoDetail customerCreditMemoDetail;

    public RecalculateCustomerCreditMemoDetailEvent(String errorPathPrefix, Document document, CustomerCreditMemoDetail customerCreditMemoDetail) {
        super("Recalculating customer credit memo detail for document " + getDocumentId(document), errorPathPrefix, document, customerCreditMemoDetail);
        this.customerCreditMemoDetail = customerCreditMemoDetail;
    }

    @SuppressWarnings("unchecked")
    public Class getRuleInterfaceClass() {
        return RecalculateCustomerCreditMemoDetailRule.class;
    }

    @SuppressWarnings("unchecked")
    public boolean invokeRuleMethod(BusinessRule rule) {
        return ((RecalculateCustomerCreditMemoDetailRule) rule).processRecalculateCustomerCreditMemoDetailRules((TransactionalDocument)document, customerCreditMemoDetail);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/qav_more_members_press" android:state_pressed="true"/>
    <item android:drawable="@drawable/qav_more_members_normal"></item>

</selector>


text:
#ifndef WorkerGlobalScopeProxyProvider_h
#define WorkerGlobalScopeProxyProvider_h

#include "platform/Supplementable.h"
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"

namespace blink {

class Page;
class WorkerGlobalScopeProxy;
class Worker;

class WorkerGlobalScopeProxyProvider : public WillBeHeapSupplement<Page> {
    WTF_MAKE_NONCOPYABLE(WorkerGlobalScopeProxyProvider);
public:
    WorkerGlobalScopeProxyProvider() { }
    virtual ~WorkerGlobalScopeProxyProvider() { }

    virtual WorkerGlobalScopeProxy* createWorkerGlobalScopeProxy(Worker*) = 0;

    static WorkerGlobalScopeProxyProvider* from(Page&);
    static const char* supplementName();
};

void provideWorkerGlobalScopeProxyProviderTo(Page&, PassOwnPtrWillBeRawPtr<WorkerGlobalScopeProxyProvider>);

} // namespace blink

#endif // WorkerGlobalScopeProxyProvider_h


text:
/*---------------------------------------------------------------------------*\

  FILE........: codec2_profile.c
  AUTHOR......: David Rowe
  DATE CREATED: 30 May 2013

  Profiling Codec 2 operation on the STM32F4.

\*---------------------------------------------------------------------------*/

/*
  Copyright (C) 2014 David Rowe

  All rights reserved.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License version 2.1, as
  published by the Free Software Foundation.  This program is
  distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with this program; if not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>

#include "stm32f4xx_conf.h"
#include "stm32f4xx.h"
#include "gdb_stdio.h"
#include "codec2.h"
#include "dump.h"
#include "sine.h"
#include "machdep.h"

#ifdef __EMBEDDED__
#define printf gdb_stdio_printf
#define fopen gdb_stdio_fopen
#define fclose gdb_stdio_fclose
#define fread gdb_stdio_fread
#define fwrite gdb_stdio_fwrite
#endif

static void c2demo(int mode, char inputfile[], char outputfile[])
{
    struct CODEC2 *codec2;
    short         *inbuf, *outbuf;
    unsigned char *bits;
    int            nsam, nbit;
    FILE          *fin, *fout;
    int            frame;
    PROFILE_VAR(enc_start, dec_start);

    codec2 = codec2_create(mode);
    nsam = codec2_samples_per_frame(codec2);
    outbuf = (short*)malloc(nsam*sizeof(short));
    inbuf = (short*)malloc(nsam*sizeof(short));
    nbit = codec2_bits_per_frame(codec2);
    bits = (unsigned char*)malloc(nbit*sizeof(char));

    fin = fopen(inputfile, "rb");
    if (fin == NULL) {
        printf("Error opening input file: %s\n\nTerminating....\n",inputfile);
        exit(1);
    }

    fout = fopen(outputfile, "wb");
    if (fout == NULL) {
        printf("Error opening output file: %s\n\nTerminating....\n",outputfile);
        exit(1);
    }

    #ifdef DUMP
    dump_on("stm32f4");
    #endif
    frame = 0;

    while (fread(inbuf, sizeof(short), nsam, fin) == nsam) {
        PROFILE_SAMPLE(enc_start);
        codec2_encode(codec2, bits, inbuf);
        PROFILE_SAMPLE_AND_LOG(dec_start, enc_start, "  enc");
	codec2_decode(codec2, outbuf, bits);
        PROFILE_SAMPLE_AND_LOG2(dec_start, "  dec");
        PROFILE_SAMPLE_AND_LOG2(enc_start, "  enc & dec");
        fwrite((char*)outbuf, sizeof(short), nsam, fout);
        printf("frame: %d\n", ++frame);
        machdep_profile_print_logged_samples();
    }

    #ifdef DUMP
    dump_off("sm32f4");
    #endif

    fclose(fin);
    fclose(fout);
    free(inbuf);
    free(outbuf);
    free(bits);
    codec2_destroy(codec2);
}

#define SPEED_TEST_SAMPLES 24000

static void c2speedtest(int mode, char inputfile[])
{
    struct CODEC2 *codec2;
    short         *inbuf, *outbuf, *pinbuf;
    unsigned char *bits;
    int            nsam, nbit, nframes;
    FILE          *fin;
    int            f, nread;

    codec2 = codec2_create(mode);
    nsam = codec2_samples_per_frame(codec2);
    nframes = SPEED_TEST_SAMPLES/nsam;
    outbuf = (short*)malloc(nsam*sizeof(short));
    inbuf = (short*)malloc(SPEED_TEST_SAMPLES*sizeof(short));
    nbit = codec2_bits_per_frame(codec2);
    bits = (unsigned char*)malloc(nbit*sizeof(char));

    fin = fopen(inputfile, "rb");
    if (fin == NULL) {
        printf("Error opening input file: %s\nTerminating....\n",inputfile);
        exit(1);
    }

    nread = fread(inbuf, sizeof(short), SPEED_TEST_SAMPLES, fin);
    if (nread != SPEED_TEST_SAMPLES) {
        printf("error reading %s, %d samples reqd, %d read\n",
               inputfile, SPEED_TEST_SAMPLES, nread);
    }
    fclose(fin);

    pinbuf = inbuf;
    for(f=0; f<nframes; f++) {
	GPIOD->ODR = (1 << 13);
        codec2_encode(codec2, bits, pinbuf);
        pinbuf += nsam;
	GPIOD->ODR &= ~(1 << 13);
	codec2_decode(codec2, outbuf, bits);
    }

    free(inbuf);
    free(outbuf);
    free(bits);
    codec2_destroy(codec2);
}

void gpio_init() {
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; // enable the clock to GPIOD
    GPIOD->MODER = (1 << 26);            // set pin 13 to be general
                                         // purpose output
}

int main(int argc, char *argv[]) {
    gpio_init();
    machdep_profile_init ();

    printf("Starting c2demo\n");

    /* File I/O test for profiling or (with #define DUMP)
       dumping states for optimisation and tiuning */

    c2demo(CODEC2_MODE_1600, "stm_in.raw", "stm_out.raw");

    printf("Starting c2 speed test\n");

    /* Another test of execution speed. Look at PD13 with a
       oscilliscope.  On time is enc, off is dec */

    c2speedtest(CODEC2_MODE_1600, "stm_in.raw");

    printf("Finished\n");

    return 0;
}


text:
This project build on Codeigniter 2.2

Developer: Tung Le Blogger http://tungle.vn

## Library ##

Use google-api-php-client on  https://github.com/google/google-api-php-client

Library google for Codeigniter: Application/libraries/google_library.php

Use library in controller: $this->load->library('google_library',NULL,'google');

## Youtube ##

Build youtube library: Application/libraries/google/youtube_google.php

User library youtube: $this->google->youtube->search($request);

View more on Application/controllers/google/youtube.php

Demo Search: http://api.tungle.vn/google/youtube/search?q=5s%20online&limit=20

Demo Video: http://api.tungle.vn/google/youtube/video?id=Ia1CbBKJI94