问:
Coding error for vivado project
I wanted to synthesis this coding, but it keep telling me that there is error at "reg button_old, button_raise;". Is there anyone who knows what mistakes I have in the coding? Thank you very much for your help.
We are doing project using nexys 4, we are able to simulate the coding, but are unable to synthesis it so we are not able to proceed to the next steps. Hope someone can help us.</p>

```<code>`timescale 1ns / 1ps

module Player (input clk, input rst,input button, input [29:0] set, input button_p1, input button_p2, output [3:0]oscore1, output [3:0]oscore2, output LED_ON, output answer, output [3:0]seg1, output [3:0]seg2)
    reg button_old, button_raise;
    reg number;
    reg [3:0] Score_P1, Score_P2;
    wire [3:0] Score_P1, Score_P2;
    reg [6:0] sevseg;
    wire answer;
    reg Clk_10000;
    reg [31:0] count;
    reg [3:0] digit;
    output [3:0] digit;

    always @(posedge clk or posedge rst) begin
        // detect rising edge
        button_old = 0;
        button = 0;
        button_raise =1'b0;
        if (button_old != button && button == 1'b1)
            button_raise <= 1'b1
        button_old <= button;
        // increment number
        if(button_raise == 1b'1)
        begin
          Score_P1 = 4'b0000;
          Score_P2 =4'b0000;
            if(~rst) number <= 0;
            else if(button_p1 && !button_p2 && answer==1'b1)
                         Score_P1 <= (Score_P1 + 1);
            else if(button_p2 && !button_p1 && answer==1'b1)
                         Score_P2 <= (Score_P2 + 1);
            else if(button_p1 && button_p2 && answer==1'b1 || answer==1'b0)
                        LED_ON [0];
            else LED_ON [7];
        end
        end
        end else
        button <=0;
        button_old <=0;
        button_raise <=0;

    end

    assign oscore1= Score_P1;
    assign oscore2= Score_P2;

    always @ (rd_ptr) begin
    set = setlist[rd_ptr];
    assign answer = set [totlen-1];
    case (digit)
    4'b1000: sevseg = set [27:21];
    4'b0100: sevseg = set [20:14];
    4'b0010: sevseg = set [13:7];
    4'b0001: sevseg = set [6:0];
    default: sevseg= 7'b0000000;
    endcase

    assign setlist[0] <= 29'b01111110100110011111101001111;
    assign setlist[1] <= 29'b11111110100111111111101001111;
    assign setlist[2] <= 29'b01111110000000111111100000000;
    assign setlist[3] <= 29'b01111110100111111111100100000;
    end

    always@(digit or seg1 or seg2) begin
    case(digit)
    4'b1110: sevseg = seg1[41:35];
    4'b1101: sevseg = seg1[34:28];
    4'b1011: sevseg = seg2[27:21];
    4'b0111: sevseg = seg2[20:14];
    endcase
    end

    always @ (posedge Clk or negedge rst) begin
    if (!rst) begin
    count <= 32'd0;
    Clk_10000<=0;
    end else begin
    if (count == 'd10000) begin
    count <= 32d'0;
    Clk_10000 <= ~Clk_10000;
    end else begin
    count <= count +1;
    end
    end
    end

    always @ (posedge Clk_10000 or negedge rst) begin
    if (!rst) begin
    digit <= 4'b1110;
    end else if (Clk_10000) begin
    digit <= {digit [2:0], digit [3]};
    end
    end

    always @ (Score_P1)
    begin
    case (Score_P1)
     4'b0000: seg1 <= 14'b0000001_0000001;
     4'b0001: seg1 <= 14'b0000001_1001111;
     4'b0010: seg1 <= 14'b0000001_0010010;
     4'b0011: seg1 <= 14'b0000001_0000110;
     4'b0100: seg1 <= 14'b0000001_1001100;
     4'b0101: seg1 <= 14'b0000001_0100100;
     4'b0110: seg1 <= 14'b0000001_0100000;
     4'b0111: seg1 <= 14'b0000001_0001111;
     4'b1000: seg1 <= 14'b0000001_0000000;
     4'b1001: seg1 <= 14'b0000001_0001100;
     4'b1010: seg1 <= 14'b1001111_0000001;
     4'b1011: seg1 <= 14'b1001111_1001111;
     4'b1100: seg1 <= 14'b1001111_0010010;
     4'b1101: seg1 <= 14'b1001111_0000110;
     4'b1110: seg1 <= 14'b1001111_0100100;
     4'b1111: seg1 <= 14'b1001111_0100000;
    endcase
    end

    always @ (Score_P2)
    begin
    case (Score_P2)
    4'b0000: seg2 <= 14'b0000001_0000001;
     4'b0001: seg1 <= 14'b0000001_1001111;
     4'b0010: seg2 <= 14'b0000001_0010010;
     4'b0011: seg2 <= 14'b0000001_0000110;
     4'b0100: seg2 <= 14'b0000001_1001100;
     4'b0101: seg2 <= 14'b0000001_0100100;
     4'b0110: seg2 <= 14'b0000001_0100000;
     4'b0111: seg2 <= 14'b0000001_0001111;
     4'b1000: seg2 <= 14'b0000001_0000000;
     4'b1001: seg2 <= 14'b0000001_0001100;
     4'b1010: seg2 <= 14'b1001111_0000001;
     4'b1011: seg2 <= 14'b1001111_1001111;
     4'b1100: seg2 <= 14'b1001111_0010010;
     4'b1101: seg2 <= 14'b1001111_0000110;
     4'b1110: seg2 <= 14'b1001111_0100100;
     4'b1111: seg2 <= 14'b1001111_0100000;
    endcase
    end
    endmodule
</code>```

答:
Okay, let's do this:

1. You're missing a semicolon after your module ports description.

```<code>module Player (
    input clk,
    input rst,
    input button,
    input [29:0] set,
    input button_p1,
    input button_p2,
    output [3:0]oscore1,
    output [3:0]oscore2,
    output LED_ON,
    output answer,
    output [3:0]seg1,
    output [3:0]seg2);
</code>```

2. You also can't declare all your inputs/outputs at the top in the module definition, and declare this output lower down:

```<code>output [3:0] digit;
</code>```

So move that up with the other outputs.

3. You're missing a semicolon here:

```<code>button_raise <= 1'b1
</code>```

4. This is a typo, it needs to be 1'b1:

```<code>if(button_raise == 1b'1)
</code>```

Same with this:

```<code>count <= 32d'0;
</code>```

5. This doesn't do anything:

```<code>LED_ON [0];
else LED_ON [7];
</code>```

I think you mean to assign LED_ON[0] <= 1'b1 and LED_ON[7] <= 1'b1.

However, you've also defined LED_ON as only 1-bit, so I'm assuming you want to define it as:

```<code>output reg [7:0] LED_ON,
</code>```

6. You're also missing an end statement somewhere, probably because you're trying to do if statements for multiple lines that aren't wrapped in a begin and end, like here:

```<code>end else
button <=0;
button_old <=0;
button_raise <=0;
</code>```

7. You're using blocking assignments = in a sequential block which isn't allowed like here:

```<code>always @(posedge clk or posedge rst) begin
    // detect rising edge
    button_old = 0;
</code>```

So make these non-blocking assignments like <=.

8. You're trying to do nonblocking assignments in a combinational block:

```<code>always @ (rd_ptr) begin
    //...
    assign setlist[0] <= 29'b01111110100110011111101001111;
</code>```

So make these blocking assignments like =.v

9. You're trying to do assignments in a combinational block like here:

```<code>always @ (rd_ptr) begin
    set = setlist[rd_ptr];
    assign answer = set [totlen-1];
</code>```

There make the assignments outside of the always block or get rid of the assign altogether.

10. These signals aren't defined anywhere. So the compiler doesn't know what to do with them.

```<code>Clk;
rd_ptr;
setlist;
totlen;
</code>```

11. Score_P1 and Score_P2 have both been defined twice as both a register and a wire.

```<code>reg [3:0] Score_P1, Score_P2;
wire [3:0] Score_P1, Score_P2;
</code>```

Same with the output/wire answer.

12. You're assigning to your input button like it's a register. That doesn't make any sense. You're only ever assigning it as 0 so get rid of the assignments and just let it be an input.

You're also assigning to your input set.

13. You're assigning to setlist in a combination block like it's a reg, but you've defined it as a wire. So define it as a reg.

14. You've also defined setlist as a single bit but you're indexing on it as [0] to [3] so let's define it as 4 bits. You're also assigning each index with with 29 bits. So let's call it a 2d array, even though it's never even read from and this makes no sense.

15. seg1 and seg2 are defined as 4-bits, but you're indexing on them all the way up to [41:35], so let's call them both 42-bits.

And there you have it, with 15+ easy fixes, now your code that makes no sense and probably does nothing still makes no sense and does nothing, but can actually compile. Final result:

```<code>`timescale 1ns / 1ps

module Player (
    input wire clk,
    input wire rst,
    input wire button,
    input wire [29:0] set,
    input wire button_p1,
    input wire button_p2,
    output wire [3:0]oscore1,
    output wire [3:0]oscore2,
    output reg [7:0] LED_ON,
    output reg answer,
    output reg [3:0] digit,
    output reg [42:0]seg1,
    output reg [42:0]seg2
);

wire  Clk;
wire  rd_ptr;
reg [28:0] setlist [3:0];
wire  totlen;

reg button_old, button_raise;
reg number;
reg [3:0] Score_P1, Score_P2;
reg [6:0] sevseg;
reg Clk_10000;
reg [31:0] count;

always @(posedge clk or posedge rst) begin
    // detect rising edge
    button_old <= 0;
    button_raise <= 1'b0;
    if (button_old != button && button == 1'b1) begin
        button_raise <= 1'b1;
        button_old <= button;
        // increment number
        if(button_raise == 1'b1) begin
            Score_P1 = 4'b0000;
            Score_P2 =4'b0000;
            if(~rst) begin
                number <= 0;
            end
        end else if(button_p1 && !button_p2 && answer==1'b1) begin
            Score_P1 <= (Score_P1 + 1);
        end else if(button_p2 && !button_p1 && answer==1'b1) begin
            Score_P2 <= (Score_P2 + 1);
        end else if(button_p1 && button_p2 && answer==1'b1 || answer==1'b0) begin
            LED_ON [0] <= 1'b1;
        end else begin
            LED_ON [7] <= 1'b1;
        end
    end else begin
        button_old <=0;
        button_raise <=0;
    end
end

assign oscore1= Score_P1;
assign oscore2= Score_P2;

always @ (rd_ptr) begin
    assign answer = set [totlen-1];
    case (digit)
        4'b1000: sevseg = set [27:21];
        4'b0100: sevseg = set [20:14];
        4'b0010: sevseg = set [13:7];
        4'b0001: sevseg = set [6:0];
        default: sevseg= 7'b0000000;
    endcase

    setlist[0] = 29'b01111110100110011111101001111;
    setlist[1] = 29'b11111110100111111111101001111;
    setlist[2] = 29'b01111110000000111111100000000;
    setlist[3] = 29'b01111110100111111111100100000;
end

always@(digit or seg1 or seg2) begin
    case(digit)
        4'b1110: sevseg = seg1[41:35];
        4'b1101: sevseg = seg1[34:28];
        4'b1011: sevseg = seg2[27:21];
        4'b0111: sevseg = seg2[20:14];
    endcase
end

always @ (posedge Clk or negedge rst) begin
    if (!rst) begin
        count <= 32'd0;
        Clk_10000<=0;
    end else begin
        if (count == 'd10000) begin
            count <= 32'd0;
            Clk_10000 <= ~Clk_10000;
        end else begin
            count <= count +1;
        end
    end
end

always @ (posedge Clk_10000 or negedge rst) begin
    if (!rst) begin
        digit <= 4'b1110;
    end else if (Clk_10000) begin
        digit <= {digit [2:0], digit [3]};
    end
end

always @ (Score_P1)
begin
    case (Score_P1)
        4'b0000: seg1 <= 14'b0000001_0000001;
        4'b0001: seg1 <= 14'b0000001_1001111;
        4'b0010: seg1 <= 14'b0000001_0010010;
        4'b0011: seg1 <= 14'b0000001_0000110;
        4'b0100: seg1 <= 14'b0000001_1001100;
        4'b0101: seg1 <= 14'b0000001_0100100;
        4'b0110: seg1 <= 14'b0000001_0100000;
        4'b0111: seg1 <= 14'b0000001_0001111;
        4'b1000: seg1 <= 14'b0000001_0000000;
        4'b1001: seg1 <= 14'b0000001_0001100;
        4'b1010: seg1 <= 14'b1001111_0000001;
        4'b1011: seg1 <= 14'b1001111_1001111;
        4'b1100: seg1 <= 14'b1001111_0010010;
        4'b1101: seg1 <= 14'b1001111_0000110;
        4'b1110: seg1 <= 14'b1001111_0100100;
        4'b1111: seg1 <= 14'b1001111_0100000;
    endcase
end

always @ (Score_P2)
begin
    case (Score_P2)
        4'b0000: seg2 <= 14'b0000001_0000001;
        4'b0001: seg1 <= 14'b0000001_1001111;
        4'b0010: seg2 <= 14'b0000001_0010010;
        4'b0011: seg2 <= 14'b0000001_0000110;
        4'b0100: seg2 <= 14'b0000001_1001100;
        4'b0101: seg2 <= 14'b0000001_0100100;
        4'b0110: seg2 <= 14'b0000001_0100000;
        4'b0111: seg2 <= 14'b0000001_0001111;
        4'b1000: seg2 <= 14'b0000001_0000000;
        4'b1001: seg2 <= 14'b0000001_0001100;
        4'b1010: seg2 <= 14'b1001111_0000001;
        4'b1011: seg2 <= 14'b1001111_1001111;
        4'b1100: seg2 <= 14'b1001111_0010010;
        4'b1101: seg2 <= 14'b1001111_0000110;
        4'b1110: seg2 <= 14'b1001111_0100100;
        4'b1111: seg2 <= 14'b1001111_0100000;
    endcase
end
endmodule
</code>```

Title: Coding error for vivado project

Body:
I wanted to synthesis this coding, but it keep telling me that there is error at "reg button_old, button_raise;". Is there anyone who knows what mistakes I have in the coding? Thank you very much for your help.
We are doing project using nexys 4, we are able to simulate the coding, but are unable to synthesis it so we are not able to proceed to the next steps. Hope someone can help us.

`timescale 1ns / 1ps

module Player (input clk, input rst,input button, input [29:0] set, input button_p1, input button_p2, output [3:0]oscore1, output [3:0]oscore2, output LED_ON, output answer, output [3:0]seg1, output [3:0]seg2)
    reg button_old, button_raise;
    reg number;
    reg [3:0] Score_P1, Score_P2;
    wire [3:0] Score_P1, Score_P2;
    reg [6:0] sevseg;
    wire answer;
    reg Clk_10000;
    reg [31:0] count;
    reg [3:0] digit;
    output [3:0] digit;

    always @(posedge clk or posedge rst) begin
        // detect rising edge
        button_old = 0;
        button = 0;
        button_raise =1'b0;
        if (button_old != button && button == 1'b1)
            button_raise <= 1'b1
        button_old <= button;
        // increment number
        if(button_raise == 1b'1)
        begin
          Score_P1 = 4'b0000;
          Score_P2 =4'b0000;
            if(~rst) number <= 0;
            else if(button_p1 && !button_p2 && answer==1'b1)
                         Score_P1 <= (Score_P1 + 1);
            else if(button_p2 && !button_p1 && answer==1'b1)
                         Score_P2 <= (Score_P2 + 1);
            else if(button_p1 && button_p2 && answer==1'b1 || answer==1'b0)
                        LED_ON [0];
            else LED_ON [7];
        end
        end
        end else
        button <=0;
        button_old <=0;
        button_raise <=0;

    end

    assign oscore1= Score_P1;
    assign oscore2= Score_P2;

    always @ (rd_ptr) begin
    set = setlist[rd_ptr];
    assign answer = set [totlen-1];
    case (digit)
    4'b1000: sevseg = set [27:21];
    4'b0100: sevseg = set [20:14];
    4'b0010: sevseg = set [13:7];
    4'b0001: sevseg = set [6:0];
    default: sevseg= 7'b0000000;
    endcase

    assign setlist[0] <= 29'b01111110100110011111101001111;
    assign setlist[1] <= 29'b11111110100111111111101001111;
    assign setlist[2] <= 29'b01111110000000111111100000000;
    assign setlist[3] <= 29'b01111110100111111111100100000;
    end

    always@(digit or seg1 or seg2) begin
    case(digit)
    4'b1110: sevseg = seg1[41:35];
    4'b1101: sevseg = seg1[34:28];
    4'b1011: sevseg = seg2[27:21];
    4'b0111: sevseg = seg2[20:14];
    endcase
    end

    always @ (posedge Clk or negedge rst) begin
    if (!rst) begin
    count <= 32'd0;
    Clk_10000<=0;
    end else begin
    if (count == 'd10000) begin
    count <= 32d'0;
    Clk_10000 <= ~Clk_10000;
    end else begin
    count <= count +1;
    end
    end
    end

    always @ (posedge Clk_10000 or negedge rst) begin
    if (!rst) begin
    digit <= 4'b1110;
    end else if (Clk_10000) begin
    digit <= {digit [2:0], digit [3]};
    end
    end

    always @ (Score_P1)
    begin
    case (Score_P1)
     4'b0000: seg1 <= 14'b0000001_0000001;
     4'b0001: seg1 <= 14'b0000001_1001111;
     4'b0010: seg1 <= 14'b0000001_0010010;
     4'b0011: seg1 <= 14'b0000001_0000110;
     4'b0100: seg1 <= 14'b0000001_1001100;
     4'b0101: seg1 <= 14'b0000001_0100100;
     4'b0110: seg1 <= 14'b0000001_0100000;
     4'b0111: seg1 <= 14'b0000001_0001111;
     4'b1000: seg1 <= 14'b0000001_0000000;
     4'b1001: seg1 <= 14'b0000001_0001100;
     4'b1010: seg1 <= 14'b1001111_0000001;
     4'b1011: seg1 <= 14'b1001111_1001111;
     4'b1100: seg1 <= 14'b1001111_0010010;
     4'b1101: seg1 <= 14'b1001111_0000110;
     4'b1110: seg1 <= 14'b1001111_0100100;
     4'b1111: seg1 <= 14'b1001111_0100000;
    endcase
    end

    always @ (Score_P2)
    begin
    case (Score_P2)
    4'b0000: seg2 <= 14'b0000001_0000001;
     4'b0001: seg1 <= 14'b0000001_1001111;
     4'b0010: seg2 <= 14'b0000001_0010010;
     4'b0011: seg2 <= 14'b0000001_0000110;
     4'b0100: seg2 <= 14'b0000001_1001100;
     4'b0101: seg2 <= 14'b0000001_0100100;
     4'b0110: seg2 <= 14'b0000001_0100000;
     4'b0111: seg2 <= 14'b0000001_0001111;
     4'b1000: seg2 <= 14'b0000001_0000000;
     4'b1001: seg2 <= 14'b0000001_0001100;
     4'b1010: seg2 <= 14'b1001111_0000001;
     4'b1011: seg2 <= 14'b1001111_1001111;
     4'b1100: seg2 <= 14'b1001111_0010010;
     4'b1101: seg2 <= 14'b1001111_0000110;
     4'b1110: seg2 <= 14'b1001111_0100100;
     4'b1111: seg2 <= 14'b1001111_0100000;
    endcase
    end
    endmodule

Body:
Okay, let's do this:

1. You're missing a semicolon after your module ports description.

module Player (
    input clk,
    input rst,
    input button,
    input [29:0] set,
    input button_p1,
    input button_p2,
    output [3:0]oscore1,
    output [3:0]oscore2,
    output LED_ON,
    output answer,
    output [3:0]seg1,
    output [3:0]seg2);

2. You also can't declare all your inputs/outputs at the top in the module definition, and declare this output lower down:

output [3:0] digit;

So move that up with the other outputs.

3. You're missing a semicolon here:

button_raise <= 1'b1

4. This is a typo, it needs to be 1'b1:

if(button_raise == 1b'1)

Same with this:

count <= 32d'0;

5. This doesn't do anything:

LED_ON [0];
else LED_ON [7];

I think you mean to assign LED_ON[0] <= 1'b1 and LED_ON[7] <= 1'b1.

However, you've also defined LED_ON as only 1-bit, so I'm assuming you want to define it as:

output reg [7:0] LED_ON,

6. You're also missing an end statement somewhere, probably because you're trying to do if statements for multiple lines that aren't wrapped in a begin and end, like here:

end else
button <=0;
button_old <=0;
button_raise <=0;

7. You're using blocking assignments = in a sequential block which isn't allowed like here:

always @(posedge clk or posedge rst) begin
    // detect rising edge
    button_old = 0;

So make these non-blocking assignments like <=.

8. You're trying to do nonblocking assignments in a combinational block:

always @ (rd_ptr) begin
    //...
    assign setlist[0] <= 29'b01111110100110011111101001111;

So make these blocking assignments like =.v

9. You're trying to do assignments in a combinational block like here:

always @ (rd_ptr) begin
    set = setlist[rd_ptr];
    assign answer = set [totlen-1];

There make the assignments outside of the always block or get rid of the assign altogether.

10. These signals aren't defined anywhere. So the compiler doesn't know what to do with them.

Clk;
rd_ptr;
setlist;
totlen;

11. Score_P1 and Score_P2 have both been defined twice as both a register and a wire.

reg [3:0] Score_P1, Score_P2;
wire [3:0] Score_P1, Score_P2;

Same with the output/wire answer.

12. You're assigning to your input button like it's a register. That doesn't make any sense. You're only ever assigning it as 0 so get rid of the assignments and just let it be an input.

You're also assigning to your input set.

13. You're assigning to setlist in a combination block like it's a reg, but you've defined it as a wire. So define it as a reg.

14. You've also defined setlist as a single bit but you're indexing on it as [0] to [3] so let's define it as 4 bits. You're also assigning each index with with 29 bits. So let's call it a 2d array, even though it's never even read from and this makes no sense.

15. seg1 and seg2 are defined as 4-bits, but you're indexing on them all the way up to [41:35], so let's call them both 42-bits.

And there you have it, with 15+ easy fixes, now your code that makes no sense and probably does nothing still makes no sense and does nothing, but can actually compile. Final result:

`timescale 1ns / 1ps

module Player (
    input wire clk,
    input wire rst,
    input wire button,
    input wire [29:0] set,
    input wire button_p1,
    input wire button_p2,
    output wire [3:0]oscore1,
    output wire [3:0]oscore2,
    output reg [7:0] LED_ON,
    output reg answer,
    output reg [3:0] digit,
    output reg [42:0]seg1,
    output reg [42:0]seg2
);

wire  Clk;
wire  rd_ptr;
reg [28:0] setlist [3:0];
wire  totlen;

reg button_old, button_raise;
reg number;
reg [3:0] Score_P1, Score_P2;
reg [6:0] sevseg;
reg Clk_10000;
reg [31:0] count;

always @(posedge clk or posedge rst) begin
    // detect rising edge
    button_old <= 0;
    button_raise <= 1'b0;
    if (button_old != button && button == 1'b1) begin
        button_raise <= 1'b1;
        button_old <= button;
        // increment number
        if(button_raise == 1'b1) begin
            Score_P1 = 4'b0000;
            Score_P2 =4'b0000;
            if(~rst) begin
                number <= 0;
            end
        end else if(button_p1 && !button_p2 && answer==1'b1) begin
            Score_P1 <= (Score_P1 + 1);
        end else if(button_p2 && !button_p1 && answer==1'b1) begin
            Score_P2 <= (Score_P2 + 1);
        end else if(button_p1 && button_p2 && answer==1'b1 || answer==1'b0) begin
            LED_ON [0] <= 1'b1;
        end else begin
            LED_ON [7] <= 1'b1;
        end
    end else begin
        button_old <=0;
        button_raise <=0;
    end
end

assign oscore1= Score_P1;
assign oscore2= Score_P2;

always @ (rd_ptr) begin
    assign answer = set [totlen-1];
    case (digit)
        4'b1000: sevseg = set [27:21];
        4'b0100: sevseg = set [20:14];
        4'b0010: sevseg = set [13:7];
        4'b0001: sevseg = set [6:0];
        default: sevseg= 7'b0000000;
    endcase

    setlist[0] = 29'b01111110100110011111101001111;
    setlist[1] = 29'b11111110100111111111101001111;
    setlist[2] = 29'b01111110000000111111100000000;
    setlist[3] = 29'b01111110100111111111100100000;
end

always@(digit or seg1 or seg2) begin
    case(digit)
        4'b1110: sevseg = seg1[41:35];
        4'b1101: sevseg = seg1[34:28];
        4'b1011: sevseg = seg2[27:21];
        4'b0111: sevseg = seg2[20:14];
    endcase
end

always @ (posedge Clk or negedge rst) begin
    if (!rst) begin
        count <= 32'd0;
        Clk_10000<=0;
    end else begin
        if (count == 'd10000) begin
            count <= 32'd0;
            Clk_10000 <= ~Clk_10000;
        end else begin
            count <= count +1;
        end
    end
end

always @ (posedge Clk_10000 or negedge rst) begin
    if (!rst) begin
        digit <= 4'b1110;
    end else if (Clk_10000) begin
        digit <= {digit [2:0], digit [3]};
    end
end

always @ (Score_P1)
begin
    case (Score_P1)
        4'b0000: seg1 <= 14'b0000001_0000001;
        4'b0001: seg1 <= 14'b0000001_1001111;
        4'b0010: seg1 <= 14'b0000001_0010010;
        4'b0011: seg1 <= 14'b0000001_0000110;
        4'b0100: seg1 <= 14'b0000001_1001100;
        4'b0101: seg1 <= 14'b0000001_0100100;
        4'b0110: seg1 <= 14'b0000001_0100000;
        4'b0111: seg1 <= 14'b0000001_0001111;
        4'b1000: seg1 <= 14'b0000001_0000000;
        4'b1001: seg1 <= 14'b0000001_0001100;
        4'b1010: seg1 <= 14'b1001111_0000001;
        4'b1011: seg1 <= 14'b1001111_1001111;
        4'b1100: seg1 <= 14'b1001111_0010010;
        4'b1101: seg1 <= 14'b1001111_0000110;
        4'b1110: seg1 <= 14'b1001111_0100100;
        4'b1111: seg1 <= 14'b1001111_0100000;
    endcase
end

always @ (Score_P2)
begin
    case (Score_P2)
        4'b0000: seg2 <= 14'b0000001_0000001;
        4'b0001: seg1 <= 14'b0000001_1001111;
        4'b0010: seg2 <= 14'b0000001_0010010;
        4'b0011: seg2 <= 14'b0000001_0000110;
        4'b0100: seg2 <= 14'b0000001_1001100;
        4'b0101: seg2 <= 14'b0000001_0100100;
        4'b0110: seg2 <= 14'b0000001_0100000;
        4'b0111: seg2 <= 14'b0000001_0001111;
        4'b1000: seg2 <= 14'b0000001_0000000;
        4'b1001: seg2 <= 14'b0000001_0001100;
        4'b1010: seg2 <= 14'b1001111_0000001;
        4'b1011: seg2 <= 14'b1001111_1001111;
        4'b1100: seg2 <= 14'b1001111_0010010;
        4'b1101: seg2 <= 14'b1001111_0000110;
        4'b1110: seg2 <= 14'b1001111_0100100;
        4'b1111: seg2 <= 14'b1001111_0100000;
    endcase
end
endmodule


来源: stackexchange

问:
Getting the IO count
I am using xen hypervisor. I am trying to get the IO count of the VMs running on top of the xen hypervisor. Can someone suggest me some way or tool to get the IO count ? I tried using xenmon and virt-top. Virt-top doesnt give any value and xenmon always shows 0. Any suggestions to get the number of read or write calls made by a VM or the read and write(Block IO) bandwidth of a particular VM. Thanks !

Regards,
Sethu

答:
You can read this directly from sysfs on most systems. You want to open the following directory:

```<code>/sys/devices/xen-backend
</code>```

And look for directories starting with vbd-

The nomenclature is:

```<code>vbd-{domain_id}-{vbd_id}/statistics
</code>```

Inside, you'll find what you need, which is:

br_req - Number of block read requests

oo_req - Number of 'out of' requests (no room left in list to service any given request)

rd_req - Number of read requests

rd_sect - Number of sectors read

wr_sect - Number of sectors written

The br_req will be an aggregate count of things like write barriers, aborts, etc.

Note, for this to work, The kernel has to be told to export Xen attributes via sysfs, but most Xen packages have this enabled. Additionally, the location in sysfs might be different with earlier versions of Xen.

ContentLicense: CC BY-SA 2.5

Title: Getting the IO count

Body:
You can read this directly from sysfs on most systems. You want to open the following directory:

/sys/devices/xen-backend

And look for directories starting with vbd-

The nomenclature is:

vbd-{domain_id}-{vbd_id}/statistics

Inside, you'll find what you need, which is:

br_req - Number of block read requests

oo_req - Number of 'out of' requests (no room left in list to service any given request)

rd_req - Number of read requests

rd_sect - Number of sectors read

wr_sect - Number of sectors written

The br_req will be an aggregate count of things like write barriers, aborts, etc.

Note, for this to work, The kernel has to be told to export Xen attributes via sysfs, but most Xen packages have this enabled. Additionally, the location in sysfs might be different with earlier versions of Xen.


问:
Pandas rank method dense but skip a number
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

```<code>import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df
</code>```

it looks like:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0
</code>```

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0
</code>```

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

```<code>    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0
</code>```

答:
```<code>rankings = df[["HP","unit"]].drop_duplicates()
rankings['rank'] = rankings['HP'].rank(ascending=False, method='min')
df = df.merge(rankings)
df
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a sample data set that i'm trying to rank based on the values in the column 'HP':

import pandas as pd

d = {
 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'],
 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'],
 'HP': [24, 24, 24,7,7,7,7,7,7,5,5,5]
}
df = pd.DataFrame(d)

df['rank']=df['HP'].rank(ascending=False, method='dense')

df

it looks like:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   3.0
10   5  E2   UB   3.0
11   5  E3   UB   3.0

the 'HP' is a calculated column based on other columns (i won't show it here, but it's necessary in my real dataset)

I also tried the method='min' but the outcome looks like this:

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   4.0
4    7  Q2   UC   4.0
5    7  Q3   UC   4.0
6    7  D1   UA   4.0
7    7  D2   UA   4.0
8    7  D3   UA   4.0
9    5  E1   UB  10.0
10   5  E2   UB  10.0
11   5  E3   UB  10.0

Units 'UC' and 'UA' tie for 2nd rank, what i'm looking for is to have the next rank which is unit 'UB' to be '4' instead of '3'. :

    HP N-D unit  rank
0   24  C1   UD   1.0
1   24  C2   UD   1.0
2   24  C3   UD   1.0
3    7  Q1   UC   2.0
4    7  Q2   UC   2.0
5    7  Q3   UC   2.0
6    7  D1   UA   2.0
7    7  D2   UA   2.0
8    7  D3   UA   2.0
9    5  E1   UB   4.0
10   5  E2   UB   4.0
11   5  E3   UB   4.0


问:
Running in Linux versus through Eclipse?
I was giving a program to look at, I am very new to java but they run it through Linux and use the command

```<code>" java -Dfile.encoding=UTF-8 -classpath $PROGRAM_DIR/bin account.Driver"
</code>```

I'm trying to run it through eclipse but its giving a file not found in main error. Is there any way to get it to run through eclipse or is this something to do with the code its self?

Here is the main function:

```<code>package account.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import account.controller.AccountController;

public class Driver {

    public static void main(String [] args) {
        String accountDataFilename = args[0];
        new AccountController(accountDataFilename);

    }

}
</code>```

Side note: this program is MVC style coding

答:
You are not launching your Java Application from the directory you think you are. The default is most likely your project's root location. If that's not what you intended, specify it.

http://help.eclipse.org/oxygen/topic/org.eclipse.jdt.doc.user/tasks/tasks-executionArgs.htm?cp=1_3_6_6

Body:
I was giving a program to look at, I am very new to java but they run it through Linux and use the command

" java -Dfile.encoding=UTF-8 -classpath $PROGRAM_DIR/bin account.Driver"

I'm trying to run it through eclipse but its giving a file not found in main error. Is there any way to get it to run through eclipse or is this something to do with the code its self?

Here is the main function:

package account.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import account.controller.AccountController;

public class Driver {

    public static void main(String [] args) {
        String accountDataFilename = args[0];
        new AccountController(accountDataFilename);

    }

}

Side note: this program is MVC style coding


问:
How to get total number of users in slack team
Currently the only way I can find is to iterate over the users.list endpoint, but I think this isn't an efficient way to do it, I expected to find an attribute number_of_users in the team.info endpoint.
Any suggestions for a better way to get the total number of users ?

答:
No, the only way to get the total numer of you users is with the user.list endpoint.

But I don't think there is any need to iterate through the list by yourself. You get an array from the endpoint, so you can just do a count on it.

e.g. in PHP you something like:
$memberCount = count($userlist['members']);


问:
Python, Pandas, inverted expanding window
Lets consider the following Series:

```<code>s=pd.Series(data=[100, 110, 120, 150, 110, 90, 80, 70, 90, 95])
</code>```

I iterate over each item and perform the following operation:

```<code>for i in range(len(s)):
    m=max(s[i]-s[i:])
</code>```

Basically comparing each item with all items that follow, and retrieving the max.

I can do that with:

```<code>r=[]
for i in range(len(s)):
    m=max(s[i]-s[i:])
    r.append(m)

result=pd.Series(r)
</code>```

But I had the feeling that this would be something that a rolling window could do? I am trying to make my code a bit cleaner and was just starting reading and exploring about the rolling function, but i cannot yet but my finger on it. This idea seems like a inverted expanding function (i.e. it takes less and less data as it goes down the data)?

If someone has ideas about how to reformat the code using rolling / expanding windows, please let me know.

Body:
Lets consider the following Series:

s=pd.Series(data=[100, 110, 120, 150, 110, 90, 80, 70, 90, 95])

I iterate over each item and perform the following operation:

for i in range(len(s)):
    m=max(s[i]-s[i:])

Basically comparing each item with all items that follow, and retrieving the max.

I can do that with:

r=[]
for i in range(len(s)):
    m=max(s[i]-s[i:])
    r.append(m)

result=pd.Series(r)

But I had the feeling that this would be something that a rolling window could do? I am trying to make my code a bit cleaner and was just starting reading and exploring about the rolling function, but i cannot yet but my finger on it. This idea seems like a inverted expanding function (i.e. it takes less and less data as it goes down the data)?

If someone has ideas about how to reformat the code using rolling / expanding windows, please let me know.

Body:
Or we can using rolling and min

s-s[::-1].rolling(len(s),min_periods=1).min()
Out[368]:
0    30.0
1    40.0
2    50.0
3    80.0
4    40.0
5    20.0
6    10.0
7     0.0
8     0.0
9     0.0
dtype: float64


问:
iOS 11 Navigation bar large title have black color when push on pop view controller
I have a problem with the new navigation bar for iOS 11.

In root view set new navigation by code:

```<code>if (@available(iOS 11.0, *)) {
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
}
</code>```

Then from root view, I pushed to another view and set code navigation bar by

```<code>if (@available(iOS 11.0, *)) {
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeNever;
}
</code>```

It works well. However, when push and pop view a black color appeared like the image below:

I don't know why the black color appeared on this view although I did not set back ground for navigation bar is a black color for the whole screen in my app.

Someone have any idea for the problem. Please drop me some suggestion to solve that bug. Thanks.

答:
I solved this issue with simple extension

```<code>extension UINavigationController {

    @IBInspectable var backgroundColor: UIColor {
        set {
            self.view.backgroundColor = newValue;
        }
        get {
            return self.view.backgroundColor ?? UIColor.black;
        }
    }

}
</code>```

You can change background color from storyboard!

Body:
I have a problem with the new navigation bar for iOS 11.

In root view set new navigation by code:

if (@available(iOS 11.0, *)) {
    self.navigationController.navigationBar.prefersLargeTitles = YES;
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
}

Then from root view, I pushed to another view and set code navigation bar by

if (@available(iOS 11.0, *)) {
    self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeNever;
}

It works well. However, when push and pop view a black color appeared like the image below:

I don't know why the black color appeared on this view although I did not set back ground for navigation bar is a black color for the whole screen in my app.

Someone have any idea for the problem. Please drop me some suggestion to solve that bug. Thanks.

Body:
I solved this issue with simple extension

extension UINavigationController {

    @IBInspectable var backgroundColor: UIColor {
        set {
            self.view.backgroundColor = newValue;
        }
        get {
            return self.view.backgroundColor ?? UIColor.black;
        }
    }

}

You can change background color from storyboard!


问:
Debian 8: Installed Python 2.7.13 But No Pip; Packages Install to Wrong Path
I am running Debain 8 Jessie and have installed python 2.7.13 into /usr/local/bin.

I do not have a new pip installed, I am still using the pip located at /usr/bin/. Any time I install a package using pip, they are installed to the dist-packages location of my new python install:

/usr/local/lib/python2.7/dist-packages

Question

How do I get my pip installs to permanently install in /usr/lib/python2.7/dist-packages? What is even weirder, is that although these packages are installing to a location seemingly setup by my new install, I cannot import whatever I download when I am using python2.7.13 via /usr/local/bin/python.

PATH

/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/sbin:/bin:

Better Yet

How do I just get my python2.7.13 install to see the installed packages from pip?

答:
Run this:

```<code>import sys
for p in sys.path:
    print p     # or print(p) if you prefer.
</code>```

Look for /usr/lib/python2.7

if not you'll want to

```<code>export PYTHONPATH=/usr/local/lib/python2.7:/usr/lib/python2.7
</code>```

in .bashrc or in a special (host-wide) script in /etc/profile.d/

If /usr/lib/python2.7/

Depending on the difference between your "stock" version and 2.7.13, you might not want to put stuff in /usr/lib/python2.7. On my system I'd really want to avoid any cross contamination, but that's something I'm a bit picky about.

Body:
Run this:

import sys
for p in sys.path:
    print p     # or print(p) if you prefer.

Look for /usr/lib/python2.7

if not you'll want to

export PYTHONPATH=/usr/local/lib/python2.7:/usr/lib/python2.7

in .bashrc or in a special (host-wide) script in /etc/profile.d/

If /usr/lib/python2.7/

Depending on the difference between your "stock" version and 2.7.13, you might not want to put stuff in /usr/lib/python2.7. On my system I'd really want to avoid any cross contamination, but that's something I'm a bit picky about.


问:
Microsoft SQL Server equivalent of MySQL REGEXP
I am trying to reconstruct a database query I created for MySQL in Microsoft SQL Server. I am looking for an operator or function SQL Server which acts like REGEXP.

Here is an example of how I am using the operator:

```<code>select *
from   musicdetails
WHERE  artistname REGEXP '^".mysql_escape_string($_GET['search'])."$'
</code>```

答:
While the code in leppie's answer will compile and execute, I would not recommend it for production use. If you want RegEx functions that:

are coded using best practices (for performance and security)

handle NULLs appropriately

perform better / more efficient

have more options (e.g. @StartAt, @RegExOptions for IgnoreCase, MultiLine, etc)

provide more functionality (e.g. CaptureGroup, CaptureGroupCapture, Escape, Unescape, etc)

require no additional effort to deploy (i.e. a single, self-contained T-SQL script that is portable and versionable, and installs cleanly with no need to manually enable "CLR enabled" or mess with the "CLR strict security" setting that was introduced in SQL Server 2017)

and are also free, then check out the SQL# SQLCLR library (that I wrote). There are 13 RegEx functions in the Free version (and 2 more in the Full / paid version, plus the ability to increase the expression cache size, which can help if you frequently use a variety of expressions).

I believe the function RegEx_IsMatch (or RegEx_IsMatch4k) is what you are looking for (yes, it is in the Free version).

ContentLicense: CC BY-SA 4.0

Body:
I am trying to reconstruct a database query I created for MySQL in Microsoft SQL Server. I am looking for an operator or function SQL Server which acts like REGEXP.

Here is an example of how I am using the operator:

select *
from   musicdetails
WHERE  artistname REGEXP '^".mysql_escape_string($_GET['search'])."$'


问:
NetSuite: An error occurred while processing item options
I am loading, doing some changes, and saving a Sales Order. I do this on approve and everything works. I do this on edit (when the status is changed to Pending Approval) and it throws the above error:
"An error occurred while processing item options."

Now I have commented out the setting of 2 fields I was setting. It still throws the error.

The only thing that comes up in SuiteAnswers doesn't really make sense to this situation.

答:
This ended up being caused by something else in my code that I didn't think mattered.

When status is changed to Pending Approval, I delete a record where there is a Custom field that references it on the SO line. I was deleting it, setting some values, and then saving the record. When i took the delete out, it worked. So I ended up pushing the id of the record to delete into an array and then looping over that AFTER I saved the record and it worked


问:
Efficiently shrink data by getting rid of every other bit
My source data is redundant and every bit is duplicated. I'm rearranging and processing this data and there are several gigs of data. I mostly work in python but have switched to working with C++ because of processing speed limitations though I'm not familiar with all the nuances.
If this is my raw data: 1100 0011 1100 1100 I want it to look like this: 1001 1010 My solution would be to bit compare each position and compose the new data bit by bit. Is there a more efficient method of doing this?

Apparently this confused people here is another attempt to illustrate the question.

INCOMING DATA: 1100 1100 0011 0011

DESIRED  DATA: 1x0x 1x0x 0x1x 0x1x

CORRECTED    : 1010 0101

The incoming data has every bit represented twice. There are two 1s and two 0s where there should be only one 1 and one 0. Rather than checking the state of the bit then shifting that into a new byte what is a more efficient solution?

答:
Based on the idea of @user4581301, you could use a mapping table that maps each possible 16 bit input into the corresponding 8 bit "shrinked" target. Note, however, that this (sparse) mapping table needs 65536 entries, since this is the  range of your 16 bit input. Of course, this approach only makes sense if you have to transform lots of 16 bit input values (such that the time for preparing the mapping table does not count):</p>

```<code>uint8_t map2uint8[65536];

void prepareMappingTable() {
    for (uint16_t i=0; i<=255; i++) {
        // dublicate the bits:
        uint16_t position = 0;
        uint16_t targetBit = 1;
        for(uint16_t sourceBit = 1; sourceBit<=128; sourceBit <<= 1) {
            if(i&sourceBit) {
                position |= targetBit;
                position |= (targetBit << 1);
            }
            targetBit <<= 2;
        }
        map2uint8[position] = i;
    }
}

int main(){

    prepareMappingTable();

    uint16_t input = 0b1100001111001100;
    uint8_t output =  map2uint8[input];

    cout <<  bitset<8>(output) <<  endl;
    return 0;
}
</code>```

Body:
Based on the idea of @user4581301, you could use a mapping table that maps each possible 16 bit input into the corresponding 8 bit "shrinked" target. Note, however, that this (sparse) mapping table needs 65536 entries, since this is the  range of your 16 bit input. Of course, this approach only makes sense if you have to transform lots of 16 bit input values (such that the time for preparing the mapping table does not count):

uint8_t map2uint8[65536];

void prepareMappingTable() {
    for (uint16_t i=0; i<=255; i++) {
        // dublicate the bits:
        uint16_t position = 0;
        uint16_t targetBit = 1;
        for(uint16_t sourceBit = 1; sourceBit<=128; sourceBit <<= 1) {
            if(i&sourceBit) {
                position |= targetBit;
                position |= (targetBit << 1);
            }
            targetBit <<= 2;
        }
        map2uint8[position] = i;
    }
}

int main(){

    prepareMappingTable();

    uint16_t input = 0b1100001111001100;
    uint8_t output =  map2uint8[input];

    cout <<  bitset<8>(output) <<  endl;
    return 0;
}


问:
Conversion of UTC time to LOCAL in SQL Query output
I'm struggling with a SQL query - a basic select statement with a UTC time conversion in the select output. I've done a bunch of searching on this and through all of that have arrived at the following query, but it does not seem to work for me.

```<code>SELECT [Id]
      ,[BaseSource]
      ,[Source]
      ,[Output]
      ,[SessionId]
      ,[Timestamp]
      ,(SELECT DATEADD(MILLISECOND,DATEDIFF(MILLISECOND,getutcdate(),GETDATE()),[Timestamp])) as LocalTime
  FROM [MYDB].[dbo].[SystemOutput]
  ORDER BY [Timestamp] DESC
</code>```

This line is where the magic should be happening, but instead i get a exact match of the Timestamp column value, so no conversion happening at all:

(SELECT
  DATEADD(MILLISECOND,DATEDIFF(MILLISECOND,getutcdate(),GETDATE()),[Timestamp]))

Does anyone know of how to get this working?

Thanks

答:
First, understand that getdate() returns the local date and time of the server - not of the person running the query.  If the server's time zone is set to UTC, then it will indeed return the UTC time.

Since you are running on SQL 2016, and you are asking for the UTC time converted to Pacific time, I suggest you use the built-in AT TIME ZONE statement, as follows:

```<code>SELECT [Id]
      ,[BaseSource]
      ,[Source]
      ,[Output]
      ,[SessionId]
      ,[Timestamp]
      ,[Timestamp] AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS LocalTime
FROM [MYDB].[dbo].[SystemOutput]
ORDER BY [Timestamp] DESC
</code>```

Note, the above assumes that the [Timestamp] field is a datetime or datetime2, and that it is a UTC-based value.  The first AT TIME ZONE makes an assertion that the given value is in UTC, resulting in a datetimeoffset.  The second AT TIME ZONE then converts from UTC to Pacific time.

If instead the field is already a datetimeoffset type, then the query is even simpler:

```<code>SELECT [Id]
      ,[BaseSource]
      ,[Source]
      ,[Output]
      ,[SessionId]
      ,[Timestamp]
      ,[Timestamp] AT TIME ZONE 'Pacific Standard Time' AS LocalTime
FROM [MYDB].[dbo].[SystemOutput]
ORDER BY [Timestamp] DESC
</code>```

Also, don't be confused by the word "Standard" in the time zone identifier.  That value covers both standard time and daylight time, as applicable in the Pacific time zone in the US and Canada.

Body:
I'm struggling with a SQL query - a basic select statement with a UTC time conversion in the select output. I've done a bunch of searching on this and through all of that have arrived at the following query, but it does not seem to work for me.

SELECT [Id]
      ,[BaseSource]
      ,[Source]
      ,[Output]
      ,[SessionId]
      ,[Timestamp]
      ,(SELECT DATEADD(MILLISECOND,DATEDIFF(MILLISECOND,getutcdate(),GETDATE()),[Timestamp])) as LocalTime
  FROM [MYDB].[dbo].[SystemOutput]
  ORDER BY [Timestamp] DESC

This line is where the magic should be happening, but instead i get a exact match of the Timestamp column value, so no conversion happening at all:

(SELECT
  DATEADD(MILLISECOND,DATEDIFF(MILLISECOND,getutcdate(),GETDATE()),[Timestamp]))

Does anyone know of how to get this working?

Thanks

Body:
First, understand that getdate() returns the local date and time of the server - not of the person running the query.  If the server's time zone is set to UTC, then it will indeed return the UTC time.

Since you are running on SQL 2016, and you are asking for the UTC time converted to Pacific time, I suggest you use the built-in AT TIME ZONE statement, as follows:

SELECT [Id]
      ,[BaseSource]
      ,[Source]
      ,[Output]
      ,[SessionId]
      ,[Timestamp]
      ,[Timestamp] AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS LocalTime
FROM [MYDB].[dbo].[SystemOutput]
ORDER BY [Timestamp] DESC

Note, the above assumes that the [Timestamp] field is a datetime or datetime2, and that it is a UTC-based value.  The first AT TIME ZONE makes an assertion that the given value is in UTC, resulting in a datetimeoffset.  The second AT TIME ZONE then converts from UTC to Pacific time.

If instead the field is already a datetimeoffset type, then the query is even simpler:

SELECT [Id]
      ,[BaseSource]
      ,[Source]
      ,[Output]
      ,[SessionId]
      ,[Timestamp]
      ,[Timestamp] AT TIME ZONE 'Pacific Standard Time' AS LocalTime
FROM [MYDB].[dbo].[SystemOutput]
ORDER BY [Timestamp] DESC

Also, don't be confused by the word "Standard" in the time zone identifier.  That value covers both standard time and daylight time, as applicable in the Pacific time zone in the US and Canada.


问:
Ignite cluster with mixed persistent/non-persistent cache nodes
In my Apache Ignite 2.3 cluster I want to run one node (probably two in the future for a backup) that has my replicated cache persistent on disk. I need to make sure this node is always up while other cache nodes don't have the persistent configuration and therefore access the cache only in memory. These non-persistent nodes can come and go frequently on demand as they are for computing but not for storing data.

When a non-persistent node is connected, what happens when the persistent node goes down? Ideally the cache should go away for the whole cluster but it doesn't. All nodes continue using the cache in memory it seems. But this means the new data will never be on disk and gone after cluster restart.
Is my configuration with mixed persistent/non-persistent nodes not common? How would I keep this type of cluster consistant?

Any background help appreciated.

答:
This is not possible; persistence is enabled on cache level and therefore all nodes where this cache is deployed will persist data to disk.

Moreover, I don't think you would benefit from such deployment. If it's a replicated cache and you start a new node, you need to copy the data to this new node before it's available in memory. Before rebalancing is not finished, you will do remote calls for this data. Loading it from disk instead will not be slower, likely much faster.


问:
How do I get inputs from a user and find the highest, lowest, and average of them?
I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.

Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.

Ex:
Inputs: 10000  30000  50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000

**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****

```<code>import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {

public static void main(String[] args) throws FileNotFoundException {

Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();

Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();

//Declarations
int total = 0;
int average = 0;

//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
    System.out.println("Enter the income of job #" + i + " : ");
    arrayOfIncomes[i] = scan.nextInt();
    total = total + arrayOfIncomes[i];
}

average = total/jobNum;

//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] > max) {
        max = arrayOfIncomes[i];
    }
}

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] < min) {
        min = arrayOfIncomes[i];
    }
}

//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
    System.out.println("");
} else {
    System.out.println("Goodbye.");
}

//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);

//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

out.close();
}
</code>```

答:
Fix the code by instantiating an array, jobIncomes with the length equivalent to the number of jobs. You could keep a running average, but you would lose precision when rounding.  You will also need to instantiate three integer variables: total, max and min, each at zero.

For every iteration of the loop, you should add the following code:

```<code>jobIncomes[i-1]=s.nextInt();
if (jobIncomes[i-1]<min)
{ min=jobIncomes[i-1];}
if (jobIncomes[i-1]>max
{max=jobIncomes[i-1];}
total+=jobIncomes[i-1];
</code>```

When you print the average, you can cast the formula average = total/jobNum.  You might also want to change the array values to read from 0 to jobNum-1, if you want to index simply by i in the if statements.

Body:
I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.

Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.

Ex:
Inputs: 10000  30000  50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000

**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {

public static void main(String[] args) throws FileNotFoundException {

Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();

Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();

//Declarations
int total = 0;
int average = 0;

//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
    System.out.println("Enter the income of job #" + i + " : ");
    arrayOfIncomes[i] = scan.nextInt();
    total = total + arrayOfIncomes[i];
}

average = total/jobNum;

//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] > max) {
        max = arrayOfIncomes[i];
    }
}

for (int i = 1; i < arrayOfIncomes.length; i++) {
    if (arrayOfIncomes[i] < min) {
        min = arrayOfIncomes[i];
    }
}

//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
    System.out.println("");
} else {
    System.out.println("Goodbye.");
}

//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);

//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");

out.close();
}

Body:
Fix the code by instantiating an array, jobIncomes with the length equivalent to the number of jobs. You could keep a running average, but you would lose precision when rounding.  You will also need to instantiate three integer variables: total, max and min, each at zero.

For every iteration of the loop, you should add the following code:

jobIncomes[i-1]=s.nextInt();
if (jobIncomes[i-1]<min)
{ min=jobIncomes[i-1];}
if (jobIncomes[i-1]>max
{max=jobIncomes[i-1];}
total+=jobIncomes[i-1];

When you print the average, you can cast the formula average = total/jobNum.  You might also want to change the array values to read from 0 to jobNum-1, if you want to index simply by i in the if statements.


问:
Run Automated Tests After Team Build On Physical Environment
We are trying to automate our tests but we have some problems.

Our solution has 7 projects, one of them is WCF server and one of them is Windows Forms project. Others are helper projects.

We created a test plan and test cases. We runned our test cases with action recording and converted manual tests to Coded UI test. After that, we assoiciate our coded ui test with test case.

We defined a new build. This new build deploys WCF server to IIS and transform app.config and copy client application files to a folder.

We setted up test controller and test agent at same build machine.

I wonder what need we to do to automate our build and test?
How our build trig automated test?

Because of VMWare infrastructure we can't use Lab Management.

答:
I solved this problem myself.

I used msdeploy to deploy WCF service

I created a database project and used VSDBCMD tool

I installed test controller and test agent my build server

I created test settings for automated tests and configured to use this agent

I attached my coded ui test with test case

Then it is ok :)


问:
how to visualize prometheus endpoint metrics using grafana
I have a simple Spring-Boot application (with Maven), which I've instrumented using Prometheus to collect application-specific metrics.  The instrumented Prometheus metrics are exposed on http://localhost:8080/prometheus by default, but I'm not sure how to visualize these metrics on Grafana. When I try to set the datasource in Grafana, I get an error:

HTTP Error Not Found

Below is my working code, which exposes metrics on http:localhost:8080/prometheus

Example.java: Simply exposes a few endpoints. Instrumented so that Prometheus counts the number of times the /homepage endpoint is hit.

```<code>@SpringBootApplication
@RestController
public class Example {

    //Just a logger that keeps track of relevant information:
    private static final Logger LOGGER = Logger.getLogger(Example.class.getName());

    //counter for counting how many times an endpoint has been hit
    static final Counter myCounter = Counter.build()
                                              .name("CounterName") //note: by convention, counters should have "_total" suffix
                                              .help("Total requests recorded by a specific endpoint")
                                              .labelNames("status")
                                              .register();

    //using a guage to set the time that a dummy process started, store the time it ends, and then calculate
    //the elapsed time between when the process started and when the process ended.
    static final Gauge myGauge =  Gauge.build()
                                .name("GaugeName")
                                .help("This is the Gauge help message")
                                .labelNames("label1")
                                .register();

    @RequestMapping("/hello")
    String hello() {

        myCounter.labels("customLabel1").inc(); //increment the number of requests by one
        myGauge.labels("customLabel1").inc(3);
        LOGGER.log(Level.INFO, "Number of times /hello has been hit: " + myCounter.labels("customLabel1").get());
        LOGGER.log(Level.INFO, "Size of our Gauge: " + myGauge.labels("customLabel1").get());
        myGauge.labels("customLabel1").dec();
        LOGGER.log(Level.INFO, "size of out Gauge after decrementing by 1: " + myGauge.labels("customLabel1").get());

        return "Hello world! This is an example response!";
    }

    @RequestMapping("/homepage")
    String homePage() {

        myCounter.labels("customLabel2").inc(); //increment the number of requests by one
        LOGGER.log(Level.INFO, "Number of times /homepage has been hit: " + myCounter.labels("customLabel2").get());

        return "this is the home page!!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}
</code>```

MonitoringConfig.java: This is how Prometheus collects the application's metric information, and exposes them on localhostL8080/prometheus

```<code>@Configuration
public class MonitoringConfig {
    @Bean
    SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics){
        SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
        springBootMetricsCollector.register();

        return springBootMetricsCollector;
    }

    @Bean
    ServletRegistrationBean servletRegistrationBean() {
        DefaultExports.initialize();
        return new ServletRegistrationBean(new MetricsServlet(), "/prometheus");
    }
}
</code>```

pom.xml: Project's Maven dependencies

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Prometheus dependencies -->
        <!-- The client -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_spring_boot</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_servlet</artifactId>
            <version>0.1.0</version>
        </dependency>
        <!-- Hotspot JVM metrics -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_hotspot</artifactId>
            <version>0.1.0</version>
        </dependency>
        <!-- Exposition HTTPServer -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_httpserver</artifactId>
            <version>0.1.0</version>
        </dependency>
        <!-- Pushgateway exposition -->
        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_pushgateway</artifactId>
            <version>0.1.0</version>
        </dependency>

        <!-- Spring Boot Actuator for exposing metrics -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>1.5.8.RELEASE</version>
        </dependency>

    </dependencies>

</project>
</code>```

答:
You need to point grafana at a prometheus server, not your application.

See the prometheus docs for more details on how to run prometheus and how to visualize prometheus metrics in grafana dashboards.

Body:
I have a simple Spring-Boot application (with Maven), which I've instrumented using Prometheus to collect application-specific metrics.  The instrumented Prometheus metrics are exposed on http://localhost:8080/prometheus by default, but I'm not sure how to visualize these metrics on Grafana. When I try to set the datasource in Grafana, I get an error:

HTTP Error Not Found

Below is my working code, which exposes metrics on http:localhost:8080/prometheus

Example.java: Simply exposes a few endpoints. Instrumented so that Prometheus counts the number of times the /homepage endpoint is hit.

@SpringBootApplication
@RestController
public class Example {

    //Just a logger that keeps track of relevant information:
    private static final Logger LOGGER = Logger.getLogger(Example.class.getName());

    //counter for counting how many times an endpoint has been hit
    static final Counter myCounter = Counter.build()
                                              .name("CounterName") //note: by convention, counters should have "_total" suffix
                                              .help("Total requests recorded by a specific endpoint")
                                              .labelNames("status")
                                              .register();

    //using a guage to set the time that a dummy process started, store the time it ends, and then calculate
    //the elapsed time between when the process started and when the process ended.
    static final Gauge myGauge =  Gauge.build()
                                .name("GaugeName")
                                .help("This is the Gauge help message")
                                .labelNames("label1")
                                .register();

    @RequestMapping("/hello")
    String hello() {

        myCounter.labels("customLabel1").inc(); //increment the number of requests by one
        myGauge.labels("customLabel1").inc(3);
        LOGGER.log(Level.INFO, "Number of times /hello has been hit: " + myCounter.labels("customLabel1").get());
        LOGGER.log(Level.INFO, "Size of our Gauge: " + myGauge.labels("customLabel1").get());
        myGauge.labels("customLabel1").dec();
        LOGGER.log(Level.INFO, "size of out Gauge after decrementing by 1: " + myGauge.labels("customLabel1").get());

        return "Hello world! This is an example response!";
    }

    @RequestMapping("/homepage")
    String homePage() {

        myCounter.labels("customLabel2").inc(); //increment the number of requests by one
        LOGGER.log(Level.INFO, "Number of times /homepage has been hit: " + myCounter.labels("customLabel2").get());

        return "this is the home page!!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

MonitoringConfig.java: This is how Prometheus collects the application's metric information, and exposes them on localhostL8080/prometheus

@Configuration
public class MonitoringConfig {
    @Bean
    SpringBootMetricsCollector springBootMetricsCollector(Collection<PublicMetrics> publicMetrics){
        SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
        springBootMetricsCollector.register();

        return springBootMetricsCollector;
    }

    @Bean
    ServletRegistrationBean servletRegistrationBean() {
        DefaultExports.initialize();
        return new ServletRegistrationBean(new MetricsServlet(), "/prometheus");
    }
}

pom.xml: Project's Maven dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_spring_boot</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_servlet</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_hotspot</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_httpserver</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.prometheus</groupId>
            <artifactId>simpleclient_pushgateway</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>1.5.8.RELEASE</version>
        </dependency>

    </dependencies>

</project>


问:
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers.  The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to just write appropriate simple algorithms myself each time rather than memorize or consult a reference to these headers each time. Am just being lazy or stubborn?  Is there actually performance gains etc when using these libraries?

Thanks,

R

答:
It's possible you're being lazy or stubborn.  Personally, I use them all the time in production code.

I don't do this to be fancy, and I don't do this because I like writing "space-age code."  Rather, I do this because I am a paranoid programmer, and I know that production environments are hostile places that will mutilate code and reduce my programs to smoking piles of worthless bytes, if given a chance.

I do this because I live by the motto, "The best code, is the code you never write."  It takes time to learn how to use the STL & Std Lib effectively, but once you do you'll find that it can be used so that what now is 1000 lines of code becomes perhaps 100.  Those 100 might take as long to write as the original 1000, but there are fewer failure points.  The code can be more robust, if you stand on the shoulders of others.


问:
How to arrange this data based on top ten hits?
How do I arrange this based on the top ten hits of this week?</p>

```<code>Billboard Hot 100 - Top 50 - Week of Dec 2, 2017
This Week   Last Week   Peak Position   Weeks on List   Title   Artist(s)
1   1   1   9   Rockstar    Post Malone Featuring 21 Savage
2   2   2   14  Havana  Camila Cabello Featuring Young Thug
3   12  3   10  Gucci Gang  Lil Pump
4   5   4   29  Thunder Imagine Dragons
5   3   1   20  Bodak Yellow (Money Moves)  Cardi B
6   4   4   10  Too Good At Goodbyes    Sam Smith
7   8   7   12  Perfect Ed Sheeran
8   6   3   29  1-800-273-8255  Logic Featuring Alessia Cara & Khalid
9   7   4   22  Feel It Still   Portugal, The Man
10  10  3   20  Mi Gente    J Balvin & Willy Wiliam Featuring Beyonce
11  9   9   12  What Lovers Do  Maroon 5 Featuring Featuring SZA
12  11  6   19  Sorry Not Sorry Demi Lovato
13  13  13  10  No Limit    G-Eazy Featuring A$AP Rocky & Cardi B
14  0   14  1   Walk On Water   Eninem Featuring Beyonce
15  23  14  3   Motorsport  Migos, Nicki Minaj & Cardi B
16  14  11  13  I Get The Bag   Gucci Mane Geaturing Migos
17  20  17  11  Bad At Love Halsey
18  30  4   11  ...Ready For It?    Taylor Swift
19  21  19  16  New Rules   Dua Lipa
20  17  13  15  What About Us   Pink
21  16  3   32  Unforgettable   French Montana Featuring Swae Lee
22  18  1   44  Despacito   Luis Fonsi & Daddy Yankee Featuring Justin Bieber
23  22  8   20  Rake It Up  Yo Gotti Featuring Nicki Minaj
24  19  5   30  Attention   Charlie Puth
25  29  25  8   I Fall Apart    Post Malone
26  24  4   41  Believer    Imagine Dragons
27  15  12  19  Bank Account    21 Savage
28  28  22  19  Praying Kesha
29  25  25  18  Young Dumb & Broke  Khalid
30  36  1   45  Shape of You    Ed Sheeran
31  37  1   13  Look What You Made Me Do    Taylor Swift
32  32  10  26  Strip That Down Liam Payne Featuring Quavo
33  33  6   30  There's Nothing Holdin' Me Back Shawn Mendes
34  36  1   44  That's What I Like  Bruno Mars
35  34  11  29  Slow Hands  Niall Horan
36  40  8   47  Congratulations Post Malone Featuring Quavo
37  31  31  12  The Way Life Goes   Lil Uzi Vert Featuring Nicki Minaj
38  43  38  16  The Weekend SZA
39  38  33  16  When It Rains It Pours  Luke Combs
40  44  40  6   How Long    Charlie Puth
41  0   18  21  Love    Kendrick Lamar Featuring Zacari
42  41  40  23  Do Re Mi    Blackbear
43  39  26  23  What Ifs    Kane Brown Featuring Lauren Alaina
44  54  42  14  Silence Marshmello Featuring Alaina
45  52  45  11  Greatest Love Story LANCO
46  47  46  10  Phil and Automobiles    Chris Brown Featuing Yo Gotti, A Boogie Wit da Hoodie & Kodak Black
47  46  1   33  Humble  Kendrick Lamar
48  45  7   34  XO TOUR Llif3   Lil Lizi Vert
49  42  3   39  Something Just Like This    The Chainsmokers & Coldplay
50  51  45  21  Crew    Goldlink Featuring Brent Faiyaz & Shy Glizzy
</code>```

答:
EDIT : The data wasn't parsed like this. But my answer would still work if the data would be a single-string, which would be simple to achieve I believe.

Please, post the code you have tried so far if you want help with your code.

You need to identify patterns in the text you want to parse.
For instance, here, you can notice the first line of your text is not what you seek ; but all the others are interesting to you.

You could even see that every top is "announced" by a succession of 4 digit numbers going from a length of 1 to 2. Maybe split on this ? Regular expressions might help.

This is pretty much everything you need to know.

EDIT_2 : My answer is also valid is she converts the data into a 2-dimension array of length 2 ([[], []] by accessing the correct indexes.

Body:
How do I arrange this based on the top ten hits of this week?

Billboard Hot 100 - Top 50 - Week of Dec 2, 2017
This Week   Last Week   Peak Position   Weeks on List   Title   Artist(s)
1   1   1   9   Rockstar    Post Malone Featuring 21 Savage
2   2   2   14  Havana  Camila Cabello Featuring Young Thug
3   12  3   10  Gucci Gang  Lil Pump
4   5   4   29  Thunder Imagine Dragons
5   3   1   20  Bodak Yellow (Money Moves)  Cardi B
6   4   4   10  Too Good At Goodbyes    Sam Smith
7   8   7   12  Perfect Ed Sheeran
8   6   3   29  1-800-273-8255  Logic Featuring Alessia Cara & Khalid
9   7   4   22  Feel It Still   Portugal, The Man
10  10  3   20  Mi Gente    J Balvin & Willy Wiliam Featuring Beyonce
11  9   9   12  What Lovers Do  Maroon 5 Featuring Featuring SZA
12  11  6   19  Sorry Not Sorry Demi Lovato
13  13  13  10  No Limit    G-Eazy Featuring A$AP Rocky & Cardi B
14  0   14  1   Walk On Water   Eninem Featuring Beyonce
15  23  14  3   Motorsport  Migos, Nicki Minaj & Cardi B
16  14  11  13  I Get The Bag   Gucci Mane Geaturing Migos
17  20  17  11  Bad At Love Halsey
18  30  4   11  ...Ready For It?    Taylor Swift
19  21  19  16  New Rules   Dua Lipa
20  17  13  15  What About Us   Pink
21  16  3   32  Unforgettable   French Montana Featuring Swae Lee
22  18  1   44  Despacito   Luis Fonsi & Daddy Yankee Featuring Justin Bieber
23  22  8   20  Rake It Up  Yo Gotti Featuring Nicki Minaj
24  19  5   30  Attention   Charlie Puth
25  29  25  8   I Fall Apart    Post Malone
26  24  4   41  Believer    Imagine Dragons
27  15  12  19  Bank Account    21 Savage
28  28  22  19  Praying Kesha
29  25  25  18  Young Dumb & Broke  Khalid
30  36  1   45  Shape of You    Ed Sheeran
31  37  1   13  Look What You Made Me Do    Taylor Swift
32  32  10  26  Strip That Down Liam Payne Featuring Quavo
33  33  6   30  There's Nothing Holdin' Me Back Shawn Mendes
34  36  1   44  That's What I Like  Bruno Mars
35  34  11  29  Slow Hands  Niall Horan
36  40  8   47  Congratulations Post Malone Featuring Quavo
37  31  31  12  The Way Life Goes   Lil Uzi Vert Featuring Nicki Minaj
38  43  38  16  The Weekend SZA
39  38  33  16  When It Rains It Pours  Luke Combs
40  44  40  6   How Long    Charlie Puth
41  0   18  21  Love    Kendrick Lamar Featuring Zacari
42  41  40  23  Do Re Mi    Blackbear
43  39  26  23  What Ifs    Kane Brown Featuring Lauren Alaina
44  54  42  14  Silence Marshmello Featuring Alaina
45  52  45  11  Greatest Love Story LANCO
46  47  46  10  Phil and Automobiles    Chris Brown Featuing Yo Gotti, A Boogie Wit da Hoodie & Kodak Black
47  46  1   33  Humble  Kendrick Lamar
48  45  7   34  XO TOUR Llif3   Lil Lizi Vert
49  42  3   39  Something Just Like This    The Chainsmokers & Coldplay
50  51  45  21  Crew    Goldlink Featuring Brent Faiyaz & Shy Glizzy


问:
Does Umbraco 7.7 support concurrent users?
Say, we have multiple users editing same document in parallel.
Is there a way to prevent this from happening? </p>

<p>For example, disabling the document from being editing if there's already another editor changes content. </p>

答:
There used to be a few packages that helped deal with this issue.  So far none of them have been ported and released as supporting v7.

The only one I could find that may be close is this one:

Look who's editing now

It's a work in progress version, but perhaps its close enough you could use it or even help get it working.

Body:
Say, we have multiple users editing same document in parallel.
Is there a way to prevent this from happening?

For example, disabling the document from being editing if there's already another editor changes content.


问:
Sparklyr read database table to distributed DF
Hi I am trying to figure out if there is a way to directly read a DB table to a sparkR dataframe. I have rstudio installed on an EMR cluster which has my hive metastore on it.

I know I can do the following:

```<code>library(sparklyr)
library(dplyr)
sc <- spark_connect(master = "local")
library(DBI)
query <- "select * from schema.table"
result <- dbGetQuery(sc, query)
result_t <- copy_to(sc,result)
</code>```

but is there a way to query directly into result_t?

答:
Like @kevinykuo suggested, </p>

```<code>result_t <- tbl(sc, "schema.table")
</code>```

Body:
Hi I am trying to figure out if there is a way to directly read a DB table to a sparkR dataframe. I have rstudio installed on an EMR cluster which has my hive metastore on it.

I know I can do the following:

library(sparklyr)
library(dplyr)
sc <- spark_connect(master = "local")
library(DBI)
query <- "select * from schema.table"
result <- dbGetQuery(sc, query)
result_t <- copy_to(sc,result)

but is there a way to query directly into result_t?

Body:
Like @kevinykuo suggested,

result_t <- tbl(sc, "schema.table")


问:
Android - OKHttp: how to enable gzip for POST
In our Android App, I'm sending pretty large files to our (NGINX) server so I was hoping to use gzip for my Retrofit POST message.

There are many documentations about OkHttp using gzip transparently or changing the headers in order to accept gzip (i.e. in a GET message).

But how can I enable this feature for sending gzip http POST messages from my device?
Do I have to write a custom Intercepter or something? Or simply add something to the headers?

答:
According to the following recipe:
The correct flow for gzip would be something like this:</p>

```<code>OkHttpClient client = new OkHttpClient.Builder()
      .addInterceptor(new GzipRequestInterceptor())
      .build();

/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
  static class GzipRequestInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
      Request originalRequest = chain.request();
      if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
        return chain.proceed(originalRequest);
      }

      Request compressedRequest = originalRequest.newBuilder()
          .header("Content-Encoding", "gzip")
          .method(originalRequest.method(), gzip(originalRequest.body()))
          .build();
      return chain.proceed(compressedRequest);
    }

    private RequestBody gzip(final RequestBody body) {
      return new RequestBody() {
        @Override public MediaType contentType() {
          return body.contentType();
        }

        @Override public long contentLength() {
          return -1; // We don't know the compressed length in advance!
        }

        @Override public void writeTo(BufferedSink sink) throws IOException {
          BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
          body.writeTo(gzipSink);
          gzipSink.close();
        }
      };
    }
  }
</code>```

Body:
According to the following recipe:
The correct flow for gzip would be something like this:

OkHttpClient client = new OkHttpClient.Builder()
      .addInterceptor(new GzipRequestInterceptor())
      .build();

/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
  static class GzipRequestInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
      Request originalRequest = chain.request();
      if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
        return chain.proceed(originalRequest);
      }

      Request compressedRequest = originalRequest.newBuilder()
          .header("Content-Encoding", "gzip")
          .method(originalRequest.method(), gzip(originalRequest.body()))
          .build();
      return chain.proceed(compressedRequest);
    }

    private RequestBody gzip(final RequestBody body) {
      return new RequestBody() {
        @Override public MediaType contentType() {
          return body.contentType();
        }

        @Override public long contentLength() {
          return -1; // We don't know the compressed length in advance!
        }

        @Override public void writeTo(BufferedSink sink) throws IOException {
          BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
          body.writeTo(gzipSink);
          gzipSink.close();
        }
      };
    }
  }


问:
Inter-service communication with Spring Boot and OAuth2
I am working on a micro-service architecture using Spring Boot. We have implemented OAuth2 in a Auth Server.

My question is - If two microservices want to communicate what should be the best way?

As of now, I have discovered below options:

If each microservice is verifying the token then we can pass the same token. But the problem is - in between same token can be expired.

If we use client_credentials grant then there we are having two issues: one is, we need to send the username in next microservice. Another one is, we need to request two times - first for getting the access token, next for actual call.

If we do the token verification in API gateway only (not in microservices) then from the API gateway we need to send the username in every microservices. And microservices implementation needs to be changed to accept that param/header.

Please suggest which option should I pick and if there is any better option please let me know.

Thanks in advance.

答:
Not an expert either, but

If we do the token verification in API gateway only (not in microservices) then from the API gateway we need to send the username in every microservices. And microservices implementation needs to be changed to accept that param/header.

could be changed this way:

You make authentication/authorisation the problem of the gateway.

When gateway authorizes the client, it attaches JWT token to every microservice request its going to make on behalf of the client (instead of sending username). JWT will contain all information that microservices might need. If the microservice will need to call other microservice, it will need to pass that token further with the request.

So the idea is - for EVERY request that comes through the gateway, a NEW JWT is being attached to the request. Then you don't have expiry problem and tokens are easy to verify.


问:
Angular - issue with ng-Click and submit
Needed some help with AngularJS as I'm new to it.

I have a form which has a button to display a dialog box, and then once that dialog box pops up, user must submit the form from the button on the Dialog box.

But currently if the user hits enter in a textBox before the dialog box has been opened, the form gets submitted without the dialog generating.

The button on the main form looks like this :

```<code><button type="button" class="xyz xyz-one" ng-Click="popDialog()">
</code>```

And the button on the dialog which finally submits the form looks like this :

```<code><button type="submit" class="xyz xyz-one">
</code>```

Is there any way that on the UI when the user hits enter, the form is blocked from automatic submission and only the dialog pops up?

答:
On each of the textfields in your form, add this directive:

ng-keydown="preventFormSubmission($event)"

Then in your controller do the following:

```<code>$scope.preventFormSubmission = (event) => {
    // Keycode 13 is the enter button
    if (event.keyCode === 13) {
        event.preventDefault()
    }
}
</code>```

$event is the object which holds all the data about the event that just happened (the key being pressed).
Calling event.preventDefault() will stop the form from automatically being submitted.

Body:
Needed some help with AngularJS as I'm new to it.

I have a form which has a button to display a dialog box, and then once that dialog box pops up, user must submit the form from the button on the Dialog box.

But currently if the user hits enter in a textBox before the dialog box has been opened, the form gets submitted without the dialog generating.

The button on the main form looks like this :

<button type="button" class="xyz xyz-one" ng-Click="popDialog()">

And the button on the dialog which finally submits the form looks like this :

<button type="submit" class="xyz xyz-one">

Is there any way that on the UI when the user hits enter, the form is blocked from automatic submission and only the dialog pops up?

Body:
On each of the textfields in your form, add this directive:

ng-keydown="preventFormSubmission($event)"

Then in your controller do the following:

$scope.preventFormSubmission = (event) => {
    // Keycode 13 is the enter button
    if (event.keyCode === 13) {
        event.preventDefault()
    }
}

$event is the object which holds all the data about the event that just happened (the key being pressed).
Calling event.preventDefault() will stop the form from automatically being submitted.


问:
Edit JavaScript blocks of web page... live
I know you can use Firebug in the DOM view to edit JavaScript variables BUT... is there a way I can use (anything else) to edit live JavaScript that is embedded in a HTML page?

Like this kind that is in a .html page:

```<code><script type="text/javascript>
// code here
</script>
</code>```

Thanks.

答:
bookmarklets

From the Wikipedia entry

A bookmarklet is an applet, a small computer application, stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. The term is a portmanteau of the terms bookmark and applet. Whether bookmarklet utilities are stored as bookmarks or hyperlinks, they are designed to add one-click functionality to a browser or web page. When clicked, a bookmarklet performs some function, one of a wide variety such as a search query or data extraction. Usually the applet is a JavaScript program.

And as a related note not trying to spam or anything I created a bookmarklet generator to help me create bookmarklets easier.

Body:
I know you can use Firebug in the DOM view to edit JavaScript variables BUT... is there a way I can use (anything else) to edit live JavaScript that is embedded in a HTML page?

Like this kind that is in a .html page:

Thanks.


问:
Define: "Operation"?
I came across this statement, not sure if he used the word correctly but I've seen it before and don't fully understand it.

The key difference between statically-typed and dynamically-typed languages is whether operations get checked at compile time or at run time.

What exactly does "operation" mean in regards to CS?

I'm familiar with operators and know that 2 + 2 is an "operation" mathematically because it uses an operator to calculate a value.

But how exactly does an "operation" relate to values, expressions, and statements?

Is any statement an operation? print 'hello world'

Is any value/expression on operation? 'hello world'

答:
Generally, any expression that evaluates a variable's value could be said to be an "operation" against that variable.  So basically, any use of the variable.

If you think about what dynamic languages do, it makes sense - they need to introspect the variable and determine its type at run time, when "operating" on the variable.  Statically typed languages don't need to introspect - at compile time, they "know" the type.

I suppose an identity expression (x or "hello world") also qualifies as an evaluation of the variable, though one without an apparent purpose.  It may well be optimized out at runtime in a non-interactive environment

Title: Define: "Operation"?


问:
Running process of remote SSH server in the background using Python Paramiko
I am finding hard to run a process on a remote SSH server at background using Paramiko. I used :

```<code>stdin, stdout, stderr = ssh.exec_command('executefile.py &')
</code>```

and found that no process of executefile.py was found running.

Then I tried using other way as including a backward slash:

```<code>stdin, stdout, stderr = ssh.exec_command('executefile.py \&')
</code>```

This method worked. There was an instance running on machine but no surprise, it was not running at background. I could come to know as it is not running at background as when code stuck at second line after this code. It was

```<code>all_inf = stdout.readlines()
</code>```

Now code was not going beyond above line unless the process of the script was killed.

I am learning Paramiko, any help is appreciated.

答:
You could try using screen

```<code>screen -d -m ping 8.8.8.8
</code>```

This is would start a screen and ping 8.8.8.8. You can view this screen by using

```<code>screen -ls
</code>```

and attach using

```<code>screen -D <<screen_name>>
</code>```

Note that the screen will terminate after the command has finished executing.

Body:
I am finding hard to run a process on a remote SSH server at background using Paramiko. I used :

stdin, stdout, stderr = ssh.exec_command('executefile.py &')

and found that no process of executefile.py was found running.

Then I tried using other way as including a backward slash:

stdin, stdout, stderr = ssh.exec_command('executefile.py \&')

This method worked. There was an instance running on machine but no surprise, it was not running at background. I could come to know as it is not running at background as when code stuck at second line after this code. It was

all_inf = stdout.readlines()

Now code was not going beyond above line unless the process of the script was killed.

I am learning Paramiko, any help is appreciated.

Body:
You could try using screen

screen -d -m ping 8.8.8.8

This is would start a screen and ping 8.8.8.8. You can view this screen by using

screen -ls

and attach using

screen -D <<screen_name>>

Note that the screen will terminate after the command has finished executing.


问:
Application.Quit command not closing the entire Excel Application
I have following code under a button. When clicked it just closes the current Excel sheet but not the entire Excel application.

```<code>Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
</code>```

Note: I don't have any other sheets open.

The following window still appears.

答:
The window does not close because you are using personal.xlsb. Cut Personal.xlsb and paste in another location.

Instead of Personal.xlsb create and work on modules. It's a better option.

Body:
I have following code under a button. When clicked it just closes the current Excel sheet but not the entire Excel application.

Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit

Note: I don't have any other sheets open.

The following window still appears.