问:
OpenGL glGetUniformBlockIndex returns INVALID_INDEX on nvidea gpus's
I've been working on this opengl game engine for quite a while now, and I'm making a game in it as well with procedurally generated planets. However, I got some weird problems that I've been stuck on for 3 weeks now.

To generate the planets on the fly, I make use of a material consisting of a tesselation and geometry shader to do the generating in. This way, it's super fast. Now in the tessellation evaluation shader, I use a uniform buffer block to send the parameters for the planet generation to the gpu (which is I believe 48 bytes x number of noise layers).

Now all this works fine on my desktop PC which has a radeon r9 390, and also on my laptop which has a gtx 1060. However, on the following desktop gpu's i get an INVALID_INDEX when calling glGetUniformBlockIndex and obviously it doesn't work as it is trying to generate with incorrect parameters.
- gtx 1050
- gtx 1060
- gtx 960
- gtx 970
- rtx 2080

On the following gpu's everything is working fine with no errors:
- radeon r9 390
- rx 580
- hd 7770

I don't have any other gpus available to me to test any further.

Now after doing some research I know that there is a limit on how big your uniform buffer block can be, as well as how many and how many components you can have etc. However, considering I brought the max number of layers down to 1 and tested again, the problem still persisted. It also can't be a memory shortage issue because an hd 7770 has only 1 GB of vram, while a 1060 has between 4-6 GB of vram and it still happens on a 1060.

Another thing I found is that shader variables can be optimized out by the driver when the variable does not contribute to the output, and as you will be able to see from the shader code it deffinitely does contribute to the output.

So, onto some code

In the material class there is a CreateUniformBuffer function that gets the index of the uniform buffer block and binds it to a buffer allowing to edit it. Note that the program already crashes after getting INVALID_INDEX so getting the index must be where the issue lies.

```<code>GLuint Material::CreateUniformBuffer(const std::string& name, GLuint bufferSize)
{
    GLuint uniformBlockIndex = glGetUniformBlockIndex(m_pShader->m_ShaderProgramID, name.data());
    Utilities::Debug::LogGLError(glGetError());
    if (uniformBlockIndex == GL_INVALID_INDEX)
    {
        Utilities::Debug::LogError("Material::CreateUniformBuffer > Uniform buffer block with name " + name + " not found!");
        return 0;
    }

    Utilities::Debug::LogGLError(glGetError());
    glUniformBlockBinding(m_pShader->m_ShaderProgramID, uniformBlockIndex, m_BufferBindIndex);
    Utilities::Debug::LogGLError(glGetError());

    // Uniform buffer object for lights
    GLuint bufferID;
    glGenBuffers(1, &bufferID);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_UNIFORM_BUFFER, bufferID);
    Utilities::Debug::LogGLError(glGetError());
    glBufferData(GL_UNIFORM_BUFFER, bufferSize, NULL, GL_DYNAMIC_DRAW);
    Utilities::Debug::LogGLError(glGetError());
    glBindBufferBase(GL_UNIFORM_BUFFER, uniformBlockIndex, bufferID);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
    Utilities::Debug::LogGLError(glGetError());

    m_UniformBufferObjects.push_back(bufferID);

    ++m_BufferBindIndex;
    return bufferID;
}
</code>```

This is the tessellation evaluation shader, note that there is an #include "SimplexNoise" line at the top, which does not work in opengl, however, the engine has a precompiler stage for shaders where it reads through the shader code and replaces any #include directives with the contents of the file that its including before compiling the shader.

planet_te.shader

```<code>#version 450

#include "SimplexNoise.shader"

layout(triangles, equal_spacing, cw) in;
in vec3 tcPosition[];
out vec3 tePosition;
out float teElevation;

uniform int NumNoiseLayers;

struct NoiseLayer
{
    float Strength;
    float BaseRoughness;
    float Roughness;
    float Persistance;

    vec3 Center;
    float MinValue;

    int NumLayers;
    int UseFirstLayerAsMask;
    int NoiseFilterType;
    float Weight;
};

const int MaxNoiseLayers = 4;
layout(std140) uniform NoiseBlock
{
    NoiseLayer NoiseLayers[MaxNoiseLayers];
} _NoiseData;

float Evaluate(vec3 p, int layer)
{
    int filterType = _NoiseData.NoiseLayers[layer].NoiseFilterType;
    if (filterType == 0)
        return SimpleEvaluate(p, int(_NoiseData.NoiseLayers[layer].NumLayers), _NoiseData.NoiseLayers[layer].BaseRoughness, _NoiseData.NoiseLayers[layer].Roughness, _NoiseData.NoiseLayers[layer].Persistance, _NoiseData.NoiseLayers[layer].Center, _NoiseData.NoiseLayers[layer].MinValue, _NoiseData.NoiseLayers[layer].Strength);

    return RigidEvaluate(p, int(_NoiseData.NoiseLayers[layer].NumLayers), _NoiseData.NoiseLayers[layer].BaseRoughness, _NoiseData.NoiseLayers[layer].Roughness, _NoiseData.NoiseLayers[layer].Persistance, _NoiseData.NoiseLayers[layer].Center, _NoiseData.NoiseLayers[layer].MinValue, _NoiseData.NoiseLayers[layer].Strength, _NoiseData.NoiseLayers[layer].Weight);
}

float CalculateTotalStrength()
{
    float strength = 0.0;
    for (int i = 0; i < NumNoiseLayers; i++)
    {
        strength += _NoiseData.NoiseLayers[i].Strength;
    }
    return strength;
}

float LayeredEvaluate(vec3 p)
{
    float firstLayerValue = 0.0;
    float elevationAverage = 0.0;

    float totalStrength = CalculateTotalStrength();

    float unscaledElevation = 0.0;
    float scaledElevation = 0.0;

    float noiseValue = 0.0;
    float strengthPercentage = 0.0;
    if (NumNoiseLayers > 0)
    {
        unscaledElevation = Evaluate(p, 0);
        scaledElevation = max(0.0, unscaledElevation);
        noiseValue = scaledElevation;
        elevationAverage = unscaledElevation;
        firstLayerValue = noiseValue;
    }

    for (int i = 1; i < NumNoiseLayers; i++)
    {
        float mask = (_NoiseData.NoiseLayers[i].UseFirstLayerAsMask == 1) ? firstLayerValue : 1.0;
        unscaledElevation = Evaluate(p, 0);
        scaledElevation = max(0.0, unscaledElevation);
        elevationAverage += unscaledElevation;

        noiseValue += scaledElevation;
    }

    elevationAverage /= totalStrength;

    teElevation = clamp(elevationAverage * 115.0, -0.99, 0.99);

    return noiseValue;
}

void main()
{
    vec3 p0 = gl_TessCoord.x * tcPosition[0];
    vec3 p1 = gl_TessCoord.y * tcPosition[1];
    vec3 p2 = gl_TessCoord.z * tcPosition[2];
    tePosition = normalize(p0 + p1 + p2);
    float hieght = LayeredEvaluate(tePosition);
    gl_Position = vec4(tePosition * (1.0 + hieght), 1);
}
</code>```

SimplexNoise.shader

```<code>const int RandomSize = 256;
const float Sqrt3 = 1.7320508075688772935;
const float Sqrt5 = 2.2360679774997896964;
uniform int _random[512];

/// Skewing and unskewing factors for 2D, 3D and 4D,
/// some of them pre-multiplied.
const float F2 = 0.5 * (Sqrt3 - 1.0);
const float G2 = (3.0 - Sqrt3) / 6.0;
const float G22 = G2 * 2.0 - 1;
const float F3 = 1.0 / 3.0;
const float G3 = 1.0 / 6.0;
const float F4 = (Sqrt5 - 1.0) / 4.0;
const float G4 = (5.0 - Sqrt5) / 20.0;
const float G42 = G4 * 2.0;
const float G43 = G4 * 3.0;
const float G44 = G4 * 4.0 - 1.0;

const int[] Grad3 =
{
    1, 1, 0, -1, 1, 0, 1, -1, 0,
    -1, -1, 0, 1, 0, 1, -1, 0, 1,
    1, 0, -1, -1, 0, -1, 0, 1, 1,
    0, -1, 1, 0, 1, -1, 0, -1, -1
};

float Dot(int index, float x, float y, float z)
{
    return Grad3[index] * x + Grad3[index + 1] * y + Grad3[index + 2] * z;
}

float Dot(int index, float x, float y)
{
    return Grad3[index] * x + Grad3[index + 1] * y;
}

int FastFloor(float x)
{
    return int(x) >= 0 ? int(x) : int(x) - 1;
}

float Evaluate(vec3 p)
{
    float x = p.x;
    float y = p.y;
    float z = p.z;
    float n0 = 0.0, n1 = 0.0, n2 = 0.0, n3 = 0.0;

    // Noise contributions from the four corners
    // Skew the input space to determine which simplex cell we're in
    float s = (x + y + z) * F3;

    // for 3D
    int i = FastFloor(x + s);
    int j = FastFloor(y + s);
    int k = FastFloor(z + s);

    float t = (i + j + k) * G3;

    // The x,y,z distances from the cell origin
    float x0 = x - (i - t);
    float y0 = y - (j - t);
    float z0 = z - (k - t);

    // For the 3D case, the simplex shape is a slightly irregular tetrahedron.
    // Determine which simplex we are in.
    // Offsets for second corner of simplex in (i,j,k)
    int i1, j1, k1;

    // coords
    int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords

    if (x0 >= y0)
    {
        if (y0 >= z0)
        {
            // X Y Z order
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
        }
        else if (x0 >= z0)
        {
            // X Z Y order
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 0;
            k2 = 1;
        }
        else
        {
            // Z X Y order
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 1;
            j2 = 0;
            k2 = 1;
        }
    }
    else
    {
        // x0 < y0
        if (y0 < z0)
        {
            // Z Y X order
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 0;
            j2 = 1;
            k2 = 1;
        }
        else if (x0 < z0)
        {
            // Y Z X order
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 0;
            j2 = 1;
            k2 = 1;
        }
        else
        {
            // Y X Z order
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
        }
    }

    // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
    // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z),
    // and
    // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z),
    // where c = 1/6.

    // Offsets for second corner in (x,y,z) coords
    float x1 = x0 - i1 + G3;
    float y1 = y0 - j1 + G3;
    float z1 = z0 - k1 + G3;

    // Offsets for third corner in (x,y,z)
    float x2 = x0 - i2 + F3;
    float y2 = y0 - j2 + F3;
    float z2 = z0 - k2 + F3;

    // Offsets for last corner in (x,y,z)
    float x3 = x0 - 0.5;
    float y3 = y0 - 0.5;
    float z3 = z0 - 0.5;

    // Work out the hashed gradient indices of the four simplex corners
    int ii = i & 0xff;
    int jj = j & 0xff;
    int kk = k & 0xff;

    // Calculate the contribution from the four corners
    float t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;

    if (t0 > 0)
    {
        t0 *= t0;
        int gi0 = _random[ii + _random[jj + _random[kk]]] % 12;
        n0 = t0 * t0 * Dot(gi0 * 3, x0, y0, z0);
    }

    float t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
    if (t1 > 0)
    {
        t1 *= t1;
        int gi1 = _random[ii + i1 + _random[jj + j1 + _random[kk + k1]]] % 12;
        n1 = t1 * t1 * Dot(gi1 * 3, x1, y1, z1);
    }

    float t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
    if (t2 > 0)
    {
        t2 *= t2;
        int gi2 = _random[ii + i2 + _random[jj + j2 + _random[kk + k2]]] % 12;
        n2 = t2 * t2 * Dot(gi2 * 3, x2, y2, z2);
    }

    float t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
    if (t3 > 0)
    {
        t3 *= t3;
        int gi3 = _random[ii + 1 + _random[jj + 1 + _random[kk + 1]]] % 12;
        n3 = t3 * t3 * Dot(gi3 * 3, x3, y3, z3);
    }

    // Add contributions from each corner to get the final noise value.
    // The result is scaled to stay just inside [-1,1]
    return float(n0 + n1 + n2 + n3) * 32;
}

float Evaluate(vec3 p, float strength, float roughness, vec3 centre)
{
    float noise = (Evaluate(p * roughness + centre) + 1.0) * 0.5;
    return noise * strength;
}

float SimpleEvaluate(vec3 p, int numLayers, float baseRoughness, float roughness, float persistance, vec3 centre, float minValue, float strength)
{
    float noiseValue = 0.0;
    float frequency = baseRoughness;
    float amplitude = 1.0;

    for (int i = 0; i < numLayers; i++)
    {
        float v = Evaluate(p * frequency + centre);
        noiseValue += (v + 1) * 0.5 * amplitude;
        frequency *= roughness;
        amplitude *= persistance;
    }

    //noiseValue = max(0.0, noiseValue - minValue);
    return (noiseValue - minValue) * strength;
}

float RigidEvaluate(vec3 p, int numLayers, float baseRoughness, float roughness, float persistance, vec3 centre, float minValue, float strength, float weight)
{
    float noiseValue = 0.0;
    float frequency = baseRoughness;
    float amplitude = 1.0;
    weight = 1.0;

    for (int i = 0; i < numLayers; i++)
    {
        float v = 1.0 - abs(Evaluate(p * frequency + centre));
        v *= v;
        v *= weight;
        weight = v;
        noiseValue += v * amplitude;
        frequency *= roughness;
        amplitude *= persistance;
    }

    //noiseValue = max(0.0, noiseValue - minValue);
    return (noiseValue - minValue) * strength;
}
</code>```

