问:
Update value of a variable without printing its value in mysql
I have a table Employees which have two columns Year and UserCount.
Table looks something like this

```<code>Year  UserCount

2001 400

2002 1000

2003 2000
</code>```

Now I want to print the year and the difference between the subsequent UserCount of two years.

I want to output something like this.

```<code>Year UserCount

2001 400

2002 600

2003 1000
</code>```

I thought of taking a variable and initializing it with 0 and updating its value after every iteration. This is the query that I came up with

```<code>SET @prev = 0;
select year, (UserCount - @prev) as diff, @prev := (UserCount) from Employees;
</code>```

Though I'm getting the difference but it adds a new column too, @prev := (Count) Is there any way by which I could update the value of prev without printing its value?

Is there any other approach which is better than this?

答:
You can conceal the column you need to handle this difference hack by using an outer query. This will remove the := update column from the returned result set. (http://sqlfiddle.com/#!9/918a75/1/0)

```<code>select year, diff
  from (
        select year, (UserCount - @prev) as diff, @prev := (UserCount)
          from Employees
          join (select @prev:= 0) init
         order by year
       ) subquery
</code>```

Notice a couple of things.

The initialization is moved to a join clause.

It's always smart to ORDER your tables. If you don't the result set ordering is unpredictable, which is bad.

Body:
I have a table Employees which have two columns Year and UserCount.
Table looks something like this

Year  UserCount

2001 400

2002 1000

2003 2000

Now I want to print the year and the difference between the subsequent UserCount of two years.

I want to output something like this.

Year UserCount

2001 400

2002 600

2003 1000

I thought of taking a variable and initializing it with 0 and updating its value after every iteration. This is the query that I came up with

SET @prev = 0;
select year, (UserCount - @prev) as diff, @prev := (UserCount) from Employees;

Though I'm getting the difference but it adds a new column too, @prev := (Count) Is there any way by which I could update the value of prev without printing its value?

Is there any other approach which is better than this?

Body:
You can conceal the column you need to handle this difference hack by using an outer query. This will remove the := update column from the returned result set. (http://sqlfiddle.com/#!9/918a75/1/0)

select year, diff
  from (
        select year, (UserCount - @prev) as diff, @prev := (UserCount)
          from Employees
          join (select @prev:= 0) init
         order by year
       ) subquery

Notice a couple of things.

The initialization is moved to a join clause.

It's always smart to ORDER your tables. If you don't the result set ordering is unpredictable, which is bad.


来源: stackexchange

问:
Does vertica flex tables has projections?
I'm using vertica flex tables i want to know how to apply projections on flex table

Thanks in advance

答:
A freshly created flex table looks like this when you export its definition:

```<code>    CREATE FLEX TABLE public.teas
    (

    );

    CREATE PROJECTION public.teas_super /*+basename(teas),createtype(P)*/
    (
     __identity__,
     __raw__
    )
    AS
     SELECT teas.__identity__,
            teas.__raw__
     FROM public.teas
     ORDER BY teas.__identity__
    SEGMENTED BY hash(teas.__identity__) ALL NODES OFFSET 0;
</code>```

No columns but the two hidden ones __identity__, which is an int, and __raw__, which is a long varbinary (130000).

Not much point in creating different projections, here.

You can load into the flex table, and then materialise a few columns that you find especially interesting in a flex table.

Then, they will appear in the output of an export_objects(), and you will be able to create projections for these.

Hope this helps ..
Marco

ContentLicense: CC BY-SA 3.0

Body:
A freshly created flex table looks like this when you export its definition:

    CREATE FLEX TABLE public.teas
    (

    );

    CREATE PROJECTION public.teas_super /*+basename(teas),createtype(P)*/
    (
     __identity__,
     __raw__
    )
    AS
     SELECT teas.__identity__,
            teas.__raw__
     FROM public.teas
     ORDER BY teas.__identity__
    SEGMENTED BY hash(teas.__identity__) ALL NODES OFFSET 0;

No columns but the two hidden ones __identity__, which is an int, and __raw__, which is a long varbinary (130000).

Not much point in creating different projections, here.

You can load into the flex table, and then materialise a few columns that you find especially interesting in a flex table.

Then, they will appear in the output of an export_objects(), and you will be able to create projections for these.

Hope this helps ..
Marco


问:
Is there a way to switch a register from positive to negative of the same number without getting a latch trimmed warning?
I'm writing a module for a game of Pong that has two registers called change_x and change_y, which switch between positive and negative one (it says TWO in the code but I changed it to 1 while debugging). These registers are 10 bits so they switch between 10'b0000_0000_01 and 10'b1111_1111_11. When I synthesize I get the warning:

```<code>Xst:1710 - FF/Latch <change_x_0> (without init value) has a constant value of 1 in block <pixel_gen>. This FF/Latch will be trimmed during the optimization process.
Xst:1710 - FF/Latch <change_y_0> (without init value) has a constant value of 1 in block <pixel_gen>. This FF/Latch will be trimmed during the optimization process.
Xst:1710 - FF/Latch <change_x_0> (without init value) has a constant value of 1 in block <PIXEL_GEN>. This FF/Latch will be trimmed during the optimization process.
Xst:1895 - Due to other FF/Latch trimming, FF/Latch <change_y_0> (without init value) has a constant value of 1 in block <PIXEL_GEN>. This FF/Latch will be trimmed during the optimization process.
</code>```

First I just want to make sure that I'm interpreting the warnings right, am I getting them because the least significant bits on these registers never change? Secondly, is there another way to assign them so that I won't get the warnings? I put a block comment above the part where the registers get switched.

```<code>module PIXEL_GEN(
input clock,
input reset,
input [9:0] pixel_x, pixel_y,
input video_on,
input btn_up,
input btn_dn,
output reg [7:0] rgb
);

// ROM signals for round ball.
wire [3:0] rom_col;
wire [3:0] rom_addr;
wire [7:0] ball_rgb, wall_rgb, paddle_rgb, background_rgb;
wire       rom_bit, round_ball_on;
reg  [8:0] rom_data;

// Ball moving parts.
reg [9:0] ball_top;
reg [9:0] ball_btm;
reg [9:0] ball_lef;
reg [9:0] ball_rit;

// Ball change reg.
reg [9:0] change_x;
reg [9:0] change_y;

// Paddle moving parts.
reg [9:0] paddle_top;
reg [9:0] paddle_btm;

// Wall limits.
localparam WALL_LEFT  = 10'd32;
localparam WALL_RIGHT = 10'd35;

// Paddle side limits.
localparam PADDLE_LEFT      = 10'd600;
localparam PADDLE_RIGHT     = 10'd603;
localparam PADDLE_BTM_RESET = 10'd276;
localparam PADDLE_TOP_RESET = 10'd204;

// Paddle length.
localparam PADDLE_LENGTH = PADDLE_BTM_RESET - PADDLE_TOP_RESET;

// Ball reset limits.
localparam BALL_LEFT_RESET  = 10'd580;
localparam BALL_RIGHT_RESET = 10'd588;
localparam BALL_TOP_RESET   = 10'd238;
localparam BALL_BTM_RESET   = 10'd246;

// Screen boundaries.
localparam TOP    = 10'd0;
localparam BOTTOM = 10'd479;
localparam LEFT   = 10'd0;
localparam RIGHT  = 10'd639;

// Two pixel shift each transition.
localparam TWO = 10'd1;
localparam ONE = 10'd1;
localparam ZERO = 10'd0;

// Assigns object colors.
localparam BALL_RGB       = 8'b000_000_11; // Blue
localparam WALL_RGB       = 8'b111_000_00; // Red
localparam PADDLE_RGB     = 8'b000_111_00; // Green
localparam BACKGROUND_RGB = 8'b111_111_11; // White
localparam BLACK          = 8'b000_000_00; // Black

// Refrence tick 60Hz.
assign ref_tick = ( pixel_y == 10'd481 ) & ( pixel_x == 10'd0 );
// Define boundaries for square ball and asserts an "on" signal.
assign square_ball_on = pixel_x >= ball_lef & pixel_x <= ball_rit &
                        pixel_y <= ball_btm & pixel_y >= ball_top;
// Selects ROM row.
assign rom_addr = pixel_y[3:0] - ball_top[3:0];
// Finds ROM column.
assign rom_col  = pixel_x[3:0] - ball_lef[3:0];
// Finds specific bit from ROM row and column.
assign rom_bit  = rom_data[ rom_col ];
// Asserts round_ball_on signal if in the correct
// region and current bit is a one.
assign round_ball_on = square_ball_on & rom_bit;

always@( posedge clock, posedge reset ) begin

   // Restore paddle and ball to reset state.
   if( reset ) begin

      // Reset paddle top / bottom limits.
      paddle_top <= PADDLE_TOP_RESET;
      paddle_btm <= PADDLE_BTM_RESET;

      // Reset ball limits.
      ball_top <= BALL_TOP_RESET;
      ball_btm <= BALL_BTM_RESET;
      ball_lef <= BALL_LEFT_RESET;
      ball_rit <= BALL_RIGHT_RESET;

      // Set change.
      change_x <= -TWO;
      change_y <= -TWO;

   end

   // Move paddle up or down if button is pushed.
   else if( ref_tick ) begin

     // Update paddle top and bottom limits.
     // BtnUp and not hitting top.
     if     ( btn_up & paddle_top >= TWO          ) begin
        paddle_top <= paddle_top - TWO;
        paddle_btm <= paddle_btm - TWO;
     end
     // BtnUp and hitting top.
     else if( btn_up                              ) begin
        paddle_top <= TOP;
        paddle_btm <= TOP + PADDLE_LENGTH;
     end
     // BtnDn and not hitting bottom.
     else if( btn_dn & paddle_btm + TWO <  BOTTOM ) begin
        paddle_top <= paddle_top + TWO;
        paddle_btm <= paddle_btm + TWO;
     end
     // BtnDn and hitting bottom.
     else if( btn_dn & paddle_btm + TWO >= BOTTOM ) begin
        paddle_top <= BOTTOM - PADDLE_LENGTH;
        paddle_btm <= BOTTOM;
     end
     else begin
        paddle_top <= paddle_top;
        paddle_btm <= paddle_btm;
     end

     /************************************************************
     This is where the values switch between positve and negative.
     ************************************************************/

     // Update change in velocity if top is hit.
     if     ( ball_top - TWO <= TOP        )
        change_y <=  TWO;
     // Update change in velocity if bottom is hit.
     else if( ball_btm + TWO >= BOTTOM     )
        change_y <= -TWO;
     // Update change in velocity if wall is hit.
     else if( ball_lef - TWO <= WALL_RIGHT )
        change_x <=  TWO;
     // Update change in velocity if paddle is hit.
     else if( ball_rit + TWO == PADDLE_LEFT &
            ~( ( ball_top < paddle_top & ball_btm < paddle_top ) |
               ( ball_top > paddle_btm & ball_btm > paddle_btm ) )
            )
        change_x <= -TWO;
     else begin
        change_y <= change_y;
        change_x <= change_x;
     end

     // Update ball limits.
     ball_top <= ball_top + change_y;
     ball_btm <= ball_btm + change_y;
     ball_lef <= ball_lef + change_x;
     ball_rit <= ball_rit + change_x;

   end

end

always@( * ) begin

   // Wall
   if( pixel_x >= WALL_LEFT & pixel_x <= WALL_RIGHT &
       video_on )
      rgb = WALL_RGB ;
   // Paddle
   else if( pixel_x >= PADDLE_LEFT & pixel_x <= PADDLE_RIGHT &
            pixel_y >= paddle_top  & pixel_y <= paddle_btm   &
            video_on )
      rgb = PADDLE_RGB ;
   // Ball
   else if( round_ball_on & video_on )
      rgb = BALL_RGB;
   // Background
   else if( video_on )
      rgb = BACKGROUND_RGB ;
   // Black if no video on signal.
   else
      rgb = BLACK;

   // Round ball image ROM.
   case( rom_addr )
      4'h0   : rom_data = 9'b000111000; //    ***
      4'h1   : rom_data = 9'b011111110; //  *******
      4'h2   : rom_data = 9'b011111110; //  *******
      4'h3   : rom_data = 9'b111111111; // *********
      4'h4   : rom_data = 9'b111111111; // *********
      4'h5   : rom_data = 9'b111111111; // *********
      4'h6   : rom_data = 9'b011111110; //  *******
      4'h7   : rom_data = 9'b011111110; //  *******
      4'h8   : rom_data = 9'b000111000; //    ***
      default: rom_data = 9'b000000000; //  Default
   endcase

end

endmodule
</code>```

答:
I did not read through your code fully, but if you are correct that this register switches between 10'b0000_0000_01 and 10'b1111_1111_11 then the LSB is always 1. No need to have a flip-flop to store that bit, so it is optimized away.

Ben's comment below points out how to deal with this. You can explicitely make this optimization. Something like:

```<code>logic change_polarity;
...
if(some_condition)
   change_polarity <= 1'b1;
else if(some_other_condition)
   change_polarity <= 1'b0;
...
logic [9:0] change;
assign change = change_polarity ? 10'h3FF : 1h'h001;
</code>```

Body:
I'm writing a module for a game of Pong that has two registers called change_x and change_y, which switch between positive and negative one (it says TWO in the code but I changed it to 1 while debugging). These registers are 10 bits so they switch between 10'b0000_0000_01 and 10'b1111_1111_11. When I synthesize I get the warning:

Xst:1710 - FF/Latch <change_x_0> (without init value) has a constant value of 1 in block <pixel_gen>. This FF/Latch will be trimmed during the optimization process.
Xst:1710 - FF/Latch <change_y_0> (without init value) has a constant value of 1 in block <pixel_gen>. This FF/Latch will be trimmed during the optimization process.
Xst:1710 - FF/Latch <change_x_0> (without init value) has a constant value of 1 in block <PIXEL_GEN>. This FF/Latch will be trimmed during the optimization process.
Xst:1895 - Due to other FF/Latch trimming, FF/Latch <change_y_0> (without init value) has a constant value of 1 in block <PIXEL_GEN>. This FF/Latch will be trimmed during the optimization process.

First I just want to make sure that I'm interpreting the warnings right, am I getting them because the least significant bits on these registers never change? Secondly, is there another way to assign them so that I won't get the warnings? I put a block comment above the part where the registers get switched.

module PIXEL_GEN(
input clock,
input reset,
input [9:0] pixel_x, pixel_y,
input video_on,
input btn_up,
input btn_dn,
output reg [7:0] rgb
);

// ROM signals for round ball.
wire [3:0] rom_col;
wire [3:0] rom_addr;
wire [7:0] ball_rgb, wall_rgb, paddle_rgb, background_rgb;
wire       rom_bit, round_ball_on;
reg  [8:0] rom_data;

// Ball moving parts.
reg [9:0] ball_top;
reg [9:0] ball_btm;
reg [9:0] ball_lef;
reg [9:0] ball_rit;

// Ball change reg.
reg [9:0] change_x;
reg [9:0] change_y;

// Paddle moving parts.
reg [9:0] paddle_top;
reg [9:0] paddle_btm;

// Wall limits.
localparam WALL_LEFT  = 10'd32;
localparam WALL_RIGHT = 10'd35;

// Paddle side limits.
localparam PADDLE_LEFT      = 10'd600;
localparam PADDLE_RIGHT     = 10'd603;
localparam PADDLE_BTM_RESET = 10'd276;
localparam PADDLE_TOP_RESET = 10'd204;

// Paddle length.
localparam PADDLE_LENGTH = PADDLE_BTM_RESET - PADDLE_TOP_RESET;

// Ball reset limits.
localparam BALL_LEFT_RESET  = 10'd580;
localparam BALL_RIGHT_RESET = 10'd588;
localparam BALL_TOP_RESET   = 10'd238;
localparam BALL_BTM_RESET   = 10'd246;

// Screen boundaries.
localparam TOP    = 10'd0;
localparam BOTTOM = 10'd479;
localparam LEFT   = 10'd0;
localparam RIGHT  = 10'd639;

// Two pixel shift each transition.
localparam TWO = 10'd1;
localparam ONE = 10'd1;
localparam ZERO = 10'd0;

// Assigns object colors.
localparam BALL_RGB       = 8'b000_000_11; // Blue
localparam WALL_RGB       = 8'b111_000_00; // Red
localparam PADDLE_RGB     = 8'b000_111_00; // Green
localparam BACKGROUND_RGB = 8'b111_111_11; // White
localparam BLACK          = 8'b000_000_00; // Black

// Refrence tick 60Hz.
assign ref_tick = ( pixel_y == 10'd481 ) & ( pixel_x == 10'd0 );
// Define boundaries for square ball and asserts an "on" signal.
assign square_ball_on = pixel_x >= ball_lef & pixel_x <= ball_rit &
                        pixel_y <= ball_btm & pixel_y >= ball_top;
// Selects ROM row.
assign rom_addr = pixel_y[3:0] - ball_top[3:0];
// Finds ROM column.
assign rom_col  = pixel_x[3:0] - ball_lef[3:0];
// Finds specific bit from ROM row and column.
assign rom_bit  = rom_data[ rom_col ];
// Asserts round_ball_on signal if in the correct
// region and current bit is a one.
assign round_ball_on = square_ball_on & rom_bit;

always@( posedge clock, posedge reset ) begin

   // Restore paddle and ball to reset state.
   if( reset ) begin

      // Reset paddle top / bottom limits.
      paddle_top <= PADDLE_TOP_RESET;
      paddle_btm <= PADDLE_BTM_RESET;

      // Reset ball limits.
      ball_top <= BALL_TOP_RESET;
      ball_btm <= BALL_BTM_RESET;
      ball_lef <= BALL_LEFT_RESET;
      ball_rit <= BALL_RIGHT_RESET;

      // Set change.
      change_x <= -TWO;
      change_y <= -TWO;

   end

   // Move paddle up or down if button is pushed.
   else if( ref_tick ) begin

     // Update paddle top and bottom limits.
     // BtnUp and not hitting top.
     if     ( btn_up & paddle_top >= TWO          ) begin
        paddle_top <= paddle_top - TWO;
        paddle_btm <= paddle_btm - TWO;
     end
     // BtnUp and hitting top.
     else if( btn_up                              ) begin
        paddle_top <= TOP;
        paddle_btm <= TOP + PADDLE_LENGTH;
     end
     // BtnDn and not hitting bottom.
     else if( btn_dn & paddle_btm + TWO <  BOTTOM ) begin
        paddle_top <= paddle_top + TWO;
        paddle_btm <= paddle_btm + TWO;
     end
     // BtnDn and hitting bottom.
     else if( btn_dn & paddle_btm + TWO >= BOTTOM ) begin
        paddle_top <= BOTTOM - PADDLE_LENGTH;
        paddle_btm <= BOTTOM;
     end
     else begin
        paddle_top <= paddle_top;
        paddle_btm <= paddle_btm;
     end

     /************************************************************
     This is where the values switch between positve and negative.
     ************************************************************/

     // Update change in velocity if top is hit.
     if     ( ball_top - TWO <= TOP        )
        change_y <=  TWO;
     // Update change in velocity if bottom is hit.
     else if( ball_btm + TWO >= BOTTOM     )
        change_y <= -TWO;
     // Update change in velocity if wall is hit.
     else if( ball_lef - TWO <= WALL_RIGHT )
        change_x <=  TWO;
     // Update change in velocity if paddle is hit.
     else if( ball_rit + TWO == PADDLE_LEFT &
            ~( ( ball_top < paddle_top & ball_btm < paddle_top ) |
               ( ball_top > paddle_btm & ball_btm > paddle_btm ) )
            )
        change_x <= -TWO;
     else begin
        change_y <= change_y;
        change_x <= change_x;
     end

     // Update ball limits.
     ball_top <= ball_top + change_y;
     ball_btm <= ball_btm + change_y;
     ball_lef <= ball_lef + change_x;
     ball_rit <= ball_rit + change_x;

   end

end

always@( * ) begin

   // Wall
   if( pixel_x >= WALL_LEFT & pixel_x <= WALL_RIGHT &
       video_on )
      rgb = WALL_RGB ;
   // Paddle
   else if( pixel_x >= PADDLE_LEFT & pixel_x <= PADDLE_RIGHT &
            pixel_y >= paddle_top  & pixel_y <= paddle_btm   &
            video_on )
      rgb = PADDLE_RGB ;
   // Ball
   else if( round_ball_on & video_on )
      rgb = BALL_RGB;
   // Background
   else if( video_on )
      rgb = BACKGROUND_RGB ;
   // Black if no video on signal.
   else
      rgb = BLACK;

   // Round ball image ROM.
   case( rom_addr )
      4'h0   : rom_data = 9'b000111000; //    ***
      4'h1   : rom_data = 9'b011111110; //  *******
      4'h2   : rom_data = 9'b011111110; //  *******
      4'h3   : rom_data = 9'b111111111; // *********
      4'h4   : rom_data = 9'b111111111; // *********
      4'h5   : rom_data = 9'b111111111; // *********
      4'h6   : rom_data = 9'b011111110; //  *******
      4'h7   : rom_data = 9'b011111110; //  *******
      4'h8   : rom_data = 9'b000111000; //    ***
      default: rom_data = 9'b000000000; //  Default
   endcase

end

endmodule

Body:
I did not read through your code fully, but if you are correct that this register switches between 10'b0000_0000_01 and 10'b1111_1111_11 then the LSB is always 1. No need to have a flip-flop to store that bit, so it is optimized away.

Ben's comment below points out how to deal with this. You can explicitely make this optimization. Something like:

logic change_polarity;
...
if(some_condition)
   change_polarity <= 1'b1;
else if(some_other_condition)
   change_polarity <= 1'b0;
...
logic [9:0] change;
assign change = change_polarity ? 10'h3FF : 1h'h001;


问:
List not filtering correctly is search string is empty
I have a list that I'm trying to have filter based on what a user types.  As the user types, it searches the string it's checking against and compares the two, if the string is found, it pushes the object to an array, which then displays the filtered objects information.  The issue I'm having is, when the search field is blank, the original, unaltered array of objects needs to be shown.  Instead, what I'm getting is the last successful returned search.

HTML

```<code><input type="text" class="in-line filter" id="searchByName" placeholder="Enter a name" (keyup)="filterByName($event.target.value)" />
<study-results-table [originalArray]="originalArray"></study-results-table>
</code>```

TS

```<code>ngOnInit(){
  originalArray = new Array<any>();
  unfiltered = new Array<any>()
}

filterByName(searchString){
    this.filtered = new Array<any>();
    _.each(this.originalArray, (result) => {
        let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        if(patientName.includes(searchString.toLowerCase())){
            this.filtered.push(result);
        }
    })

    if(searchString === ""){
        this.originalArray= this.unfiltered;
    }
    this.originalArray= this.filtered;
}
</code>```

Can anyone explain how to fix this?

答:
Why don't you use the array's filter function? You can simplify the code to the following:

```<code>filterByName(searchString){
    if(searchString.trim().length==0){
        this.originalArray = this.unfiltered;
        return;
    };
    this.originalArray = this.unfiltered.filter( (result)=>{
        let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        return (name.includes(searchString.toLowerCase()));
    });
}
</code>```

Body:
I have a list that I'm trying to have filter based on what a user types.  As the user types, it searches the string it's checking against and compares the two, if the string is found, it pushes the object to an array, which then displays the filtered objects information.  The issue I'm having is, when the search field is blank, the original, unaltered array of objects needs to be shown.  Instead, what I'm getting is the last successful returned search.

HTML

<input type="text" class="in-line filter" id="searchByName" placeholder="Enter a name" (keyup)="filterByName($event.target.value)" />
<study-results-table [originalArray]="originalArray"></study-results-table>

TS

ngOnInit(){
  originalArray = new Array<any>();
  unfiltered = new Array<any>()
}

filterByName(searchString){
    this.filtered = new Array<any>();
    _.each(this.originalArray, (result) => {
        let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        if(patientName.includes(searchString.toLowerCase())){
            this.filtered.push(result);
        }
    })

    if(searchString === ""){
        this.originalArray= this.unfiltered;
    }
    this.originalArray= this.filtered;
}

Can anyone explain how to fix this?

Body:
Why don't you use the array's filter function? You can simplify the code to the following:

filterByName(searchString){
    if(searchString.trim().length==0){
        this.originalArray = this.unfiltered;
        return;
    };
    this.originalArray = this.unfiltered.filter( (result)=>{
        let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        return (name.includes(searchString.toLowerCase()));
    });
}


问:
Change the content (different languages) of React Components when clicking on a button
I want to create a React Website where you can click on a button and change the language to German or English. I'm new to React and still learning.

I created a simple JSON that looks like this:

```<code>{
  "de": {
    "header": "Willkommen",
    "footer": "Auf Wiedersehen"
  },
  "eng": {
    "header": "Welcome",
    "footer": "Goodbye"
  }
}
</code>```

I created a button that toggles its state when onClick. But I think state is the wrong way to do this if I want to access it everywhere.

```<code>class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isOn: true};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    if (this.state.isOn) {
      this.setState({isOn: false})
    } else {
      this.setState({isOn: true})
    }
  }
  render() {
    return(
      <button type="button" onClick={this.handleClick}>DE/ENG{JSON.stringify(this.state.isOn)}</button>
    );
  }
}
</code>```

And now I want to import the JSON data and put the right one in the components. This one down here isn't working. I don't know how to do it. Every component should get the German or English data when the button is clicked. I want to use it in many components. (It's working when I use const data = DATA.de for example but that won't change the content when I click the button.)

```<code>import DATA from './data.json';

class Main extends React.Component {
  render() {
    const data = Button.state.isOn ? DATA.de : DATA.eng;
    return (
      <div>
        <Button onIsOnChange={this.buttonChange} />
        <span>{data.header}</span>
      </div>
    );
  }
}
</code>```

Do you know how to do this?

答:
React encourages you to "lift state", and this is a great opportunity to do so. I'd recommend you remove the state and handleClick method from the Button element (try using a functional stateless component), and instead add the same state (on/off) to the Main element. When the button is clicked, simply make a call (using the onClick attribute) to this.props.handleClick. You'll need to give handleClick as a prop to the button, and in your Main element's handleClick method, set your state accordingly. You'll also need to give your Button component an isOn prop.

In Main your data const will then respond to this.state.isOn.

Body:
I want to create a React Website where you can click on a button and change the language to German or English. I'm new to React and still learning.

I created a simple JSON that looks like this:

{
  "de": {
    "header": "Willkommen",
    "footer": "Auf Wiedersehen"
  },
  "eng": {
    "header": "Welcome",
    "footer": "Goodbye"
  }
}

I created a button that toggles its state when onClick. But I think state is the wrong way to do this if I want to access it everywhere.

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isOn: true};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    if (this.state.isOn) {
      this.setState({isOn: false})
    } else {
      this.setState({isOn: true})
    }
  }
  render() {
    return(
      <button type="button" onClick={this.handleClick}>DE/ENG{JSON.stringify(this.state.isOn)}</button>
    );
  }
}

