问:
Calculate histogram in OPENGL
I try to calculate histogram of a image, using OPENGL. I have read some post about that but I still get error. My histogram buffer always return zeros.
Some post which I have read:

Maknoll Histogram

Luminance histogram calculation in GPU-android opengl es 3.0

My code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>

// Include GLEW
#include <GL/glew.h>

// Include GLFW
#include <GLFW/glfw3.h>
GLFWwindow* window;

// Include GLM
#include <glm/glm.hpp>
using namespace glm;
#include <SOIL.h>

// Shader sources
const GLchar* vertexSource = "\n"
"#version 330 core\n"
"attribute vec3 inPosition;\n"
"void main()\n"
"{\n"
"    float x = inPosition.x;\n"
"\n"
"    gl_Position = vec4(\n"
"        -1.0 + ((x) * 0.0078125),\n"
"        -1,\n"
"        0.0,\n"
"        1.0\n"
"    );\n"
"}\n";

const GLchar* fragmentSource = "\n"
"#version 330 core\n"
"out vec4 outputColor;\n"
"void main()\n"
"{\n"
"    outputColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
"}\n";

void CheckStatus(GLuint obj)
{
    GLint status = GL_FALSE, len = 10;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_LINK_STATUS, &status );
    if( status == GL_TRUE ) return;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_INFO_LOG_LENGTH, &len );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_INFO_LOG_LENGTH, &len );
    std::vector< char > log( len, 'X' );
    if( glIsShader(obj) )   glGetShaderInfoLog( obj, len, NULL, &log[0] );
    if( glIsProgram(obj) )  glGetProgramInfoLog( obj, len, NULL, &log[0] );
    std::cerr << &log[0] << std::endl;
    exit( -1 );
}

GLfloat buffer[256];
GLuint hist[256];
float _image[512*512*3];

int main()
{
    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        getchar();
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    int width, height;
    unsigned char* image = SOIL_load_image("sample_gray.bmp", &width, &height, 0, SOIL_LOAD_RGB);
    unsigned char image_gray[width * height];
    printf("%d\t%d\n", width, height);

    for (int i = 0; i < width * height; ++i)
    {
        image_gray[i] = image[i * 3];
        _image[i * 3] = image[i * 3];
        _image[i * 3 + 1] = image[i * 3 + 1];
        _image[i * 3 + 2] = image[i * 3 + 2];
    }

    for (int i = 0; i < width * height; ++i)
    {
        hist[image_gray[i]]++;
    }

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(width, height, "Basic", NULL, NULL);
    if( window == NULL ){
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
        getchar();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        getchar();
        glfwTerminate();
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    GLuint num_input_data = width * height;

    /* Upload data */
    glBufferData(GL_ARRAY_BUFFER, num_input_data * sizeof(float) * 3, _image, GL_STATIC_DRAW);

    GLuint vertexShader, fragmentShader, shaderProgram;
    // Create and compile the vertex shader
    vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);
    CheckStatus(vertexShader);
    // Create and compile the fragment shader
    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);
    CheckStatus(fragmentShader);
    // Link the vertex and fragment shader into a shader program
    shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outputColor");
    glLinkProgram(shaderProgram);

    CheckStatus(shaderProgram);

    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "inPosition");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);

    GLuint tex;
    GLuint fbo;
    glGenTextures(1, &tex);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    glGenFramebuffers(1, &fbo);
    glActiveTexture(GL_TEXTURE0);
    // glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, 256, 1);
    // glBindTexture(GL_TEXTURE_2D, 0);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex, 0);

    /* Clear buffer */
    glClearColor(1.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_ONE, GL_ONE);
    glEnable(GL_BLEND);

    /* Init viewport */
    glViewport(0, 0, 256, 1);
    glUseProgram(shaderProgram);
    /* Draw */
    glDrawArrays(GL_POINTS, 0, num_input_data);

    glReadPixels(0, 0, 256, 1, GL_RED, GL_FLOAT, buffer);

    for (int i = 0; i < 256; ++i)
    {
        printf("%d\t%f\t%d\n", i, buffer[i], hist[i]);
    }

}
</code>```

Could anybody help me,thanks in advance.

I have updated my code, it's working now :D

```<code>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
// Include GLEW
#include <GL/glew.h>

// Include GLFW
#include <GLFW/glfw3.h>
GLFWwindow* window;

// Include GLM
#include <glm/glm.hpp>
using namespace glm;
#include <SOIL.h>

// Shader sources
const GLchar* vertexSource = "\n"
"#version 330 core\n"
"in vec3 inPosition;\n"
"void main()\n"
"{\n"
"    float x = inPosition.x;\n"
"\n"
"    gl_Position = vec4(\n"
"        -1.0 + ((x + 1) * 0.0078125),\n"
"        0.0,\n"
"        0.0,\n"
"        1.0\n"
"    );\n"
"}\n";

const GLchar* fragmentSource = "\n"
"#version 330 core\n"
"out vec4 outputColor;\n"
"void main()\n"
"{\n"
"    outputColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
"}\n";

void CheckStatus(GLuint obj)
{
    GLint status = GL_FALSE, len = 10;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_LINK_STATUS, &status );
    if( status == GL_TRUE ) return;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_INFO_LOG_LENGTH, &len );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_INFO_LOG_LENGTH, &len );
    std::vector< char > log( len, 'X' );
    if( glIsShader(obj) )   glGetShaderInfoLog( obj, len, NULL, &log[0] );
    if( glIsProgram(obj) )  glGetProgramInfoLog( obj, len, NULL, &log[0] );
    std::cerr << &log[0] << std::endl;
    exit( -1 );
}

void _check_gl_error(int line)
{
    GLenum err (glGetError());

    while(err!=GL_NO_ERROR)
    {
        std::string error;

        switch(err)
        {
            case GL_INVALID_OPERATION:      error="INVALID_OPERATION";      break;
            case GL_INVALID_ENUM:           error="INVALID_ENUM";           break;
            case GL_INVALID_VALUE:          error="INVALID_VALUE";          break;
            case GL_OUT_OF_MEMORY:          error="OUT_OF_MEMORY";          break;
            case GL_INVALID_FRAMEBUFFER_OPERATION:  error="INVALID_FRAMEBUFFER_OPERATION";  break;
        }

        std::cerr << "GL_" << error.c_str() <<":"<<line<<std::endl;
        err=glGetError();
    }
}

GLfloat buffer[256];
GLuint hist[256];
float _image[512*512*3];

