问:
How to properly blend colors across two triangles and remove diagonal smear
I am learning WebGL and I've drawn a full screen quad with colors for each vertex. No lighting or normals or perspective matrix or depth buffer; I'm just drawing a gradient background. This is what I get:

It looks good but I cannot help noticing the diagonal smear from the bottom right to the top left. I feel this is an artifact of linear interpolating the far opposite vertices. I'm drawing two triangles: the bottom left, and the top right. I think I would get similar results using OpenGL instead of WebGL.

Given the same four colors and the same size rectangle, is there a way to render this so the edge between the two triangles isn't so apparent? Maybe more vertices, or a different blending function? I'm not sure exactly what the colors should be at each pixel; I just want to know how to get rid of the diagonal smear.

答:
Number of dimensions

You should be passing the 2D coordinate space of the quad to the fragment shader rather than the one dimensional (per channel) color space.

Then in the fragment shader you can do the color interpolation in 2D space removing the color artifact due to the diagonal line interpolating in 1D.

The shader snippet for linear color interpolation, where coord2D is the 2D coordinate space

```<code>pixel = vec4(vec3(mix(
        mix(colors[0], colors[1], coord2D.x),
        mix(colors[2], colors[3], coord2D.x),
        coord2D.y
    )), 1);
</code>```

Improved color interpolation

When interpolating colors by their RGB values the results can visually darken between opposing hues.

An easy fix is to use a closer approximation of the sRGB color model by interpolating between the squares of the color channel values. The final output is the square root of the interpolated values.

The interpolation snippet.

```<code>pixel = vec4(sqrt(vec3(mix(
        mix(colors[0], colors[1], coord2D.x),
        mix(colors[2], colors[3], coord2D.x),
        coord2D.y
    ))) / 255.0, 1);
</code>```

Note that the color channel values in the uniform colors are in logarithmic space. [R^2, G^2, B^2] and thus range from 0 to 65025.

Example

In the example click the canvas to switch between interpolation methods.

You will note that when using approx ~sRGB that the brightness in the center of the canvas out towards the center edges does not dip as much below the perceivable brightness at the corners.

Also note that the balance of the transition from the bottom blue and redish to the top orange and white moves down closer the the center. This is because interpolating the RGB model will darken colors that have strong components from 2 or more channels, Reds, greens, blues and blacks will dominate over yellows, cyans, magentas and whites making the interpolation seem to shift and stretch out the RGB primaries.

    var program, colorsLoc, modelLoc, loc, text = " interpolation. Click for ", model = "RGB"; // or sRGB
const vertSrc = `#version 300 es
    in vec2 verts;
    out vec2 coord2D;
    void main() {
        coord2D = verts * 0.5 + 0.5; // convert to quad space 0,0 <=> 1, 1
        gl_Position = vec4(verts, 1, 1);
    }`;
const fragSrc = `#version 300 es
    #define channelMax 255.0
    // color location indexes
    #define TR 3
    #define TL 2
    #define BR 1
    #define BL 0
    precision mediump float;
    uniform vec3 colors[4];
    uniform bool isRGB;
    in vec2 coord2D;
    out vec4 pixel;
    void main() {
        if (isRGB) {
            pixel = vec4(vec3(mix(
                    mix(colors[BL], colors[BR], coord2D.x),
                    mix(colors[TL], colors[TR], coord2D.x),
                    coord2D.y
                )) / channelMax, 1);
         } else {
            pixel = vec4(vec3(sqrt(mix(
                    mix(colors[BL], colors[BR], coord2D.x),
                    mix(colors[TL], colors[TR], coord2D.x),
                    coord2D.y
                ))) / channelMax, 1);
         }
    }`;
const fArr = arr => new Float32Array(arr);
const colors = [64,140,190, 224,81,141, 247,223,140, 245,245,245];
const gl = canvas.getContext("webgl2", {premultipliedAlpha: false, antialias: false, alpha: false});
addEventListener("resize", draw);
addEventListener("click", draw);
setup();
draw();
function compileShader(src, type, shader = gl.createShader(type)) {
    gl.shaderSource(shader, src);
    gl.compileShader(shader);
    return shader;
}
function setup() {
    program = gl.createProgram();
    gl.attachShader(program, compileShader(vertSrc, gl.VERTEX_SHADER));
    gl.attachShader(program, compileShader(fragSrc, gl.FRAGMENT_SHADER));
    gl.linkProgram(program);
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array([0,1,2,0,2,3]), gl.STATIC_DRAW);
    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
    gl.bufferData(gl.ARRAY_BUFFER, fArr([-1,-1,1,-1,1,1,-1,1]), gl.STATIC_DRAW);
    gl.enableVertexAttribArray(loc = gl.getAttribLocation(program, "verts"));
    gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
    colorsLoc = gl.getUniformLocation(program, "colors");
    modelLoc = gl.getUniformLocation(program, "isRGB");
    gl.useProgram(program);
}
function draw() {
    [info.textContent, model] = model != "RGB"? [`RGB${text}~sRGB.`, "RGB"]: [`~sRGB${text}RGB.`, "~sRGB"];
    if (canvas.width !== innerWidth || canvas.height !== innerHeight) {
        [canvas.width, canvas.height] = [innerWidth, innerHeight];
        gl.viewport(0, 0, canvas.width, canvas.height);
    }
    gl.uniform3fv(colorsLoc, fArr(colors.map(v => model=="RGB"? v: v*v)), 0, 12);
    gl.uniform1i(modelLoc, model=="RGB");
    gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_BYTE, 0);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    padding: 0px;
    margin: 0px;
    font-family: arial;
    color: white;
}
canvas {
    position: absolute;
    top: 0px;
    left: 0px;
}
h2 {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    text-align: center;

}</code>```

<canvas id="canvas"></canvas>

```

Body:
Number of dimensions

You should be passing the 2D coordinate space of the quad to the fragment shader rather than the one dimensional (per channel) color space.

Then in the fragment shader you can do the color interpolation in 2D space removing the color artifact due to the diagonal line interpolating in 1D.

The shader snippet for linear color interpolation, where coord2D is the 2D coordinate space

pixel = vec4(vec3(mix(
        mix(colors[0], colors[1], coord2D.x),
        mix(colors[2], colors[3], coord2D.x),
        coord2D.y
    )), 1);

Improved color interpolation

When interpolating colors by their RGB values the results can visually darken between opposing hues.

An easy fix is to use a closer approximation of the sRGB color model by interpolating between the squares of the color channel values. The final output is the square root of the interpolated values.

The interpolation snippet.

pixel = vec4(sqrt(vec3(mix(
        mix(colors[0], colors[1], coord2D.x),
        mix(colors[2], colors[3], coord2D.x),
        coord2D.y
    ))) / 255.0, 1);

Note that the color channel values in the uniform colors are in logarithmic space. [R^2, G^2, B^2] and thus range from 0 to 65025.

Example

In the example click the canvas to switch between interpolation methods.

You will note that when using approx ~sRGB that the brightness in the center of the canvas out towards the center edges does not dip as much below the perceivable brightness at the corners.

Also note that the balance of the transition from the bottom blue and redish to the top orange and white moves down closer the the center. This is because interpolating the RGB model will darken colors that have strong components from 2 or more channels, Reds, greens, blues and blacks will dominate over yellows, cyans, magentas and whites making the interpolation seem to shift and stretch out the RGB primaries.

    var program, colorsLoc, modelLoc, loc, text = " interpolation. Click for ", model = "RGB"; // or sRGB
const vertSrc = `#version 300 es
    in vec2 verts;
    out vec2 coord2D;
    void main() {
        coord2D = verts * 0.5 + 0.5; // convert to quad space 0,0 <=> 1, 1
        gl_Position = vec4(verts, 1, 1);
    }`;
const fragSrc = `#version 300 es
    #define channelMax 255.0
    // color location indexes
    #define TR 3
    #define TL 2
    #define BR 1
    #define BL 0
    precision mediump float;
    uniform vec3 colors[4];
    uniform bool isRGB;
    in vec2 coord2D;
    out vec4 pixel;
    void main() {
        if (isRGB) {
            pixel = vec4(vec3(mix(
                    mix(colors[BL], colors[BR], coord2D.x),
                    mix(colors[TL], colors[TR], coord2D.x),
                    coord2D.y
                )) / channelMax, 1);
         } else {
            pixel = vec4(vec3(sqrt(mix(
                    mix(colors[BL], colors[BR], coord2D.x),
                    mix(colors[TL], colors[TR], coord2D.x),
                    coord2D.y
                ))) / channelMax, 1);
         }
    }`;