And now I want to import the JSON data and put the right one in the components. This one down here isn't working. I don't know how to do it. Every component should get the German or English data when the button is clicked. I want to use it in many components. (It's working when I use const data = DATA.de for example but that won't change the content when I click the button.)

import DATA from './data.json';

class Main extends React.Component {
  render() {
    const data = Button.state.isOn ? DATA.de : DATA.eng;
    return (

        <Button onIsOnChange={this.buttonChange} />
        {data.header}

    );
  }
}

Do you know how to do this?


问:
Is it always necessary for a notifying thread to lock the shared data during modification?
When using a condition variable, http://en.cppreference.com/w/cpp/thread/condition_variable describes the typical steps for the thread that notifies as:

acquire a std::mutex (typically via std::lock_guard)

perform the modification while the lock is held

execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)

For the simple case shown below, is it necessary for the main thread to lock "stop" when it modifies it? While I understand that locking when modifying shared data is almost always a good idea, I'm not sure why it would be necessary in this case.

```<code>std::condition_variable cv;
std::mutex mutex;
bool stop = false;

void worker() {
    std::unique_lock<std::mutex> lock(mutex);
    cv.wait(lock, [] { return stop; })
}

// No lock (Why would this not work?)
void main() {
     std::thread(worker);
     std::this_thread::sleep_for(1s);
     stop = true;
     cv.notify_one();
}

// With lock: why is this neccesary?
void main() {
     std::thread mythread(worker);
     std::this_thread::sleep_for(1s);
     {
         std::unique_lock<std::mutex>(mutex);
         stop = true;
     }
     cv.notify_one();
     mythread.join();
}
</code>```