int main()
{
    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        getchar();
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    int width, height;
    unsigned char* image = SOIL_load_image("sample_gray.bmp", &width, &height, 0, SOIL_LOAD_RGB);
    unsigned char* image_gray = new unsigned char[width * height];

    printf("%d\t%d\n", width, height);

    for (int i = 0; i < width * height; ++i)
    {
        image_gray[i] = image[i * 3];
        _image[i * 3] = image[i * 3];
        _image[i * 3 + 1] = image[i * 3 + 1];
        _image[i * 3 + 2] = image[i * 3 + 2];
    }

    for (int i = 0; i < width * height; ++i)
    {
        hist[image_gray[i]]++;
    }

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(width, height, "Basic", NULL, NULL);
    if( window == NULL ){
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
        getchar();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        getchar();
        glfwTerminate();
        return -1;
    }
    _check_gl_error(__LINE__);
    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    GLuint num_input_data = width * height;

    /* Upload data */
    glBufferData(GL_ARRAY_BUFFER, num_input_data * sizeof(float) * 3, _image, GL_STATIC_DRAW);

    GLuint vertexShader, fragmentShader, shaderProgram;
    // Create and compile the vertex shader
    vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);
    CheckStatus(vertexShader);
    // Create and compile the fragment shader
    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);
    CheckStatus(fragmentShader);
    // Link the vertex and fragment shader into a shader program
    shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outputColor");
    glLinkProgram(shaderProgram);

    CheckStatus(shaderProgram);

    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "inPosition");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);

    GLuint tex;
    GLuint fbo;
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    glGenTextures(1, &tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 256, 1, 0, GL_RED, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    // glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, 256, 1);

    glBindTexture(GL_TEXTURE_2D, 0);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex, 0);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    _check_gl_error(__LINE__);

    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    /* Clear buffer */
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_ONE, GL_ONE);
    glEnable(GL_BLEND);
    _check_gl_error(__LINE__);

    /* Init viewport */
    glViewport(0, 0, 256, 1);
    glUseProgram(shaderProgram);
    /* Draw */
    glDrawArrays(GL_POINTS, 0, num_input_data);

    glReadPixels(0, 0, 256, 1, GL_RED, GL_FLOAT, buffer);
    _check_gl_error(__LINE__);
    for (int i = 0; i < 256; ++i)
    {
        printf("%d\t%f\t%d\n", i, buffer[i], hist[i]);
    }
    free(image_gray);
}
</code>```

Special thank to @Vallentin for your enthusiasm!

答:
My histogram buffer always return zeros.

Interesting. Because I don't know which compiler that let's something like this fly by:

```<code>int width, height;
unsigned char* image = SOIL_load_image("sample_gray.bmp", &width, &height, 0, SOIL_LOAD_RGB);
unsigned char image_gray[width * height];
</code>```

Where you'd need to do:

```<code>unsigned char *image_gray = new unsigned char[width * height];
</code>```

Remember to later free the memory delete[] image_gray.

Your shader also doesn't compile or maybe your driver is a bit more lean than mine. As given #version 330 core you can't use attribute and would have to use in.

```<code>in vec3 inPosition;
</code>```

As is CheckStatus() also tells this:

```<code>0(3) : error C7555: 'attribute' is deprecated, use 'in/out' instead
</code>```

You're also trying to bind a framebuffer you don't even have yet.

```<code>GLuint fbo;
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
[...]
glGenFramebuffers(1, &fbo);
</code>```

You'd need to flip that around:

```<code>GLuint fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
</code>```

It also puzzles me why your compiler would let that slide, as MSVC screams at me.

```<code>Error C4700 uninitialized local variable 'fbo'
</code>```

You're also not binding the texture before applying any changes to it.

```<code>// glBindTexture(GL_TEXTURE_2D, tex);
</code>```

So uncomment that glBindTexture() call.

You're also not creating any vertex arrays. Which checking glGetError() would have told.

```<code>GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
</code>```

Do so before calling glEnableVertexAttribArray().

Also your clear color is red. So that's not going to help you that much. As now your call to glReadPixels() would only yield 1.0.

```<code>glClearColor(0.0, 0.0, 0.0, 1.0)
</code>```

Now glReadPixels() still only yield zero. However unbinding or not creating the framebuffer at all. Then it gives what I assume is the desired result. Since not using the framebuffer shouldn't be so, I'm suspecting that there's something wrong with it. I can't however seem to pin point it by glancing over your code. But as the code is riddled with problems already, this is a fair starting point.

Additional:

You're targeting OpenGL 3.3 while glTexStorage2D() is core in 4.2. Point being, that if you want to make sure glTexStorage2D() is supported, target 4.2.

The call to glActiveTexture() is redundant.

Since your texture has a height of 1, consider using a 1D texture.

Remember to check glGetError() or better yet utilize Debug Output

Edit

First of all You can't call _check_gl_error() before having created the window (and context) and called glewInit().

Instead of manually adding the line number you could use __LINE__. Thus _check_gl_error(__LINE__).

Again don't use a red clear color. Use a black clear color glClearColor(0.0, 0.0, 0.0, 1.0). As blending 1.0 and say 0.1 results in 1.1, which is clamped back to 1.0. Thus the red color channel should be 0.0 from the get-go.

I realized the problem. In your vertex shader you're manually setting y to -1.0. This ends up falling out of the screen, given that you're drawing GL_POINTS.
Setting it to y to -0.9999 seems to give the desired result now. However relying on this is like playing with fire.

If you now run the application you'll now see a mixture of 0.0 and 1.0. The reason you get 1.0 is because in your fragment shader you're setting outputColor for the red channel as 1.0. Again summing all those might be some crazy value, but in the end it'll get clamped back down to 1.0.

Instead try with:

```<code>unsigned char *image_gray = new unsigned char[width * height];
</code>```0

Now you should see the output increasing and decreasing, instead of being either 0.0 or 1.0. However note that if hist[i] is greater than 200, then any that are so will result in 1.0. Because 1 / 0.005 = 200.

Everything is at least working now.

Title: Calculate histogram in OPENGL

Body:
I try to calculate histogram of a image, using OPENGL. I have read some post about that but I still get error. My histogram buffer always return zeros.
Some post which I have read:

Maknoll Histogram

Luminance histogram calculation in GPU-android opengl es 3.0

My code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>

// Include GLEW
#include <GL/glew.h>

// Include GLFW
#include <GLFW/glfw3.h>
GLFWwindow* window;

// Include GLM
#include <glm/glm.hpp>
using namespace glm;
#include <SOIL.h>

// Shader sources
const GLchar* vertexSource = "\n"
"#version 330 core\n"
"attribute vec3 inPosition;\n"
"void main()\n"
"{\n"
"    float x = inPosition.x;\n"
"\n"
"    gl_Position = vec4(\n"
"        -1.0 + ((x) * 0.0078125),\n"
"        -1,\n"
"        0.0,\n"
"        1.0\n"
"    );\n"
"}\n";

const GLchar* fragmentSource = "\n"
"#version 330 core\n"
"out vec4 outputColor;\n"
"void main()\n"
"{\n"
"    outputColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
"}\n";

void CheckStatus(GLuint obj)
{
    GLint status = GL_FALSE, len = 10;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_LINK_STATUS, &status );
    if( status == GL_TRUE ) return;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_INFO_LOG_LENGTH, &len );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_INFO_LOG_LENGTH, &len );
    std::vector< char > log( len, 'X' );
    if( glIsShader(obj) )   glGetShaderInfoLog( obj, len, NULL, &log[0] );
    if( glIsProgram(obj) )  glGetProgramInfoLog( obj, len, NULL, &log[0] );
    std::cerr << &log[0] << std::endl;
    exit( -1 );
}

GLfloat buffer[256];
GLuint hist[256];
float _image[512*512*3];

int main()
{
    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        getchar();
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    int width, height;
    unsigned char* image = SOIL_load_image("sample_gray.bmp", &width, &height, 0, SOIL_LOAD_RGB);
    unsigned char image_gray[width * height];
    printf("%d\t%d\n", width, height);

    for (int i = 0; i < width * height; ++i)
    {
        image_gray[i] = image[i * 3];
        _image[i * 3] = image[i * 3];
        _image[i * 3 + 1] = image[i * 3 + 1];
        _image[i * 3 + 2] = image[i * 3 + 2];
    }

    for (int i = 0; i < width * height; ++i)
    {
        hist[image_gray[i]]++;
    }

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(width, height, "Basic", NULL, NULL);
    if( window == NULL ){
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
        getchar();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        getchar();
        glfwTerminate();
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    GLuint num_input_data = width * height;

    /* Upload data */
    glBufferData(GL_ARRAY_BUFFER, num_input_data * sizeof(float) * 3, _image, GL_STATIC_DRAW);

    GLuint vertexShader, fragmentShader, shaderProgram;
    // Create and compile the vertex shader
    vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);
    CheckStatus(vertexShader);
    // Create and compile the fragment shader
    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);
    CheckStatus(fragmentShader);
    // Link the vertex and fragment shader into a shader program
    shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outputColor");
    glLinkProgram(shaderProgram);

    CheckStatus(shaderProgram);

    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "inPosition");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);

    GLuint tex;
    GLuint fbo;
    glGenTextures(1, &tex);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    glGenFramebuffers(1, &fbo);
    glActiveTexture(GL_TEXTURE0);
    // glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, 256, 1);
    // glBindTexture(GL_TEXTURE_2D, 0);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex, 0);

    /* Clear buffer */
    glClearColor(1.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_ONE, GL_ONE);
    glEnable(GL_BLEND);

    /* Init viewport */
    glViewport(0, 0, 256, 1);
    glUseProgram(shaderProgram);
    /* Draw */
    glDrawArrays(GL_POINTS, 0, num_input_data);

    glReadPixels(0, 0, 256, 1, GL_RED, GL_FLOAT, buffer);

    for (int i = 0; i < 256; ++i)
    {
        printf("%d\t%f\t%d\n", i, buffer[i], hist[i]);
    }

}

Could anybody help me,thanks in advance.

I have updated my code, it's working now :D

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
// Include GLEW
#include <GL/glew.h>

// Include GLFW
#include <GLFW/glfw3.h>
GLFWwindow* window;

// Include GLM
#include <glm/glm.hpp>
using namespace glm;
#include <SOIL.h>

// Shader sources
const GLchar* vertexSource = "\n"
"#version 330 core\n"
"in vec3 inPosition;\n"
"void main()\n"
"{\n"
"    float x = inPosition.x;\n"
"\n"
"    gl_Position = vec4(\n"
"        -1.0 + ((x + 1) * 0.0078125),\n"
"        0.0,\n"
"        0.0,\n"
"        1.0\n"
"    );\n"
"}\n";

const GLchar* fragmentSource = "\n"
"#version 330 core\n"
"out vec4 outputColor;\n"
"void main()\n"
"{\n"
"    outputColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
"}\n";

void CheckStatus(GLuint obj)
{
    GLint status = GL_FALSE, len = 10;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_LINK_STATUS, &status );
    if( status == GL_TRUE ) return;
    if( glIsShader(obj) )   glGetShaderiv( obj, GL_INFO_LOG_LENGTH, &len );
    if( glIsProgram(obj) )  glGetProgramiv( obj, GL_INFO_LOG_LENGTH, &len );
    std::vector< char > log( len, 'X' );
    if( glIsShader(obj) )   glGetShaderInfoLog( obj, len, NULL, &log[0] );
    if( glIsProgram(obj) )  glGetProgramInfoLog( obj, len, NULL, &log[0] );
    std::cerr << &log[0] << std::endl;
    exit( -1 );
}

void _check_gl_error(int line)
{
    GLenum err (glGetError());

    while(err!=GL_NO_ERROR)
    {
        std::string error;

        switch(err)
        {
            case GL_INVALID_OPERATION:      error="INVALID_OPERATION";      break;
            case GL_INVALID_ENUM:           error="INVALID_ENUM";           break;
            case GL_INVALID_VALUE:          error="INVALID_VALUE";          break;
            case GL_OUT_OF_MEMORY:          error="OUT_OF_MEMORY";          break;
            case GL_INVALID_FRAMEBUFFER_OPERATION:  error="INVALID_FRAMEBUFFER_OPERATION";  break;
        }

        std::cerr << "GL_" << error.c_str() <<":"<<line<<std::endl;
        err=glGetError();
    }
}

GLfloat buffer[256];
GLuint hist[256];
float _image[512*512*3];

int main()
{
    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        getchar();
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    int width, height;
    unsigned char* image = SOIL_load_image("sample_gray.bmp", &width, &height, 0, SOIL_LOAD_RGB);
    unsigned char* image_gray = new unsigned char[width * height];

    printf("%d\t%d\n", width, height);

    for (int i = 0; i < width * height; ++i)
    {
        image_gray[i] = image[i * 3];
        _image[i * 3] = image[i * 3];
        _image[i * 3 + 1] = image[i * 3 + 1];
        _image[i * 3 + 2] = image[i * 3 + 2];
    }

    for (int i = 0; i < width * height; ++i)
    {
        hist[image_gray[i]]++;
    }

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(width, height, "Basic", NULL, NULL);
    if( window == NULL ){
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
        getchar();
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        getchar();
        glfwTerminate();
        return -1;
    }
    _check_gl_error(__LINE__);
    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    GLuint num_input_data = width * height;

    /* Upload data */
    glBufferData(GL_ARRAY_BUFFER, num_input_data * sizeof(float) * 3, _image, GL_STATIC_DRAW);

    GLuint vertexShader, fragmentShader, shaderProgram;
    // Create and compile the vertex shader
    vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);
    CheckStatus(vertexShader);
    // Create and compile the fragment shader
    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);
    CheckStatus(fragmentShader);
    // Link the vertex and fragment shader into a shader program
    shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outputColor");
    glLinkProgram(shaderProgram);

    CheckStatus(shaderProgram);

    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "inPosition");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);

    GLuint tex;
    GLuint fbo;
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    glGenTextures(1, &tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 256, 1, 0, GL_RED, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    // glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, 256, 1);

    glBindTexture(GL_TEXTURE_2D, 0);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex, 0);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    _check_gl_error(__LINE__);

    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    /* Clear buffer */
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_ONE, GL_ONE);
    glEnable(GL_BLEND);
    _check_gl_error(__LINE__);

    /* Init viewport */
    glViewport(0, 0, 256, 1);
    glUseProgram(shaderProgram);
    /* Draw */
    glDrawArrays(GL_POINTS, 0, num_input_data);

    glReadPixels(0, 0, 256, 1, GL_RED, GL_FLOAT, buffer);
    _check_gl_error(__LINE__);
    for (int i = 0; i < 256; ++i)
    {
        printf("%d\t%f\t%d\n", i, buffer[i], hist[i]);
    }
    free(image_gray);
}

Special thank to @Vallentin for your enthusiasm!

Body:
My histogram buffer always return zeros.

Interesting. Because I don't know which compiler that let's something like this fly by:

int width, height;
unsigned char* image = SOIL_load_image("sample_gray.bmp", &width, &height, 0, SOIL_LOAD_RGB);
unsigned char image_gray[width * height];

Where you'd need to do:

unsigned char *image_gray = new unsigned char[width * height];

Remember to later free the memory delete[] image_gray.

Your shader also doesn't compile or maybe your driver is a bit more lean than mine. As given #version 330 core you can't use attribute and would have to use in.

in vec3 inPosition;

As is CheckStatus() also tells this:

0(3) : error C7555: 'attribute' is deprecated, use 'in/out' instead

You're also trying to bind a framebuffer you don't even have yet.

GLuint fbo;
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
[...]
glGenFramebuffers(1, &fbo);

You'd need to flip that around:

GLuint fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);

It also puzzles me why your compiler would let that slide, as MSVC screams at me.

Error C4700 uninitialized local variable 'fbo'

You're also not binding the texture before applying any changes to it.

// glBindTexture(GL_TEXTURE_2D, tex);

So uncomment that glBindTexture() call.

You're also not creating any vertex arrays. Which checking glGetError() would have told.

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

Do so before calling glEnableVertexAttribArray().

Also your clear color is red. So that's not going to help you that much. As now your call to glReadPixels() would only yield 1.0.

glClearColor(0.0, 0.0, 0.0, 1.0)

Now glReadPixels() still only yield zero. However unbinding or not creating the framebuffer at all. Then it gives what I assume is the desired result. Since not using the framebuffer shouldn't be so, I'm suspecting that there's something wrong with it. I can't however seem to pin point it by glancing over your code. But as the code is riddled with problems already, this is a fair starting point.

Additional:

You're targeting OpenGL 3.3 while glTexStorage2D() is core in 4.2. Point being, that if you want to make sure glTexStorage2D() is supported, target 4.2.

The call to glActiveTexture() is redundant.

Since your texture has a height of 1, consider using a 1D texture.

Remember to check glGetError() or better yet utilize Debug Output

Edit

First of all You can't call _check_gl_error() before having created the window (and context) and called glewInit().

Instead of manually adding the line number you could use __LINE__. Thus _check_gl_error(__LINE__).

Again don't use a red clear color. Use a black clear color glClearColor(0.0, 0.0, 0.0, 1.0). As blending 1.0 and say 0.1 results in 1.1, which is clamped back to 1.0. Thus the red color channel should be 0.0 from the get-go.

I realized the problem. In your vertex shader you're manually setting y to -1.0. This ends up falling out of the screen, given that you're drawing GL_POINTS.
Setting it to y to -0.9999 seems to give the desired result now. However relying on this is like playing with fire.

If you now run the application you'll now see a mixture of 0.0 and 1.0. The reason you get 1.0 is because in your fragment shader you're setting outputColor for the red channel as 1.0. Again summing all those might be some crazy value, but in the end it'll get clamped back down to 1.0.

Instead try with:

outputColor = vec4(0.005, 1.0, 1.0, 1.0);

Now you should see the output increasing and decreasing, instead of being either 0.0 or 1.0. However note that if hist[i] is greater than 200, then any that are so will result in 1.0. Because 1 / 0.005 = 200.

Everything is at least working now.


来源: stackexchange

问:
Why does the command, alert($(this).attr("id")); return "undefined"?
Why does the command

```<code>alert($(this).attr("id"));
</code>```

return "undefined"? I'm using it in ASP NET and Internet Explorer 8.

答: I think 'this' is referring to the alert box which I am guessing does not have an attribute called id.</p>

ContentLicense: CC BY-SA 2.5

Body:
Why does the command

alert($(this).attr("id"));

return "undefined"? I'm using it in ASP NET and Internet Explorer 8.


问:
JQuery Set Value of ASP Textbox and have the .Text property return that value
Ok, I've searched for a while but still haven't found anything that fixes my issue.

I am updating a readonly Textbox in ASP.NET with JQuery after the selection of radio buttons. The value shows up and everything seems to work from an HTML standpoint but Address.Text in the code behind returns nothing.

Also, I've posted all my attempts in the JavaScript section, I know I should only need one of these to update what I'm trying to update.

HTML:

```<code><asp:TextBox class="form-control form-inline" runat="server" ID="Address" placeholder="Populates based off account type" readonly="true"/>
</code>```

JavaScript:

```<code>$(document).ready(function () {
    $('input[type=radio]').click(function () {
        $('#Address').attr("value", $(this).val());
        $('#Address').attr("Text", $(this).val())
        $('#Address').val($(this).val());
        $('#<%= Address.ClientID %>').val($(this).val());
        $('#<%= Address.ClientID %>').text($(this).val());
        $('#AccountType').val($(this).val());
    });
});
</code>```

ASP.NET

```<code>ClientScript.RegisterStartupScript(GetType(), "myalert", "alert('Address: " + Address.Text + "' );", true);
</code>```

Thanks in advance to anyone that can help me out.

答:
When you set the ReadOnly property to true of an ASP.NET TextBox, it basically assumes the value can't be changed clientside and won't post changes back.  Try setting it readonly like:

```<code>textBox.Attributes.Add("readonly", "readonly");
</code>```

Additional SO post for reference.

ContentLicense: CC BY-SA 3.0

Body:
Ok, I've searched for a while but still haven't found anything that fixes my issue.

I am updating a readonly Textbox in ASP.NET with JQuery after the selection of radio buttons. The value shows up and everything seems to work from an HTML standpoint but Address.Text in the code behind returns nothing.

Also, I've posted all my attempts in the JavaScript section, I know I should only need one of these to update what I'm trying to update.

HTML:

<asp:TextBox class="form-control form-inline" runat="server" ID="Address" placeholder="Populates based off account type" readonly="true"/>

JavaScript:

$(document).ready(function () {
    $('input[type=radio]').click(function () {
        $('#Address').attr("value", $(this).val());
        $('#Address').attr("Text", $(this).val())
        $('#Address').val($(this).val());
        $('#<%= Address.ClientID %>').val($(this).val());
        $('#<%= Address.ClientID %>').text($(this).val());
        $('#AccountType').val($(this).val());
    });
});

ASP.NET

ClientScript.RegisterStartupScript(GetType(), "myalert", "alert('Address: " + Address.Text + "' );", true);

Thanks in advance to anyone that can help me out.

Body:
When you set the ReadOnly property to true of an ASP.NET TextBox, it basically assumes the value can't be changed clientside and won't post changes back.  Try setting it readonly like:

textBox.Attributes.Add("readonly", "readonly");

Additional SO post for reference.


问:
How to process files in nested directories?
I'm trying to make my JavaScript files a little smaller.

I've got a javascripts/ directory, and then a _website/javascripts/ directory where my static assets get compiled. Inside of the javascripts/ directory I have a few nested directories for polyfills, libraries and so on, and then files for my site.

How can I recursively iterate through all the nested directories of javascripts/ and pump out minified, compressed, but not concatenated files into my _website/javascripts/ directory?

Here's the code I have so far. Ideally I can do this in an npm script. It's totally cool if it only works on Linux for now.

```<code>find scripts/ -name '*.js' -print0 | xargs -0 uglifyjs
</code>```

And then I don't know how to pass the inputs to each xargs execution as names for the --output flag of uglifyjs.

How do I do this with xargs? Is it the {} notion?

答:
Here's how I ended up doing this:

find javascripts/ -name '*.js' -print0 | xargs -0 -I file uglifyjs file -o _website/file

So, find scurries around looking through everything in javascripts/. Every time it finds something with the name ending in .js it sends writes that to STDOUT. The | accepts those writes and sends them into xargs.

(The -print0 flag on find makes sure not to add new lines or extra spaces. The -0 flag on xargs, makes sure to handle each whole output from find, even when file names have new lines or spaces and such in them.)

The -I file creates a variable file which holds the filename which it got form each of the outputs from the find command. Then we use that variable in uglifyjs file -o _website/file to run uglify on each js file and drop it in the appropriate place in our compiled website directory _website. Small note: it's possible this won't automatically create new directories in _website/javascripts. Haven't tested that.

Best of luck to anyone who comes around here!

Body:
I'm trying to make my JavaScript files a little smaller.

I've got a javascripts/ directory, and then a _website/javascripts/ directory where my static assets get compiled. Inside of the javascripts/ directory I have a few nested directories for polyfills, libraries and so on, and then files for my site.

How can I recursively iterate through all the nested directories of javascripts/ and pump out minified, compressed, but not concatenated files into my _website/javascripts/ directory?

Here's the code I have so far. Ideally I can do this in an npm script. It's totally cool if it only works on Linux for now.

find scripts/ -name '*.js' -print0 | xargs -0 uglifyjs

And then I don't know how to pass the inputs to each xargs execution as names for the --output flag of uglifyjs.

How do I do this with xargs? Is it the {} notion?


问:
I want to reuse an array that already has been modified
I am making a cinema booking system in Python and I am having trouble saving the modified array so it shows that the seat has been taken I am using this to create the array.

```<code>def seats():
    rows = "ABCDE"
    columns = range(0, 10)
    x = [{ltr + str(y): 'Empty' for ltr in rows} for y in columns]
    pprint(x)
    res = str(raw_input("Pick a seat "))
    if res[1] == '0':
        if x[0][res] == 'Taken':
            print ('Seat taken')
    else:
       x[0][res] = 'Taken'