Note that this is a noise algorithm I found online and converted it to glsl code (shoutout to Sebastian Lague for his amazing series on procedural planets in Unity)

I am using SDL to open a window and to handle input, audio and textrendering, OpenGL 4.6 and GLEW 2.1.0

Things I've tried:
- Lower the size of the block by lowering the number of layers (so a smaller array)
- A uniform array instead of a uniform block (same outcome only the crash is not there, but for gpus that had the crash it just renders all planets incorrectly)
- Updating SDL and all its plugins to the latest version, and updating OpenGL to 4.6 from 3.1, also updating GLEW from 1.10.0 to 2.1.0
- Changing the name of the uniform block
- Playing around with amount of values inside the block (while respecting the size having to be a multiplication of 4 floats)
- Having binding = 0 next to the std140 in the glsl code
- Logging any errors or warnings from shader compilation to the console (no errors or warnings found)

I have a bit of a deadline next friday to upload a build to steam, and they won't except it if it only works on amd gpu's (understandable off course) so I'm hoping someone has an idea of what I'm doing wrong here, or has had a similar issue before in the past, any help is welcome!

EDIT: I tried using an SSBO, this had a harsh impact on performance, and while it does not crash anymore (because I'm not looking for the block index by name) it does not render anything on nvidea gpu's and spit out Unknown Errors in the log file.

Code for binding the SSBO

```<code>GLuint Material::CreateShaderStorageBuffer(const std::string& name, GLsizeiptr bufferSize, const void* data, GLint bindingIndex, GLenum usage)
{
    GLuint ssbo;
    glGenBuffers(1, &ssbo);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
    Utilities::Debug::LogGLError(glGetError());
    glBufferData(GL_SHADER_STORAGE_BUFFER, bufferSize, data, usage);
    Utilities::Debug::LogGLError(glGetError());
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, bindingIndex, ssbo);
    Utilities::Debug::LogGLError(glGetError());

    /*GLuint blockIndex = glGetProgramResourceIndex(m_pShader->m_ShaderProgramID, GL_SHADER_STORAGE_BLOCK, name.c_str());
    Utilities::Debug::LogGLError(glGetError());

    if (blockIndex == GL_INVALID_INDEX)
    {
        Utilities::Debug::LogError("Material::CreateShaderStorageBuffer > Shader Storage Buffer Block with name " + name + " not found!");
        return 0;
    }

    glShaderStorageBlockBinding(m_pShader->m_ShaderProgramID, blockIndex, bindingIndex);
    Utilities::Debug::LogGLError(glGetError());*/

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, NULL);
    Utilities::Debug::LogGLError(glGetError());
    return ssbo;
}
</code>```

Code for setting SSBO data

```<code>void Material::WriteToShaderStorageBuffer(GLuint ssboID, const void* data, GLsizeiptr size)
{
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssboID);
    Utilities::Debug::LogGLError(glGetError());
    GLvoid* bufferData = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY);
    Utilities::Debug::LogGLError(glGetError());
    memcpy(bufferData, data, size);
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, NULL);
    Utilities::Debug::LogGLError(glGetError());
}
</code>```

The change in the shader to turn the uniform block into an SSBO

```<code>const int MaxNoiseLayers = 4;
layout(std430, binding = 0) buffer NoiseBlock
{
    NoiseLayer NoiseLayers[MaxNoiseLayers];
} _NoiseData;
</code>```

答:
I figured out that the issue was caused by the int array buffer _random[512] in the SimplexNoise shader file, I'm not sure why this was causing issues on only nvidea gpu's but I am assuming it was some kind of limit it was exceeding on nvideas gpus that caused the entire shader to break without any warnings or errors.

I fixed it by turning this array into another UBO and bind it to index 1.

Body:
I've been working on this opengl game engine for quite a while now, and I'm making a game in it as well with procedurally generated planets. However, I got some weird problems that I've been stuck on for 3 weeks now.

To generate the planets on the fly, I make use of a material consisting of a tesselation and geometry shader to do the generating in. This way, it's super fast. Now in the tessellation evaluation shader, I use a uniform buffer block to send the parameters for the planet generation to the gpu (which is I believe 48 bytes x number of noise layers).

Now all this works fine on my desktop PC which has a radeon r9 390, and also on my laptop which has a gtx 1060. However, on the following desktop gpu's i get an INVALID_INDEX when calling glGetUniformBlockIndex and obviously it doesn't work as it is trying to generate with incorrect parameters.
- gtx 1050
- gtx 1060
- gtx 960
- gtx 970
- rtx 2080

On the following gpu's everything is working fine with no errors:
- radeon r9 390
- rx 580
- hd 7770

I don't have any other gpus available to me to test any further.

Now after doing some research I know that there is a limit on how big your uniform buffer block can be, as well as how many and how many components you can have etc. However, considering I brought the max number of layers down to 1 and tested again, the problem still persisted. It also can't be a memory shortage issue because an hd 7770 has only 1 GB of vram, while a 1060 has between 4-6 GB of vram and it still happens on a 1060.

Another thing I found is that shader variables can be optimized out by the driver when the variable does not contribute to the output, and as you will be able to see from the shader code it deffinitely does contribute to the output.

So, onto some code

In the material class there is a CreateUniformBuffer function that gets the index of the uniform buffer block and binds it to a buffer allowing to edit it. Note that the program already crashes after getting INVALID_INDEX so getting the index must be where the issue lies.

GLuint Material::CreateUniformBuffer(const std::string& name, GLuint bufferSize)
{
    GLuint uniformBlockIndex = glGetUniformBlockIndex(m_pShader->m_ShaderProgramID, name.data());
    Utilities::Debug::LogGLError(glGetError());
    if (uniformBlockIndex == GL_INVALID_INDEX)
    {
        Utilities::Debug::LogError("Material::CreateUniformBuffer > Uniform buffer block with name " + name + " not found!");
        return 0;
    }

    Utilities::Debug::LogGLError(glGetError());
    glUniformBlockBinding(m_pShader->m_ShaderProgramID, uniformBlockIndex, m_BufferBindIndex);
    Utilities::Debug::LogGLError(glGetError());

    // Uniform buffer object for lights
    GLuint bufferID;
    glGenBuffers(1, &bufferID);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_UNIFORM_BUFFER, bufferID);
    Utilities::Debug::LogGLError(glGetError());
    glBufferData(GL_UNIFORM_BUFFER, bufferSize, NULL, GL_DYNAMIC_DRAW);
    Utilities::Debug::LogGLError(glGetError());
    glBindBufferBase(GL_UNIFORM_BUFFER, uniformBlockIndex, bufferID);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
    Utilities::Debug::LogGLError(glGetError());

    m_UniformBufferObjects.push_back(bufferID);

    ++m_BufferBindIndex;
    return bufferID;
}

This is the tessellation evaluation shader, note that there is an #include "SimplexNoise" line at the top, which does not work in opengl, however, the engine has a precompiler stage for shaders where it reads through the shader code and replaces any #include directives with the contents of the file that its including before compiling the shader.

planet_te.shader

#version 450

#include "SimplexNoise.shader"

layout(triangles, equal_spacing, cw) in;
in vec3 tcPosition[];
out vec3 tePosition;
out float teElevation;

uniform int NumNoiseLayers;

struct NoiseLayer
{
    float Strength;
    float BaseRoughness;
    float Roughness;
    float Persistance;

    vec3 Center;
    float MinValue;

    int NumLayers;
    int UseFirstLayerAsMask;
    int NoiseFilterType;
    float Weight;
};

const int MaxNoiseLayers = 4;
layout(std140) uniform NoiseBlock
{
    NoiseLayer NoiseLayers[MaxNoiseLayers];
} _NoiseData;