答:
For the simple case shown below, is it necessary for the main thread to lock "stop" when it modifies it?

Yes, to prevent race condition. Aside from issues of accessing shared data from different threads, which could be fixed by std::atomic, imagine this order of events:

```<code>worker_thread: checks value of `stop` it is false
main_thread: sets `stop` to true and sends signal
worker_thread: sleeps on condition variable
</code>```

In this situation worker thread would possibly sleep forever and it would miss event of stop set to true simply because wakeup signal was already sent and it missed it.

Acquiring mutex on modification of shared data is required because only then you can treat checking condition and going to sleep or acting on it in worker thread as atomic operation as whole.

Body:
When using a condition variable, http://en.cppreference.com/w/cpp/thread/condition_variable describes the typical steps for the thread that notifies as:

acquire a std::mutex (typically via std::lock_guard)

perform the modification while the lock is held

execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)

For the simple case shown below, is it necessary for the main thread to lock "stop" when it modifies it? While I understand that locking when modifying shared data is almost always a good idea, I'm not sure why it would be necessary in this case.

std::condition_variable cv;
std::mutex mutex;
bool stop = false;

void worker() {
    std::unique_lock<std::mutex> lock(mutex);
    cv.wait(lock, [] { return stop; })
}

// No lock (Why would this not work?)
void main() {
     std::thread(worker);
     std::this_thread::sleep_for(1s);
     stop = true;
     cv.notify_one();
}

// With lock: why is this neccesary?
void main() {
     std::thread mythread(worker);
     std::this_thread::sleep_for(1s);
     {
         std::unique_lock<std::mutex>(mutex);
         stop = true;
     }
     cv.notify_one();
     mythread.join();
}

Body:
For the simple case shown below, is it necessary for the main thread to lock "stop" when it modifies it?

Yes, to prevent race condition. Aside from issues of accessing shared data from different threads, which could be fixed by std::atomic, imagine this order of events:

worker_thread: checks value of `stop` it is false
main_thread: sets `stop` to true and sends signal
worker_thread: sleeps on condition variable

In this situation worker thread would possibly sleep forever and it would miss event of stop set to true simply because wakeup signal was already sent and it missed it.

Acquiring mutex on modification of shared data is required because only then you can treat checking condition and going to sleep or acting on it in worker thread as atomic operation as whole.


问:
Python 3 - Randomly printing items from list of dictionaries without repeat
I have a modified version of some code I am using in a quiz, my problem is my code is using random.choice to select a quiz question, how do I have it still randomly select a question but also not repeat a question already asked to the user?

Appologies for the odd questions and answers in "quiz_data"

Code:

```<code>def InformationToDictionaries():
quiz_data = [
    {
        "question": "What day is it today?",
        "choices": {"a": "Monday", "b": "Friday", "c": "Wednesday", "d": "Sunday"},
        "answer": "Wednesday")
    },
    {
        "question": "What food am I thinking of?",
        "choices": "Pizza", "b": "Curry", "c": "Pie", "d": "Pasta"},
        "answer": "Curry"
    }
]
return quiz_data

def Quiz():
    score = 0
    for i in range(1,6):
        q = random.choice(quiz_data)
        print("Q." + str(i) + ": ", q.get("question"))
        print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
        userans = str(input("\n>"))

    if userans == q.get("answer"):
        print("Correct")
        score = score + 1
    else: print("Incorrect")

quiz_data = InformationToDictionaries()
Quiz()
</code>```

Many thanks for any responses in advance, if you have any suggestions for me please let me know, this is my first question.

--------EDIT 1----------

Modified code after first suggestions:

```<code>def Quiz():
score = 0
random.shuffle(quiz_data)
for question in quiz_data:
    q = random.choice(quiz_data)
    print("Q." + str("1") + ": ", q.get("question"))
    print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
</code>```

答:
In your modified code, you're still picking a random question inside the loop. You can just take them in the shuffled order if you get rid of the line q = random.choice(quiz_data) and use the question variable in the loop body.

```<code>score = 0
random.shuffle(quiz_data)
for question in quiz_data:
    print("Q." + str("1") + ": ", question.get("question"))
    print('\n'.join("{}: {}".format(x, y) for x, y in question.get("choices").items()))
</code>```

Body:
I have a modified version of some code I am using in a quiz, my problem is my code is using random.choice to select a quiz question, how do I have it still randomly select a question but also not repeat a question already asked to the user?

Appologies for the odd questions and answers in "quiz_data"

Code:

def InformationToDictionaries():
quiz_data = [
    {
        "question": "What day is it today?",
        "choices": {"a": "Monday", "b": "Friday", "c": "Wednesday", "d": "Sunday"},
        "answer": "Wednesday")
    },
    {
        "question": "What food am I thinking of?",
        "choices": "Pizza", "b": "Curry", "c": "Pie", "d": "Pasta"},
        "answer": "Curry"
    }
]
return quiz_data

def Quiz():
    score = 0
    for i in range(1,6):
        q = random.choice(quiz_data)
        print("Q." + str(i) + ": ", q.get("question"))
        print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
        userans = str(input("\n>"))

    if userans == q.get("answer"):
        print("Correct")
        score = score + 1
    else: print("Incorrect")

quiz_data = InformationToDictionaries()
Quiz()

Many thanks for any responses in advance, if you have any suggestions for me please let me know, this is my first question.

--------EDIT 1----------

Modified code after first suggestions:

def Quiz():
score = 0
random.shuffle(quiz_data)
for question in quiz_data:
    q = random.choice(quiz_data)
    print("Q." + str("1") + ": ", q.get("question"))
    print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))

Body:
In your modified code, you're still picking a random question inside the loop. You can just take them in the shuffled order if you get rid of the line q = random.choice(quiz_data) and use the question variable in the loop body.

score = 0
random.shuffle(quiz_data)
for question in quiz_data:
    print("Q." + str("1") + ": ", question.get("question"))
    print('\n'.join("{}: {}".format(x, y) for x, y in question.get("choices").items()))


问:
Text space doesn't fit when adding new row to Kendo Grid
When I add a new row to a kendo grid using js (partial code below), the text doesn't fit inside the row, as you can see with this picture: print-screen-kendo-grid.

How I can solve it?

```<code>var dataSource = section.find(".k-grid").getKendoGrid().dataSource;
dataSource.add({
        Description: description.val(),
        StepTimer: timer
    });
</code>```

Thank you.

EDIT: I added more info

css rules for columns

```<code>.recipe-steps-grid .step-description {
    max-height: 60px;
    overflow: hidden;
    white-space: pre-wrap;
    margin-top: 0;
    margin-bottom: 0;
    text-indent: 0;
    text-align: left;
    font-family: inherit;
    font-size: inherit;
    color: inherit;
    border: none;
    background-color: inherit;
    padding: 0;
}

.recipe-steps-grid .step-order-col, .recipe-steps-grid .step-description-col {
    vertical-align: top;
}

.recipe-steps-grid tr.k-state-selected .step-order-col, .recipe-steps-grid tr.k-state-selected .step-description-col {
    vertical-align: middle;
}

.recipe-steps-grid {
    font-size: 13px;
    color: #342922;
    margin: 0 -30px;
}

.recipe-steps-grid .step-order-col {
    vertical-align: top;
    color: #9d9d9d;
    font-size: 11px;
}

.recipe-steps-grid .step-order-col,
.recipe-steps-grid .step-description-col {
    vertical-align: top;
}

.recipe-steps-grid tr.k-state-selected .step-order-col,
.recipe-steps-grid tr.k-state-selected .step-description-col {
    vertical-align: middle;
}
</code>```

Kendo Grid:

```<code> @(Html.Kendo().Grid<RecipeStepsViewModel>()
.Name(gridName)
.HtmlAttributes(new { @class = "recipe-steps-grid" })
  .Columns(columns =>
  {
      columns.Template(t => { }).ClientTemplate("#= generateHandleTemplate() #").HtmlAttributes(new { @class = "dummy-col" }).Width("30px");
      columns.Template(t => { }).ClientTemplate("STEP #= StepOrder #").HtmlAttributes(new { @class = "step-order-col" }).Width("50px");
      columns.Bound(p => p.Description).ClientTemplate("#= generateStepDescriptionTemplate(Description) #")
          .HtmlAttributes(new { @class = "step-description-col" }).Width("100%");
      columns.Bound(p => p.StepTimer).ClientTemplate("#= generateTimerTemplate(StepTimer) #").HtmlAttributes(new { @class = "right-cell" }).Width("80px");
      columns.Template(t => { }).ClientTemplate("#= generateDeleteTemplate(" + isLocked.ToString().ToLower() + ") #").HtmlAttributes(new { @class = "dummy-col" }).Width("30px");
  })
  .DataSource(dataSource => dataSource
      .Ajax()
      .Batch(true)
      .ServerOperation(false)
      .Read(read => read.Action("GetRecipeSteps", "RecipeSteps", new { sectionId = Model.Item1 }).Data("getLanguage"))
      .Create(create => create.Action("CreateRecipeStep", "RecipeSteps"))
      .Update(update => update.Action("UpdateRecipeStep", "RecipeSteps"))
      .Destroy(destroy => destroy.Action("DeleteRecipeStep", "RecipeSteps"))
      .Model(model =>
      {
          model.Id(a => a.Id);
          model.Field(a => a.Description).Editable(true);
          model.Field(a => a.StepTimer).Editable(true);
      })
  )
  .Events(e =>
  {
      e.Save("onStepSave");
      e.DataBound("onStepDatabound");
      e.Change("onStepRowSelection");
  })
  .Selectable(s => s.Mode(GridSelectionMode.Single))
  .Editable(editable => editable.Mode(GridEditMode.InCell)
      .CreateAt(GridInsertRowPosition.Bottom))
            )

            @(Html.Kendo().Sortable()
                .For("#" + gridName)
                .ConnectWith(".recipe-steps-grid")
                .Filter("table > tbody > tr:not(.k-grid-edit-row)")
                .Handler("table > tbody .drag-handle-icon")
                .Cursor("move")
                .Disabled(".no-drag")
                .HintHandler("noHint")
                .PlaceholderHandler("placeholder")
                .ContainerSelector(".section-container[data-type=recipe-steps]")
                .Events(events => events.Change("onStepSort"))
            )

            @{
                if (Model.Item3 && !Convert.ToBoolean(isLocked.ToString().ToLower()))
                {
                    <table class="add-recipe-step">
                        <colgroup>
                            <col class="add-colgroup" />
                            <col class="description-colgroup" />
                            <col class="timer-colgroup" />
                        </colgroup>
                        <tr>
                            <td class="centered-cell"><img class="add-btn" src='@Url.Content("~/Content/Images/grey-plus-thin.png")'></td>
                            <td>
                                <input class="input-box" type="text" placeholder='@Resources.placeholderNewRecipeStep' name="description" />
                            </td>
                            <td class="timer">
                                @(Html.Kendo().TimePicker()
                                    .Name("timer-" + guid)
                                    .HtmlAttributes(new { @class = "gl-timer" })
                                    .Format("mm:ss")
                                    .Interval(1)
                                    .Value("00:00:00")
                                    .Min("00:00:00")
                                    .Max("00:59:00")
                                )
                            </td>
                        </tr>
                    </table>
                }
            }
</code>```

js:

```<code>function generateStepDescriptionTemplate(text) {
    var bold = /\*(.*?)\*/gm;
    var html = text.replace(bold, '<span class="emph-word">$1</span>');

    return "<pre class='step-description'>" + html + "```";
}
```

Above the kendo grid, there is a div class named "recipe-steps-section section".
The idea is to add a step to a recipe. The recipe-steps-grid has 5 columns: the first is the handle so that the user can drag the step to change its order. The second column is the recipe step order number, then it is followed by the recipe step description (this is the one that I want to increase the text space). The following column is the time that recipe step takes to cook. The last column has the option to delete this step.

The kendo grid also has a toolbar at the end to add a new step with the step description and step time ("add-recipe-step" class).

答:
I found the solution.
The problem was this "pre" before class:

```<code> return "<pre class='step-description'>" + html + "```";
```

According to https://www.w3schools.com/tags/tag_pre.asp:

"The  tag defines preformatted text.
Text in a  element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.Text in a  element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks."

So when I removed it, it stopped cutting the text of larger rows in kendo grid

Body:
When I add a new row to a kendo grid using js (partial code below), the text doesn't fit inside the row, as you can see with this picture: print-screen-kendo-grid.

How I can solve it?

var dataSource = section.find(".k-grid").getKendoGrid().dataSource;
dataSource.add({
        Description: description.val(),
        StepTimer: timer
    });

Thank you.

EDIT: I added more info

css rules for columns

.recipe-steps-grid .step-description {
    max-height: 60px;
    overflow: hidden;
    white-space: pre-wrap;
    margin-top: 0;
    margin-bottom: 0;
    text-indent: 0;
    text-align: left;
    font-family: inherit;
    font-size: inherit;
    color: inherit;
    border: none;
    background-color: inherit;
    padding: 0;
}

.recipe-steps-grid .step-order-col, .recipe-steps-grid .step-description-col {
    vertical-align: top;
}

.recipe-steps-grid tr.k-state-selected .step-order-col, .recipe-steps-grid tr.k-state-selected .step-description-col {
    vertical-align: middle;
}

.recipe-steps-grid {
    font-size: 13px;
    color: #342922;
    margin: 0 -30px;
}

.recipe-steps-grid .step-order-col {
    vertical-align: top;
    color: #9d9d9d;
    font-size: 11px;
}

.recipe-steps-grid .step-order-col,
.recipe-steps-grid .step-description-col {
    vertical-align: top;
}

.recipe-steps-grid tr.k-state-selected .step-order-col,
.recipe-steps-grid tr.k-state-selected .step-description-col {
    vertical-align: middle;
}

Kendo Grid:

 @(Html.Kendo().Grid<RecipeStepsViewModel>()
.Name(gridName)
.HtmlAttributes(new { @class = "recipe-steps-grid" })
  .Columns(columns =>
  {
      columns.Template(t => { }).ClientTemplate("#= generateHandleTemplate() #").HtmlAttributes(new { @class = "dummy-col" }).Width("30px");
      columns.Template(t => { }).ClientTemplate("STEP #= StepOrder #").HtmlAttributes(new { @class = "step-order-col" }).Width("50px");
      columns.Bound(p => p.Description).ClientTemplate("#= generateStepDescriptionTemplate(Description) #")
          .HtmlAttributes(new { @class = "step-description-col" }).Width("100%");
      columns.Bound(p => p.StepTimer).ClientTemplate("#= generateTimerTemplate(StepTimer) #").HtmlAttributes(new { @class = "right-cell" }).Width("80px");
      columns.Template(t => { }).ClientTemplate("#= generateDeleteTemplate(" + isLocked.ToString().ToLower() + ") #").HtmlAttributes(new { @class = "dummy-col" }).Width("30px");
  })
  .DataSource(dataSource => dataSource
      .Ajax()
      .Batch(true)
      .ServerOperation(false)
      .Read(read => read.Action("GetRecipeSteps", "RecipeSteps", new { sectionId = Model.Item1 }).Data("getLanguage"))
      .Create(create => create.Action("CreateRecipeStep", "RecipeSteps"))
      .Update(update => update.Action("UpdateRecipeStep", "RecipeSteps"))
      .Destroy(destroy => destroy.Action("DeleteRecipeStep", "RecipeSteps"))
      .Model(model =>
      {
          model.Id(a => a.Id);
          model.Field(a => a.Description).Editable(true);
          model.Field(a => a.StepTimer).Editable(true);
      })
  )
  .Events(e =>
  {
      e.Save("onStepSave");
      e.DataBound("onStepDatabound");
      e.Change("onStepRowSelection");
  })
  .Selectable(s => s.Mode(GridSelectionMode.Single))
  .Editable(editable => editable.Mode(GridEditMode.InCell)
      .CreateAt(GridInsertRowPosition.Bottom))
            )

            @(Html.Kendo().Sortable()
                .For("#" + gridName)
                .ConnectWith(".recipe-steps-grid")
                .Filter("table > tbody > tr:not(.k-grid-edit-row)")
                .Handler("table > tbody .drag-handle-icon")
                .Cursor("move")
                .Disabled(".no-drag")
                .HintHandler("noHint")
                .PlaceholderHandler("placeholder")
                .ContainerSelector(".section-container[data-type=recipe-steps]")
                .Events(events => events.Change("onStepSort"))
            )

            @{
                if (Model.Item3 && !Convert.ToBoolean(isLocked.ToString().ToLower()))
                {

                        <colgroup>
                            <col class="add-colgroup" />
                            <col class="description-colgroup" />
                            <col class="timer-colgroup" />
                        </colgroup>

                                <input class="input-box" type="text" placeholder='@Resources.placeholderNewRecipeStep' name="description" />

                                @(Html.Kendo().TimePicker()
                                    .Name("timer-" + guid)
                                    .HtmlAttributes(new { @class = "gl-timer" })
                                    .Format("mm:ss")
                                    .Interval(1)
                                    .Value("00:00:00")
                                    .Min("00:00:00")
                                    .Max("00:59:00")
                                )

                }
            }

js:

function generateStepDescriptionTemplate(text) {
    var bold = /\*(.*?)\*/gm;
    var html = text.replace(bold, '$1');

    return "
" + html + "
";
}

Above the kendo grid, there is a div class named "recipe-steps-section section".
The idea is to add a step to a recipe. The recipe-steps-grid has 5 columns: the first is the handle so that the user can drag the step to change its order. The second column is the recipe step order number, then it is followed by the recipe step description (this is the one that I want to increase the text space). The following column is the time that recipe step takes to cook. The last column has the option to delete this step.

The kendo grid also has a toolbar at the end to add a new step with the step description and step time ("add-recipe-step" class).

Body:
I found the solution.
The problem was this "pre" before class:

 return "<pre class='step-description'>" + html + "</pre>";

According to https://www.w3schools.com/tags/tag_pre.asp:

"The  tag defines preformatted text.
Text in a  element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.Text in a  element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks."

So when I removed it, it stopped cutting the text of larger rows in kendo grid


问:
window.print() tries to print a page( which is created dynamically) before it finishes rendering
I am trying to print a table in a new window.
The thing is, print tries to print before the page is rendered.
I suspect document.write is asynchronous.
I tried to use  document.outerHTML / document.innerHTML instead of document.write(), but the CSS/JS files are not being parsed correctly as CSS.
The table has images in cells which are being loaded from cache, also after window.print().

Please, any idea would be helpful.

function printData() {
    let newWin = window.open("");
    styles="";

    //read styles in different page
    Array.prototype.forEach.call(
      document.querySelectorAll("link, style"),
      function(el){
      styles += (el.outerHTML);
    });

   //DOESNT WORK NOT RENDER STYLES
   // newWin.document.document.querySelector("html").innerHTML=(styles + document.querySelector("table").outerHTML);
    //THIS FINISHES RENDERING AFTER PRINT
      newWin.document.write(styles + document.querySelector("table").outerHTML);

      //DOESNT WORK
      newWin.document.addEventListener("DOMContentLoaded", function(){
      if(newWin.document.addEventListener === "loading"){
          newWin.print();
      }
      //DOESNT WORK
      newWin.window.onload= function(){
          newWin.print();
      }

      //WORKS
      setTimeout(function(){
        newWin.print();
        newWin.close();
      }, 2000);
    });
}```

答:
I resolved the similar issue by appending the following code to the end of . It works in IE11, Chrome and Firefox. Calling window.close() without wrapping in setTimeout() causes IE11 to close window before showing print dialog.

```<code><script type="text/javascript">
    setTimeout(function() {
        window.print();
        setTimeout(function() {window.close();});
    });
</script>
</code>```

Body:
I resolved the similar issue by appending the following code to the end of <body>. It works in IE11, Chrome and Firefox. Calling window.close() without wrapping in setTimeout() causes IE11 to close window before showing print dialog.

<script type="text/javascript">
    setTimeout(function() {
        window.print();
        setTimeout(function() {window.close();});
    });
</script>


问:
Haskell parsing csv with header to list of lists
New to haskell trying to get a csv file of ints with a header (type string) to output the 2nd to nth rows into a list of lists. eg [[row, 1], [row, 2]..]
so far with the Pipes library, got it to output each row as a list with the numbers as strings, and it prints "Right" for some reason?. eg output: 'Right ["1","3","5"..]' new line 'Right ["32","38","45"]'. Any suggestions would be appreciated. Code:</p>

```<code>{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
import qualified Data.Vector as V
import Pipes
import qualified Pipes.Prelude as P
import qualified System.IO as IO
import qualified Pipes.ByteString as PB
import qualified Data.Text as Text
import qualified Pipes.Csv as PCsv
import Control.Monad (forever)

showPipe :: Proxy () (Either String (V.Vector Text.Text)) () String IO b
showPipe = forever $ do
    x::(Either String (V.Vector Text.Text)) <- await
    yield $ show x

main :: IO ()
main = do
    putStrLn "Filename? "
    fName <- getLine
    IO.withFile fName
                IO.ReadMode
                (\handle -> do
                    let producer = (PCsv.decode PCsv.NoHeader
(PB.fromHandle handle))
                    runEffect ( (producer)>->
                                (showPipe) >->
                                P.stdoutLn)
                )
</code>```

答:
I'm not familiar with Pipe, but it looks like you're pulling data out into an Either, which conventionally uses the Right constructor for data and the Left constructor for an error message.

```<code>data Either a b = Left a | Right b
</code>```

In this case you're building an Either String (V.Vector Text.Text), so your result will either be:

```<code>:: Left String
</code>```

or

```<code>:: Right (V.Vector Text.Text)
</code>```

in this case you're getting the latter, and want to show the value pulled out of the Either monad. You can use either to handle both possibilities at once (in much the same way you'd use maybe in the Maybe monad).

```<code>showPipe :: Proxy () (Either String (V.Vector Text.Text)) () String IO b
showPipe = forever $ do
    x::(Either String (V.Vector Text.Text)) <- await
    let v = either id show x
    yield v
</code>```

This checks if x is a Left a or a Right b and returns either id a or show b depending. either is type

```<code>either :: (a -> c) -> (b -> c) -> Either a b -> c
-- or, specialized for this case:
either :: (String -> String)
           -> ((V.Vector Text.Text) -> String)
           -> Either String (V.Vector Text.Text)
           -> String
</code>```

Either (a hyuk) way you should be yielding a String back to be printed in main

ContentLicense: CC BY-SA 4.0

Body:
New to haskell trying to get a csv file of ints with a header (type string) to output the 2nd to nth rows into a list of lists. eg [[row, 1], [row, 2]..]
so far with the Pipes library, got it to output each row as a list with the numbers as strings, and it prints "Right" for some reason?. eg output: 'Right ["1","3","5"..]' new line 'Right ["32","38","45"]'. Any suggestions would be appreciated. Code:

{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
import qualified Data.Vector as V
import Pipes
import qualified Pipes.Prelude as P
import qualified System.IO as IO
import qualified Pipes.ByteString as PB
import qualified Data.Text as Text
import qualified Pipes.Csv as PCsv
import Control.Monad (forever)

showPipe :: Proxy () (Either String (V.Vector Text.Text)) () String IO b
showPipe = forever $ do
    x::(Either String (V.Vector Text.Text)) <- await
    yield $ show x

main :: IO ()
main = do
    putStrLn "Filename? "
    fName <- getLine
    IO.withFile fName
                IO.ReadMode
                (\handle -> do
                    let producer = (PCsv.decode PCsv.NoHeader
(PB.fromHandle handle))
                    runEffect ( (producer)>->
                                (showPipe) >->
                                P.stdoutLn)
                )

Body:
I'm not familiar with Pipe, but it looks like you're pulling data out into an Either, which conventionally uses the Right constructor for data and the Left constructor for an error message.

data Either a b = Left a | Right b

In this case you're building an Either String (V.Vector Text.Text), so your result will either be:

:: Left String

or

:: Right (V.Vector Text.Text)

in this case you're getting the latter, and want to show the value pulled out of the Either monad. You can use either to handle both possibilities at once (in much the same way you'd use maybe in the Maybe monad).

showPipe :: Proxy () (Either String (V.Vector Text.Text)) () String IO b
showPipe = forever $ do
    x::(Either String (V.Vector Text.Text)) <- await
    let v = either id show x
    yield v

This checks if x is a Left a or a Right b and returns either id a or show b depending. either is type

either :: (a -> c) -> (b -> c) -> Either a b -> c
-- or, specialized for this case:
either :: (String -> String)
           -> ((V.Vector Text.Text) -> String)
           -> Either String (V.Vector Text.Text)
           -> String

Either (a hyuk) way you should be yielding a String back to be printed in main


问:
Full Outer Join self with null values
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

```<code>N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6
</code>```

(where N is a general index column to enable a self-join on sequential groups) and I do:

```<code>SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name
</code>```

I want:

```<code>N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6
</code>```

but what I get is more like a cross-join:

```<code>n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6
</code>```

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

答:
Please see the code below:

```<code>create table Data (n int, name char(3), val int)

insert into data values (1, 'ABC',8)
insert into data values (1,   'DEF',    7)
insert into data values (2 ,  'ABC' ,   9)
insert into data values (2  , 'XYZ',    6)

SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name
</code>```

The output is this:

There are nulls on both sides.

Title: Full Outer Join self with null values

Body:
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6

(where N is a general index column to enable a self-join on sequential groups) and I do:

SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name

I want:

N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6

but what I get is more like a cross-join:

n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

Body:
Please see the code below:

create table Data (n int, name char(3), val int)

insert into data values (1, 'ABC',8)
insert into data values (1,   'DEF',    7)
insert into data values (2 ,  'ABC' ,   9)
insert into data values (2  , 'XYZ',    6)

SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name

The output is this:

There are nulls on both sides.


问:
Two divs side by side, one is scolling the other is fixed, but scroll a div if mouse is on fixed div too
I have a parent div called with two child divs side by side. I want the right div scolling and the left one to be fixed.
Precisely, I want something exactly like this: https://venmo.com/about/product/

So far, here is the code:

HTML:

```<code><div class="row" id="spec" style="height:700px">
   <div class="col-sm-12 col-md-6 scrollable" style="height:700px;overflow-y:scroll">
      <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section1</section>
      <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section2</section>
      <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
   </div>
   <div id="how-it-works" class="col-sm-12 col-md-6 text-center">
   <img src="image_phone.png"/></div>
</div>
</code>```

The issue is when mouse is over fixed div, the scrolling div stop scroll vertically! I want the scrolling div keeps scrolling if mouse is on another div too just like the sample above.

Thanks

答:
if you want copy other template, please check DOM, css and the js first.

```<code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
.phone{
    position: fixed;
    top: 100px;
    left: 0px;
}
</style>

<div class="container-fluid">
    <div class="row" id="spec" >
       <div class="col-sm-12 col-md-6 text-center">
            <div class="phone">
                <img src="https://www.bell.ca/Styles/wireless/all_languages/all_regions/catalog_images/iPhone_7/iPhone7_MatBlk_lrg1_en.png"/>
            </div>
       </div>

       <div class="col-sm-12 col-md-6 " >
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section1</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section2</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
       </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

UPDATE:

Your question is only for that.

but your comment want more than that. so please next time provide a complete question, so you can prevent someone who want help you do work twice. (or maybe i just wrong to read your question)

the key to copy/cloning template is just look at DOM, css and JS you
  can copy that, analyze and see what is changed

here i will show you what i get from that template

open console. You will find
 with no inline element css at the beginning.

when you start scroll. You will notice that .phone have inline css. So we can say: 1. there is a javascript who changed that. 2. they added css: position: fixed and opacity:1

we scroll until the end. We will know that .phone still there. But we cant see that. because the opacity is same or below 0.

we notice that event scroll is the trigger (just guessing now). To make sure, let's find the javascript. And we found https://cdn1.venmo.com/production/js/auth-legacy.min.js. we unminified with http://jsbeautifier.org/ , so we can read that. Then i find scroll, so i found scrollspy.

..snippet..
}), define("auth-legacy/public/js/phone", ["jquery", "jquery-scrollspy"], function(e) {
..snippet..

let's google this and we found https://github.com/softwarespot/jquery-scrollspy

try and try. demo : http://output.jsbin.com/xoyenamafe

what's i did is not exactly same with venmo.com because venmo.com run function on each .spec-text differently (change phone image, opacity, transform, etc). What i did is only show and hide phone image with opacity using 2nd last .spec-text as trigger.

good luck

Body:
I have a parent div called with two child divs side by side. I want the right div scolling and the left one to be fixed.
Precisely, I want something exactly like this: https://venmo.com/about/product/

So far, here is the code:

HTML:

scrolling text in section1

scrolling text in section2

scrolling text in section3

The issue is when mouse is over fixed div, the scrolling div stop scroll vertically! I want the scrolling div keeps scrolling if mouse is on another div too just like the sample above.

Thanks

Body:
if you want copy other template, please check DOM, css and the js first.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
.phone{
    position: fixed;
    top: 100px;
    left: 0px;
}
</style>

<div class="container-fluid">
    <div class="row" id="spec" >
       <div class="col-sm-12 col-md-6 text-center">
            <div class="phone">
                <img src="https://www.bell.ca/Styles/wireless/all_languages/all_regions/catalog_images/iPhone_7/iPhone7_MatBlk_lrg1_en.png"/>
            </div>
       </div>

       <div class="col-sm-12 col-md-6 " >
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section1</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section2</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
          <section id="spec-text1" class="spec-text" style="height:400px">scrolling text in section3</section>
       </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

UPDATE:

Your question is only for that.

but your comment want more than that. so please next time provide a complete question, so you can prevent someone who want help you do work twice. (or maybe i just wrong to read your question)

the key to copy/cloning template is just look at DOM, css and JS you
  can copy that, analyze and see what is changed

here i will show you what i get from that template

open console. You will find <div class="phone asset-feature-iphone"> with no inline element css at the beginning.

when you start scroll. You will notice that .phone have inline css. So we can say: 1. there is a javascript who changed that. 2. they added css: position: fixed and opacity:1

we scroll until the end. We will know that .phone still there. But we cant see that. because the opacity is same or below 0.

we notice that event scroll is the trigger (just guessing now). To make sure, let's find the javascript. And we found https://cdn1.venmo.com/production/js/auth-legacy.min.js. we unminified with http://jsbeautifier.org/ , so we can read that. Then i find scroll, so i found scrollspy.

..snippet..
}), define("auth-legacy/public/js/phone", ["jquery", "jquery-scrollspy"], function(e) {
..snippet..

let's google this and we found https://github.com/softwarespot/jquery-scrollspy

try and try. demo : http://output.jsbin.com/xoyenamafe

what's i did is not exactly same with venmo.com because venmo.com run function on each .spec-text differently (change phone image, opacity, transform, etc). What i did is only show and hide phone image with opacity using 2nd last .spec-text as trigger.

good luck


答:
If you can add a value and subtract the same value in an expression, it cancels out.

```<code>select year, (UserCount - @prev + ((@prev:=UserCount)-UserCount)) as diff
from Employees;
</code>```

But I question why you feel you need to do this. It shouldn't be a problem to have an extra column in a query result that you don't need. Your application code doesn't need to display it.

Title: Update value of a variable without printing its value in mysql

Body:
I have a table Employees which have two columns Year and UserCount.
Table looks something like this

Year  UserCount

2001 400

2002 1000

2003 2000

Now I want to print the year and the difference between the subsequent UserCount of two years.

I want to output something like this.

Year UserCount

2001 400

2002 600

2003 1000

I thought of taking a variable and initializing it with 0 and updating its value after every iteration. This is the query that I came up with

SET @prev = 0;
select year, (UserCount - @prev) as diff, @prev := (UserCount) from Employees;

Though I'm getting the difference but it adds a new column too, @prev := (Count) Is there any way by which I could update the value of prev without printing its value?

Is there any other approach which is better than this?

Body:
If you can add a value and subtract the same value in an expression, it cancels out.

select year, (UserCount - @prev + ((@prev:=UserCount)-UserCount)) as diff
from Employees;

But I question why you feel you need to do this. It shouldn't be a problem to have an extra column in a query result that you don't need. Your application code doesn't need to display it.


问:
jquery mobile - JQM 1.4.5 navbar not keeping active state after panel overlay
https://jsfiddle.net/7xwrxkrd/

Initially Tab One is set with ui-btn-active and ui-state-persist styles - if you click the burger icon the panel overlay is revealed and if you click away Tab One is still active.

But if you select Tab Two and then click the burger icon to show the panel overlay the Tab Two loses its active state.

Is there a way I can keep the Tabs Active while using the panel overlay?

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
        <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
    </head>

    <body>
        <div data-role="page">

            <div data-role="header" data-position="fixed" data-fullscreen="false">
                <a href="#panel-overlay" class="ui-btn ui-btn-left ui-alt-icon ui-nodisc-icon ui-corner-all ui-btn-icon-notext ui-icon-bars">Menu</a>
                <h1>Demo</h1>
            </div>

            <div data-role="tabs" id="tabs" style="padding:0px;">
                <div data-role="navbar">
                    <ul>
                        <li><a href="#one" class="ui-btn-active ui-state-persist">Tab One</a></li>
                        <li><a href="#two">Tab Two</a></li>
                        <li><a href="#three">Tab Three</a></li>
                    </ul>
                </div>

                <div id="one" class="ui-content" date-role="content">
                    <p>First tab Content</p>
                </div>

                <div id="two" class="ui-content" date-role="content">
                    <p>Second tab contentnt</p>
                </div>

                <div id="three" class="ui-content" date-role="content">
                    <p>Thrid tab contentnt</p>
                </div>
            </div>

            <div data-role="panel" id="panel-overlay" data-display="overlay">
                <ul data-role="listview">
                    <li><a href="#">Menu 1</a></li>
                    <li><a href="#">Menu 2</a></li>
                </ul>
            </div>

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

答:
Here is a generic fix for this issue:

```<code>$(document).on("panelbeforeopen", "div[data-role='panel']", function(e,ui) {
    $.mobile.activeClickedLink = null;
});
</code>```

If you have already somewhere in your code the panelbeforeopen callback, simply put the hotfix $.mobile.activeClickedLink = null; inside your function.

Body:
https://jsfiddle.net/7xwrxkrd/

Initially Tab One is set with ui-btn-active and ui-state-persist styles - if you click the burger icon the panel overlay is revealed and if you click away Tab One is still active.

But if you select Tab Two and then click the burger icon to show the panel overlay the Tab Two loses its active state.

Is there a way I can keep the Tabs Active while using the panel overlay?

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />

                Menu

Demo

Tab One

Tab Two

Tab Three

First tab Content

Second tab contentnt

Thrid tab contentnt

Menu 1

Menu 2

Body:
Here is a generic fix for this issue:

$(document).on("panelbeforeopen", "div[data-role='panel']", function(e,ui) {
    $.mobile.activeClickedLink = null;
});

If you have already somewhere in your code the panelbeforeopen callback, simply put the hotfix $.mobile.activeClickedLink = null; inside your function.


问:
Converting columns with multiple values into binary variables
Goal: Clean a data frame that has a column (let's call it, v1) containing one or (often) more than one value in each cell. I would like to generate multiple binary variables (say: v1_1, v1_2, v1_3) based on values contained in the cells in v1. (Reality: I have a very large, ugly excel dataset from elsewhere with many cells that have multiple values and would like to efficiently sort them into binary columns, ideally with tidyverse tools, but base works too).

Reproducible example:

```<code>df <- data.frame(caseID = c(1:5),
                 v1 = c(2, 1, "1,3", 1, "2, 3"))