</code>```

Note that I'm not that experienced so any tips to make the code cleaner will be appraised as well. The customer should be able to buy multiple seats and I have that sorted out but if I return to the menu and then back to the seats, all the 'taken' seats appear as 'empty' again.

答:
Maybe you would want to put it in a class and define x as an attribute. I have changed quite a lot, not quite sure whether this is what you want. For example I have renamed x to self.seats and changed it's structure to be a dict only instead of a list of dicts because that seems easier to me.

```<code>#!/usr/bin/env python3
class Cinema(object):

     def __init__(self, rows, columns):
         self.rows = rows
         self.columns = columns
         # True: seat is free, seat is availbale
         self.seats = {"{row}{col}".format(row=row, col=col): True for row in rows for col in columns}

     def ask_for_seat(self):
         print("The following seats are still available:")
         self.print_free_seats()
         seat = input("Pick a seat: ")
         if seat in self.seats:
             if self.seats[seat]:
                 print("Thank you. We are reserving seat {} for you.".format(seat))
                 self.seats[seat] = False
                 return seat
             else:
                 print("Seat {} is already reserved. Please choose another one.".format(seat))
                 return self.ask_for_seat()
         else:
             print("Sorry, this cinema does not have a seat {}. Please choose another one.".format(seat))
             return self.ask_for_seat()

     def print_free_seats(self):
         for row in self.rows:
             for col in self.columns:
                 seat = "{row}{col}".format(row=row, col=col)
                 if self.seats[seat]:
                     print(seat, end=" ")
                 else:
                     print(" "*len(seat), end=" ")
             print()