float Evaluate(vec3 p, int layer)
{
    int filterType = _NoiseData.NoiseLayers[layer].NoiseFilterType;
    if (filterType == 0)
        return SimpleEvaluate(p, int(_NoiseData.NoiseLayers[layer].NumLayers), _NoiseData.NoiseLayers[layer].BaseRoughness, _NoiseData.NoiseLayers[layer].Roughness, _NoiseData.NoiseLayers[layer].Persistance, _NoiseData.NoiseLayers[layer].Center, _NoiseData.NoiseLayers[layer].MinValue, _NoiseData.NoiseLayers[layer].Strength);

    return RigidEvaluate(p, int(_NoiseData.NoiseLayers[layer].NumLayers), _NoiseData.NoiseLayers[layer].BaseRoughness, _NoiseData.NoiseLayers[layer].Roughness, _NoiseData.NoiseLayers[layer].Persistance, _NoiseData.NoiseLayers[layer].Center, _NoiseData.NoiseLayers[layer].MinValue, _NoiseData.NoiseLayers[layer].Strength, _NoiseData.NoiseLayers[layer].Weight);
}

float CalculateTotalStrength()
{
    float strength = 0.0;
    for (int i = 0; i < NumNoiseLayers; i++)
    {
        strength += _NoiseData.NoiseLayers[i].Strength;
    }
    return strength;
}

float LayeredEvaluate(vec3 p)
{
    float firstLayerValue = 0.0;
    float elevationAverage = 0.0;

    float totalStrength = CalculateTotalStrength();

    float unscaledElevation = 0.0;
    float scaledElevation = 0.0;

    float noiseValue = 0.0;
    float strengthPercentage = 0.0;
    if (NumNoiseLayers > 0)
    {
        unscaledElevation = Evaluate(p, 0);
        scaledElevation = max(0.0, unscaledElevation);
        noiseValue = scaledElevation;
        elevationAverage = unscaledElevation;
        firstLayerValue = noiseValue;
    }

    for (int i = 1; i < NumNoiseLayers; i++)
    {
        float mask = (_NoiseData.NoiseLayers[i].UseFirstLayerAsMask == 1) ? firstLayerValue : 1.0;
        unscaledElevation = Evaluate(p, 0);
        scaledElevation = max(0.0, unscaledElevation);
        elevationAverage += unscaledElevation;

        noiseValue += scaledElevation;
    }

    elevationAverage /= totalStrength;

    teElevation = clamp(elevationAverage * 115.0, -0.99, 0.99);

    return noiseValue;
}

void main()
{
    vec3 p0 = gl_TessCoord.x * tcPosition[0];
    vec3 p1 = gl_TessCoord.y * tcPosition[1];
    vec3 p2 = gl_TessCoord.z * tcPosition[2];
    tePosition = normalize(p0 + p1 + p2);
    float hieght = LayeredEvaluate(tePosition);
    gl_Position = vec4(tePosition * (1.0 + hieght), 1);
}

SimplexNoise.shader

const int RandomSize = 256;
const float Sqrt3 = 1.7320508075688772935;
const float Sqrt5 = 2.2360679774997896964;
uniform int _random[512];

/// Skewing and unskewing factors for 2D, 3D and 4D,
/// some of them pre-multiplied.
const float F2 = 0.5 * (Sqrt3 - 1.0);
const float G2 = (3.0 - Sqrt3) / 6.0;
const float G22 = G2 * 2.0 - 1;
const float F3 = 1.0 / 3.0;
const float G3 = 1.0 / 6.0;
const float F4 = (Sqrt5 - 1.0) / 4.0;
const float G4 = (5.0 - Sqrt5) / 20.0;
const float G42 = G4 * 2.0;
const float G43 = G4 * 3.0;
const float G44 = G4 * 4.0 - 1.0;

const int[] Grad3 =
{
    1, 1, 0, -1, 1, 0, 1, -1, 0,
    -1, -1, 0, 1, 0, 1, -1, 0, 1,
    1, 0, -1, -1, 0, -1, 0, 1, 1,
    0, -1, 1, 0, 1, -1, 0, -1, -1
};

float Dot(int index, float x, float y, float z)
{
    return Grad3[index] * x + Grad3[index + 1] * y + Grad3[index + 2] * z;
}

float Dot(int index, float x, float y)
{
    return Grad3[index] * x + Grad3[index + 1] * y;
}

int FastFloor(float x)
{
    return int(x) >= 0 ? int(x) : int(x) - 1;
}

float Evaluate(vec3 p)
{
    float x = p.x;
    float y = p.y;
    float z = p.z;
    float n0 = 0.0, n1 = 0.0, n2 = 0.0, n3 = 0.0;

    // Noise contributions from the four corners
    // Skew the input space to determine which simplex cell we're in
    float s = (x + y + z) * F3;

    // for 3D
    int i = FastFloor(x + s);
    int j = FastFloor(y + s);
    int k = FastFloor(z + s);

    float t = (i + j + k) * G3;

    // The x,y,z distances from the cell origin
    float x0 = x - (i - t);
    float y0 = y - (j - t);
    float z0 = z - (k - t);

    // For the 3D case, the simplex shape is a slightly irregular tetrahedron.
    // Determine which simplex we are in.
    // Offsets for second corner of simplex in (i,j,k)
    int i1, j1, k1;

    // coords
    int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords

    if (x0 >= y0)
    {
        if (y0 >= z0)
        {
            // X Y Z order
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
        }
        else if (x0 >= z0)
        {
            // X Z Y order
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 0;
            k2 = 1;
        }
        else
        {
            // Z X Y order
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 1;
            j2 = 0;
            k2 = 1;
        }
    }
    else
    {
        // x0 < y0
        if (y0 < z0)
        {
            // Z Y X order
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 0;
            j2 = 1;
            k2 = 1;
        }
        else if (x0 < z0)
        {
            // Y Z X order
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 0;
            j2 = 1;
            k2 = 1;
        }
        else
        {
            // Y X Z order
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
        }
    }

    // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
    // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z),
    // and
    // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z),
    // where c = 1/6.

    // Offsets for second corner in (x,y,z) coords
    float x1 = x0 - i1 + G3;
    float y1 = y0 - j1 + G3;
    float z1 = z0 - k1 + G3;

    // Offsets for third corner in (x,y,z)
    float x2 = x0 - i2 + F3;
    float y2 = y0 - j2 + F3;
    float z2 = z0 - k2 + F3;

    // Offsets for last corner in (x,y,z)
    float x3 = x0 - 0.5;
    float y3 = y0 - 0.5;
    float z3 = z0 - 0.5;

    // Work out the hashed gradient indices of the four simplex corners
    int ii = i & 0xff;
    int jj = j & 0xff;
    int kk = k & 0xff;

    // Calculate the contribution from the four corners
    float t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;

    if (t0 > 0)
    {
        t0 *= t0;
        int gi0 = _random[ii + _random[jj + _random[kk]]] % 12;
        n0 = t0 * t0 * Dot(gi0 * 3, x0, y0, z0);
    }

    float t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
    if (t1 > 0)
    {
        t1 *= t1;
        int gi1 = _random[ii + i1 + _random[jj + j1 + _random[kk + k1]]] % 12;
        n1 = t1 * t1 * Dot(gi1 * 3, x1, y1, z1);
    }

    float t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
    if (t2 > 0)
    {
        t2 *= t2;
        int gi2 = _random[ii + i2 + _random[jj + j2 + _random[kk + k2]]] % 12;
        n2 = t2 * t2 * Dot(gi2 * 3, x2, y2, z2);
    }

    float t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
    if (t3 > 0)
    {
        t3 *= t3;
        int gi3 = _random[ii + 1 + _random[jj + 1 + _random[kk + 1]]] % 12;
        n3 = t3 * t3 * Dot(gi3 * 3, x3, y3, z3);
    }

    // Add contributions from each corner to get the final noise value.
    // The result is scaled to stay just inside [-1,1]
    return float(n0 + n1 + n2 + n3) * 32;
}

float Evaluate(vec3 p, float strength, float roughness, vec3 centre)
{
    float noise = (Evaluate(p * roughness + centre) + 1.0) * 0.5;
    return noise * strength;
}

float SimpleEvaluate(vec3 p, int numLayers, float baseRoughness, float roughness, float persistance, vec3 centre, float minValue, float strength)
{
    float noiseValue = 0.0;
    float frequency = baseRoughness;
    float amplitude = 1.0;

    for (int i = 0; i < numLayers; i++)
    {
        float v = Evaluate(p * frequency + centre);
        noiseValue += (v + 1) * 0.5 * amplitude;
        frequency *= roughness;
        amplitude *= persistance;
    }

    //noiseValue = max(0.0, noiseValue - minValue);
    return (noiseValue - minValue) * strength;
}

float RigidEvaluate(vec3 p, int numLayers, float baseRoughness, float roughness, float persistance, vec3 centre, float minValue, float strength, float weight)
{
    float noiseValue = 0.0;
    float frequency = baseRoughness;
    float amplitude = 1.0;
    weight = 1.0;

    for (int i = 0; i < numLayers; i++)
    {
        float v = 1.0 - abs(Evaluate(p * frequency + centre));
        v *= v;
        v *= weight;
        weight = v;
        noiseValue += v * amplitude;
        frequency *= roughness;
        amplitude *= persistance;
    }

    //noiseValue = max(0.0, noiseValue - minValue);
    return (noiseValue - minValue) * strength;
}

Note that this is a noise algorithm I found online and converted it to glsl code (shoutout to Sebastian Lague for his amazing series on procedural planets in Unity)

I am using SDL to open a window and to handle input, audio and textrendering, OpenGL 4.6 and GLEW 2.1.0

Things I've tried:
- Lower the size of the block by lowering the number of layers (so a smaller array)
- A uniform array instead of a uniform block (same outcome only the crash is not there, but for gpus that had the crash it just renders all planets incorrectly)
- Updating SDL and all its plugins to the latest version, and updating OpenGL to 4.6 from 3.1, also updating GLEW from 1.10.0 to 2.1.0
- Changing the name of the uniform block
- Playing around with amount of values inside the block (while respecting the size having to be a multiplication of 4 floats)
- Having binding = 0 next to the std140 in the glsl code
- Logging any errors or warnings from shader compilation to the console (no errors or warnings found)

I have a bit of a deadline next friday to upload a build to steam, and they won't except it if it only works on amd gpu's (understandable off course) so I'm hoping someone has an idea of what I'm doing wrong here, or has had a similar issue before in the past, any help is welcome!