const fArr = arr => new Float32Array(arr);
const colors = [64,140,190, 224,81,141, 247,223,140, 245,245,245];
const gl = canvas.getContext("webgl2", {premultipliedAlpha: false, antialias: false, alpha: false});
addEventListener("resize", draw);
addEventListener("click", draw);
setup();
draw();
function compileShader(src, type, shader = gl.createShader(type)) {
    gl.shaderSource(shader, src);
    gl.compileShader(shader);
    return shader;
}
function setup() {
    program = gl.createProgram();
    gl.attachShader(program, compileShader(vertSrc, gl.VERTEX_SHADER));
    gl.attachShader(program, compileShader(fragSrc, gl.FRAGMENT_SHADER));
    gl.linkProgram(program);
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array([0,1,2,0,2,3]), gl.STATIC_DRAW);
    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
    gl.bufferData(gl.ARRAY_BUFFER, fArr([-1,-1,1,-1,1,1,-1,1]), gl.STATIC_DRAW);
    gl.enableVertexAttribArray(loc = gl.getAttribLocation(program, "verts"));
    gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
    colorsLoc = gl.getUniformLocation(program, "colors");
    modelLoc = gl.getUniformLocation(program, "isRGB");
    gl.useProgram(program);
}
function draw() {
    [info.textContent, model] = model != "RGB"? [`RGB${text}~sRGB.`, "RGB"]: [`~sRGB${text}RGB.`, "~sRGB"];
    if (canvas.width !== innerWidth || canvas.height !== innerHeight) {
        [canvas.width, canvas.height] = [innerWidth, innerHeight];
        gl.viewport(0, 0, canvas.width, canvas.height);
    }
    gl.uniform3fv(colorsLoc, fArr(colors.map(v => model=="RGB"? v: v*v)), 0, 12);
    gl.uniform1i(modelLoc, model=="RGB");
    gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_BYTE, 0);
}

body {
    padding: 0px;
    margin: 0px;
    font-family: arial;
    color: white;
}
canvas {
    position: absolute;
    top: 0px;
    left: 0px;
}
h2 {
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    text-align: center;

}

<canvas id="canvas"></canvas>
<h2 id="info"></h2>


来源: stackexchange

问:
Understanding GraphQL
I started experimenting with the GraphQL wp api.

I am querying the menus. As for the documentation, the query is very long

I would expect that querying

```<code>{
    menus
}
</code>```

only would bring about all the data nested in menus, it does not.

Why is this? What is the way to getting all nested data in an object as to see what's in there?

Thank you for your time

答:
If you keep in mind that you're getting back a JSON object, you can think of your GraphQL query as defining the left-hand side of the response (this is intentional in how it was designed), e.g. just the keys. So unless there are null values, what you get back should exactly match the shape of the query.

If you want to see what can be queried, you need access to the schema itself. If it's a schema provided by someone else (looks like WordPress in this case), they should also have provided the means to explore and understand it.

ContentLicense: CC BY-SA 4.0

Title: Understanding GraphQL

Body:
I started experimenting with the GraphQL wp api.

I am querying the menus. As for the documentation, the query is very long

I would expect that querying

{
    menus
}

only would bring about all the data nested in menus, it does not.

Why is this? What is the way to getting all nested data in an object as to see what's in there?

Thank you for your time


问:
How to access incremented values inside a loop in c
I'm new in programming and I'm stuck on code that reads the integer N from input and prints the first N integers of the following series:

```<code>1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, ...
</code>```

for example if the N is 4 it prints:

```<code>1, -1, -2, 2
</code>```

I wrote my code and it contains a while loop. I need the last value of t and i, which are incremented in the loop, outside of the loop but it doesn't work.

This is my code:

```<code>#include <stdio.h>

int main(void) {
    int n;
    printf("Enter your number: ");
    scanf("%d", &n);

    int i = 1;
    int t = 1;
    while (i <= (n / 2)) {
        int t = i;
        if (i % 2 == 0)
            t *= -1;

        printf("%d", t);
        printf(", %d, ", -t);
        i++;
    }
    if (n % 2 == 1) {
        printf("%d", -t / i * (n + 1) / 2);
    }
    return 0;
}
</code>```

Actually I need that outer part of the code for the odd N's (because when N is an even number like 4, numbers are paired like 1, -1, -2, 2 but when it's odd the last number is single like N=5,1, -1, -2, 2, 3 ). For even N's it works but for the odd's it prints 0 instead of  the last number of the series.

Sorry if my explanation is not clear but I would appreciate any help.

答:
On Some Iterative Improvements to the Code

There are at least a couple of fundamental problems in the OP posted code.

int t = i inside the loop shadows the t defined outside of the loop, and this inner t is lost when the loop is exited. At this point, the value of t in the expression -t / i * (n + 1) / 2) is 1, the value that t was initialized to in this scope. This problem can be fixed by changing int t = i --> t = i in the loop, utilizing the variable t that exists outside of the loop, and allowing that variable to be changed in the loop, but still used after the loop exits.

But here we come to another problem. t is set to the value of i at the top of the loop, but before the loop exits i is incremented. This means that the value of i is greater than the value of t when the loop exits. Thus -t / i is zero in the final print statement! One way to fix this would be to change the final print statement from printf("%d", -t / i * (n + 1) / 2) to printf("%d", -t / (i-1) * (n + 1) / 2). Note that this solution has a serious problem when i == 1; this happens when n == 1.

Since we are really only after the sign of -t here, it might be more clear to use a conditional operator:

```<code>printf("%d", (-t < 0 ? -1 : 1) * (n + 1) / 2)
</code>```

Now that i is no longer needed outside of the loop, we should consider reducing the scope of i. A good general principle is to keep the scopes of variables as small as practically possible. To do this, a for loop seems appropriate:

```<code>int t = 1;
for (int i = 1; i <= (n / 2); i++) {  // reduce scope of `i`
    t = i;
    if (i % 2 == 0)
        t *= -1;

    printf("%d", t);
    printf(", %d, ", -t);
}
if (n % 2 == 1) {
    printf("%d", (-t < 0 ? -1 : 1) * (n + 1) / 2);
}
</code>```

Note now that there are still some significant problems with the code. An input of 1 skips the loop entirely and leads to the incorrect output -1. A newline is never printed after the end of the series (this is just bad form), but worse, even inputs lead to a series printed with a comma and a space on the end! Formatting is important, and looking at the edge cases helps us to avoid bugs. In this case, the first number in a series of only one term is wrong. In a couple of previous (now deleted) answers the solutions partially worked, but gave incorrect results in the last number when the input was an odd number (for every second odd number). Lesson: investigate the edge cases when you code.

When the input is 1, the loop is never entered, but we only need to print the first number of the series. A simple way to handle this is just to handle that input explicitly before the loop.

```<code>if (n == 1) {           // n == 1: the loop is not entered
    printf("1\n");     // handle this special case
}
</code>```

To handle the formatting issue, consider that each pass through the loop prints a pair of numbers. After the last pass, OP code prints one more line when input is an odd number. Instead, handle the last pass through the loop explicitly. If the loop is in its final iteration, print three numbers when input is odd, or print two numbers when input is even. Otherwise, in the typical case, print a pair of numbers with commas as before. Coding in this way allows all series code, except for the special case when input is 1, to be brought inside of the loop, including allowing t to be defined inside the loop (further reducing the scope of t). Here is what that code looks like:

```<code>#include <stdio.h>

int main(void) {
    int n;
    printf("Enter your number: ");
    scanf("%d", &n);

    if (n == 1) {           // n == 1: the loop is not entered
        printf("1\n");     // handle this special case
    }

    for (int i = 1; i <= (n / 2); i++) {
        int t = i;         // reduced scope for `t`
        if (i % 2 == 0)
            t *= -1;

        if (i == n / 2) {  // print last numbers in the series
            if (n % 2) {   // n is odd: print 3 numbers
                printf("%d, %d, %d\n",
                       t,
                       -t,
                       (-t < 0 ? -1 : 1) * (n + 1) / 2);
            } else {       // n is even: print two numbers
                printf("%d, %d\n", t, -t);
            }
        } else {           // print typical pair in the series
            printf("%d, %d, ", t, -t);
        }
    }

    return 0;
}
</code>```

On Input Validation

OP code does not check for valid input from the user. In practice, code as if users are malicious and will provide any input to break your code. Even without malicious intent, a user may accidentally provide improper input. In the OP posted code, if a user inadvertently enters a letter, or anything other than a number, no value is stored in n. In such a case n has indeterminate value, and further attempts to use n will result in undefined behavior. Note that scanf() returns the number of successful assignments made, and checking this value is a part of any input validation (you should almost always check the result returned by any function that returns a value).

You could check this value, and abort the program if the user fails to enter a number. This is not graceful. A better solution might be to take input in a loop, checking to see if a successful assignment was made by scanf(), and looping until a number is entered. This is more complicated than it sounds because the bad (and unassigned) input remains in the input stream after the call to scanf(), and needs to be cleared before progress can be made. The scanf() function is difficult to use correctly, and a better solution is to use fgets() which reads a line of input into a buffer. After this, the buffer can be parsed with sscanf().

The fgets() function returns a null pointer in the unlikely event of a read error; robust code checks for such errors. The code below places the series printing code in a function print_series(), and takes and does very basic validation of input in main(). If there is an input read error, the code simply prints an error message and exits. Note that the input[] array is used as an input buffer, and it is generously sized so that normal input should be contained within it. More robust code would plan for the possibility that more input could arrive than can be held in this buffer. fgets() will not overflow this buffer, but extra input would remain in the input stream in such a case, potentially causing problems for later I/O operations.