if __name__=='__main__':
     c = Cinema("ABCDE", range(0, 10))
     while True:
         c.ask_for_seat()
</code>```

Please note that this is Python 3 code and does not work with Python 2.

Body:
I am making a cinema booking system in Python and I am having trouble saving the modified array so it shows that the seat has been taken I am using this to create the array.

def seats():
    rows = "ABCDE"
    columns = range(0, 10)
    x = [{ltr + str(y): 'Empty' for ltr in rows} for y in columns]
    pprint(x)
    res = str(raw_input("Pick a seat "))
    if res[1] == '0':
        if x[0][res] == 'Taken':
            print ('Seat taken')
    else:
       x[0][res] = 'Taken'

Note that I'm not that experienced so any tips to make the code cleaner will be appraised as well. The customer should be able to buy multiple seats and I have that sorted out but if I return to the menu and then back to the seats, all the 'taken' seats appear as 'empty' again.

Body:
Maybe you would want to put it in a class and define x as an attribute. I have changed quite a lot, not quite sure whether this is what you want. For example I have renamed x to self.seats and changed it's structure to be a dict only instead of a list of dicts because that seems easier to me.

#!/usr/bin/env python3
class Cinema(object):

     def __init__(self, rows, columns):
         self.rows = rows
         self.columns = columns
         # True: seat is free, seat is availbale
         self.seats = {"{row}{col}".format(row=row, col=col): True for row in rows for col in columns}

     def ask_for_seat(self):
         print("The following seats are still available:")
         self.print_free_seats()
         seat = input("Pick a seat: ")
         if seat in self.seats:
             if self.seats[seat]:
                 print("Thank you. We are reserving seat {} for you.".format(seat))
                 self.seats[seat] = False
                 return seat
             else:
                 print("Seat {} is already reserved. Please choose another one.".format(seat))
                 return self.ask_for_seat()
         else:
             print("Sorry, this cinema does not have a seat {}. Please choose another one.".format(seat))
             return self.ask_for_seat()

     def print_free_seats(self):
         for row in self.rows:
             for col in self.columns:
                 seat = "{row}{col}".format(row=row, col=col)
                 if self.seats[seat]:
                     print(seat, end=" ")
                 else:
                     print(" "*len(seat), end=" ")
             print()

if __name__=='__main__':
     c = Cinema("ABCDE", range(0, 10))
     while True:
         c.ask_for_seat()

Please note that this is Python 3 code and does not work with Python 2.


问:
How to know whether the Register Email is verified or not in Firebase?
```<code>onSubmit(formData) {
if(formData.valid) {
  console.log(formData.value);
  this.af.auth.createUser({
    email: formData.value.email,
    password: formData.value.password
  }).then(
    authState => {
    authState.auth.sendEmailVerification();
    this.router.navigate(['/login'])
  }).catch(
    (err) => {
    console.log(err);
    this.error = err;
  })
}
}
</code>```

In Firebase, I set the SendEmailVerfication like the code above, and the email could send normally.However, in my app, there is no difference between the user who does not click the verification email with those clicked, how to make a difference?

答: you can add an attribute at firebase database for the state of your user verification link</p>

ContentLicense: CC BY-SA 4.0

Body:
onSubmit(formData) {
if(formData.valid) {
  console.log(formData.value);
  this.af.auth.createUser({
    email: formData.value.email,
    password: formData.value.password
  }).then(
    authState => {
    authState.auth.sendEmailVerification();
    this.router.navigate(['/login'])
  }).catch(
    (err) => {
    console.log(err);
    this.error = err;
  })
}
}

In Firebase, I set the SendEmailVerfication like the code above, and the email could send normally.However, in my app, there is no difference between the user who does not click the verification email with those clicked, how to make a difference?


问:
Htaccess and url for multilingual site
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

```<code>- Same filename
site.com/fr/login
site.com/en/login
</code>```

OR

```<code>- Different filename
site.com/fr/connexion
site.com/en/login
</code>```

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)

答:
Think about humans at the first. Is the URL translation important for users in France? Some people may think what it’s fine to get translated words in the URL. Users from other locales may think otherwise. Search engines take into account user behavioral factors. SEO factors will higher if you solution is more convinient for users.

It whould be nice if users get an expected language version. A site could help them if it suggests a language version by IP, HTTP headers, cookies and so on. Some people may prefer another language, some people may be on a trip.  So it's still important let them to choice a language version manually.

Please read manuals and analyze competitors sites in case of doubt.

Title: Htaccess and url for multilingual site

Body:
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

- Same filename
site.com/fr/login
site.com/en/login

OR

- Different filename
site.com/fr/connexion
site.com/en/login

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)


问:
Node Express Can't set headers after they are sent
I know this has been asked in multiple ways already, but my issue seems to be different from those already posted.

I'm trying to send data from a form into google firebase. I have a node app using express.

Here's my function that is sending the data to firebase:

```<code>function validateForm() {

async.series([
    function (callback) {
        var errors = "<strong>The following errors were entered:\n";
        var name = $('#name').val();
        var story = $('#story').val();

        if (name.length < 1) {
            errors += "\n-Please enter a valid name";
            callback("Please enter a valid name", null);
        }

        if (story.length < 1) {
            errors += "\n-Please enter a valid story";
            callback("Please enter a valid story", null);
        }
        console.log("FInished validating");
        callback(null, "finished validating");
    }, function (callback) {
        firebase.database().ref('stories/' + Date.now()).set({
            name: name,
            story: story
        }, function() {
            console.log("Firebase callback");
            callback(null, "sent data!");
        });
    }, function (callback) {
        console.log("Finished!");
        callback(null, "done")
    }
])
}
</code>```

(added some console.logging for clarity to ensure I had the callbacks right)

The submission is trigger by clicking on a div that's styles to look like a button, so I know there's no default behavior of forms issues that are causing the problem. Below is the error I'm getting in Node.

Error: /Users/keegan/WebstormProjects/hack4health/views/error.hbs:
  Can't set headers after they are sent.
      at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
      at ServerResponse.header (/Users/keegan/WebstormProjects/hack4health/node_modules/express/lib/response.js:719:10)
      at ServerResponse.send (/Users/keegan/WebstormProjects/hack4health/node_modules/express/lib/response.js:164:12)
      at res.render.done (/Users/keegan/WebstormProjects/hack4health/node_modules/express/lib/response.js:956:10)
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:93:9
      at done (/Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/async.js:74:20)
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:88:18
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:69:11
      at done (/Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/async.js:74:20)
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:64:20

答:
Here you are calling the callback up to three times:

```<code>if (name.length < 1) {
    …
    callback("Please enter a valid name", null);
}
if (story.length < 1) {
    …
    callback("Please enter a valid story", null);
}
…
callback(null, "finished validating");
</code>```

That will lead to the callback that writes the response to be called multiple times, failing when it tries to write the headers again after sending the first body.

You will either want to return after calling the callback, or you want to call it only once in the end with the accumulated errors.

Body:
I know this has been asked in multiple ways already, but my issue seems to be different from those already posted.

I'm trying to send data from a form into google firebase. I have a node app using express.

Here's my function that is sending the data to firebase:

function validateForm() {

async.series([
    function (callback) {
        var errors = "The following errors were entered:\n";
        var name = $('#name').val();
        var story = $('#story').val();

        if (name.length < 1) {
            errors += "\n-Please enter a valid name";
            callback("Please enter a valid name", null);
        }

        if (story.length < 1) {
            errors += "\n-Please enter a valid story";
            callback("Please enter a valid story", null);
        }
        console.log("FInished validating");
        callback(null, "finished validating");
    }, function (callback) {
        firebase.database().ref('stories/' + Date.now()).set({
            name: name,
            story: story
        }, function() {
            console.log("Firebase callback");
            callback(null, "sent data!");
        });
    }, function (callback) {
        console.log("Finished!");
        callback(null, "done")
    }
])
}

(added some console.logging for clarity to ensure I had the callbacks right)

The submission is trigger by clicking on a div that's styles to look like a button, so I know there's no default behavior of forms issues that are causing the problem. Below is the error I'm getting in Node.

Error: /Users/keegan/WebstormProjects/hack4health/views/error.hbs:
  Can't set headers after they are sent.
      at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
      at ServerResponse.header (/Users/keegan/WebstormProjects/hack4health/node_modules/express/lib/response.js:719:10)
      at ServerResponse.send (/Users/keegan/WebstormProjects/hack4health/node_modules/express/lib/response.js:164:12)
      at res.render.done (/Users/keegan/WebstormProjects/hack4health/node_modules/express/lib/response.js:956:10)
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:93:9
      at done (/Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/async.js:74:20)
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:88:18
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:69:11
      at done (/Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/async.js:74:20)
      at /Users/keegan/WebstormProjects/hack4health/node_modules/hbs/lib/hbs.js:64:20

Body:
Here you are calling the callback up to three times:

if (name.length < 1) {
    …
    callback("Please enter a valid name", null);
}
if (story.length < 1) {
    …
    callback("Please enter a valid story", null);
}
…
callback(null, "finished validating");

That will lead to the callback that writes the response to be called multiple times, failing when it tries to write the headers again after sending the first body.

You will either want to return after calling the callback, or you want to call it only once in the end with the accumulated errors.


问:
Elegant way to count the number of lines that contain a string in a file
I have a quick question.

As the title says, I'd like to find a way to count the number of lines that contain a specified string in a file, in PHP.

I know I could simply open the file and loop through all the lines and see if anything matches, but that seems kind of cumbersome. Is there a better way?

To further illustrate what I want to do, here's how it could look with awk:

```<code>awk '/KEYWORD/ {i++} END { print i }' FILE
</code>```

Thanks!

答: be aware that file() will choke when run with stupid huge files such as 500MB+. If this is common in your web application, such as many concurrent users counting huge file sizes, this will impact on performance.</p>

Body:
I have a quick question.

As the title says, I'd like to find a way to count the number of lines that contain a specified string in a file, in PHP.

I know I could simply open the file and loop through all the lines and see if anything matches, but that seems kind of cumbersome. Is there a better way?

To further illustrate what I want to do, here's how it could look with awk:

awk '/KEYWORD/ {i++} END { print i }' FILE

Thanks!


问:
Writting a file with german letters like ü ,ä, ö and ß in python
I am creating files with this function in python 2

```<code> with io.FileIO(station_data['name']+".pls", "w") as file:
       file.write("[playlist] " + \n + "numberofentries=1" + \n + "File1=" + station_data['streamURL'] + \n + "Title1=" + station_data['name'] )