EDIT: I tried using an SSBO, this had a harsh impact on performance, and while it does not crash anymore (because I'm not looking for the block index by name) it does not render anything on nvidea gpu's and spit out Unknown Errors in the log file.

Code for binding the SSBO

GLuint Material::CreateShaderStorageBuffer(const std::string& name, GLsizeiptr bufferSize, const void* data, GLint bindingIndex, GLenum usage)
{
    GLuint ssbo;
    glGenBuffers(1, &ssbo);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
    Utilities::Debug::LogGLError(glGetError());
    glBufferData(GL_SHADER_STORAGE_BUFFER, bufferSize, data, usage);
    Utilities::Debug::LogGLError(glGetError());
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, bindingIndex, ssbo);
    Utilities::Debug::LogGLError(glGetError());

    /*GLuint blockIndex = glGetProgramResourceIndex(m_pShader->m_ShaderProgramID, GL_SHADER_STORAGE_BLOCK, name.c_str());
    Utilities::Debug::LogGLError(glGetError());

    if (blockIndex == GL_INVALID_INDEX)
    {
        Utilities::Debug::LogError("Material::CreateShaderStorageBuffer > Shader Storage Buffer Block with name " + name + " not found!");
        return 0;
    }

    glShaderStorageBlockBinding(m_pShader->m_ShaderProgramID, blockIndex, bindingIndex);
    Utilities::Debug::LogGLError(glGetError());*/

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, NULL);
    Utilities::Debug::LogGLError(glGetError());
    return ssbo;
}

Code for setting SSBO data

void Material::WriteToShaderStorageBuffer(GLuint ssboID, const void* data, GLsizeiptr size)
{
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssboID);
    Utilities::Debug::LogGLError(glGetError());
    GLvoid* bufferData = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_WRITE_ONLY);
    Utilities::Debug::LogGLError(glGetError());
    memcpy(bufferData, data, size);
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
    Utilities::Debug::LogGLError(glGetError());
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, NULL);
    Utilities::Debug::LogGLError(glGetError());
}

The change in the shader to turn the uniform block into an SSBO

const int MaxNoiseLayers = 4;
layout(std430, binding = 0) buffer NoiseBlock
{
    NoiseLayer NoiseLayers[MaxNoiseLayers];
} _NoiseData;


来源: stackexchange

问:
Why MongoDB adding extra slash to path?
Good evening for everyone, I have some trouble with saving my url to mongodb database as string. Because mongo adding extra slash to every part of url. Like this:
"localhost:3333\uploads\Untitled1.cpp"
but in my console log I have normal result(look at the terminal in the screenshot). Whyy? Please, help

```<code>let storage = multer.diskStorage({
    destination: (req, file, cb) =>{
        cb(null, '/uploads')
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
})

let upload = multer({ storage: storage })
let type = upload.single('myFile');

app.post('/upload', type, (req, res) => {
    const url = `http://localhost:3333${req.file.path}`;
    const image = {
        name: req.file.originalname,
        url: url
    }
    console.log(image.url)
    const newImage = new Image(image);
    newImage.save()
        .then (res.json('Картинку додано'))
        .catch(err => res.status(400).json(err));
});
</code>```

答:
I have found the solution. What you need to do is when you are posting/saving your file into db there you need to use replace function and then your path will be saved with forward slash into your DB.

Here is the snippet:

```<code>app.post('/upload', upload.single('file'), (req, res, next) => {
  const file = new Cluster1({
    filePath: req.file.path.replace(/\\/g, '/'),
    name: req.file.originalname
  });
  file.save()
</code>```

You can see how I am using the replace fucntion to avoid \\ or \

ContentLicense: CC BY-SA 4.0

Title: Why MongoDB adding extra slash to path?

Body:
Good evening for everyone, I have some trouble with saving my url to mongodb database as string. Because mongo adding extra slash to every part of url. Like this:
"localhost:3333\uploads\Untitled1.cpp"
but in my console log I have normal result(look at the terminal in the screenshot). Whyy? Please, help

let storage = multer.diskStorage({
    destination: (req, file, cb) =>{
        cb(null, '/uploads')
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
})

let upload = multer({ storage: storage })
let type = upload.single('myFile');

app.post('/upload', type, (req, res) => {
    const url = `http://localhost:3333${req.file.path}`;
    const image = {
        name: req.file.originalname,
        url: url
    }
    console.log(image.url)
    const newImage = new Image(image);
    newImage.save()
        .then (res.json('Картинку додано'))
        .catch(err => res.status(400).json(err));
});

Body:
I have found the solution. What you need to do is when you are posting/saving your file into db there you need to use replace function and then your path will be saved with forward slash into your DB.

Here is the snippet:

app.post('/upload', upload.single('file'), (req, res, next) => {
  const file = new Cluster1({
    filePath: req.file.path.replace(/\\/g, '/'),
    name: req.file.originalname
  });
  file.save()

You can see how I am using the replace fucntion to avoid \\ or \


问:
Does exist a similar REPL for JavaScript in the browser, like Pry for Ruby development?
I experienced that the Pry introspection gem https://github.com/pry/pry for Ruby makes the program develompent easier a lot: one can stop the program at a given point with the statement "binding.pry", it gives a console, where I can introspect the values of the variables, which are existing that point. Would be so helpfil such a tool for JavaScript too, in the browser. To debug the programs, as it is so easy to make mistakes, which are then barely recognizable.</p>

答: If you've been developing without such a tool thus far I commend you-- that sounds painful.  In chrome, F12 or Menu > More Tools > Developer Tools will open the Chrome Dev Tools.  There is a fully featured debugger in which you can set breakpoints, or you can simply put a debugger statement directly in your code to have it pause.  These tools are robust, mature, and built into every modern browser (although note that different browsers will have different ways in which to access them).  The Console tool acts as more of a REPL, if that's what you desire; plus, it gets the environment of the current scope in which the debugger is paused, so you can use it to inspect variables, etc.  Good luck!


问:
How do I match numbers and create 2-dimensional array?
I have an array like so [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7]

How can I turn it into a 2-dimensional array that's based on matching numbers before the decimal?

ex.[[1.2, 1.3, 1.4], [2.2, 2.3], [3.0], [4.3, 4.4, 4.5, 4.6, 4.7]]

答:
Since it's always sorted, you can use this imperative approach:

const arr = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];

let curr = -Infinity;
let currArr = null;
const res = [];

for (let n of arr) {
  if (Math.trunc(n) > curr) {
    res.push(currArr = [curr = n]);
  } else {
    currArr.push(n);
  }
}

console.log(res);```

It just tracks the latest number, and its current sub-array. If the next integer is greater than the current number, it creates a new array, otherwise it pushes into the current sub-array.

Some may not like using the result of an assignment as a value. If not, it can easily be reworked with a couple extra lines of code.

Body:
Since it's always sorted, you can use this imperative approach:

const arr = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];

let curr = -Infinity;
let currArr = null;
const res = [];

for (let n of arr) {
  if (Math.trunc(n) > curr) {
    res.push(currArr = [curr = n]);
  } else {
    currArr.push(n);
  }
}

console.log(res);

It just tracks the latest number, and its current sub-array. If the next integer is greater than the current number, it creates a new array, otherwise it pushes into the current sub-array.

Some may not like using the result of an assignment as a value. If not, it can easily be reworked with a couple extra lines of code.


问:
Django vs Flask - Which framework is more powerful considering I want to design an end to end IOT solution
Planning to build an end to end IOT application. I know that we can do it using Django and Flask. Which one is a better choice and how it is better?</p>

答:
I was in your position 2 months ago. Let me save you some trouble.

Flask may seem the more flexible or direct path as it is easy to have something up and running in moments. Whereas Django, at times, can feel like an entirely different language, and takes much more time and effort to get running. Still, the problem lies in getting everything to play nicely with flask and other packages. This will be tricky and Django shines in this area. Once the project is rolling, it just works, and generally continues to do so unless the packages utilized in your app become deprecated or you break it.

Both are viable but any project of scale will be better off being maintained by Django while you focus on implementation. Good luck.


问:
html css tabs handle clips and sizes of tabs
I want to use tabs that I made with HTML and CSS only I don't use javascript at all, but I have some issues that I can not fix .. so I need your help.
so I got two questions I hope that I will be clear and you understand my problems :

how can I fix the problem of tabs clip when I resize the screen(or use phone)

can I sperate the tabs on the ALL contact block without care of tabs numbers?

here the code
    http://jsfiddle.net/waL0d6gu/

.tabss {
  position: relative;
  min-height: 200px;
  clear: both;
  margin: 25px 0;

}
.tabb {
  float: left;
  margin-right:3px;

}
.tabb label {
  background: #eee;
  padding: 7px;
  border: 1px solid #ccc;
  margin-left: -1px;
  position: relative;
  left: 1px;
  border-radius: 15px 15px 0px 0px;
  padding-left: 50px;
  padding-right: 50px;
  cursor: pointer;

}
.tabb [type=radio] {
  display: none;

}
.contentt {

  position: absolute;
  top: 28px;
  left: 0;
  background: #11426f;
  padding: 20px;
  border: 1px solid #ccc;
  display:none;
  min-width:700px;
  color:white;
}
[type=radio]:checked ~ label {
  background: #11426f;
  border-bottom: 1px solid #11426f;
  color:white;
  z-index: 2;
  padding-left: 75px;
  padding-right: 75px;

}
[type=radio]:checked ~ label ~ .contentt {
  display:block;
  border-radius: 0px 15px 15px 15px;
  width:95%

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tabss">
<div class="tabb"><input type="radio" id="tab-1" name="tab-group-1" checked="checked" /> <label for="tab-1"><i class="fas fa-dollar-sign"></i><span> </span>aaaaa</label>
<div class="clear"></div>
<div class="contentt">[[aaaaa]]</div>
</div>
<div class="tabb"><input type="radio" id="tab-2" name="tab-group-1" /> <label for="tab-2"><i class="fa fa-truck"></i> bbbbb</label>
<div class="contentt">[[bbbb]]</div>
</div>
<div class="tabb"><input type="radio" id="tab-3" name="tab-group-1" /> <label for="tab-3"><i class="fa fa-info-circle"></i><span> </span>dddddd</label>
<div class="contentt">[[dddddd]]</div>
<div class="tabb"><input type="radio" id="tab-4" name="tab-group-1" /> <label for="tab-4"><i class="fas fa-undo"></i> cccccc</label>
<div class="contentt">[[cccccc]]</div>
</div></code>```

答:
What CanUver said is correct, css media queries can be set to whichever device display you want, for example this certain view would work on devices with a 1920x1080 display ONLY. Or else you could use the bootstrap framework, however im not sure if they cater for resizing of anything unrelated to what they provide.

```<code><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
</code>```

Put these in your  element, and make sure to put the bootstrap link before any other link in the  element as stated by the bootstrap site itself. Should work I think :)

Body:
I want to use tabs that I made with HTML and CSS only I don't use javascript at all, but I have some issues that I can not fix .. so I need your help.
so I got two questions I hope that I will be clear and you understand my problems :

how can I fix the problem of tabs clip when I resize the screen(or use phone)

can I sperate the tabs on the ALL contact block without care of tabs numbers?

here the code
    http://jsfiddle.net/waL0d6gu/