df
desired_df <- data.frame(caseID = c(1:5),
                      v1_1 = c(0, 1, 1, 1, 0),
                      v1_2 = c(1, 0, 0, 0, 1),
                      v1_3 = c(0, 0, 1, 0, 1))
desired_df
</code>```

答:
A solution using dplyr and tidyr.

```<code>library(dplyr)
library(tidyr)

df2 <- df %>%
  separate_rows(v1) %>%
  mutate(Value = 1) %>%
  spread(v1, Value, fill = 0) %>%
  rename_at(vars(-caseID), funs(paste0("v1_", .)))
df2
#   caseID v1_1 v1_2 v1_3
# 1      1    0    1    0
# 2      2    1    0    0
# 3      3    1    0    1
# 4      4    1    0    0
# 5      5    0    1    1
</code>```

Body:
Goal: Clean a data frame that has a column (let's call it, v1) containing one or (often) more than one value in each cell. I would like to generate multiple binary variables (say: v1_1, v1_2, v1_3) based on values contained in the cells in v1. (Reality: I have a very large, ugly excel dataset from elsewhere with many cells that have multiple values and would like to efficiently sort them into binary columns, ideally with tidyverse tools, but base works too).

Reproducible example:

df <- data.frame(caseID = c(1:5),
                 v1 = c(2, 1, "1,3", 1, "2, 3"))
df
desired_df <- data.frame(caseID = c(1:5),
                      v1_1 = c(0, 1, 1, 1, 0),
                      v1_2 = c(1, 0, 0, 0, 1),
                      v1_3 = c(0, 0, 1, 0, 1))
desired_df

Body:
A solution using dplyr and tidyr.

library(dplyr)
library(tidyr)

df2 <- df %>%
  separate_rows(v1) %>%
  mutate(Value = 1) %>%
  spread(v1, Value, fill = 0) %>%
  rename_at(vars(-caseID), funs(paste0("v1_", .)))
df2
#   caseID v1_1 v1_2 v1_3
# 1      1    0    1    0
# 2      2    1    0    0
# 3      3    1    0    1
# 4      4    1    0    0
# 5      5    0    1    1


问:
How to know if job is running in SQL Server 2000?
I need to know if a job is running in SQL Server 2000, so I can stop it using msdb.dbo.sp_stop_job.
 I found this code that works in 2005:

```<code>IF EXISTS(
            select 1
            from msdb.dbo.sysjobs_view job
            inner join msdb.dbo.sysjobactivity activity on job.job_id = activity.job_id
            where
                activity.run_Requested_date is not null
                and activity.stop_execution_date is null
                and job.name = 'myjobname'
            )
    BEGIN

        EXEC msdb.dbo.sp_stop_job  @name_job;
    END
</code>```

However, in SQL 2000 msdb.dbo.sysjobactivity table does not exist. What could be the alternative solution?

Thanks.

答:
I think saying you did no research is a bit harsh, so I'll throw you a bone...  Next time, spend 10-15 minutes googling, and you'd likely eventually stumble across this.

Try this...

```<code>DECLARE @jobname VARCHAR(100)

SET @jobname='my job name'

IF OBJECT_ID('tempdb..#jobs') IS NOT NULL DROP TABLE #jobs

CREATE TABLE #jobs (JOB_ID UNIQUEIDENTIFIER, LAST_RUN_DATE INT, LAST_RUN_TIME INT, NEXT_RUN_DATE INT, NEXT_RUN_TIME INT, NEXT_RUN_SCHEDULE_ID INT, REQUESTED_TO_RUN INT, REQUEST_SOURCE INT, REQUEST_SOURCE_ID VARCHAR(100), RUNNING INT, CURRENT_STEP INT, CURRENT_RETRY_ATTEMPT INT, STATE INT)

INSERT INTO #jobs EXEC MASTER.DBO.XP_SQLAGENT_ENUM_JOBS 1,NOTHING

SELECT *
FROM #jobs e
JOIN MSDB..SYSJOBS j ON e.JOB_ID=j.JOB_ID
WHERE RUNNING=1
--AND j.name=@jobname
</code>```

Body:
I need to know if a job is running in SQL Server 2000, so I can stop it using msdb.dbo.sp_stop_job.
 I found this code that works in 2005:

IF EXISTS(
            select 1
            from msdb.dbo.sysjobs_view job
            inner join msdb.dbo.sysjobactivity activity on job.job_id = activity.job_id
            where
                activity.run_Requested_date is not null
                and activity.stop_execution_date is null
                and job.name = 'myjobname'
            )
    BEGIN

        EXEC msdb.dbo.sp_stop_job  @name_job;
    END

However, in SQL 2000 msdb.dbo.sysjobactivity table does not exist. What could be the alternative solution?

Thanks.

Body:
I think saying you did no research is a bit harsh, so I'll throw you a bone...  Next time, spend 10-15 minutes googling, and you'd likely eventually stumble across this.

Try this...

DECLARE @jobname VARCHAR(100)

SET @jobname='my job name'

IF OBJECT_ID('tempdb..#jobs') IS NOT NULL DROP TABLE #jobs

CREATE TABLE #jobs (JOB_ID UNIQUEIDENTIFIER, LAST_RUN_DATE INT, LAST_RUN_TIME INT, NEXT_RUN_DATE INT, NEXT_RUN_TIME INT, NEXT_RUN_SCHEDULE_ID INT, REQUESTED_TO_RUN INT, REQUEST_SOURCE INT, REQUEST_SOURCE_ID VARCHAR(100), RUNNING INT, CURRENT_STEP INT, CURRENT_RETRY_ATTEMPT INT, STATE INT)

INSERT INTO #jobs EXEC MASTER.DBO.XP_SQLAGENT_ENUM_JOBS 1,NOTHING

SELECT *
FROM #jobs e
JOIN MSDB..SYSJOBS j ON e.JOB_ID=j.JOB_ID
WHERE RUNNING=1
--AND j.name=@jobname


问:
Javascript Opacity Slider Not Working in Internet Explorer
I needed a component to change the color of an image with a slider. To do this, I modified Javascript code to change the opacity of a different colored image on top of the original image as the slider moved. I also added a dimming function that dims the image using opacity and a black div.

It works perfect in Chrome and Firefox. I can't for the life of me figure out how to get it to work in Internet Explorer. I'm new to Javascript so it may be obvious, but can someone help?!?

HTML

```<code><img src="images/warm-1170.jpg" id="warm">
<img src="images/cool-1170.jpg" id="cool">
<div class="blackBoxDimmer" id="dimmer"></div>
<div id="slidecontainer">
    <input type="range" min="0" max=".99" step=".01" value=".5" class="slider" id="myRange">
</div>
<p id="x1">2700K</p>
<p id="x2">5000K</p>
<h4 id="sliderTitleColor">Color Adjustment</h4>
<div id="dimAdjustSlider">
<div id="slidecontainer">
    <input type="range" min="0" max=".5" step=".01" value="0" class="slider" id="myRangeDim">
</div>
</div>
<p id="y1">5%</p>
<p id="y2">100%</p>
<h4 id="sliderTitleDim">Dimming Function</h4>
</code>```

CSS

```<code>body {
    font-family: "arial", serif;
}
.container {
    width: 1170px;
    margin: 0 auto;
    padding: 0;
}
.blackBoxDimmer {
    display: block;
    width: 1170px; /* !!!Adjust this to match image width */
    height: 671px; /* !!!Adjust this to match image height */
    margin-top: -675px;
    opacity: 0;
    background-color: black;
}
#warm {
    position: absolute;
}
#cool {
    opacity: .5;
}
input[type=range] {
  /*removes default webkit styles*/
  -webkit-appearance: none;
  /*fix for FF unable to apply focus style bug */
  border: 1px solid white;
  /*required for proper track sizing in FF*/
  width: 800px;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 800px;
  height: 5px;
  background: #ddd;
  border: none;
  border-radius: 3px;
}
input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #82c341;
  margin-top: -4px;
}
input[type=range]:focus {
  outline: none;
}
input[type=range]:focus::-webkit-slider-runnable-track {
  background: #ccc;
}
input[type=range]::-moz-range-track {
  width: 800px;
  height: 5px;
  background: #ddd;
  border: none;
  border-radius: 3px;
}
input[type=range]::-moz-range-thumb {
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #82c341;
}
/*hide the outline behind the border*/

input[type=range]:-moz-focusring {
  outline: 1px solid white;
  outline-offset: -1px;
}

input[type=range]::-ms-track {
  width: 800px;
  height: 5px;
  /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */
  background: transparent;
  /*leave room for the larger thumb to overflow with a transparent border */
  border-color: transparent;
  border-width: 6px 0;
  /*remove default tick marks*/
  color: transparent;
}

input[type=range]::-ms-fill-lower {
  background: #777;
  border-radius: 10px;
}

input[type=range]::-ms-fill-upper {
  background: #ddd;
  border-radius: 10px;
}

input[type=range]::-ms-thumb {
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #82c341;
}
input[type=range]:focus::-ms-fill-lower {
  background: #888;
}
input[type=range]:focus::-ms-fill-upper {
  background: #ccc;
}
#slidecontainer {
    margin-top: 50px;
    margin-left: 180px;
}
#dimAdjustSlider {
    display: inline-block;
    transform: rotate(180deg);
    margin-left: 180px;
    margin-bottom: 50px;
}
#y1 {
    display: inline-block;
    position: absolute;
    font-size: 12px !important;
    margin: 25px 0 0 -972px;
}
#y2 {
    display: inline-block;
    position: absolute;
    font-size: 12px !important;
    margin: 25px 0 0 -233px;
}
#sliderTitleDim {
    margin-top: -70px;
    margin-left: 513px;
    margin-bottom: 75px;
}
.dimmingBox {
    display: block;
}
#x1 {
    display: inline-block;
    font-size: 12px !important;
    margin-left: 190px;
    margin-right: 705px;
    margin-bottom: 30px;
}

#x2 {
    display: inline-block;
    font-size: 12px !important;
}

#sliderTitleColor {
    margin-top: -30px;
    margin-bottom: 45px;
    margin-left: 513px;
}
.textAlignLeft {
    text-align: left !important;
}
</code>```

Javascript

```<code>var slider = document.getElementById("myRange");
        var output = .5;
        var imageTrans = document.getElementById("cool");
        output.innerHTML = slider.value; // Display the default slider value

        // Update the current slider value (each time you drag the slider handle)
        slider.oninput = function() {
            output.innerHTML = this.value;
            imageTrans.style.opacity = slider.value;
        }

        var sliderDim = document.getElementById("myRangeDim");
        var outputDim = 0;
        var imageTransDim = document.getElementById("dimmer");
        outputDim.innerHTML = sliderDim.value; // Display the default slider value

        // Update the current slider value (each time you drag the slider handle)
        sliderDim.oninput = function() {
            outputDim.innerHTML = this.value;
            imageTransDim.style.opacity = sliderDim.value;
        }