</code>```

But when in station_[name] is an "Ä" or "Ü" and so on, I get this error

```<code>UnicodeEncodeError: 'ascii' codec can't enconde character u'\xfc' in position 171: ordinal not in range(128)
</code>```

This is the whole script

```<code>import requests
import sys
import os
import json
import io
from objbrowser import browse

class RadioStations():
  user_agent = {'User-agent': 'User-Agent: XBMC Addon Radio'}
  data = []
  no_data = True
  url = "http://radio.de/info/menu/broadcastsofcategory?category=_top"
  try:
    response  = requests.get(url, headers = user_agent)
    data = response.json()
    no_data = False
    print("Data found")
  except requests.HTTPError, e:
    print("HTTP error %s", e.code)
    no_data = False
  except requests.ConnectionError, e:
    data.append({'name': 'no station data'})
    no_data = True
    print("Connection error %s", e)
  print("Getting StreamUrls and creating files")
  for item in data:
     id2 = str(item['id'])
     url = "http://radio.de/info/broadcast/getbroadcastembedded?broadcast=" + id2
     response = requests.get(url, headers = user_agent)
     station_data = response.json()
     with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
       txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
       file.write(txt)
     if "errorCode" in station_data.keys():
       print("no such entry")

  print("Finished")
</code>```

It is based on this script on GitHub

答:
Try something like this:

```<code>import sys

fname = "RöckDöts!"
efname = fname.encode(sys.getfilesystemencoding())
open(efname, 'w')
</code>```

See if that works.

Body:
I am creating files with this function in python 2

 with io.FileIO(station_data['name']+".pls", "w") as file:
       file.write("[playlist] " + \n + "numberofentries=1" + \n + "File1=" + station_data['streamURL'] + \n + "Title1=" + station_data['name'] )

But when in station_[name] is an "Ä" or "Ü" and so on, I get this error

UnicodeEncodeError: 'ascii' codec can't enconde character u'\xfc' in position 171: ordinal not in range(128)

This is the whole script

import requests
import sys
import os
import json
import io
from objbrowser import browse

class RadioStations():
  user_agent = {'User-agent': 'User-Agent: XBMC Addon Radio'}
  data = []
  no_data = True
  url = "http://radio.de/info/menu/broadcastsofcategory?category=_top"
  try:
    response  = requests.get(url, headers = user_agent)
    data = response.json()
    no_data = False
    print("Data found")
  except requests.HTTPError, e:
    print("HTTP error %s", e.code)
    no_data = False
  except requests.ConnectionError, e:
    data.append({'name': 'no station data'})
    no_data = True
    print("Connection error %s", e)
  print("Getting StreamUrls and creating files")
  for item in data:
     id2 = str(item['id'])
     url = "http://radio.de/info/broadcast/getbroadcastembedded?broadcast=" + id2
     response = requests.get(url, headers = user_agent)
     station_data = response.json()
     with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
       txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
       file.write(txt)
     if "errorCode" in station_data.keys():
       print("no such entry")

  print("Finished")

It is based on this script on GitHub

Body:
Try something like this:

import sys

fname = "RöckDöts!"
efname = fname.encode(sys.getfilesystemencoding())
open(efname, 'w')

See if that works.


问:
How to iterate this multi dimensional array in php?
I have got this very difficult array to iterate. I want value of only name index. I have tried a lot but not sure how to find this.

```<code>Array ( [0] => Array ( [created_time] => DateTime Object
( [date] => 2017-04-01 12:58:25.000000 [timezone_type] => 1 [timezone] =>
+00:00 ) [from] => Array ( [name] => Ghulam Mohe Ud Din [id] =>
1242172779233884 ) [message] => Hi there[id] => 10154774339307663_10154774534942663 ))
</code>```

Here is my some practice of code:

```<code>foreach ($getPostlikes as $key=> $item) {//suppose array is $getPostlikes

    foreach($item as $i)
    {
        echo $i['name'];
    }

}
</code>```

Any help would be appreciated. Thanks

答:
Data:

```<code>Array (
    [0] => Array (
        [created_time] => DateTime Object,
        (
            [date] => 2017-04-01 12:58:25.000000,
            [timezone_type] => 1,
            [timezone] => +00:00),
        [from] => Array ( [name] => Ghulam Mohe Ud Din [id] => 1242172779233884 ),
        [message] => Hi there[id] => 10154774339307663_10154774534942663 )
    )
</code>```

This will also eliminate duplicate names (each name will display only once).

```<code>$name_list = array();
foreach($postGetLikes as $postno => $post) {
    if(!isset($name_list[$post['from']['name']])) {
        $name_list[$post['from']['name']] = 0;
    }
    $name_list[$post['from']['name']]++;
}

foreach($name_list as $name => $count) {
    echo $name;
}
</code>```

Body:
I have got this very difficult array to iterate. I want value of only name index. I have tried a lot but not sure how to find this.

Array ( [0] => Array ( [created_time] => DateTime Object
( [date] => 2017-04-01 12:58:25.000000 [timezone_type] => 1 [timezone] =>
+00:00 ) [from] => Array ( [name] => Ghulam Mohe Ud Din [id] =>
1242172779233884 ) [message] => Hi there[id] => 10154774339307663_10154774534942663 ))

Here is my some practice of code:

foreach ($getPostlikes as $key=> $item) {//suppose array is $getPostlikes

    foreach($item as $i)
    {
        echo $i['name'];
    }

}

Any help would be appreciated. Thanks

Body:
Data:

Array (
    [0] => Array (
        [created_time] => DateTime Object,
        (
            [date] => 2017-04-01 12:58:25.000000,
            [timezone_type] => 1,
            [timezone] => +00:00),
        [from] => Array ( [name] => Ghulam Mohe Ud Din [id] => 1242172779233884 ),
        [message] => Hi there[id] => 10154774339307663_10154774534942663 )
    )

This will also eliminate duplicate names (each name will display only once).

$name_list = array();
foreach($postGetLikes as $postno => $post) {
    if(!isset($name_list[$post['from']['name']])) {
        $name_list[$post['from']['name']] = 0;
    }
    $name_list[$post['from']['name']]++;
}

foreach($name_list as $name => $count) {
    echo $name;
}


问:
Check if one of the values from both lists are present in the string in ruby
I have two arrays with logins and file extensions:
logins = ['bob', 'mark', 'joe']
extensions = ['.doc', '.xls']

I need to check if one of the values from both lists are present in the string (string is like str = "aaa bob test.txt test text"), and if yes do some work.

How to correctly perform this checking in Ruby.

Now I'm perform this with several loop and if statements.

答:
You can simply add the array to get the union with unique vales and then iterate to check if the string has a matching value.

```<code>   str = 'aaa bob test.txt test text'
  (logins + extensions).any? { |word| str.include?(word) }