.tabss {
  position: relative;
  min-height: 200px;
  clear: both;
  margin: 25px 0;

}
.tabb {
  float: left;
  margin-right:3px;

}
.tabb label {
  background: #eee;
  padding: 7px;
  border: 1px solid #ccc;
  margin-left: -1px;
  position: relative;
  left: 1px;
  border-radius: 15px 15px 0px 0px;
  padding-left: 50px;
  padding-right: 50px;
  cursor: pointer;

}
.tabb [type=radio] {
  display: none;

}
.contentt {

  position: absolute;
  top: 28px;
  left: 0;
  background: #11426f;
  padding: 20px;
  border: 1px solid #ccc;
  display:none;
  min-width:700px;
  color:white;
}
[type=radio]:checked ~ label {
  background: #11426f;
  border-bottom: 1px solid #11426f;
  color:white;
  z-index: 2;
  padding-left: 75px;
  padding-right: 75px;

}
[type=radio]:checked ~ label ~ .contentt {
  display:block;
  border-radius: 0px 15px 15px 15px;
  width:95%

}

<input type="radio" id="tab-1" name="tab-group-1" checked="checked" />  aaaaa

[[aaaaa]]

<input type="radio" id="tab-2" name="tab-group-1" />  bbbbb

[[bbbb]]

<input type="radio" id="tab-3" name="tab-group-1" />  dddddd

[[dddddd]]

<input type="radio" id="tab-4" name="tab-group-1" />  cccccc

[[cccccc]]

Body:
What CanUver said is correct, css media queries can be set to whichever device display you want, for example this certain view would work on devices with a 1920x1080 display ONLY. Or else you could use the bootstrap framework, however im not sure if they cater for resizing of anything unrelated to what they provide.

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

Put these in your <head> element, and make sure to put the bootstrap link before any other link in the <head> element as stated by the bootstrap site itself. Should work I think :)


问:
After upgrade MacOS terminal showing: zsh: command not found: flutter
Recently I updated Mac OS to latest Catalina. Now my terminal which is using zsh and showing me following error:

```<code>zsh: command not found: flutter
</code>```

It was working fine before update.

答:
I tried installing flutter on my MAC according to the advice here, but it still doesn't work, after searching for it I found an article here.

So, I change my .zshrc file to:

```<code>export PATH="$PATH:/Users/YOUR_PROVILE_NAME/YOUR_DEVELOPMENT_FOLDER/flutter/bin"
</code>```

Change YOUR_PROVILE_NAME to your name profile, also YOUR_DEVELOPMENT_FOLDER to your development folder for flutter

and now it's working.

Note:
I use Catalina OS v10.15.4

Body:
Recently I updated Mac OS to latest Catalina. Now my terminal which is using zsh and showing me following error:

zsh: command not found: flutter

It was working fine before update.

Body:
I tried installing flutter on my MAC according to the advice here, but it still doesn't work, after searching for it I found an article here.

So, I change my .zshrc file to:

export PATH="$PATH:/Users/YOUR_PROVILE_NAME/YOUR_DEVELOPMENT_FOLDER/flutter/bin"

Change YOUR_PROVILE_NAME to your name profile, also YOUR_DEVELOPMENT_FOLDER to your development folder for flutter

and now it's working.

Note:
I use Catalina OS v10.15.4


问:
Hystrix fallback method not called if Feign Client manually created with Feign.Builder
I am trying to create a Feign client that has a fallback method in case of failure.

By following examples i created a simple Feign Client:

```<code>@Component
@FeignClient(value = "authenticationClient", fallback = AuthenticationClientFallback.class)
public interface AuthenticationClient
{
@RequestMapping(method = RequestMethod.GET, value = "/auth/userinfo")
UserInfoResource getUserInfo(@RequestHeader("Authorization") String token);

@RequestMapping(method = RequestMethod.GET, value = "/auth/token")
TokenResource getToken(@RequestHeader("Authorization") String basicAuth);
</code>```

}

The AuthenticaionClientFallback class is following:

```<code> @Component
    public class AuthenticationClientFallback implements AuthenticationClient
    {
        public static final String NO_TOKEN = "No Token";

        @Override
        public UserInfoResource getUserInfo(String token)
        {
            return null;
        }

        @Override
        public TokenResource getToken(String basicAuth)
        {
            return new TokenResource(NO_TOKEN);
        }
}
</code>```

When i use my client with the @Autowire annotation, the fallback gets triggered. But i have a need to create my own feign client instance so i can dynamically set the URL.

Initialization of the AuthenticationClient:

```<code>public AuthenticationClient getAuthenticationClient()
    {
        return HystrixFeign.builder().contract(new SpringMvcContract())
                 .encoder(new JacksonEncoder())
                 .decoder(new JacksonDecoder())
                 .client(new OkHttpClient())
                 .logger(new Slf4jLogger(AuthenticationClient.class))
                 .logLevel(Logger.Level.FULL).target(AuthenticationClient.class, getTargetURL());
    }
</code>```

And now my fallback methods never get called, just a FeignException is thrown with a message that a 401 status code is returned.

PS i have set feign.hystrix.enabled=true in .yml file and @EnableCircuitBreaker on app level.

答:
I think you have mixed the 2 feign client initialization methods; the declarative and manual initializations. You need to stick to one method.

If you are using the declarative initialization; you can use the @FeignClient annotation with the fallback like below;

```<code>@FeignClient(value = "authenticationClient", url = "${feign.url}", fallback = AuthenticationClientFallback.class)
public interface AuthenticationClient
</code>```

And you can autowire the feign client in your components like this.

```<code>@Autowired
AuthenticationClient client;
</code>```

If you are using the manual initialization of feign clients with some customizations; then you don't have to use @FeignClient annotation on AuthenticationClient class. You can create your customized feign clients like below;

```<code>@Autowired
AuthenticationClientFallback fallbackClient;

public AuthenticationClient getAuthenticationClient()
    {
        return HystrixFeign.builder().contract(new SpringMvcContract())
                 .encoder(new JacksonEncoder())
                 .decoder(new JacksonDecoder())
                 .client(new OkHttpClient())
                 .logger(new Slf4jLogger(AuthenticationClient.class))
                 .logLevel(Logger.Level.FULL).target(AuthenticationClient.class, getTargetURL(), fallbackClient);
    }
</code>```

Please note that the fallbackClient object is passed in the .target() as an argument.

For more details refer the Spring cloud feign documentation

Body:
I am trying to create a Feign client that has a fallback method in case of failure.

By following examples i created a simple Feign Client:

@Component
@FeignClient(value = "authenticationClient", fallback = AuthenticationClientFallback.class)
public interface AuthenticationClient
{
@RequestMapping(method = RequestMethod.GET, value = "/auth/userinfo")
UserInfoResource getUserInfo(@RequestHeader("Authorization") String token);

@RequestMapping(method = RequestMethod.GET, value = "/auth/token")
TokenResource getToken(@RequestHeader("Authorization") String basicAuth);

}

The AuthenticaionClientFallback class is following:

 @Component
    public class AuthenticationClientFallback implements AuthenticationClient
    {
        public static final String NO_TOKEN = "No Token";

        @Override
        public UserInfoResource getUserInfo(String token)
        {
            return null;
        }

        @Override
        public TokenResource getToken(String basicAuth)
        {
            return new TokenResource(NO_TOKEN);
        }
}

When i use my client with the @Autowire annotation, the fallback gets triggered. But i have a need to create my own feign client instance so i can dynamically set the URL.

Initialization of the AuthenticationClient:

public AuthenticationClient getAuthenticationClient()
    {
        return HystrixFeign.builder().contract(new SpringMvcContract())
                 .encoder(new JacksonEncoder())
                 .decoder(new JacksonDecoder())
                 .client(new OkHttpClient())
                 .logger(new Slf4jLogger(AuthenticationClient.class))
                 .logLevel(Logger.Level.FULL).target(AuthenticationClient.class, getTargetURL());
    }

And now my fallback methods never get called, just a FeignException is thrown with a message that a 401 status code is returned.

PS i have set feign.hystrix.enabled=true in .yml file and @EnableCircuitBreaker on app level.

Body:
I think you have mixed the 2 feign client initialization methods; the declarative and manual initializations. You need to stick to one method.

If you are using the declarative initialization; you can use the @FeignClient annotation with the fallback like below;

@FeignClient(value = "authenticationClient", url = "${feign.url}", fallback = AuthenticationClientFallback.class)
public interface AuthenticationClient

And you can autowire the feign client in your components like this.

@Autowired
AuthenticationClient client;

If you are using the manual initialization of feign clients with some customizations; then you don't have to use @FeignClient annotation on AuthenticationClient class. You can create your customized feign clients like below;

@Autowired
AuthenticationClientFallback fallbackClient;

public AuthenticationClient getAuthenticationClient()
    {
        return HystrixFeign.builder().contract(new SpringMvcContract())
                 .encoder(new JacksonEncoder())
                 .decoder(new JacksonDecoder())
                 .client(new OkHttpClient())
                 .logger(new Slf4jLogger(AuthenticationClient.class))
                 .logLevel(Logger.Level.FULL).target(AuthenticationClient.class, getTargetURL(), fallbackClient);
    }

Please note that the fallbackClient object is passed in the .target() as an argument.

For more details refer the Spring cloud feign documentation


问:
Best practice for removing Mesh objects in ThreeJS?
What are some common ways in ThreeJS to work with creating Meshes (consisting of Geometry and Materials) and then later deleting those objects?

My use case is to display lat/long points on a rotating 3D globe. Each point should be clickable and show further information. The points displayed should also be able to change based on data that is binded with Vue.

I currently use something like this but am running into memory leak issues:

var material = new THREE.MeshPhongMaterial({
  color: 0xdc143c,
});

var cone = new THREE.Mesh(
  new THREE.ConeBufferGeometry(radius, height, 8, 1, true),
  material
);
cone.position.y = height * 0.5;
cone.rotation.x = Math.PI;

var sphere = new THREE.Mesh(
  new THREE.SphereBufferGeometry(sphereRadius, 16, 8),
  material
);

export default class Marker extends THREE.Object3D {
  constructor() {
    super();
    this.name = "Marker";
    this.add(cone, sphere);
  }