</code>```

Thanks!

答: You probably need to change the event you are attaching your javascript function to - from oninput to onchange or onmousemove for old IE users.

Body:
I needed a component to change the color of an image with a slider. To do this, I modified Javascript code to change the opacity of a different colored image on top of the original image as the slider moved. I also added a dimming function that dims the image using opacity and a black div.

It works perfect in Chrome and Firefox. I can't for the life of me figure out how to get it to work in Internet Explorer. I'm new to Javascript so it may be obvious, but can someone help?!?

HTML

    <input type="range" min="0" max=".99" step=".01" value=".5" class="slider" id="myRange">

2700K

5000K

Color Adjustment

    <input type="range" min="0" max=".5" step=".01" value="0" class="slider" id="myRangeDim">

5%

100%

Dimming Function

CSS

body {
    font-family: "arial", serif;
}
.container {
    width: 1170px;
    margin: 0 auto;
    padding: 0;
}
.blackBoxDimmer {
    display: block;
    width: 1170px; /* !!!Adjust this to match image width */
    height: 671px; /* !!!Adjust this to match image height */
    margin-top: -675px;
    opacity: 0;
    background-color: black;
}
#warm {
    position: absolute;
}
#cool {
    opacity: .5;
}
input[type=range] {
  /*removes default webkit styles*/
  -webkit-appearance: none;
  /*fix for FF unable to apply focus style bug */
  border: 1px solid white;
  /*required for proper track sizing in FF*/
  width: 800px;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 800px;
  height: 5px;
  background: #ddd;
  border: none;
  border-radius: 3px;
}
input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #82c341;
  margin-top: -4px;
}
input[type=range]:focus {
  outline: none;
}
input[type=range]:focus::-webkit-slider-runnable-track {
  background: #ccc;
}
input[type=range]::-moz-range-track {
  width: 800px;
  height: 5px;
  background: #ddd;
  border: none;
  border-radius: 3px;
}
input[type=range]::-moz-range-thumb {
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #82c341;
}
/*hide the outline behind the border*/

input[type=range]:-moz-focusring {
  outline: 1px solid white;
  outline-offset: -1px;
}

input[type=range]::-ms-track {
  width: 800px;
  height: 5px;
  /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */
  background: transparent;
  /*leave room for the larger thumb to overflow with a transparent border */
  border-color: transparent;
  border-width: 6px 0;
  /*remove default tick marks*/
  color: transparent;
}

input[type=range]::-ms-fill-lower {
  background: #777;
  border-radius: 10px;
}

input[type=range]::-ms-fill-upper {
  background: #ddd;
  border-radius: 10px;
}

input[type=range]::-ms-thumb {
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #82c341;
}
input[type=range]:focus::-ms-fill-lower {
  background: #888;
}
input[type=range]:focus::-ms-fill-upper {
  background: #ccc;
}
#slidecontainer {
    margin-top: 50px;
    margin-left: 180px;
}
#dimAdjustSlider {
    display: inline-block;
    transform: rotate(180deg);
    margin-left: 180px;
    margin-bottom: 50px;
}
#y1 {
    display: inline-block;
    position: absolute;
    font-size: 12px !important;
    margin: 25px 0 0 -972px;
}
#y2 {
    display: inline-block;
    position: absolute;
    font-size: 12px !important;
    margin: 25px 0 0 -233px;
}
#sliderTitleDim {
    margin-top: -70px;
    margin-left: 513px;
    margin-bottom: 75px;
}
.dimmingBox {
    display: block;
}
#x1 {
    display: inline-block;
    font-size: 12px !important;
    margin-left: 190px;
    margin-right: 705px;
    margin-bottom: 30px;
}

#x2 {
    display: inline-block;
    font-size: 12px !important;
}

#sliderTitleColor {
    margin-top: -30px;
    margin-bottom: 45px;
    margin-left: 513px;
}
.textAlignLeft {
    text-align: left !important;
}

Javascript

var slider = document.getElementById("myRange");
        var output = .5;
        var imageTrans = document.getElementById("cool");
        output.innerHTML = slider.value; // Display the default slider value

        // Update the current slider value (each time you drag the slider handle)
        slider.oninput = function() {
            output.innerHTML = this.value;
            imageTrans.style.opacity = slider.value;
        }

        var sliderDim = document.getElementById("myRangeDim");
        var outputDim = 0;
        var imageTransDim = document.getElementById("dimmer");
        outputDim.innerHTML = sliderDim.value; // Display the default slider value

        // Update the current slider value (each time you drag the slider handle)
        sliderDim.oninput = function() {
            outputDim.innerHTML = this.value;
            imageTransDim.style.opacity = sliderDim.value;
        }

Thanks!


问:
how do i make labels list manually for my imported images in tensorflow
```<code>fq=glob.glob("*.jpg") # ['0.jpg','1.jpg','2.jpg','3.jpg','4.jpg'],labels for images=[1,1,1,0,0]
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=onehot))
</code>```

assuming that there is  just  2 classes and batch size is 2 and logits are [2,2] tensor,how do i make "onehot" variable list which contains one hot encoded labels like [1,0] for image 0,1,2  .jpg and [0,1] for image 3,4 .jpg. much thanks :)

答:
If your input array is a NumPy array, you can use np.eye:

```<code>label_array = np.array([1, 1, 1, 0, 0])
onehot_array = np.eye(2)[label_array]
</code>```

The result is: [[ 0.  1.], [ 0.  1.], [ 0.  1.], [ 1.  0.], [ 1.  0.]]

Body:
fq=glob.glob("*.jpg") # ['0.jpg','1.jpg','2.jpg','3.jpg','4.jpg'],labels for images=[1,1,1,0,0]
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=onehot))

assuming that there is  just  2 classes and batch size is 2 and logits are [2,2] tensor,how do i make "onehot" variable list which contains one hot encoded labels like [1,0] for image 0,1,2  .jpg and [0,1] for image 3,4 .jpg. much thanks :)

Body:
If your input array is a NumPy array, you can use np.eye:

label_array = np.array([1, 1, 1, 0, 0])
onehot_array = np.eye(2)[label_array]

The result is: [[ 0.  1.], [ 0.  1.], [ 0.  1.], [ 1.  0.], [ 1.  0.]]


问:
Store a closure as a variable in Swift
In Objective-C, you can define a block's input and output, store one of those blocks that's passed in to a method, then use that block later:

```<code>// in .h

    typedef void (^APLCalibrationProgressHandler)(float percentComplete);
    typedef void (^APLCalibrationCompletionHandler)(NSInteger measuredPower, NSError *error);

    // in .m

    @property (strong) APLCalibrationProgressHandler progressHandler;
    @property (strong) APLCalibrationCompletionHandler completionHandler;

    - (id)initWithRegion:(CLBeaconRegion *)region completionHandler:(APLCalibrationCompletionHandler)handler
    {
        self = [super init];
        if(self)
        {
            ...
            _completionHandler = [handler copy];
            ..
        }

        return self;
}

- (void)performCalibrationWithProgressHandler:(APLCalibrationProgressHandler)handler
{
    ...

            self.progressHandler = [handler copy];

     ...
            dispatch_async(dispatch_get_main_queue(), ^{
                _completionHandler(0, error);
            });
     ...
}
</code>```

So I'm trying to do the equivilant in Swift:

```<code>var completionHandler:(Float)->Void={}

init() {
    locationManager = CLLocationManager()
    region = CLBeaconRegion()
    timer = NSTimer()
}

convenience init(region: CLBeaconRegion, handler:((Float)->Void)) {
    self.init()
    locationManager.delegate = self
    self.region = region
    completionHandler = handler
    rangedBeacons = NSMutableArray()
}
</code>```

The compiler doesn't like that declaration of completionHandler. Not that I blame it, but, how do I define a closure that can be set and used later in Swift?

答:
In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.

```<code> var completionHandler:([String:Any], Bool)->Void = { dict, success  in
    if success {
      print(dict)
    }
  }
</code>```

Calling the closure variable

```<code>self.completionHandler(["name":"Gurjinder singh"],true)
</code>```

Title: Store a closure as a variable in Swift

Body:
In Objective-C, you can define a block's input and output, store one of those blocks that's passed in to a method, then use that block later:

// in .h

    typedef void (^APLCalibrationProgressHandler)(float percentComplete);
    typedef void (^APLCalibrationCompletionHandler)(NSInteger measuredPower, NSError *error);

    // in .m

    @property (strong) APLCalibrationProgressHandler progressHandler;
    @property (strong) APLCalibrationCompletionHandler completionHandler;

    - (id)initWithRegion:(CLBeaconRegion *)region completionHandler:(APLCalibrationCompletionHandler)handler
    {
        self = [super init];
        if(self)
        {
            ...
            _completionHandler = [handler copy];
            ..
        }

        return self;
}

- (void)performCalibrationWithProgressHandler:(APLCalibrationProgressHandler)handler
{
    ...

            self.progressHandler = [handler copy];

     ...
            dispatch_async(dispatch_get_main_queue(), ^{
                _completionHandler(0, error);
            });
     ...
}

So I'm trying to do the equivilant in Swift:

var completionHandler:(Float)->Void={}

init() {
    locationManager = CLLocationManager()
    region = CLBeaconRegion()
    timer = NSTimer()
}

convenience init(region: CLBeaconRegion, handler:((Float)->Void)) {
    self.init()
    locationManager.delegate = self
    self.region = region
    completionHandler = handler
    rangedBeacons = NSMutableArray()
}

The compiler doesn't like that declaration of completionHandler. Not that I blame it, but, how do I define a closure that can be set and used later in Swift?

Body:
In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.

 var completionHandler:([String:Any], Bool)->Void = { dict, success  in
    if success {
      print(dict)
    }
  }

Calling the closure variable

self.completionHandler(["name":"Gurjinder singh"],true)


问:
Match two strings in one line with grep
I am trying to use grep to match lines that contain two different strings. I have tried the following but this matches lines that contain either string1 or string2 which not what I want.

```<code>grep 'string1\|string2' filename
</code>```

So how do I match with grep only the lines that contain both strings?

答:
And as people suggested perl and python, and convoluted shell scripts, here a simple awk approach:

```<code>awk '/string1/ && /string2/' filename
</code>```

Having looked at the comments to the accepted answer: no, this doesn't do multi-line; but then that's also not what the author of the question asked for.

Title: Match two strings in one line with grep

Body:
I am trying to use grep to match lines that contain two different strings. I have tried the following but this matches lines that contain either string1 or string2 which not what I want.

grep 'string1\|string2' filename

So how do I match with grep only the lines that contain both strings?

Body:
And as people suggested perl and python, and convoluted shell scripts, here a simple awk approach:

awk '/string1/ && /string2/' filename

Having looked at the comments to the accepted answer: no, this doesn't do multi-line; but then that's also not what the author of the question asked for.