</code>```

This returns 'true' or 'false'

Body:
You can simply add the array to get the union with unique vales and then iterate to check if the string has a matching value.

   str = 'aaa bob test.txt test text'
  (logins + extensions).any? { |word| str.include?(word) }

This returns 'true' or 'false'


问:
default settings visual C#
How can i return the settings to default in Visual C# 2008 Express?</p>

答: Tools... Import and Export Settings... Reset All Settings...</p>

Title: default settings visual C#


问:
capture git branch name in makefile variable
I am writing a Makefile and would like to capture the current branch name in a variable to be passed into a --define.
Since the script sometimes but not always runs on travis the git repository might be in detached state.

I can extract the branch name on the command line but unfortunately not capture it in a variable. It seems as if the print $$2 does not work within the Makefile environment.

My current line is:

```<code>BRANCH := $(shell git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$$(git rev-parse HEAD)/ {print $$2}")
</code>```

and I get

```<code>dfd943a57015dbd2129ca7b7033c4e1749f18974 BRANCH_NAME
</code>```

instead of just

```<code> BRANCH_NAME
</code>```

答:
What worked best for me is:

```<code>BRANCH := $(shell git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$$(git rev-parse HEAD)/ {print \$$2}")
HASH := $(shell git rev-parse HEAD)
</code>```

Those variables can then be used e.g. with $(BRANCH)

Body:
I am writing a Makefile and would like to capture the current branch name in a variable to be passed into a --define.
Since the script sometimes but not always runs on travis the git repository might be in detached state.

I can extract the branch name on the command line but unfortunately not capture it in a variable. It seems as if the print $$2 does not work within the Makefile environment.

My current line is:

BRANCH := $(shell git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$$(git rev-parse HEAD)/ {print $$2}")

and I get

dfd943a57015dbd2129ca7b7033c4e1749f18974 BRANCH_NAME

instead of just

 BRANCH_NAME

Body:
What worked best for me is:

BRANCH := $(shell git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$$(git rev-parse HEAD)/ {print \$$2}")
HASH := $(shell git rev-parse HEAD)

Those variables can then be used e.g. with $(BRANCH)


问:
MySql InnoDB Repeatable Read Unexpected behavior of locks
As I know, innoDB use mechanism of consistent non blocking read,
so every transaction works with its own snapshot.

it is told also in official documentation

A consistent read does not set any locks on the tables it accesses, and therefore other sessions are free to modify those tables at the same time a consistent read is being performed on the table.

But I unexpectedly faced with behavior when classic 'read/update' deadlock appears:

Isolation level REPEATABLE READ (also is reproduced with READ COMMITTED)

Transaction 1 reads row (NOT lock in share mode).

Transaction 2 reads the same row ( ALSO NOT lock in share mode).
then

Transaction 1 tries to update this row.

Transaction 2 also tries to update this row.

After last step, innoDB detects deadlock (there is LATEST DETECTED DEADLOCK below):
    ----------------
    2017-03-31 16:07:03 0x1f58
    *** (1) TRANSACTION:
    TRANSACTION 413412, ACTIVE 20 sec starting index read
    mysql tables in use 1, locked 1
    LOCK WAIT 9 lock struct(s), heap size 1136, 6 row lock(s), undo log entries 3
    MySQL thread id 33, OS thread handle 8148, query id 102005 localhost 127.0.0.1 root updating

```<code>/* update Order */ update `Order` set ... <fields to update>

*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 2151 page no 709 n bits 88 index PRIMARY of table `ooapp2`.`order` trx id 413412 lock_mode X locks rec but not gap waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 54; compact format; info bits 0

*** (2) TRANSACTION:
TRANSACTION 413413, ACTIVE 11 sec starting index read
mysql tables in use 1, locked 1
9 lock struct(s), heap size 1136, 6 row lock(s), undo log entries 3
MySQL thread id 28, OS thread handle 8024, query id 102008 localhost 127.0.0.1 root updating

/* update Order */ update `Order` set ...<fields to update>

*** (2) **HOLDS THE LOCK(S):**
RECORD LOCKS space id 2151 page no 709 n bits 88 index PRIMARY of table `ooapp2`.`order` trx id 413413 lock mode S locks rec but not gap
Record lock, heap no 3 PHYSICAL RECORD: n_fields 54; compact format; info bits 0

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 2151 page no 709 n bits 88 index PRIMARY of table `ooapp2`.`order` trx id 413413 lock_mode X locks rec but not gap waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 54; compact format; info bits 0

 *** WE ROLL BACK TRANSACTION (2)
</code>```

I can't understand, what happens, why Transaction 2

HOLDS THE LOCK(S)

so if innoDB nevertheless not use Consistent Read with snapshot and sets S-locks
this does not correspond to the fact that is written in official manual.

答:
Don't do that.  If you might be updating a row, but meanwhile need the value, use SELECT ... FOR UPDATE;.  Just do that, and forget about tx_isolation.  Normally, this will turn a Deadlock into a delay.  (See innodb_lock_wait_timeout, which defaults to an over-generous 50 seconds.)

Also, when you do get a Deadlock, re-run the entire transaction.  Deadlocks will happen no matter how hard you try to avoid them.

Body:
As I know, innoDB use mechanism of consistent non blocking read,
so every transaction works with its own snapshot.

it is told also in official documentation

A consistent read does not set any locks on the tables it accesses, and therefore other sessions are free to modify those tables at the same time a consistent read is being performed on the table.

But I unexpectedly faced with behavior when classic 'read/update' deadlock appears:

Isolation level REPEATABLE READ (also is reproduced with READ COMMITTED)

Transaction 1 reads row (NOT lock in share mode).

Transaction 2 reads the same row ( ALSO NOT lock in share mode).
then

Transaction 1 tries to update this row.

Transaction 2 also tries to update this row.

After last step, innoDB detects deadlock (there is LATEST DETECTED DEADLOCK below):
    ----------------
    2017-03-31 16:07:03 0x1f58
    *** (1) TRANSACTION:
    TRANSACTION 413412, ACTIVE 20 sec starting index read
    mysql tables in use 1, locked 1
    LOCK WAIT 9 lock struct(s), heap size 1136, 6 row lock(s), undo log entries 3
    MySQL thread id 33, OS thread handle 8148, query id 102005 localhost 127.0.0.1 root updating

/* update Order */ update `Order` set ... <fields to update>

*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 2151 page no 709 n bits 88 index PRIMARY of table `ooapp2`.`order` trx id 413412 lock_mode X locks rec but not gap waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 54; compact format; info bits 0

*** (2) TRANSACTION:
TRANSACTION 413413, ACTIVE 11 sec starting index read
mysql tables in use 1, locked 1
9 lock struct(s), heap size 1136, 6 row lock(s), undo log entries 3
MySQL thread id 28, OS thread handle 8024, query id 102008 localhost 127.0.0.1 root updating

/* update Order */ update `Order` set ...<fields to update>

*** (2) **HOLDS THE LOCK(S):**
RECORD LOCKS space id 2151 page no 709 n bits 88 index PRIMARY of table `ooapp2`.`order` trx id 413413 lock mode S locks rec but not gap
Record lock, heap no 3 PHYSICAL RECORD: n_fields 54; compact format; info bits 0

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 2151 page no 709 n bits 88 index PRIMARY of table `ooapp2`.`order` trx id 413413 lock_mode X locks rec but not gap waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 54; compact format; info bits 0

 *** WE ROLL BACK TRANSACTION (2)

I can't understand, what happens, why Transaction 2

HOLDS THE LOCK(S)

so if innoDB nevertheless not use Consistent Read with snapshot and sets S-locks
this does not correspond to the fact that is written in official manual.


问:
Android studio internal file path, file not saved
Small problem, I am trying to save my PDF file in phone (LG G5 - no SD card), but file is never saved, is there a problem with file path? Using PdfBox-Android library. See picture from debugger - Debugger picture. The aim is to save pdf file to internal downloads folder. I tried 10x solutions, nothing is working. Please help.</p>

答:
The aim is to save pdf file to internal downloads folder

Use Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), not getFilesDir(). Also:

You will need the WRITE_EXTERNAL_STORAGE permission

You will need to handle runtime permissions

You will need to get the file indexed by the MediaStore before it will show up


问:
Sending email from specific server gives socket forbidden error
I get this error
An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.xxx.xxx:587 when sending email from a godaddy server.

I have seen many questions like this but what's unique here is that, this code works on my local computer. It also works on my other Go daddy hosting Server.

This original server has TLS 1.0, because i needed TLS 1.2, I purchased a deluxe hosting plan and moved my code to this new server, then i start getting this error.  I've searched everywhere and used every combination of  port 587, 465, 25 along with ssl = false or true.

Any ideas please?

```<code>        using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
        {

            MailMessage mail = new MailMessage();
           smtpClient.UseDefaultCredentials = false;

           smtpClient.Credentials = new NetworkCredential("********@gmail.com", "********");
            smtpClient.EnableSsl = true;
            string fromEmail = "********@gmail.com";
            mail.From = new MailAddress(fromEmail, "System");
            mail.To.Add(new MailAddress(toEmail));
            mail.Body = body.ToString();
            mail.Subject = subject;
            smtpClient.Send(mail);
        }
</code>```

答: Sounds like a firewall or AV or other port blocking software preventing outbound connections to port 587. Check your server config and look in the windows event log as there might be an entry in there indicating who did the blocking.</p>

Body:
I get this error
An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.xxx.xxx:587 when sending email from a godaddy server.

I have seen many questions like this but what's unique here is that, this code works on my local computer. It also works on my other Go daddy hosting Server.

This original server has TLS 1.0, because i needed TLS 1.2, I purchased a deluxe hosting plan and moved my code to this new server, then i start getting this error.  I've searched everywhere and used every combination of  port 587, 465, 25 along with ssl = false or true.

Any ideas please?

        using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
        {

            MailMessage mail = new MailMessage();
           smtpClient.UseDefaultCredentials = false;

           smtpClient.Credentials = new NetworkCredential("********@gmail.com", "********");
            smtpClient.EnableSsl = true;
            string fromEmail = "********@gmail.com";
            mail.From = new MailAddress(fromEmail, "System");
            mail.To.Add(new MailAddress(toEmail));
            mail.Body = body.ToString();
            mail.Subject = subject;
            smtpClient.Send(mail);
        }


问:
The results are different ; recv(sock,buf,sizeof(buf),0) and strlen(buf) in c++
This is my code..

```<code>char buf[5000];
bool isHandshaking = false;
bool isSingaling = false;

while(1)
{
    //-----------클라이언트로부터 수신------------

    int recvsize = recv(sock,buf,sizeof(buf),0);
    printf("recvsize = %d\n",recvsize);

    buf[recvsize] = '\0';
    printf("buf_len = %d\n",strlen(buf));
    .
    .
    .
}
</code>```

The above result...

```<code>recvsize = 2525
buf_len = 126 /*(or different value, sometimes 2525)*/
</code>```

value of recvsize is alaways 2525
And I expected that the strlen value of buf would of course be equal to recvsize.However, bufsize is sometimes equal to 2525 ,But sometimes it is not the same.
What am I missing?

答:
This means there is a null byte in the received data (which means you likely shouldn't be treating it as textual data to begin with, it is clearly binary data instead).  recv() received 2525 bytes, but the byte located at index 126 was 0x00. strlen() stops counting at the first '\0' char it encounters.

You also have a potential buffer overflow. If recv() happens to receive exactly sizeof(buf) number of bytes, you are writing a NULL terminator out of bounds of your array.  You would need to request sizeof(buf)-1 bytes instead. Otherwise, don't insert a NULL terminator into buf at all. Dont treat it as null-terminated text, since it is technically arbitrary data, and do use the value returned by recv() to know how many bytes buf actually holds.

Body:
This is my code..

char buf[5000];
bool isHandshaking = false;
bool isSingaling = false;

while(1)
{
    //-----------클라이언트로부터 수신------------

    int recvsize = recv(sock,buf,sizeof(buf),0);
    printf("recvsize = %d\n",recvsize);

    buf[recvsize] = '\0';
    printf("buf_len = %d\n",strlen(buf));
    .
    .
    .
}

The above result...

recvsize = 2525
buf_len = 126 /*(or different value, sometimes 2525)*/

value of recvsize is alaways 2525
And I expected that the strlen value of buf would of course be equal to recvsize.However, bufsize is sometimes equal to 2525 ,But sometimes it is not the same.
What am I missing?


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: I've only been programming for about a year, so for me, it was LINQ. I looked at codes in books that exposed the query string to the DB, and thought "wow, that's kind of lame.". The I met LINQ and we have been happily married ever since.</p>

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: Bbetances


问:
help with Jsonp and jQuery
I have a web service served in jsonp, but since I'm new to this I have difficulties retrieving the data. Here's my code:

```<code>$(document).ready(function(){
   $.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=myData",
       function myData(result){
           $('#status').append(result.name.text);
        }
   );

});
</code>```

the div #status returns empty.

could you help?

Thanks in advance

Mauro

Update: now it works! Bout it does't when I'm trying to loop though the data:

```<code>$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?",
         function (result){
              $.each(result.items, function(item){
                 $('#status').append(item.response.lines[0].name);
        });
     }
);
</code>```

What am I doing wrong?

Thanks

答:
This is the output of the URL:

```<code>myData({"response":{"lines":[{"name":"Central"},{"name":"Victoria"}]}});
</code>```

You can reformat the object to make it clearer:

```<code>{
    "response": {
        "lines": [
            {"name":"Central"},
            {"name":"Victoria"}
        ]
    }
}
</code>```

I see no property called text. You probably mean:

```<code>$('#status').append(result.response.lines[0].name);
</code>```

Update: this solution doesn't fully solve the problem. As suggested in the accepted answer, you need to instruct jQuery to generate a random function name (you cannot provide your own, not at least with getJSON).

Title: help with Jsonp and jQuery

Body:
I have a web service served in jsonp, but since I'm new to this I have difficulties retrieving the data. Here's my code:

$(document).ready(function(){
   $.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=myData",
       function myData(result){
           $('#status').append(result.name.text);
        }
   );

});

the div #status returns empty.

could you help?

Thanks in advance

Mauro

Update: now it works! Bout it does't when I'm trying to loop though the data:

$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?",
         function (result){
              $.each(result.items, function(item){
                 $('#status').append(item.response.lines[0].name);
        });
     }
);

What am I doing wrong?

Thanks

Body:
This is the output of the URL:

myData({"response":{"lines":[{"name":"Central"},{"name":"Victoria"}]}});

You can reformat the object to make it clearer:

{
    "response": {
        "lines": [
            {"name":"Central"},
            {"name":"Victoria"}
        ]
    }
}

I see no property called text. You probably mean:

$('#status').append(result.response.lines[0].name);

Update: this solution doesn't fully solve the problem. As suggested in the accepted answer, you need to instruct jQuery to generate a random function name (you cannot provide your own, not at least with getJSON).


答:
```<code>foreach ($getPostlikes as $key=> $item) {//suppose array is $getPostlikes
  echo $item['from']['name'];
}
</code>```

Title: How to iterate this multi dimensional array in php?


问:
OpenCV with Python - Placing an image of a hat over the head of a webcam feed
I am trying to place a png image of a hat over the head of a webcam feed. I am trying to detect a face and place the image above it. This is my code so far -

```<code>import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')