  destroy() {
    this.remove(cone, sphere);
  }
}
```

Are there libraries on top of Three that makes the management of Meshes/Materials/Geometry more simple to work with?

答:
What I do is create a function in some utils file, and any time I need to dispose of a mesh, I pass the mesh in as the function parameter:</p>

```<code>    const removeMesh = (meshToRemove) => {

  meshToRemove.visible = false;
  scene.remove(meshToRemove);
  meshToRemove.geometry.dispose();
  meshToRemove.material.dispose();
  meshToRemove= undefined;

}
</code>```

Body:
What are some common ways in ThreeJS to work with creating Meshes (consisting of Geometry and Materials) and then later deleting those objects?

My use case is to display lat/long points on a rotating 3D globe. Each point should be clickable and show further information. The points displayed should also be able to change based on data that is binded with Vue.

I currently use something like this but am running into memory leak issues:

var material = new THREE.MeshPhongMaterial({
  color: 0xdc143c,
});

var cone = new THREE.Mesh(
  new THREE.ConeBufferGeometry(radius, height, 8, 1, true),
  material
);
cone.position.y = height * 0.5;
cone.rotation.x = Math.PI;

var sphere = new THREE.Mesh(
  new THREE.SphereBufferGeometry(sphereRadius, 16, 8),
  material
);

export default class Marker extends THREE.Object3D {
  constructor() {
    super();
    this.name = "Marker";
    this.add(cone, sphere);
  }

  destroy() {
    this.remove(cone, sphere);
  }
}

Are there libraries on top of Three that makes the management of Meshes/Materials/Geometry more simple to work with?

Body:
What I do is create a function in some utils file, and any time I need to dispose of a mesh, I pass the mesh in as the function parameter:

    const removeMesh = (meshToRemove) => {

  meshToRemove.visible = false;
  scene.remove(meshToRemove);
  meshToRemove.geometry.dispose();
  meshToRemove.material.dispose();
  meshToRemove= undefined;

}


问:
Rails: I'm having a problem with inherited associations
Here's the problem I'm having:
https://gist.github.com/1003813

or

Say you have a derived class:

```<code>class User < ActiveRecord::Base
 include ThisThing
 include ThatThing

 [...]

end

class OurUser < User
 set_table_name 'users'

 [...]

end
</code>```

I need some associations, for example:

```<code>belongs_to :friend,
        :class_name => 'User',
        :foreign_key => :friend_of
</code>```

The problem is that if this is declared in the User class, the friend of an OurUser will be a User, and will not have any of the extra methods included in OurUser. And of course you don't know the correct class name when the User class is written.

I need some suggestons on how I can make it so OurUser will have a .friend of the correct class

答:
Create a module with all the shared behaviour and use the Module#included hook to define your associations dynamically at include. i.e.:</p>

```<code>module SharedBehaviour
  def self.included(base)
    base.class_eval do
      set_table_name 'users'

      belongs_to :friend, :class_name => base.name, :foreign_key => :friend_of

      include ThisThing
      include ThatThing

      # other class method calls go here (validations, etc)
    end
  end

  module ClassMethods
    # shared class methods go here
  end

  # shared instance methods go here
end

class User < ActiveRecord::Base
  inclde SharedBehaviour
end

class OtherUser < ActiveRecord::Base
  include SharedBehaviour
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's the problem I'm having:
https://gist.github.com/1003813

or

Say you have a derived class:

class User < ActiveRecord::Base
 include ThisThing
 include ThatThing

 [...]

end

class OurUser < User
 set_table_name 'users'

 [...]

end

I need some associations, for example:

belongs_to :friend,
        :class_name => 'User',
        :foreign_key => :friend_of

The problem is that if this is declared in the User class, the friend of an OurUser will be a User, and will not have any of the extra methods included in OurUser. And of course you don't know the correct class name when the User class is written.

I need some suggestons on how I can make it so OurUser will have a .friend of the correct class

Body:
Create a module with all the shared behaviour and use the Module#included hook to define your associations dynamically at include. i.e.:

module SharedBehaviour
  def self.included(base)
    base.class_eval do
      set_table_name 'users'

      belongs_to :friend, :class_name => base.name, :foreign_key => :friend_of

      include ThisThing
      include ThatThing

      # other class method calls go here (validations, etc)
    end
  end

  module ClassMethods
    # shared class methods go here
  end

  # shared instance methods go here
end

class User < ActiveRecord::Base
  inclde SharedBehaviour
end

class OtherUser < ActiveRecord::Base
  include SharedBehaviour
end


问:
In Javascript: Can you convert a if/else statement to a switch?
I tried to convert my working If/ Else statement in Javascript to a Switch Statement. However I could not get the Switch Statement to work for some reason. Is this possible/did I something wrong/ syntax error?  I have included the code below: Can someone clarify this for me, thanks.

Working If/Else statement:

```<code>
function displayCityInfo() {
    var cd = document.getElementById("cityData").value;
    var h2 = document.getElementById("main");

    switch(cd){
      var spacing = "";
      case 1:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + ", latitude is " + cities[i].latitude + "<p>";
      }
      h2.innerHTML = "<h2>Results</h2>" + spacing;

        break;

      case 2:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + " population is " + cities[i].population + "<p>";
      }
      h2.innerHTML = "<h2>Results</h2>" + spacing;

      break;

      case 3:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].elevation
          + ", latitude is " + cities[i].elevation + "<p>";
      }
      h2.innerHTML = "<h2>Results</h2>" + spacing;

      break;

    }

}
</code>```

Javascript Switch statement that is not working:

```<code>
function displayCityInfo() {
    var cd = document.getElementById("cityData").value;
    var h2 = document.getElementById("main");

    switch(cd){
      var spacing = "";
      case 1:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + ", latitude is " + cities[i].latitude + "<p>";
      }
      h2.innerHTML = "<h2>Results</h2>" + spacing;

        break;

      case 2:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + " population is " + cities[i].population + "<p>";
      }
      h2.innerHTML = "<h2>Results</h2>" + spacing;

      break;

      case 3:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].elevation
          + ", latitude is " + cities[i].elevation + "<p>";
      }
      h2.innerHTML = "<h2>Results</h2>" + spacing;

      break;

    }

}
</code>```

答: Switch statement except case or default after initiating switch. Which means you can't put var spacing = ""; below switch(cd){. Declare the variable above the switch.

Body:
I tried to convert my working If/ Else statement in Javascript to a Switch Statement. However I could not get the Switch Statement to work for some reason. Is this possible/did I something wrong/ syntax error?  I have included the code below: Can someone clarify this for me, thanks.

Working If/Else statement:

function displayCityInfo() {
    var cd = document.getElementById("cityData").value;
    var h2 = document.getElementById("main");

    switch(cd){
      var spacing = "";
      case 1:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + ", latitude is " + cities[i].latitude + "
";
      }
      h2.innerHTML = "
Results
" + spacing;

        break;

      case 2:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + " population is " + cities[i].population + "
";
      }
      h2.innerHTML = "
Results
" + spacing;

      break;

      case 3:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].elevation
          + ", latitude is " + cities[i].elevation + "
";
      }
      h2.innerHTML = "
Results
" + spacing;

      break;

    }

}

Javascript Switch statement that is not working:

function displayCityInfo() {
    var cd = document.getElementById("cityData").value;
    var h2 = document.getElementById("main");

    switch(cd){
      var spacing = "";
      case 1:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + ", latitude is " + cities[i].latitude + "
";
      }
      h2.innerHTML = "
Results
" + spacing;

        break;

      case 2:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].city
          + " population is " + cities[i].population + "
";
      }
      h2.innerHTML = "
Results
" + spacing;

      break;

      case 3:

      for(i=0; i<cities.length; i++){
          spacing += "City of " + cities[i].elevation
          + ", latitude is " + cities[i].elevation + "
";
      }
      h2.innerHTML = "
Results
" + spacing;

      break;

    }

}


问:
Path of current working directory
I installed clisp on windows. I want to load a file but I can't. I do not know what is my current working directory. How can I see it and change it? Thanks in advance</p>

答:
try to use default-pathname-defaults

```<code>(print *default-pathname-defaults*)
</code>```

or load-pathname

```<code>(print *load-pathname*)
</code>```

Title: Path of current working directory

Body:
try to use default-pathname-defaults

(print *default-pathname-defaults*)

or load-pathname

(print *load-pathname*)


答:
Just use default, like this:

```<code>switch(x){
  case 1:
    //do stuff
  break;
  default:
    //do the stuff that you would do in the else block
  break;
}
</code>```

Note: I'm not sure why you would use this over if/else, but you could add onto it, like:

```<code>  case 1:
    //do stuff
  break;
  case 2:
    //do other stuff
  break;
  default:
    //do the stuff that you would do in the else block
  break;
</code>```

Title: In Javascript: Can you convert a if/else statement to a switch?

Body:
Just use default, like this:

switch(x){
  case 1:
    //do stuff
  break;
  default:
    //do the stuff that you would do in the else block
  break;
}

Note: I'm not sure why you would use this over if/else, but you could add onto it, like:

  case 1:
    //do stuff
  break;
  case 2:
    //do other stuff
  break;
  default:
    //do the stuff that you would do in the else block
  break;


问:
django i18n: Make sure you have GNU gettext tools
I try django-admin.py makemessages -l zh_CN but has error :

```<code>CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.
</code>```

after I use brew install gettext,it still get wrong.

Do I need to do something? here is my terminal screenshot

Please guide me thank you.

答:
Just below solution solved my problem. I am using Windows 10 64bit

1- Go to this link :
https://mlocati.github.io/articles/gettext-iconv-windows.html

2- Download 32 or 64 bit shared and static windows installation files

3-Install both of files

4-Restart your computer

Body:
I try django-admin.py makemessages -l zh_CN but has error :

CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.

after I use brew install gettext,it still get wrong.

Do I need to do something? here is my terminal screenshot

Please guide me thank you.


问:
How to use group by and sum in Mongoose?
I have a JSON array that contains objects like this one

```<code> {
            "InvoiceNo": "FA 2019/1",
            "Period": "01",
            "DocumentTotals": {
                "TaxPayable": "26.94",
                "NetTotal": "117.16",
                "GrossTotal": "144.10"
            },
            "WithholdingTax": {
                "WithholdingTaxAmount": "0.00"
            }
        },
</code>```

I want to sum the GrossTotal of the various objects and group it by Period.
I tried with the following code:

```<code>saftFileController.revenuePerMonth = function (req, res) {
  Saft.find().exec(function (err, fileContent) {
    if (err) {
      console.log(err);
    } else {
      const JSONObject = JSON.parse(JSON.stringify(fileContent));
      const sales = JSONObject[3].SalesInvoices.Invoice;
      const revenuePerMonth = Saft.aggregate([
        {
          $group: {
            Period: sales.Period,
            revenue: {
              $sum: "$GrossTotal",
            },
          },
        },
      ]);
      res.json({ revenue: revenuePerMonth });
    }
  });
};
</code>```

But the output wasn´t the desired one. What I am doing wrong? This was the output:

```<code>{
    "revenue": {
        "_pipeline": [
            {
                "$group": {
                    "revenue": {
                        "$sum": "$GrossTotal"
                    }
                }
            }
        ],
        "options": {}
    }
}
</code>```

Here are some printscreens of my Database

https://snipboard.io/QOfiYz.jpg

https://snipboard.io/72LSRC.jpg