If no number can be parsed by sscanf(), the input loop continues, printing another prompt and fetching a fresh line of input into the input buffer. Once a number has been assigned to max, another loop prints all series from length 1 to length max; this helps us to see that the series outputs are as expected for different values of N. Note that when the input is less than 1 for max, the printing loop is not entered at all, and nothing is printed. This may not be the best way to handle such inputs.

```<code>#include <stdio.h>

#define MAX_INPUT  1000

void print_series(int n);

int main(void) {
    char input[MAX_INPUT];
    int max;

    // get user input and do minimal validation
    do {
        printf("Enter longest series to print: ");
        if (fgets(input, sizeof input, stdin) == NULL) {
            puts("Input Failure");
            return 1;
        }
    } while (sscanf(input, "%d", &max) != 1);

    // printing loop
    putchar('\n');
    for (int n = 1; n <= max; n++) {
        print_series(n);
    }

    return 0;
}

void print_series(int n) {
    if (n == 1) {
        printf("1\n");
    }

    for (int i = 1; i <= (n / 2); i++) {
        int t = i;
        if (i % 2 == 0)
            t *= -1;

        if (i == n / 2) {
            if (n % 2) {
                printf("%d, %d, %d\n",
                       t,
                       -t,
                       (-t < 0 ? -1 : 1) * (n + 1) / 2);
            } else {
                printf("%d, %d\n", t, -t);
            }
        } else {
            printf("%d, %d, ", t, -t);
        }
    }
}
</code>```

Sample runs:

$ ./a.out
Enter longest series to print: bad input
Enter longest series to print: 0

$ ./a.out
Enter longest series to print: 19