imghat = cv2.imread('hat.png', -1)

print imghat is None

imghatGray = cv2.cvtColor(imghat, cv2.COLOR_BGR2GRAY)

ret, orig_mask = cv2.threshold(imghatGray, 0, 255, cv2.THRESH_BINARY)
orig_mask_inv = cv2.bitwise_not(orig_mask)

# Convert hat image to BGR
# and save the original image size (used later when re-sizing the image)
imghat = imghat[:,:,0:3]
origHatHeight, origHatWidth = imghat.shape[:2]

video_capture = cv2.VideoCapture(0)

while True:

    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5, flags=cv2.cv.CV_HAAR_SCALE_IMAGE)

    for (x, y, w, h) in faces:
        print "x : %d , y : %d, w: %d, h: %d " %(x,y,w,h)
        cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)
        cv2.rectangle(frame, (x-15,y-h), (x+w+15, y), (255,255,0), 2)

        print w
        print h
        hatWidth = w
        hatHeight = hatWidth * origHatHeight / origHatWidth

        roi_gray = gray[y-hatHeight:y, x-15:x+w+15]
        roi_color = frame[y-hatHeight:y, x-15:x+w+15]

        # Center the hat
        x1 = x - 15
        y1 = y - h
        x2 = x + w +15
        y2 = y

        cv2.rectangle(frame, (x1,y1), (x2, y2), (0,255,0), 2)

        # Check for clipping
        if x1 < 0:
            x1 = 0
        if y1 < 0:
            y1 = 0
        if x2 > w:
            x2 = w
        if y2 > h:
            y2 = h

        # Re-calculate the width and height of the hat image
        hatWidth = x2 - x1
        hatHeight = y2 - y1

        # Re-size the original image and the masks to the hat sizes
        # calcualted above
        hat = cv2.resize(imghat, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
        mask = cv2.resize(orig_mask, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
        mask_inv = cv2.resize(orig_mask_inv, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)

        # take ROI for hat from background equal to size of hat image
        roi = roi_color[y1:y2, x1:x2]

        # roi_bg contains the original image only where the hat is not
        # in the region that is the size of the hat.
        roi_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

        # roi_fg contains the image of the hat only where the hat is
        roi_fg = cv2.bitwise_and(hat,hat,mask = mask)

        # join the roi_bg and roi_fg
        dst = cv2.add(roi_bg,roi_fg)

        # place the joined image, saved to dst back over the original image
        roi_color[y1:y2, x1:x2] = dst

        break

    # Display the resulting frame
        cv2.imshow('Video', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

video_capture.release()
cv2.destroyAllWindows()
</code>```

I get this error - OpenCV Error: Assertion failed (s >= 0) in setSize everytime I run it. The webcam start and closes abruptly. The error is somewhere in -

```<code>            hat = cv2.resize(imghat, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
            mask = cv2.resize(orig_mask, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
            mask_inv = cv2.resize(orig_mask_inv, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
</code>```

The values of hatWidth and hatHeight are negative. But I cannot find an error in the assignment of the coordinates. Is it because of the ROI in the program?

答: I faced the same error. The solution is found by plotting the co ordinates values. One such point was lying outside the dimensions of the image. So was getting error. I fixed it later and set bounding conditions so that the ROI dimensions dont exceed the image dimensions. Thanks anyway. </p>

Body:
I am trying to place a png image of a hat over the head of a webcam feed. I am trying to detect a face and place the image above it. This is my code so far -

import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')

imghat = cv2.imread('hat.png', -1)

print imghat is None

imghatGray = cv2.cvtColor(imghat, cv2.COLOR_BGR2GRAY)

ret, orig_mask = cv2.threshold(imghatGray, 0, 255, cv2.THRESH_BINARY)
orig_mask_inv = cv2.bitwise_not(orig_mask)

# Convert hat image to BGR
# and save the original image size (used later when re-sizing the image)
imghat = imghat[:,:,0:3]
origHatHeight, origHatWidth = imghat.shape[:2]

video_capture = cv2.VideoCapture(0)

while True:

    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5, flags=cv2.cv.CV_HAAR_SCALE_IMAGE)

    for (x, y, w, h) in faces:
        print "x : %d , y : %d, w: %d, h: %d " %(x,y,w,h)
        cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)
        cv2.rectangle(frame, (x-15,y-h), (x+w+15, y), (255,255,0), 2)

        print w
        print h
        hatWidth = w
        hatHeight = hatWidth * origHatHeight / origHatWidth

        roi_gray = gray[y-hatHeight:y, x-15:x+w+15]
        roi_color = frame[y-hatHeight:y, x-15:x+w+15]

        # Center the hat
        x1 = x - 15
        y1 = y - h
        x2 = x + w +15
        y2 = y

        cv2.rectangle(frame, (x1,y1), (x2, y2), (0,255,0), 2)

        # Check for clipping
        if x1 < 0:
            x1 = 0
        if y1 < 0:
            y1 = 0
        if x2 > w:
            x2 = w
        if y2 > h:
            y2 = h

        # Re-calculate the width and height of the hat image
        hatWidth = x2 - x1
        hatHeight = y2 - y1

        # Re-size the original image and the masks to the hat sizes
        # calcualted above
        hat = cv2.resize(imghat, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
        mask = cv2.resize(orig_mask, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
        mask_inv = cv2.resize(orig_mask_inv, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)

        # take ROI for hat from background equal to size of hat image
        roi = roi_color[y1:y2, x1:x2]

        # roi_bg contains the original image only where the hat is not
        # in the region that is the size of the hat.
        roi_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

        # roi_fg contains the image of the hat only where the hat is
        roi_fg = cv2.bitwise_and(hat,hat,mask = mask)

        # join the roi_bg and roi_fg
        dst = cv2.add(roi_bg,roi_fg)

        # place the joined image, saved to dst back over the original image
        roi_color[y1:y2, x1:x2] = dst

        break

    # Display the resulting frame
        cv2.imshow('Video', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

video_capture.release()
cv2.destroyAllWindows()

I get this error - OpenCV Error: Assertion failed (s >= 0) in setSize everytime I run it. The webcam start and closes abruptly. The error is somewhere in -

            hat = cv2.resize(imghat, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
            mask = cv2.resize(orig_mask, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)
            mask_inv = cv2.resize(orig_mask_inv, (hatWidth,hatHeight), interpolation = cv2.INTER_AREA)

The values of hatWidth and hatHeight are negative. But I cannot find an error in the assignment of the coordinates. Is it because of the ROI in the program?


问:
Scrape all matching contents using XPath function
How do I make sure that my selenium code scrapes all matching contents of my XPath?

Please help me with your ideas.

For example, these are my HTML Tags:

```<code><tr class="1" role="r1">
    <td class="c1">
        <a href="www.google.com">
        </a>
    </td>
</tr>
<tr class="2" role="r2">
    <td class="c2">
        <a href="www.youtube.com">
        </a>
    </td>
</tr>
<tr class="3" role="c3">
    <td class="c3">
        <a href="www.facebook.com">
        </a>
    </td>
</tr>
</code>```

I want my selenium code to fetch all links from href tag.

So, below is my XPath:

```<code>String links = driver.findElement(By.xpath("//tr[@role='cad']//td[@class='c1']//a")).getAttribute("href");
System.out.println(links);
</code>```

but it fetches only the first href output, i.e. www.google.com.

The desired output is:

```<code>www.google.com
www.youtube.com
www.facebook.com
</code>```

How can I achieve this?

Any array implementation would be better options?

答:
Try Following code:</p>

```<code> List<WebElement> elements= driver.findElements(By.xpath("//table/tbody/tr"));

    int i =0 ;

    while(i<elements.size()){

        WebElement childElement =  elements.get(i).findElement(By.cssSelector("a"));

    System.out.println(childElement.getAttribute("href"));

    i++;
    }
</code>```

Body:
How do I make sure that my selenium code scrapes all matching contents of my XPath?

Please help me with your ideas.

For example, these are my HTML Tags:

I want my selenium code to fetch all links from href tag.

So, below is my XPath:

String links = driver.findElement(By.xpath("//tr[@role='cad']//td[@class='c1']//a")).getAttribute("href");
System.out.println(links);

but it fetches only the first href output, i.e. www.google.com.

The desired output is:

www.google.com
www.youtube.com
www.facebook.com

How can I achieve this?

Any array implementation would be better options?

Body:
Try Following code:

 List<WebElement> elements= driver.findElements(By.xpath("//table/tbody/tr"));

    int i =0 ;

    while(i<elements.size()){

        WebElement childElement =  elements.get(i).findElement(By.cssSelector("a"));

    System.out.println(childElement.getAttribute("href"));

    i++;
    }


问:
Swift: Convert string to hex color code
I have generated user Ids (with a format like ""XzSYoKJaqKYREkdB2dgwt0fLOPP2"") from a database that I would like to use to create an UIColor.

I found several solutions on how to crate an UIColor with a color hex code, but I don't quite know how I would generate a color hex code (#ffffff) from a string like the one above. Any help would be appreciated, thanks.

答:
As of my understanding, you're trying to generate a random colour each time for every user and store it in the Firebase? Correct me if I'm wrong.

I hope this solution would fix your issue of creating random colours each time. In short, wherever and whenever you need a random unique colour - call the method and check if the returned UIColor already exists in the database. If it doesn't exist then use it!

```<code>func getRandomColor() -> UIColor {
let randomRed:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomGreen:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomBlue:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
</code>```

I hope the above solution from Oscar De Moya's from https://classictutorials.com/2014/08/generate-a-random-color-in-swift/ would help you.

Title: Swift: Convert string to hex color code

Body:
As of my understanding, you're trying to generate a random colour each time for every user and store it in the Firebase? Correct me if I'm wrong.

I hope this solution would fix your issue of creating random colours each time. In short, wherever and whenever you need a random unique colour - call the method and check if the returned UIColor already exists in the database. If it doesn't exist then use it!

func getRandomColor() -> UIColor {
let randomRed:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomGreen:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomBlue:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}

I hope the above solution from Oscar De Moya's from https://classictutorials.com/2014/08/generate-a-random-color-in-swift/ would help you.


问:
What does this error mean, and how do I resolve it? (java.lang.InternalError: Memory Pool not found)
We're getting a very curious error in our application.

java.lang.InternalError: Memory Pool not found

```<code> for ( final MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans() ) {
  final MemoryUsage usage = bean.getUsage(); // Error thrown on this line
  System.out.println(usage);
 }
</code>```

What does this error mean, and how do I resolve it? I've googled around quite a bit, and it looks like few people have experienced it and no one has provided any good solutions.

Thanks in advance.

EDIT:

I am running JRockit jrrt-3.0.0-1.6.0_sun_jdk1.6_16 on Linux.

答:
I think one of the pools has been deallocated while iterating over the list of MXBeans, hence it is not found anymore.

This is highly specific to the environment used, maybe you could provide some more details about the JVM and/or applicationserver/container in use.

Body:
We're getting a very curious error in our application.

java.lang.InternalError: Memory Pool not found

 for ( final MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans() ) {
  final MemoryUsage usage = bean.getUsage(); // Error thrown on this line
  System.out.println(usage);
 }

What does this error mean, and how do I resolve it? I've googled around quite a bit, and it looks like few people have experienced it and no one has provided any good solutions.

Thanks in advance.

EDIT:

I am running JRockit jrrt-3.0.0-1.6.0_sun_jdk1.6_16 on Linux.


问:
Class must either be declared abstract or implement abstract method toArray
I have a Foo class that extends AbstractList and implements List. This class implements some of the List methods, but some just throw UnsupportedOperationException.

toArray is one of the later and while the compiler doesn't complain about other not really implemented methods, it complains about the toArray with error:

Class must either be declared abstract or implement abstract method toArray(T[]) in List.

```<code>public class Foo extends AbstractList implementst List  {
    ...
     public <T> T[] toArray(T[] a) throws UnsupportedOperationException {
        throw new UnsupportedOperationException(error);
    }
}
</code>```

What is wrong here and why the compiler still thinks the toArray(T[]) method is not implemented?

答:
Since you are using generic method public  T[] toArray(T[] a), you should add parameter to class signature and make it extend and implement parameterized class and interface respectively, not the raw ones. Then it will compile:</p>

```<code>public class Foo<T> extends AbstractList<T> implements List<T> {

    @Override
    public <E> E[] toArray(E[] a) throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Error!");
    }

    ...
}
</code>```

Body:
I have a Foo class that extends AbstractList and implements List. This class implements some of the List methods, but some just throw UnsupportedOperationException.

toArray is one of the later and while the compiler doesn't complain about other not really implemented methods, it complains about the toArray with error:

Class must either be declared abstract or implement abstract method toArray(T[]) in List.

public class Foo extends AbstractList implementst List  {
    ...
     public <T> T[] toArray(T[] a) throws UnsupportedOperationException {
        throw new UnsupportedOperationException(error);
    }
}

What is wrong here and why the compiler still thinks the toArray(T[]) method is not implemented?

Body:
Since you are using generic method public  T[] toArray(T[] a), you should add parameter to class signature and make it extend and implement parameterized class and interface respectively, not the raw ones. Then it will compile:

public class Foo<T> extends AbstractList<T> implements List<T> {

    @Override
    public <E> E[] toArray(E[] a) throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Error!");
    }

    ...
}