Did this and now returns the Period but it is ignoring the sum because it is a string type.How can I convert?

```<code>saftFileController.revenuePerMonth = function (req, res) {
  Saft.aggregate([
    {
      $group: {
        _id: "$SalesInvoices.Invoice.Period",
        revenue: {
          $sum: "SalesInvoices.Invoice.DocumentTotals.GrossTotal",
        },
      },
    },
  ]).exec(function (err, fileContent) {
    if (err) {
      console.log("Error: ", error);
    } else {
      res.json({ revenuePerMonth: fileContent });
    }
  });
};
</code>```

答:
You should pass the MongoDB expression what you want to group it by as _id in the $group stage (documentation). The $sum expression should contain the full path as well.

```<code>          $group: {
            _id: '$Period',
            revenue: {
              $sum: "$DocumentTotals.GrossTotal",
            },
          },
</code>```

aggregate accepts a callback, or returns a Promise just like when you use Saft.find()

```<code>Saft.aggregate([/* ... */]).exec(function (err, result) {
  /* use result here */
})
</code>```

Body:
I have a JSON array that contains objects like this one

 {
            "InvoiceNo": "FA 2019/1",
            "Period": "01",
            "DocumentTotals": {
                "TaxPayable": "26.94",
                "NetTotal": "117.16",
                "GrossTotal": "144.10"
            },
            "WithholdingTax": {
                "WithholdingTaxAmount": "0.00"
            }
        },

I want to sum the GrossTotal of the various objects and group it by Period.
I tried with the following code:

saftFileController.revenuePerMonth = function (req, res) {
  Saft.find().exec(function (err, fileContent) {
    if (err) {
      console.log(err);
    } else {
      const JSONObject = JSON.parse(JSON.stringify(fileContent));
      const sales = JSONObject[3].SalesInvoices.Invoice;
      const revenuePerMonth = Saft.aggregate([
        {
          $group: {
            Period: sales.Period,
            revenue: {
              $sum: "$GrossTotal",
            },
          },
        },
      ]);
      res.json({ revenue: revenuePerMonth });
    }
  });
};

But the output wasn´t the desired one. What I am doing wrong? This was the output:

{
    "revenue": {
        "_pipeline": [
            {
                "$group": {
                    "revenue": {
                        "$sum": "$GrossTotal"
                    }
                }
            }
        ],
        "options": {}
    }
}

Here are some printscreens of my Database

https://snipboard.io/QOfiYz.jpg

https://snipboard.io/72LSRC.jpg

Did this and now returns the Period but it is ignoring the sum because it is a string type.How can I convert?

saftFileController.revenuePerMonth = function (req, res) {
  Saft.aggregate([
    {
      $group: {
        _id: "$SalesInvoices.Invoice.Period",
        revenue: {
          $sum: "SalesInvoices.Invoice.DocumentTotals.GrossTotal",
        },
      },
    },
  ]).exec(function (err, fileContent) {
    if (err) {
      console.log("Error: ", error);
    } else {
      res.json({ revenuePerMonth: fileContent });
    }
  });
};

Body:
You should pass the MongoDB expression what you want to group it by as _id in the $group stage (documentation). The $sum expression should contain the full path as well.

          $group: {
            _id: '$Period',
            revenue: {
              $sum: "$DocumentTotals.GrossTotal",
            },
          },

aggregate accepts a callback, or returns a Promise just like when you use Saft.find()

Saft.aggregate([/* ... */]).exec(function (err, result) {
  /* use result here */
})


问:
Setting template parameter default value
I have written this class :

```<code>class Queue<T> {
    var value: T
    var next: Queue<T>?

    init(_ items: Any...)
    {
        self.value = items[0]
    }

</code>```

However I was wondering is there a way to implement the constructor  by setting some default value for the parameter "value".I know if I decalre it as "  var value: T?" it will be ok , but is there any "hacky" solution with the current code in the constructor to set some default value, it doesn't matter what it is , cause I want to make object like this : var obj = Queue() , cause currently Queue() crashes

答:
If you are certain that you will set the value and would rather not deal with Optionals, you could use a ! to declare an implicitly unwrapped optional

```<code>class Queue<T> {
   var value: T!

   // ...
}
</code>```

Here's more on this on docs.swift.org

Body:
I have written this class :

class Queue<T> {
    var value: T
    var next: Queue<T>?

    init(_ items: Any...)
    {
        self.value = items[0]
    }

However I was wondering is there a way to implement the constructor  by setting some default value for the parameter "value".I know if I decalre it as "  var value: T?" it will be ok , but is there any "hacky" solution with the current code in the constructor to set some default value, it doesn't matter what it is , cause I want to make object like this : var obj = Queue() , cause currently Queue() crashes

Body:
If you are certain that you will set the value and would rather not deal with Optionals, you could use a ! to declare an implicitly unwrapped optional

class Queue<T> {
   var value: T!