1
1, -1
1, -1, -2
1, -1, -2, 2
1, -1, -2, 2, 3
1, -1, -2, 2, 3, -3
1, -1, -2, 2, 3, -3, -4
1, -1, -2, 2, 3, -3, -4, 4
1, -1, -2, 2, 3, -3, -4, 4, 5
1, -1, -2, 2, 3, -3, -4, 4, 5, -5
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8, 9
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8, 9, -9
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8, 9, -9, -10
```

Body:
I'm new in programming and I'm stuck on code that reads the integer N from input and prints the first N integers of the following series:

1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, ...

for example if the N is 4 it prints:

1, -1, -2, 2

I wrote my code and it contains a while loop. I need the last value of t and i, which are incremented in the loop, outside of the loop but it doesn't work.

This is my code:

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter your number: ");
    scanf("%d", &n);

    int i = 1;
    int t = 1;
    while (i <= (n / 2)) {
        int t = i;
        if (i % 2 == 0)
            t *= -1;

        printf("%d", t);
        printf(", %d, ", -t);
        i++;
    }
    if (n % 2 == 1) {
        printf("%d", -t / i * (n + 1) / 2);
    }
    return 0;
}

Actually I need that outer part of the code for the odd N's (because when N is an even number like 4, numbers are paired like 1, -1, -2, 2 but when it's odd the last number is single like N=5,1, -1, -2, 2, 3 ). For even N's it works but for the odd's it prints 0 instead of  the last number of the series.

Sorry if my explanation is not clear but I would appreciate any help.

Body:
On Some Iterative Improvements to the Code

There are at least a couple of fundamental problems in the OP posted code.

int t = i inside the loop shadows the t defined outside of the loop, and this inner t is lost when the loop is exited. At this point, the value of t in the expression -t / i * (n + 1) / 2) is 1, the value that t was initialized to in this scope. This problem can be fixed by changing int t = i --> t = i in the loop, utilizing the variable t that exists outside of the loop, and allowing that variable to be changed in the loop, but still used after the loop exits.

But here we come to another problem. t is set to the value of i at the top of the loop, but before the loop exits i is incremented. This means that the value of i is greater than the value of t when the loop exits. Thus -t / i is zero in the final print statement! One way to fix this would be to change the final print statement from printf("%d", -t / i * (n + 1) / 2) to printf("%d", -t / (i-1) * (n + 1) / 2). Note that this solution has a serious problem when i == 1; this happens when n == 1.

Since we are really only after the sign of -t here, it might be more clear to use a conditional operator:

printf("%d", (-t < 0 ? -1 : 1) * (n + 1) / 2)

Now that i is no longer needed outside of the loop, we should consider reducing the scope of i. A good general principle is to keep the scopes of variables as small as practically possible. To do this, a for loop seems appropriate:

int t = 1;
for (int i = 1; i <= (n / 2); i++) {  // reduce scope of `i`
    t = i;
    if (i % 2 == 0)
        t *= -1;

    printf("%d", t);
    printf(", %d, ", -t);
}
if (n % 2 == 1) {
    printf("%d", (-t < 0 ? -1 : 1) * (n + 1) / 2);
}

Note now that there are still some significant problems with the code. An input of 1 skips the loop entirely and leads to the incorrect output -1. A newline is never printed after the end of the series (this is just bad form), but worse, even inputs lead to a series printed with a comma and a space on the end! Formatting is important, and looking at the edge cases helps us to avoid bugs. In this case, the first number in a series of only one term is wrong. In a couple of previous (now deleted) answers the solutions partially worked, but gave incorrect results in the last number when the input was an odd number (for every second odd number). Lesson: investigate the edge cases when you code.

When the input is 1, the loop is never entered, but we only need to print the first number of the series. A simple way to handle this is just to handle that input explicitly before the loop.

if (n == 1) {           // n == 1: the loop is not entered
    printf("1\n");     // handle this special case
}

To handle the formatting issue, consider that each pass through the loop prints a pair of numbers. After the last pass, OP code prints one more line when input is an odd number. Instead, handle the last pass through the loop explicitly. If the loop is in its final iteration, print three numbers when input is odd, or print two numbers when input is even. Otherwise, in the typical case, print a pair of numbers with commas as before. Coding in this way allows all series code, except for the special case when input is 1, to be brought inside of the loop, including allowing t to be defined inside the loop (further reducing the scope of t). Here is what that code looks like:

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter your number: ");
    scanf("%d", &n);

    if (n == 1) {           // n == 1: the loop is not entered
        printf("1\n");     // handle this special case
    }

    for (int i = 1; i <= (n / 2); i++) {
        int t = i;         // reduced scope for `t`
        if (i % 2 == 0)
            t *= -1;

        if (i == n / 2) {  // print last numbers in the series
            if (n % 2) {   // n is odd: print 3 numbers
                printf("%d, %d, %d\n",
                       t,
                       -t,
                       (-t < 0 ? -1 : 1) * (n + 1) / 2);
            } else {       // n is even: print two numbers
                printf("%d, %d\n", t, -t);
            }
        } else {           // print typical pair in the series
            printf("%d, %d, ", t, -t);
        }
    }

    return 0;
}

On Input Validation

OP code does not check for valid input from the user. In practice, code as if users are malicious and will provide any input to break your code. Even without malicious intent, a user may accidentally provide improper input. In the OP posted code, if a user inadvertently enters a letter, or anything other than a number, no value is stored in n. In such a case n has indeterminate value, and further attempts to use n will result in undefined behavior. Note that scanf() returns the number of successful assignments made, and checking this value is a part of any input validation (you should almost always check the result returned by any function that returns a value).

You could check this value, and abort the program if the user fails to enter a number. This is not graceful. A better solution might be to take input in a loop, checking to see if a successful assignment was made by scanf(), and looping until a number is entered. This is more complicated than it sounds because the bad (and unassigned) input remains in the input stream after the call to scanf(), and needs to be cleared before progress can be made. The scanf() function is difficult to use correctly, and a better solution is to use fgets() which reads a line of input into a buffer. After this, the buffer can be parsed with sscanf().

The fgets() function returns a null pointer in the unlikely event of a read error; robust code checks for such errors. The code below places the series printing code in a function print_series(), and takes and does very basic validation of input in main(). If there is an input read error, the code simply prints an error message and exits. Note that the input[] array is used as an input buffer, and it is generously sized so that normal input should be contained within it. More robust code would plan for the possibility that more input could arrive than can be held in this buffer. fgets() will not overflow this buffer, but extra input would remain in the input stream in such a case, potentially causing problems for later I/O operations.

If no number can be parsed by sscanf(), the input loop continues, printing another prompt and fetching a fresh line of input into the input buffer. Once a number has been assigned to max, another loop prints all series from length 1 to length max; this helps us to see that the series outputs are as expected for different values of N. Note that when the input is less than 1 for max, the printing loop is not entered at all, and nothing is printed. This may not be the best way to handle such inputs.

#include <stdio.h>

#define MAX_INPUT  1000

void print_series(int n);

int main(void) {
    char input[MAX_INPUT];
    int max;

    // get user input and do minimal validation
    do {
        printf("Enter longest series to print: ");
        if (fgets(input, sizeof input, stdin) == NULL) {
            puts("Input Failure");
            return 1;
        }
    } while (sscanf(input, "%d", &max) != 1);

    // printing loop
    putchar('\n');
    for (int n = 1; n <= max; n++) {
        print_series(n);
    }

    return 0;
}

void print_series(int n) {
    if (n == 1) {
        printf("1\n");
    }

    for (int i = 1; i <= (n / 2); i++) {
        int t = i;
        if (i % 2 == 0)
            t *= -1;

        if (i == n / 2) {
            if (n % 2) {
                printf("%d, %d, %d\n",
                       t,
                       -t,
                       (-t < 0 ? -1 : 1) * (n + 1) / 2);
            } else {
                printf("%d, %d\n", t, -t);
            }
        } else {
            printf("%d, %d, ", t, -t);
        }
    }
}

Sample runs:

$ ./a.out
Enter longest series to print: bad input
Enter longest series to print: 0

$ ./a.out
Enter longest series to print: 19

1
1, -1
1, -1, -2
1, -1, -2, 2
1, -1, -2, 2, 3
1, -1, -2, 2, 3, -3
1, -1, -2, 2, 3, -3, -4
1, -1, -2, 2, 3, -3, -4, 4
1, -1, -2, 2, 3, -3, -4, 4, 5
1, -1, -2, 2, 3, -3, -4, 4, 5, -5
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8, 9
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8, 9, -9
1, -1, -2, 2, 3, -3, -4, 4, 5, -5, -6, 6, 7, -7, -8, 8, 9, -9, -10


问:
How to dispatch events from an OpenLayers overlay to the map
When adding an overlay element to a map in OpenLayers, I can set the stopEvent property of the overlay to true. This enables me to handle different events like mouse moves, clicks etc. on the overlay element.

But I also would like some events not be stopped, especially the wheel event. I would like to have this event propagated, so that the zoom behaviour of the map works even when the mouse is over the overlay.

How can I achieve this? I can intercept the wheel event in the overlay, how can I send this to the map element or wherever it is needed to trigger the noemal scroll behaviour?

答:
You can use pointer-events to none for overlay target html element.

CSS

```<code>#marker {
  pointer-events: none;
}
</code>```

JS

```<code>new Overlayer({
    element: document.getElementById('marker')
})
</code>```

Body:
You can use pointer-events to none for overlay target html element.

CSS

#marker {
  pointer-events: none;
}

JS

new Overlayer({
    element: document.getElementById('marker')
})


问:
How to use NSPredicate with Date type
I am trying to make NSPredicate based on a date... I have tried this:

```<code>let datePredicate = NSPredicate(format: "due_date < %@", Date())
</code>```

I am not sure, but iirc, this worked before?

Now I get this error:

Argument type 'Date' does not conform to expected type 'CVarArg'

I tried smth like this

... Date() as NSDate,
but that failed too.

How to solve this?

答:
To use the current date as a predicate parameter just create an NSDate instance

```<code>let datePredicate = NSPredicate(format: "due_date < %@", NSDate())
</code>```

For a date variable you can use

```<code>aDate as NSDate
</code>```

or

```<code>aDate as CVarArg
</code>```

If you get the error

'Date?' is not convertible to 'NSDate'

then the code is not the real code because both Date() and NSDate() are non-optional.

Title: How to use NSPredicate with Date type

Body:
I am trying to make NSPredicate based on a date... I have tried this:

let datePredicate = NSPredicate(format: "due_date < %@", Date())

I am not sure, but iirc, this worked before?

Now I get this error:

Argument type 'Date' does not conform to expected type 'CVarArg'

I tried smth like this

... Date() as NSDate,
but that failed too.

How to solve this?

Body:
To use the current date as a predicate parameter just create an NSDate instance

let datePredicate = NSPredicate(format: "due_date < %@", NSDate())

For a date variable you can use

aDate as NSDate

or

aDate as CVarArg

If you get the error

'Date?' is not convertible to 'NSDate'

then the code is not the real code because both Date() and NSDate() are non-optional.


问:
How to change value in main vuetify app from component vue
I have two vue files, app.vue and logincomponent.vue.

I use logincomponent.vue to make template that does login box and uses scripts to communicate with go backend in wails, the code itself works, but I'm trying to change value in main app.vue but i cant get it working.

The question is:
"How do I change value of variable in main vue app from component?"

Import:

```<code>    import LoginScreen from "./components/LoginScreen.vue"
</code>```

Variable:

```<code>        data: () => ({
            drawer: false,
            currentScreenID: 0,
            logged: false
</code>```

Setter:

```<code>sendLogin: function () {
                var self = this;
                if (this.$refs.login_form.validate()) {
                    self.dialog = true;
                    self.loadingCircleLogin = true;
                    self.login_dialog_title = self.login_dialog_logging_title;
                    window.backend.sendLoginToBackend(self.email, self.password, self.remember_email).then(result => {
                        if (result === false) {
                            self.loadingCircleLogin = false;
                            self.loginFailText = true;
                            self.login_dialog_title = self.login_dialog_error_title;
                        } else {
                            self.dialog = false;
                            self.currentScreenID = 3;
                        }
                    })
                }
            },
</code>```

答:
The short answer to if the state of the parent component (or main Vue instance) can be changed from a child component, is no or at least it should not be done. It's an anti-pattern and can produce bugs in your code.

But you have two choices here.

To emit an event from child component, and handling it from parent. So the parent is responsible of changing its own state with its own logic.
When you need to change a value from the main instance from a child component, you emit the event, even with a value you can pass to the emit function, and you program your main instance to listen that event and respond accordingly.
More info here: listening to child component events.

To add a Vuex store to your app. In this way you abstract the state of the app that's common to several components. So your child component could ask the store to change certain state.
More info here: Vuex

Using Vuex is more complex dough, if your app is simple I'd go with first option.

Body:
I have two vue files, app.vue and logincomponent.vue.

I use logincomponent.vue to make template that does login box and uses scripts to communicate with go backend in wails, the code itself works, but I'm trying to change value in main app.vue but i cant get it working.

The question is:
"How do I change value of variable in main vue app from component?"

Import:

    import LoginScreen from "./components/LoginScreen.vue"

Variable:

        data: () => ({
            drawer: false,
            currentScreenID: 0,
            logged: false

Setter:

sendLogin: function () {
                var self = this;
                if (this.$refs.login_form.validate()) {
                    self.dialog = true;
                    self.loadingCircleLogin = true;
                    self.login_dialog_title = self.login_dialog_logging_title;
                    window.backend.sendLoginToBackend(self.email, self.password, self.remember_email).then(result => {
                        if (result === false) {
                            self.loadingCircleLogin = false;
                            self.loginFailText = true;
                            self.login_dialog_title = self.login_dialog_error_title;
                        } else {
                            self.dialog = false;
                            self.currentScreenID = 3;
                        }
                    })
                }
            },


问:
(Python) psycopg2 installation
I have a fairly light amount of experience with Python and got stuck on what should be a pretty simple issue.  I am using Jupyter Notebook on a Mac.

I wanted to install psycopg2 in Python so I typed in

```<code>import psycopg2 as pg2
</code>```

But, I got the following error:

```<code>ModuleNotFoundError                       Traceback (most recent call
last)
<ipython-input-1-32fa0c891bdd> in <module>
 ----> 1 import psycopg2 as pg2

ModuleNotFoundError: No module named 'psycopg2'
</code>```

I then went over to the terminal and typed in:

```<code>pip install psycopg2
</code>```

which resulted in another error:

```<code>Error: pg_config executable not found.
pg_config is required to build psycopg2 from source.  Please add the
directory
containing pg_config to the $PATH or specify the full executable path
with the
option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
</code>```

I'm not sure how to go about using this information in the error message.  Can someone help point me in the right direction?

Also follow up question:

a.) Why would I need to use pip install modulename in the terminal when I don't have to do that with either pandas or numpy?

Any help would be appreciated.

答:
Please try installing psycopg2-binary as you probaly do not have all the C library dependencies installed on your computer.
pip install psycopg2-binary

Title: (Python) psycopg2 installation

Body:
I have a fairly light amount of experience with Python and got stuck on what should be a pretty simple issue.  I am using Jupyter Notebook on a Mac.

I wanted to install psycopg2 in Python so I typed in

import psycopg2 as pg2

But, I got the following error:

ModuleNotFoundError                       Traceback (most recent call
last)
<ipython-input-1-32fa0c891bdd> in <module>
 ----> 1 import psycopg2 as pg2

ModuleNotFoundError: No module named 'psycopg2'

I then went over to the terminal and typed in:

pip install psycopg2

which resulted in another error:

Error: pg_config executable not found.
pg_config is required to build psycopg2 from source.  Please add the
directory
containing pg_config to the $PATH or specify the full executable path
with the
option:
python setup.py build_ext --pg-config /path/to/pg_config build ...

I'm not sure how to go about using this information in the error message.  Can someone help point me in the right direction?

Also follow up question:

a.) Why would I need to use pip install modulename in the terminal when I don't have to do that with either pandas or numpy?

Any help would be appreciated.


问:
GroupBy aggregation based on condition and year wise sum using pandas
I have a data frame as shown below

```<code>ID    Sector  Plot  Tenancy_Start_Date      Rental
1     SE1     A     2018-08-14              100
1     SE1     A     2019-08-18              200
2     SE1     B     2017-08-12              150
3     SE1     A     2020-02-12              300
5     SE2     A     2017-08-13              400
5     SE2     A     2019-08-12              300
6     SE2     B     2019-08-11              150
5     SE2     A     2020-01-10              300
7     SE2     B     2019-08-11              500
</code>```

From the above I would like to prepare below data frame as Sector and Plot aggregation level.

Expected Output:

```<code>Sector  Plot       Total_Rental   Rental_2017  Rental_2018  Rental_2019    Rental_2020
SE1     A          600            0            100          200            300
SE1     B          150            150          0            0              0
SE2     A          1000           400          0            300            300
SE2     B          650            0            0            650            0
</code>```

Body:
I have a data frame as shown below

ID    Sector  Plot  Tenancy_Start_Date      Rental
1     SE1     A     2018-08-14              100
1     SE1     A     2019-08-18              200
2     SE1     B     2017-08-12              150
3     SE1     A     2020-02-12              300
5     SE2     A     2017-08-13              400
5     SE2     A     2019-08-12              300
6     SE2     B     2019-08-11              150
5     SE2     A     2020-01-10              300
7     SE2     B     2019-08-11              500

From the above I would like to prepare below data frame as Sector and Plot aggregation level.

Expected Output:

Sector  Plot       Total_Rental   Rental_2017  Rental_2018  Rental_2019    Rental_2020
SE1     A          600            0            100          200            300
SE1     B          150            150          0            0              0
SE2     A          1000           400          0            300            300
SE2     B          650            0            0            650            0

Body:
I'd create a year column:

df['Year'] = df['Tenancy_State_date'].dt.year

then do your groupby

df['Rent_by_cats'] = df.groupby(['Sector', 'Year', 'Plot'])['Rental'].transform(sum)

then lastly move it into separate columns

yrs = df['Year'].unique().tolist()
for y in yrs:
    df['Rental_' + str(y)] = 0
    df.loc[df['Year'] == y, 'Rental_' + str(y)] = df['Rent_by_cats']

Output:

    ID Sector Plot Tenancy_Start_Date  Rental  Year  Rent_by_cats  Rental_2018  Rental_2019  Rental_2017  Rental_2020
0   1    SE1    A         2018-08-14     100  2018           100          100            0            0            0
1   1    SE1    A         2019-08-18     200  2019           200            0          200            0            0
2   2    SE1    B         2017-08-12     150  2017           150            0            0          150            0
3   3    SE1    A         2020-02-12     300  2020           300            0            0            0          300
4   5    SE2    A         2017-08-13     400  2017           400            0            0          400            0
5   5    SE2    A         2019-08-12     300  2019           300            0          300            0            0
6   6    SE2    B         2019-08-11     150  2019           650            0          650            0            0
7   5    SE2    A         2020-01-10     300  2020           300            0            0            0          300
8   7    SE2    B         2019-08-11     500  2019           650            0          650            0            0


问:
How to change the values of cv2.boundingRect
is there a way to change the values of cv2.boundingRect

I want to adjust so I can get the accurate cv2.drawContours

```<code>import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find bounding box

x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()
</code>```

答:
I am not sure what you want to do. But I see two different ways to approach this in Python/OpenCV.

1) Just increase w

```<code>import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find bounding box
x,y,w,h = cv2.boundingRect(thresh)
w = w + 9
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()
</code>```

2) Dilate your thresholded image

```<code>import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# apply morphology dilate
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, kernel)

# Find bounding box
x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()
</code>```

Body:
is there a way to change the values of cv2.boundingRect

I want to adjust so I can get the accurate cv2.drawContours

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find bounding box

x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()

Body:
I am not sure what you want to do. But I see two different ways to approach this in Python/OpenCV.

1) Just increase w

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find bounding box
x,y,w,h = cv2.boundingRect(thresh)
w = w + 9
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()

2) Dilate your thresholded image

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# apply morphology dilate
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, kernel)

# Find bounding box
x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()


问:
Opencv Mat vector assignment to a row of a matrix, fastest way?
What is the fastest way of assigning a vector to a matrix row in a loop? I want to fill a data matrix along its rows with vectors. These vectors are computed in a loop. This loop last until all the entries of data matrix is filled those vectors.

Currently I am using cv::Mat::at<>() method for accessing the elements of the matrix and fill them with the vector, however, it seems this process is quite slow. I have tried another way by using cv::Mat::X.row(index) = data_vector, it works fast but fill my matrix X with some garbage values which I can not understand, why.

I read that there exists another way of using pointers (fastest way), however, I can not able to understand. Can somebody explain how to use them or other different methods?

Here is a part of my code:

```<code>#define OFFSET 2

cv::Mat im = cv::imread("001.png", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat X = cv::Mat((im.rows - 2*OFFSET)*(im.cols - 2*OFFSET), 25, CV_64FC1); // Holds the training data. Data contains image patches
cv::Mat patch = cv::Mat(5, 5, im.type()); // Holds a cropped image patch
typedef cv::Vec<float, 25> Vec25f;

int ind = 0;
for (int row = 0; row < (im.rows - 2*OFFSET); row++){
    for (int col = 0; col < (im.cols - 2*OFFSET); col++){

    cv::Mat temp_patch = im(cv::Rect(col, row, 5, 5)); // crop an image patch (5x5) at each pixel
    patch = temp_patch.clone(); // Needs to do this because temp_patch is not continuous in memory
    patch.convertTo(patch, CV_64FC1);

    Vec25f data_vector = patch.reshape(0, 1); // make it row vector (1X25).
    for (int i = 0; i < 25; i++)
    {
        X.at<float>(ind, i) = data_vector[i]; // Currently I am using this way (quite slow).
    }

    //X_train.row(ind) = patch.reshape(0, 1); // Tried this but it assigns some garbage values to the data matrix!
    ind += 1;
    }
}
</code>```

答:
According to the docs:

if you need to process a whole row of matrix, the most efficient way is to get the pointer to the row first, and then just use plain C operator []:

```<code>// compute sum of positive matrix elements
// (assuming that M is double-precision matrix)
double sum=0;
for(int i = 0; i < M.rows; i++)
{
    const double* Mi = M.ptr<double>(i);
    for(int j = 0; j < M.cols; j++)
        sum += std::max(Mi[j], 0.);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What is the fastest way of assigning a vector to a matrix row in a loop? I want to fill a data matrix along its rows with vectors. These vectors are computed in a loop. This loop last until all the entries of data matrix is filled those vectors.

Currently I am using cv::Mat::at<>() method for accessing the elements of the matrix and fill them with the vector, however, it seems this process is quite slow. I have tried another way by using cv::Mat::X.row(index) = data_vector, it works fast but fill my matrix X with some garbage values which I can not understand, why.

I read that there exists another way of using pointers (fastest way), however, I can not able to understand. Can somebody explain how to use them or other different methods?

Here is a part of my code:

#define OFFSET 2

cv::Mat im = cv::imread("001.png", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat X = cv::Mat((im.rows - 2*OFFSET)*(im.cols - 2*OFFSET), 25, CV_64FC1); // Holds the training data. Data contains image patches
cv::Mat patch = cv::Mat(5, 5, im.type()); // Holds a cropped image patch
typedef cv::Vec<float, 25> Vec25f;

int ind = 0;
for (int row = 0; row < (im.rows - 2*OFFSET); row++){
    for (int col = 0; col < (im.cols - 2*OFFSET); col++){

    cv::Mat temp_patch = im(cv::Rect(col, row, 5, 5)); // crop an image patch (5x5) at each pixel
    patch = temp_patch.clone(); // Needs to do this because temp_patch is not continuous in memory
    patch.convertTo(patch, CV_64FC1);

    Vec25f data_vector = patch.reshape(0, 1); // make it row vector (1X25).
    for (int i = 0; i < 25; i++)
    {
        X.at<float>(ind, i) = data_vector[i]; // Currently I am using this way (quite slow).
    }

    //X_train.row(ind) = patch.reshape(0, 1); // Tried this but it assigns some garbage values to the data matrix!
    ind += 1;
    }
}

Body:
According to the docs:

if you need to process a whole row of matrix, the most efficient way is to get the pointer to the row first, and then just use plain C operator []:

// compute sum of positive matrix elements
// (assuming that M is double-precision matrix)
double sum=0;
for(int i = 0; i < M.rows; i++)
{
    const double* Mi = M.ptr<double>(i);
    for(int j = 0; j < M.cols; j++)
        sum += std::max(Mi[j], 0.);
}


问:
Formatted date for vue-date-pick is 1 day bigger
In my vue/cli 4/vuex / bootstrap-vue project app I install date picker with custom format, like here
https://dbrekalo.github.io/vue-date-pick/examples.html#custom-date-parser

I use moment/moment-timezone in my project, so I do not want to use fecha as in example
I have to convert date value from mysql to datepicker format and I have a problem that my converted date for
datepicker is 1 day bigger...

I have in my component:

```<code>                        <date-pick
                                v-model="editableAd.expire_date_formatted"
                                :format="date_picker_format"
                                :parseDate="parseDate"
                                :formatDate="formatDate"
                                :inputAttributes="{size: 32}"
                        ></date-pick>

...
    import moment from 'moment-timezone'

    console.log('settingsTimeZone::')
    console.log(settingsTimeZone) // it shows Europe/Kiev

    moment.tz.setDefault(settingsTimeZone)

...
    date_picker_format: 'Do MMMM, YYYY',

...
    // setting formated date for dapicker
    this.editableAd.expire_date_formatted = this.formatDate(this.editableAd.expire_date, this.date_picker_format)
...

            formatDate(dateObj) {

                console.log('typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj)  // it has ‘2023-01-19’ value

                if (typeof dateObj === 'string') {
                    dateObj = moment(dateObj, this.date_picker_format)
                }
                console.log('++typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj)

                console.log('RESULT moment(dateObj).format(this.date_picker_format)::')
                console.log(moment(dateObj).format(this.date_picker_format)) // BUT it has ‘20th January, 2023’ value

                return moment(dateObj).format(this.date_picker_format) // returns invalid ‘20th January, 2023’ value which I see in datepicker
</code>```

What I see in console for dateObj var : https://imgur.com/a/KZLtXiL

```<code>"bootstrap-vue": "^2.1.0",
"font-awesome": "^4.7.0",
"moment": "^2.24.0",
"moment-timezone": "^0.5.27",
"vue": "^2.6.10",
"vue-date-pick": "^1.2.1",
</code>```

Why error and how it can be fixed?

MODIFIED BLOCK 2:

I removed moment.tz from my project.
In /etc/php/7.2/apache2/php.ini I changed

```<code>Timezone ='Europe/Uzhgorod'  // That it near my place I live
date.timezone = "Europe/Uzhgorod"
</code>```

So my phpinfo has this output:

```<code>"Olson" Timezone Database Version   0.system
Timezone Database   internal
Default timezone    Europe/Uzhgorod
</code>```

I searched how to get a timezone from client browser and found this
get client time zone from browser branch and checking :

```<code>var timedifference = new Date().getTimezoneOffset();
console.log('timedifference::')
console.log(timedifference)

var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
console.log('std_time_offset::')
console.log(std_time_offset)

let jstz = require('jstimezonedetect')
let timezone = jstz.determine()
console.log('timezone::')
console.log(timezone)

console.log('===========================')
</code>```

I have next output: https://imgur.com/a/84RqqPJ and again running code when I see date is changed +1 day :

```<code>console.log('__')
console.log('__')

console.log('typeof dateObj::')
console.log(typeof dateObj)
console.log(dateObj)

if (typeof dateObj === 'string') {
    dateObj = moment(dateObj, this.date_picker_format)
}
console.log('++typeof dateObj::')
console.log(typeof dateObj)
console.log(dateObj) // it has ‘2023-01-19’ value

console.log('RESULT moment(dateObj).format(this.date_picker_format)::')
console.log(moment(dateObj).format(this.date_picker_format)) // BUT it has ‘20th January, 2023’ value

return moment(dateObj).format(this.date_picker_format)
</code>```

and what I see in console: https://imgur.com/a/Y1aSBez
That is strange that .d has 20 day. What is it? Some day zero based option?

答:
The problem you're having is due to some automatic localization formatting. I too don't get why does this happens, since we are providing only dates, they should be treated as such regardless of our timezone. But to solve this issue we have to read it as UTC with moment.utc() and then format it using your desired format.

From vue-date-pick docs example I've worked out a solution using moment.

var app = new Vue({
  el: '#app',
  components: {
    'date-pick': VueDatePick,
  },
  data: () => ({
    format: 'Do MMMM, YYYY',
    date: '19th January, 2023',
  }),
  methods: {
    parseDate(value) {
      const m = moment.utc(value, this.format);
      return new Date(m.year(), m.month(), m.date());
    },
    formatDate(value) {
      return moment.utc(value).format(this.format);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/vue-date-pick@1.2.1/dist/vueDatePick.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-date-pick@1.2.1/dist/vueDatePick.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.min.js"></script>

<div id='app'>
    <date-pick v-model="date" :format="format" :parse-date="parseDate" :format-date="formatDate"></date-pick>

</div></code>```

Body:
In my vue/cli 4/vuex / bootstrap-vue project app I install date picker with custom format, like here
https://dbrekalo.github.io/vue-date-pick/examples.html#custom-date-parser

I use moment/moment-timezone in my project, so I do not want to use fecha as in example
I have to convert date value from mysql to datepicker format and I have a problem that my converted date for
datepicker is 1 day bigger...

I have in my component:

                        <date-pick
                                v-model="editableAd.expire_date_formatted"
                                :format="date_picker_format"
                                :parseDate="parseDate"
                                :formatDate="formatDate"
                                :inputAttributes="{size: 32}"
                        ></date-pick>

...
    import moment from 'moment-timezone'

    console.log('settingsTimeZone::')
    console.log(settingsTimeZone) // it shows Europe/Kiev

    moment.tz.setDefault(settingsTimeZone)

...
    date_picker_format: 'Do MMMM, YYYY',

...
    // setting formated date for dapicker
    this.editableAd.expire_date_formatted = this.formatDate(this.editableAd.expire_date, this.date_picker_format)
...

            formatDate(dateObj) {

                console.log('typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj)  // it has ‘2023-01-19’ value

                if (typeof dateObj === 'string') {
                    dateObj = moment(dateObj, this.date_picker_format)
                }
                console.log('++typeof dateObj::')
                console.log(typeof dateObj)
                console.log(dateObj)

                console.log('RESULT moment(dateObj).format(this.date_picker_format)::')
                console.log(moment(dateObj).format(this.date_picker_format)) // BUT it has ‘20th January, 2023’ value

                return moment(dateObj).format(this.date_picker_format) // returns invalid ‘20th January, 2023’ value which I see in datepicker

What I see in console for dateObj var : https://imgur.com/a/KZLtXiL

"bootstrap-vue": "^2.1.0",
"font-awesome": "^4.7.0",
"moment": "^2.24.0",
"moment-timezone": "^0.5.27",
"vue": "^2.6.10",
"vue-date-pick": "^1.2.1",

Why error and how it can be fixed?

MODIFIED BLOCK 2:

I removed moment.tz from my project.
In /etc/php/7.2/apache2/php.ini I changed

Timezone ='Europe/Uzhgorod'  // That it near my place I live
date.timezone = "Europe/Uzhgorod"

So my phpinfo has this output:

"Olson" Timezone Database Version   0.system
Timezone Database   internal
Default timezone    Europe/Uzhgorod

I searched how to get a timezone from client browser and found this
get client time zone from browser branch and checking :

var timedifference = new Date().getTimezoneOffset();
console.log('timedifference::')
console.log(timedifference)

var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
console.log('std_time_offset::')
console.log(std_time_offset)

let jstz = require('jstimezonedetect')
let timezone = jstz.determine()
console.log('timezone::')
console.log(timezone)

console.log('===========================')

I have next output: https://imgur.com/a/84RqqPJ and again running code when I see date is changed +1 day :

console.log('__')
console.log('__')

console.log('typeof dateObj::')
console.log(typeof dateObj)
console.log(dateObj)

if (typeof dateObj === 'string') {
    dateObj = moment(dateObj, this.date_picker_format)
}
console.log('++typeof dateObj::')
console.log(typeof dateObj)
console.log(dateObj) // it has ‘2023-01-19’ value

console.log('RESULT moment(dateObj).format(this.date_picker_format)::')
console.log(moment(dateObj).format(this.date_picker_format)) // BUT it has ‘20th January, 2023’ value

return moment(dateObj).format(this.date_picker_format)

and what I see in console: https://imgur.com/a/Y1aSBez
That is strange that .d has 20 day. What is it? Some day zero based option?

Body:
The problem you're having is due to some automatic localization formatting. I too don't get why does this happens, since we are providing only dates, they should be treated as such regardless of our timezone. But to solve this issue we have to read it as UTC with moment.utc() and then format it using your desired format.

From vue-date-pick docs example I've worked out a solution using moment.

var app = new Vue({
  el: '#app',
  components: {
    'date-pick': VueDatePick,
  },
  data: () => ({
    format: 'Do MMMM, YYYY',
    date: '19th January, 2023',
  }),
  methods: {
    parseDate(value) {
      const m = moment.utc(value, this.format);
      return new Date(m.year(), m.month(), m.date());
    },
    formatDate(value) {
      return moment.utc(value).format(this.format);
    }
  }
});

<link href="https://cdn.jsdelivr.net/npm/vue-date-pick@1.2.1/dist/vueDatePick.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-date-pick@1.2.1/dist/vueDatePick.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.min.js"></script>

<div id='app'>
    <date-pick v-model="date" :format="format" :parse-date="parseDate" :format-date="formatDate"></date-pick>

</div>


问:
How to change the color of correct answer using JavaScript when check answer button clicked

Lorem ipsum dolor sit amet, consectetur adipiscing elit
 (A)Lorem ipsum dolor

  (B)Lorem ipsum dolor
 (C) Lorem ipsum dolor
 (D) Lorem ipsum dolor

<button class="ans-button">check answer</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit

  (A)Lorem ipsum dolor
 (B)Lorem ipsum dolor
 (C) Lorem ipsum dolor
 (D) Lorem ipsum dolor

<button class="ans-button">check answer</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit
 (A)Lorem ipsum dolor
 (B)Lorem ipsum dolor
 (C) Lorem ipsum dolor

  (D) Lorem ipsum dolor

<button class="ans-button">check answer</button>```

how to change the color of the correct option when 'check answer' button of the question clicked?

答: You can use the IF ELSE  here, if answer is correct, you make .class in css giving it color, if answer is correct, CSS applies, if not, it goes to else, which can be left empty not applying anything or you can give alert if you want as bonus telling its wrong or giving it other color  </p>

Body:
Lorem ipsum dolor sit amet, consectetur adipiscing elit
 (A)Lorem ipsum dolor

  (B)Lorem ipsum dolor
 (C) Lorem ipsum dolor
 (D) Lorem ipsum dolor

<button class="ans-button">check answer</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit

  (A)Lorem ipsum dolor
 (B)Lorem ipsum dolor
 (C) Lorem ipsum dolor
 (D) Lorem ipsum dolor

<button class="ans-button">check answer</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit
 (A)Lorem ipsum dolor
 (B)Lorem ipsum dolor
 (C) Lorem ipsum dolor

  (D) Lorem ipsum dolor

<button class="ans-button">check answer</button>

how to change the color of the correct option when 'check answer' button of the question clicked?


问:
How to Initialize Vectors Using C++; Scripted Value is Not An Array, pointer or Vector Error
I am trying to reconstruct two Z bosons.
I am using this tutorial as an example. https://root.cern.ch/doc/master/df103__NanoAODHiggsAnalysis_8C.html
However, I am still not familiar in using ROOT data frame and I am writing it in terms of what I am familiar with.

What I do not understand is how is i1, i2, and idx that is shown in the ROOT tutorial defined?

In my tree, I have the BranchMuon and the variables in this branch are called Muon.PT, Muon.Eta, Muon.Phi and Muon.Charge, and Muon.Mass.

My attempt to follow the tutorial is constructing a muon vector and defining the variables (which generates errors but I am still learning how to work with it):

```<code>#ifdef __CLING__
R__LOAD_LIBRARY(libDelphes)
#include "classes/DelphesClasses.h"
#include "external/ExRootAnalysis/ExRootTreeReader.h"
#include "external/ExRootAnalysis/ExRootResult.h"
#else
class ExRootTreeReader;
class ExRootResult;
#endif
#include <vector>

#include "ROOT/RDataFrame.hxx"
#include "ROOT/RVec.hxx"
#include "ROOT/RDF/RInterface.hxx"
#include "TCanvas.h"
#include "TH1D.h"
#include "TLatex.h"
#include "TLegend.h"
#include "Math/Vector4Dfwd.h"
#include "TStyle.h"
using namespace ROOT::VecOps;
using RNode = ROOT::RDF::RNode;
using rvec_f = const RVec<float> &;
using rvec_i = const RVec<int> &;
const auto z_mass = 91.2;

template<typename T>
void CollectionFilter(const TClonesArray& inColl ,vector<T*>& outColl, Double_t ptMin=30, Double_t etaMax=2.5)
{

const TObject *object;

for (Int_t i = 0; i < inColl.GetEntriesFast(); i++)
{

object = inColl.At(i);
const T *t = static_cast<const T*>(object);

if(t->P4().Pt() < ptMin) continue;
if(TMath::Abs(t->P4().Eta()) > etaMax) continue;

outColl.push_back(t);

}
}

void selectMuon(const char *inputFile)
{
  gSystem->Load("libDelphes");

  // Create chain of root trees
  TChain chain("Delphes");
  chain.Add(inputFile);

  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();

  // Get pointers to branches used in this analysis
  TClonesArray *branchMuon = treeReader->UseBranch("Muon");

  // Book histograms

  TH1F *histZMass = new TH1F("mass", "M_{inv}(Z[1]); M_inv (GeV/c^2); Events", 50, 0.0, 1500);
  TH1F *histDiMuonMass = new TH1F("mass", "M_{inv}(Z[3]Z[5]); M_inv (GeV/c^2); Events", 50, 0.0, 1500);

  // Define variables

  float_t PT, Eta, Phi, Mass, Charge;

  // Initializing the vectors
  //vector<const Muon*>  *muons = new vector<const Muon*>();;
  //MuonVector muon(PT, Eta, Phi, Mass, Charge);
  RVec<RVec<size_t>> reco_zz_to_4l(rvec_f PT, rvec_f Eta, rvec_f Phi, rvec_f Mass, rvec_i Charge);

    RVec<RVec<size_t>> idx(2);
    idx[0].reserve(2); idx[1].reserve(2);
    auto idx_cmb = Combinations(PT, 2);
    for (size_t i = 0; i < idx_cmb[0].size(); i++)
    {
      const auto i1 = idx_cmb[0][i];
      const auto i2 = idx_cmb[1][i];

      if(Charge[i1] != Charge[i2]
      {

        ROOT::Math::PtEtaPhiMVector m1(PT[0], Eta[0], Phi[0], Mass[0]);
        ROOT::Math::PtEtaPhiMVector m2(PT[1], Eta[1], Phi[1], Mass[1]);
        const auto mass = (m1 + m2).M();
     }
    }

      histDiMuonMass->Fill(mass);

   // end of event for loop
  histDiMuonMass->Draw();

  }
</code>```

The errors that I am getting is below.

```<code>In file included from input_line_188:1:
/mnt/c/1/MG5_aMC_v2_6_6/Delphes/examples/selectMuon.C:89:16: error: subscripted value is not an array, pointer, or vector
      if(Charge[i1] != Charge[i2]
         ~~~~~~^~~
/mnt/c/1/MG5_aMC_v2_6_6/Delphes/examples/selectMuon.C:89:30: error: subscripted value is not an array, pointer, or vector
      if(Charge[i1] != Charge[i2]
                       ~~~~~~^~~
/mnt/c/1/MG5_aMC_v2_6_6/Delphes/examples/selectMuon.C:100:28: error: use of undeclared identifier 'mass'
      histDiMuonMass->Fill(mass);
</code>```

How can I fix it?
Thank you.

答: I learnt that I had a previous definition of charge to be a float while I am using it to be an array.</p>

Body:
I am trying to reconstruct two Z bosons.
I am using this tutorial as an example. https://root.cern.ch/doc/master/df103__NanoAODHiggsAnalysis_8C.html
However, I am still not familiar in using ROOT data frame and I am writing it in terms of what I am familiar with.

What I do not understand is how is i1, i2, and idx that is shown in the ROOT tutorial defined?

In my tree, I have the BranchMuon and the variables in this branch are called Muon.PT, Muon.Eta, Muon.Phi and Muon.Charge, and Muon.Mass.

My attempt to follow the tutorial is constructing a muon vector and defining the variables (which generates errors but I am still learning how to work with it):

#ifdef __CLING__
R__LOAD_LIBRARY(libDelphes)
#include "classes/DelphesClasses.h"
#include "external/ExRootAnalysis/ExRootTreeReader.h"
#include "external/ExRootAnalysis/ExRootResult.h"
#else
class ExRootTreeReader;
class ExRootResult;
#endif
#include <vector>

#include "ROOT/RDataFrame.hxx"
#include "ROOT/RVec.hxx"
#include "ROOT/RDF/RInterface.hxx"
#include "TCanvas.h"
#include "TH1D.h"
#include "TLatex.h"
#include "TLegend.h"
#include "Math/Vector4Dfwd.h"
#include "TStyle.h"
using namespace ROOT::VecOps;
using RNode = ROOT::RDF::RNode;
using rvec_f = const RVec<float> &;
using rvec_i = const RVec<int> &;
const auto z_mass = 91.2;

template<typename T>
void CollectionFilter(const TClonesArray& inColl ,vector<T*>& outColl, Double_t ptMin=30, Double_t etaMax=2.5)
{

const TObject *object;

for (Int_t i = 0; i < inColl.GetEntriesFast(); i++)
{

object = inColl.At(i);
const T *t = static_cast<const T*>(object);

if(t->P4().Pt() < ptMin) continue;
if(TMath::Abs(t->P4().Eta()) > etaMax) continue;

outColl.push_back(t);

}
}

void selectMuon(const char *inputFile)
{
  gSystem->Load("libDelphes");

  // Create chain of root trees
  TChain chain("Delphes");
  chain.Add(inputFile);

  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();

  // Get pointers to branches used in this analysis
  TClonesArray *branchMuon = treeReader->UseBranch("Muon");

  // Book histograms

  TH1F *histZMass = new TH1F("mass", "M_{inv}(Z[1]); M_inv (GeV/c^2); Events", 50, 0.0, 1500);
  TH1F *histDiMuonMass = new TH1F("mass", "M_{inv}(Z[3]Z[5]); M_inv (GeV/c^2); Events", 50, 0.0, 1500);

  // Define variables

  float_t PT, Eta, Phi, Mass, Charge;

  // Initializing the vectors
  //vector<const Muon*>  *muons = new vector<const Muon*>();;
  //MuonVector muon(PT, Eta, Phi, Mass, Charge);
  RVec<RVec<size_t>> reco_zz_to_4l(rvec_f PT, rvec_f Eta, rvec_f Phi, rvec_f Mass, rvec_i Charge);

    RVec<RVec<size_t>> idx(2);
    idx[0].reserve(2); idx[1].reserve(2);
    auto idx_cmb = Combinations(PT, 2);
    for (size_t i = 0; i < idx_cmb[0].size(); i++)
    {
      const auto i1 = idx_cmb[0][i];
      const auto i2 = idx_cmb[1][i];

      if(Charge[i1] != Charge[i2]
      {

        ROOT::Math::PtEtaPhiMVector m1(PT[0], Eta[0], Phi[0], Mass[0]);
        ROOT::Math::PtEtaPhiMVector m2(PT[1], Eta[1], Phi[1], Mass[1]);
        const auto mass = (m1 + m2).M();
     }
    }

      histDiMuonMass->Fill(mass);

   // end of event for loop
  histDiMuonMass->Draw();

  }

The errors that I am getting is below.

In file included from input_line_188:1:
/mnt/c/1/MG5_aMC_v2_6_6/Delphes/examples/selectMuon.C:89:16: error: subscripted value is not an array, pointer, or vector
      if(Charge[i1] != Charge[i2]
         ~~~~~~^~~
/mnt/c/1/MG5_aMC_v2_6_6/Delphes/examples/selectMuon.C:89:30: error: subscripted value is not an array, pointer, or vector
      if(Charge[i1] != Charge[i2]
                       ~~~~~~^~~
/mnt/c/1/MG5_aMC_v2_6_6/Delphes/examples/selectMuon.C:100:28: error: use of undeclared identifier 'mass'
      histDiMuonMass->Fill(mass);

How can I fix it?
Thank you.


问:
How do I make bitcoind listen on 0.0.0.0:8332?
I'm running bitcoind on one machine and would like to control it from another (using python and the JSON RPC interface).

~/.bitcoin/bitcoin.config on the bitcoind host (192.168.2.4):

```<code>rpcuser=xxx
rpcpassword=xxx
gen=1
rcpallowip=127.0.0.1
rcpallowip=192.168.2.6   # This is the other machine
paytxfee=0.01
</code>```

Now, I start bitcoind -daemon, but my python program fails with

```<code>IOError: [Errno socket error] [Errno 111] Connection refused
</code>```

On the bitcoind host, ps -nlp shows bitcoind listening on 127.0.0.1:8332, and not 0.0.0.0:8332 (which is what I would have expected). Wireshark shows a response of RST,ACK to the TCP connection attempt, which appears to be logical.

What am I missing?

答: Try rpcallowip, instead of rcpallowip :)</p>

Body:
I'm running bitcoind on one machine and would like to control it from another (using python and the JSON RPC interface).

~/.bitcoin/bitcoin.config on the bitcoind host (192.168.2.4):

rpcuser=xxx
rpcpassword=xxx
gen=1
rcpallowip=127.0.0.1
rcpallowip=192.168.2.6   # This is the other machine
paytxfee=0.01

Now, I start bitcoind -daemon, but my python program fails with

IOError: [Errno socket error] [Errno 111] Connection refused

On the bitcoind host, ps -nlp shows bitcoind listening on 127.0.0.1:8332, and not 0.0.0.0:8332 (which is what I would have expected). Wireshark shows a response of RST,ACK to the TCP connection attempt, which appears to be logical.

What am I missing?


问:
Failed to save data in mongoDB
when trying to save in my Mongo database, I can't record the data, to the point of connection with the DB is fine but then it doesn't save the data.
Today is my first day with Mongo, it may be that something is wrongly configured.

My controller

```<code>exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    const paciente = new Paciente(req.body);
    try {
        await paciente.save();
        res.json({ mensaje : 'El cliente se agregó correctamente'});
        console.log(paciente);

    } catch (error) {
        console.log(error);
        next();
    }
}
</code>```

When I run:

```<code>console.log(paciente);
</code>```

Result = __v: 0

Model:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pacientesSchema = new Schema({
    nombre: {
        type: String,
        trim: true,
    },
    propietario: {
        type: String,
        trim: true
    },
    fecha: {
        type: String,
        trim: true
    },
    telefono: {
        type: String,
        trim: true
    },
    hora: {
        type: String,
        trim: true
    },
    sintomas: {
        type: String,
        trim: true
    }
});

module.exports = mongoose.model('Paciente', pacientesSchema);
</code>```

Routes

```<code>const express = require('express');
const router = express.Router();
// Importar el controlador
const pacienteController = require('../controllers/pacienteControllers');

module.exports = function() {

    // router.get('/', () => {
    //     console.log('en home');

    // });

    // Agrega nuevos pacientes via POST
    router.post('/pacientes',
        pacienteController.nuevoCliente
    );

    return router;
}
</code>```

And the index:

```<code>const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const bodyParser = require('body-parser');

// Crear el servidor
const app = express();

// Conectar con MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/veterinaria', {
    useNewUrlParser: true,
    useUnifiedTopology:true,
    useFindAndModify:false
});

// Habilitar el body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Habilitar Routing
app.use('/', routes())

// Puerto y Arrancar
app.listen(4000, () => {
    console.log('Servidor funcionando')
})
</code>```

A screenshot of the configuration in atlas

Thanks friends.

答:
```<code>exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    // Crear Objeto de paciente con datos de req.body
    const paciente = new Paciente(req.body);

    paciente.save(function (err, saved) {
        if (err) {
          console.log(err);
        }
        else {
           console.log(saved);
           res.json({ mensaje : 'El cliente se agregó correctamente'});
        }
    }
    )
}
</code>```

Many thanks for your response

Title: Failed to save data in mongoDB

Body:
when trying to save in my Mongo database, I can't record the data, to the point of connection with the DB is fine but then it doesn't save the data.
Today is my first day with Mongo, it may be that something is wrongly configured.

My controller

exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    const paciente = new Paciente(req.body);
    try {
        await paciente.save();
        res.json({ mensaje : 'El cliente se agregó correctamente'});
        console.log(paciente);

    } catch (error) {
        console.log(error);
        next();
    }
}

When I run:

console.log(paciente);

Result = __v: 0

Model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pacientesSchema = new Schema({
    nombre: {
        type: String,
        trim: true,
    },
    propietario: {
        type: String,
        trim: true
    },
    fecha: {
        type: String,
        trim: true
    },
    telefono: {
        type: String,
        trim: true
    },
    hora: {
        type: String,
        trim: true
    },
    sintomas: {
        type: String,
        trim: true
    }
});

module.exports = mongoose.model('Paciente', pacientesSchema);

Routes

const express = require('express');
const router = express.Router();
// Importar el controlador
const pacienteController = require('../controllers/pacienteControllers');

module.exports = function() {

    // router.get('/', () => {
    //     console.log('en home');

    // });

    // Agrega nuevos pacientes via POST
    router.post('/pacientes',
        pacienteController.nuevoCliente
    );

    return router;
}

And the index:

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const bodyParser = require('body-parser');

// Crear el servidor
const app = express();

// Conectar con MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/veterinaria', {
    useNewUrlParser: true,
    useUnifiedTopology:true,
    useFindAndModify:false
});

// Habilitar el body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Habilitar Routing
app.use('/', routes())

// Puerto y Arrancar
app.listen(4000, () => {
    console.log('Servidor funcionando')
})

A screenshot of the configuration in atlas

Thanks friends.

Body:
exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    // Crear Objeto de paciente con datos de req.body
    const paciente = new Paciente(req.body);

    paciente.save(function (err, saved) {
        if (err) {
          console.log(err);
        }
        else {
           console.log(saved);
           res.json({ mensaje : 'El cliente se agregó correctamente'});
        }
    }
    )
}

Many thanks for your response


问:
Use COUNTIFS with two criteria?
I am stuck please help me,
basically I want use a formula which counts data within the day range that ı have defined and also counts just the name I describe.
Likes data which is in photo enter image description here

I want to learn just Anthony's done works number but just in first month like in 1/1/2019-1/30/2019

Sample Data

```<code>NAME       DATE        IS THERE ANY DONE WORK IN THIS DATE
anthony    1/1/2019    YES
jacob      1/25/2019   YES
anthony    1/30/2019   YES
justin     2/1/2019    YES
marc       2/5/2019    YES
anthony    3/1/2019    YES
jacob      3/1/2019    YES
</code>```

答:
If you can insert a column nest to your data, then enter a formula nest to each record as shown in the formula bar in the following screenshot and then use the sumifs formula to sum the total work done or countifs to count the number or records, Else, if its a huge data you can also create a pivot table as shown

Now that you have edited your question, I have to edit my anser:)

See SUMIFS formula in the image above.
Just replace if with COUNTIFS and add once more argument for work (F) column to check if it is = YES

so your new formula will be
COUNTIFS(D7:D13,"a",G7:G13,1,F7:F13,"YES")

This link will help you.. Please check

https://exceljet.net/formula/new-customers-per-month

Title: Use COUNTIFS with two criteria?

Body:
I am stuck please help me,
basically I want use a formula which counts data within the day range that ı have defined and also counts just the name I describe.
Likes data which is in photo enter image description here

I want to learn just Anthony's done works number but just in first month like in 1/1/2019-1/30/2019

Sample Data

NAME       DATE        IS THERE ANY DONE WORK IN THIS DATE
anthony    1/1/2019    YES
jacob      1/25/2019   YES
anthony    1/30/2019   YES
justin     2/1/2019    YES
marc       2/5/2019    YES
anthony    3/1/2019    YES
jacob      3/1/2019    YES