   // ...
}

Here's more on this on docs.swift.org


问:
Typescript annotation error for default React Native app?
When creating a fresh React Native project and opening the default app.js file in VSCode, this line;

const App: () => React$Node = () => {

returns

Type annotations can only be used in TypeScript files.

as a VSCode problem.

Am I suppose to have typescript installed with React Native, or is this some kind of other issue with VSCode or something? Surely React Native isn't releasing their default app.js file with an error.

Here's the contents of the problem.

```<code>{
    "resource": "/d:/App/sw_lbi_app/App.js",
    "owner": "typescript",
    "code": "8010",
    "severity": 8,
    "message": "Type annotations can only be used in TypeScript files.",
    "source": "ts",
    "startLineNumber": 27,
    "startColumn": 12,
    "endLineNumber": 27,
    "endColumn": 28
}
</code>```

答:
```<code>const App: () => React$Node = () => {
</code>```

Type annotations can only be used in TypeScript files.

In case you want to leave this line of Facebook's code to stay peacefully in Microsoft's VS Code, there is a Setting switch to turn off the TypeScript-style validation in a .js file.

Open Preferences => Settings, search javascript.validate, and locate

Uncheck it, and re-open App.js file. The validation will be gone.

PS: There is an option to make this setting change in User scope or Workspace scope.

Body:
When creating a fresh React Native project and opening the default app.js file in VSCode, this line;

const App: () => React$Node = () => {

returns

Type annotations can only be used in TypeScript files.

as a VSCode problem.

Am I suppose to have typescript installed with React Native, or is this some kind of other issue with VSCode or something? Surely React Native isn't releasing their default app.js file with an error.

Here's the contents of the problem.

{
    "resource": "/d:/App/sw_lbi_app/App.js",
    "owner": "typescript",
    "code": "8010",
    "severity": 8,
    "message": "Type annotations can only be used in TypeScript files.",
    "source": "ts",
    "startLineNumber": 27,
    "startColumn": 12,
    "endLineNumber": 27,
    "endColumn": 28
}

Body:
const App: () => React$Node = () => {

Type annotations can only be used in TypeScript files.

In case you want to leave this line of Facebook's code to stay peacefully in Microsoft's VS Code, there is a Setting switch to turn off the TypeScript-style validation in a .js file.

Open Preferences => Settings, search javascript.validate, and locate

Uncheck it, and re-open App.js file. The validation will be gone.

PS: There is an option to make this setting change in User scope or Workspace scope.


问:
Having trouble with Bootstrap 4 dropdown menu
For some reason, my dropdown menu doesn't function in bootstrap4. I have jquery, bootstrap, and I'm not totally sure if popper was properly imported. Was wondering if anyone could point me as to if I did something wrong.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Learning BootStrap</title>

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <script src="js/jquery.min.js"  ></script>

    <script src="js/bootstrap.min.js" ></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"> </script>

</head>

<body>

<p class="lead text-center">This is my website.</p>
<div class="dropdown">

<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Menu</button/>
    <div class="dropdown-menu">

        <a href="#" class="dropdown-item">first link</a>
        <a href="#" class="dropdown-item">second link</a>
        <a href="#" class="dropdown-item">third link</a>

</div>
</div>

</body>
</html>
</code>```

答:
Swap the order of your bootstrap and popper.js script tags, so bootstrap is the very last to load.

jquery

popper.js

bootstrap

Body:
For some reason, my dropdown menu doesn't function in bootstrap4. I have jquery, bootstrap, and I'm not totally sure if popper was properly imported. Was wondering if anyone could point me as to if I did something wrong.

<!DOCTYPE html>

    <title>Learning BootStrap</title>

    <link rel="stylesheet" href="css/bootstrap.min.css">

This is my website.

<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Menu</button/>

        first link
        second link
        third link


问:
extend functionality of UIAlertView?
I am using a UIAlertView with a message Peer Disconnected.Back ground works/remaining codes are working without dismiss it.there is a button called Continue. I need to work the remaining codes only after the continue button click.
and also I need to Quit my application in cancel button click.can any one tell me a good way to do it.

My Code is:

```<code>UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];
</code>```

答:
You can call UIAlertView's delegate method explained below......

```<code> - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
 {
      if (buttonIndex == 0) {
          //Your Code   //For First Button
      } else if (buttonIndex == 1) {
          //Your Code   //For Second Button
      }
 }
</code>```

Please follow this Link to quit the application

Title: extend functionality of UIAlertView?

Body:
I am using a UIAlertView with a message Peer Disconnected.Back ground works/remaining codes are working without dismiss it.there is a button called Continue. I need to work the remaining codes only after the continue button click.
and also I need to Quit my application in cancel button click.can any one tell me a good way to do it.

My Code is:

UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];

Body:
You can call UIAlertView's delegate method explained below......

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
 {
      if (buttonIndex == 0) {
          //Your Code   //For First Button
      } else if (buttonIndex == 1) {
          //Your Code   //For Second Button
      }
 }

Please follow this Link to quit the application


问:
Problem with the readline() function in r
I want to take user input into a variable and display it on the screen. However, when I try to take the input using the readline() function it works fine sometimes but not always. Sometimes, I run into the error as below:

So, is there any other function that can take in the user input like the input() function in python.

The code which I have tried is as follows:

```<code>my.name <- readline(prompt="Enter name: ")
my.age <- readline(prompt="Enter age: ")
# convert character into integer
my.age <- as.integer(my.age)
print(paste("Hi,", my.name, "next year you will be", my.age+1, "years old."))
</code>```

Could someone please help me out with this?

答: Are you using RStudio?  If so, the issue is likely due to an incompatibility between your versions of R and RStudio and the solution would be to update your version of RStudio. </p>

Body:
I want to take user input into a variable and display it on the screen. However, when I try to take the input using the readline() function it works fine sometimes but not always. Sometimes, I run into the error as below:

So, is there any other function that can take in the user input like the input() function in python.

The code which I have tried is as follows:

my.name <- readline(prompt="Enter name: ")
my.age <- readline(prompt="Enter age: ")
# convert character into integer
my.age <- as.integer(my.age)
print(paste("Hi,", my.name, "next year you will be", my.age+1, "years old."))

Could someone please help me out with this?


问:
How Change Hue of Javascript/Html Canvas Image
I have a spritesheet image made up of 16*16 tiles. I already have a good loading system and I have handled drawing them without losing the aspect ratio. The problem is that I want to get a 16 * 16 tile of that sheet, copy it, and change the hue of the new image by some amount.

I think I have copying working, but here is all my code

```<code>let temp = document.createElement('canvas').getContext('2d');

temp.drawImage('spritesheet.png',0,0)

let pixels = temp.getImageData(0, 0, 16,16);

//manipulate them so that the hue is changed (can't find code for)

let Shifted = new Image();
Shifted.src = temp.canvas.toDataUrl("image/png");

</code>```

答:
This QA can be useful (explaining how to change the image colors). Otherwise a canvas filter can be applied to the image, this article demonstrate it in details. </p>

<p>Example from the linked howto: </p>

```<code>var gradientColors = createGradient('#0096ff', '#ff00f0');
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
applyGradient(imageData.data);

for (var i = 0; i < data.length; i += 4) {
  // Get the each channel color value
  var redValue = data[i];
  var greenValue = data[i+1];
  var blueValue = data[i+2];

  // Mapping the color values to the gradient index
  // Replacing the grayscale color value with a color for the duotone gradient
  data[i] = gradientColors[redValue].r;
  data[i+1] = gradientColors[greenValue].g;
  data[i+2] = gradientColors[blueValue].b;
  data[i+3] = 255;
}
</code>```

Body:
I have a spritesheet image made up of 16*16 tiles. I already have a good loading system and I have handled drawing them without losing the aspect ratio. The problem is that I want to get a 16 * 16 tile of that sheet, copy it, and change the hue of the new image by some amount.

I think I have copying working, but here is all my code

let temp = document.createElement('canvas').getContext('2d');

temp.drawImage('spritesheet.png',0,0)

let pixels = temp.getImageData(0, 0, 16,16);

//manipulate them so that the hue is changed (can't find code for)

let Shifted = new Image();
Shifted.src = temp.canvas.toDataUrl("image/png");

Body:
This QA can be useful (explaining how to change the image colors). Otherwise a canvas filter can be applied to the image, this article demonstrate it in details.

Example from the linked howto:

var gradientColors = createGradient('#0096ff', '#ff00f0');
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
applyGradient(imageData.data);

for (var i = 0; i < data.length; i += 4) {
  // Get the each channel color value
  var redValue = data[i];
  var greenValue = data[i+1];
  var blueValue = data[i+2];

  // Mapping the color values to the gradient index
  // Replacing the grayscale color value with a color for the duotone gradient
  data[i] = gradientColors[redValue].r;
  data[i+1] = gradientColors[greenValue].g;
  data[i+2] = gradientColors[blueValue].b;
  data[i+3] = 255;
}


问:
xsl: split and get the X position of param
xsl: I need to split and get the X position param, @class attribute 2nd param:

Input XML:

```<code><root>
    <div class="zone zona_central ui-sortable">
        <div class="region contenedor_3col ui-sortable">
            <div style="position: relative; left: 0px; top: 0px;" class="destacado">
                <p class="id_contenido">567662</p>
                <p class="tipo_contenido">destacado</p>
                <p class="titulo">destacado: Home Actualidad ES</p>
            </div>
        </div>
    </div>
</root>
</code>```

output XML that I NEED:

```<code><zone type="zona_central">
    <region type="contenedor_3col">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>
</code>```

i have this xsl:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <zone style="">
            <xsl:for-each select="div[contains(@class, 'region')]">
                <region style="">
                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </region>
            </xsl:for-each>
        </zone>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

output XML that I HAVE with previous XSL, i don't know how i can get second param of CLASS ATTRIBUTE :(

```<code><zone type="">
    <region type="">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>
</code>```

Solution:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <xsl:element name="zone">
            <xsl:attribute name="type">
                <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
            </xsl:attribute>
            <xsl:for-each select="div[contains(@class, 'region')]">
                <xsl:element name="region">
                    <xsl:attribute name="type">
                        <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
                    </xsl:attribute>

                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </xsl:element>
            </xsl:for-each>
        </xsl:element>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

答:
A more generic XSLT 1.0 solution with templates.

```<code><xsl:template match="root">
  <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="*[@class]">
  <xsl:variable name="name">
    <xsl:choose>
      <xsl:when test="contains(@class, ' ')">
        <xsl:value-of select="substring-before(@class, ' ')"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="@class"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <xsl:variable name="type">
    <xsl:variable name="tail" select="substring-after(@class, ' ')"/>
    <xsl:choose>
      <xsl:when test="contains($tail, ' ')">
        <xsl:value-of select="substring-before($tail, ' ')"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$tail"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <xsl:element name="{$name}">
    <xsl:if test="string($type)">
      <xsl:attribute name="type">
        <xsl:value-of select="$type"/>
      </xsl:attribute>
    </xsl:if>
    <xsl:apply-templates/>
  </xsl:element>
</xsl:template>
</code>```

If you have elements other than root that do not have a class attribute, add a template for them.

XSLT 2.0 solution is:

```<code><xsl:template match="root">
  <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="*[@class]">
  <xsl:variable name="class" select="tokenize(@class, '\s')"/>
  <xsl:element name="{$class[1]}">
    <xsl:if test="count($class) > 1">
      <xsl:attribute name="type" select="$class[2]"/>
    </xsl:if>
    <xsl:apply-templates/>
  </xsl:element>
</xsl:template>
</code>```

Body:
xsl: I need to split and get the X position param, @class attribute 2nd param:

Input XML:

<root>

567662

destacado

destacado: Home Actualidad ES

</root>

output XML that I NEED:

<zone type="zona_central">
    <region type="contenedor_3col">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>

i have this xsl:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <zone style="">
            <xsl:for-each select="div[contains(@class, 'region')]">
                <region style="">
                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </region>
            </xsl:for-each>
        </zone>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

output XML that I HAVE with previous XSL, i don't know how i can get second param of CLASS ATTRIBUTE :(

<zone type="">
    <region type="">
        <destacado>
            <id_contenido>567662</id_contenido>
            <tipo_contenido>destacado</tipo_contenido>
            <titulo>destacado: Home Actualidad ES</titulo>
        </destacado>
    </region>
</zone>

Solution:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
    <xsl:for-each select="div[contains(@class, 'zone')]">
        <xsl:element name="zone">
            <xsl:attribute name="type">
                <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
            </xsl:attribute>
            <xsl:for-each select="div[contains(@class, 'region')]">
                <xsl:element name="region">
                    <xsl:attribute name="type">
                        <xsl:value-of select="substring-before(substring-after(@class, ' '), ' ')"/>
                    </xsl:attribute>

                    <xsl:for-each select="div[contains(@class, 'destacado')]">
                        <destacado>
                            <id_contenido><xsl:value-of select="p[@class='id_contenido']"/></id_contenido>
                            <tipo_contenido><xsl:value-of select="p[@class='tipo_contenido']"/></tipo_contenido>
                            <titulo><xsl:value-of select="p[@class='titulo']"/></titulo>
                        </destacado>
                    </xsl:for-each>
                </xsl:element>
            </xsl:for-each>
        </xsl:element>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Body:
A more generic XSLT 1.0 solution with templates.

<xsl:template match="root">
  <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="*[@class]">
  <xsl:variable name="name">
    <xsl:choose>
      <xsl:when test="contains(@class, ' ')">
        <xsl:value-of select="substring-before(@class, ' ')"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="@class"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <xsl:variable name="type">
    <xsl:variable name="tail" select="substring-after(@class, ' ')"/>
    <xsl:choose>
      <xsl:when test="contains($tail, ' ')">
        <xsl:value-of select="substring-before($tail, ' ')"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$tail"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <xsl:element name="{$name}">
    <xsl:if test="string($type)">
      <xsl:attribute name="type">
        <xsl:value-of select="$type"/>
      </xsl:attribute>
    </xsl:if>
    <xsl:apply-templates/>
  </xsl:element>
</xsl:template>

If you have elements other than root that do not have a class attribute, add a template for them.

XSLT 2.0 solution is:

<xsl:template match="root">
  <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="*[@class]">
  <xsl:variable name="class" select="tokenize(@class, '\s')"/>
  <xsl:element name="{$class[1]}">
    <xsl:if test="count($class) > 1">
      <xsl:attribute name="type" select="$class[2]"/>
    </xsl:if>
    <xsl:apply-templates/>
  </xsl:element>
</xsl:template>


问:
Getting White Lable Error with This application has no explicit mapping for /error, so you are seeing this as a fallback in Spring boot
I am using Spring boot. I am trying to use thymeleaf template. I have used lombok. I am getting WhiteLabel error while running the project that says There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/design.html ]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/design.html  ]")

This is my project structure
enter image description here

<!DOCTYPE html>

    <title>Taco Cloud</title>

Design your taco!

    <form method="POST" th:object="${design}">

Designate your wrap:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Pick your protein:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Choose your cheese:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Determine your veggies:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Select your sauce:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Name your taco creation:

      <input type="text" th:field="*{name}"/>

      <button>Submit Your Taco</button>

    </form>

```

And I am getting following error:

enter image description here

I am trying to learn Spring boot. Your help will be highly appreciated

答:
You need to code a form action:

```<code> <form method="POST" th:object="${design}" th:action="@{taco/save}">
</code>```

WhiteLabel Error Page is a generic Spring Boot error page that is displayed when no custom error page is present. So you need to setup a page for status 500 error:
http://zetcode.com/springboot/whitelabelerror/

Body:
I am using Spring boot. I am trying to use thymeleaf template. I have used lombok. I am getting WhiteLabel error while running the project that says There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/design.html ]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/design.html  ]")

This is my project structure
enter image description here

<!DOCTYPE html>

    <title>Taco Cloud</title>

Design your taco!

    <form method="POST" th:object="${design}">

Designate your wrap:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Pick your protein:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Choose your cheese:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Determine your veggies:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Select your sauce:

        <input th:field="*{ingredients}" type="checkbox"
               th:value="${ingredient.id}"/>
        INGREDIENT

Name your taco creation:

      <input type="text" th:field="*{name}"/>

      <button>Submit Your Taco</button>

    </form>

And I am getting following error:

enter image description here

I am trying to learn Spring boot. Your help will be highly appreciated

Body:
You need to code a form action:

 <form method="POST" th:object="${design}" th:action="@{taco/save}">

WhiteLabel Error Page is a generic Spring Boot error page that is displayed when no custom error page is present. So you need to setup a page for status 500 error:
http://zetcode.com/springboot/whitelabelerror/