问:
How to make a form secure in redux-form
I am trying to use redux-form to build a credit card info form. However, when the user put in their card details on it, this pop up appear:

it said

Automatic credit card filling is disabled because this form does not use a secure connection

So my question is how to make a form secure using redux-form?

This is the code where I input the Payment redux-form

```<code>import React from 'react'
import { connect } from 'react-redux'
import PaymentView from './Payment.js'
import { reduxForm } from 'redux-form'

class Payment extends React.Component{

    render() {
        const { cardDetail } = this.props
        return(<PaymentView onCheckOut={()=>console.log(cardDetail)} />)
    }
}

Payment = reduxForm({
    form: 'payment'
})(Payment)

const mapStateToProps = state => ({
    cardDetail : state.form.payment ? state.form.payment.values : null
})

export default connect(mapStateToProps)(Payment)
</code>```

This is the code for my Payment View

```<code>import React from 'react'
import { Panel, Button, Row, Col } from 'react-bootstrap'
import { TextInput } from '.Form'

export default ({onCheckOut})=> <div>
    <Row>
        <Col sm={12} md={8} lg={6} mdOffset={2} lgOffset={3}>
            <Panel className="scb" header="bank transfer">
                123-456-789
            </Panel>
        </Col>
    </Row>
    <Row>
        <Col sm={12} md={8} mdOffset={2} lg={6} lgOffset={3}>
        <Panel className="credit-card" header="credit card" >
            <Row>
                <Col sm={12} md={8} lg={6}>
                <TextInput
                    name="creditCard"
                    label="credit card number"
                    type="text"
                    validateState="success"
                    controlId="credit-card"
                    value="12345678910111213"
                    placeholder="xxxx xxxx xxxx xxxx"
                    onChange={()=>{}}
                    helptext="16card number"
                >
                    card number
                </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={8} lg={6}>
                    <TextInput
                        name="name"
                        label="name"
                        type="text"
                        validateState="success"
                        controlId="name-card"
                        value="steve jobs"
                        placeholder="steve jobs"
                        onChange={()=>{}}
                        helptext="name on card"
                    >
                        Name on Card
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={8} md={8} lg={8}>
                    <h5>Expiry Date</h5>
                </Col>
            </Row>
            <Row>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="month"
                        label="month"
                        type="text"
                        validateState="success"
                        controlId="month"
                        value="12"
                        placeholder="01"
                        onChange={()=>{}}
                        helptext="month"
                    >
                        month
                    </TextInput>
                </Col>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="year"
                        label="year"
                        type="text"
                        validateState="success"
                        controlId="year"
                        value="18"
                        placeholder="18"
                        onChange={()=>{}}
                        helptext="year"
                    >
                        Year
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <TextInput
                        name="cvv"
                        label="cvv"
                        type="text"
                        validateState="cvv"
                        controlId="cvv"
                        value="123"
                        placeholder="123"
                        onChange={()=>{}}
                        helptext="cvv"
                    >
                        Cvv
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <Button bsStyle="primary" bsSize="large" block onClick={onCheckOut}>
                        Pay Now
                    </Button>
                </Col>
            </Row>
        </Panel>
        </Col>
    </Row>
</div>
</code>```

This is my TextInput

```<code>export const TextInput = (
    {
        type,
        name,
        placeholder,
        helpTextArray,
        status,
        label,
        value
    }
) =>
<FormGroup
    name="formBasicText"
    validationState={status || null}
>
    <ControlLabel>{label}</ControlLabel>
    <Field
        className="form-control"
        id="formBasicText"
        name={name}
        component="input"
        type={type}
        placeholder={placeholder}
    />
    <FormControl.Feedback />
    {
        value !== null?
        helpTextArray.map( (helpText, key) =>
            <HelpBlock key={key}>{helpText}</HelpBlock>
        ): null
    }
</FormGroup>
</code>```

答: You have this message maybe because you don't use a 'HTTPS' connexion and your navigator detect that and disabled auto-filling ?</p>

Title: How to make a form secure in redux-form

Body:
I am trying to use redux-form to build a credit card info form. However, when the user put in their card details on it, this pop up appear:

it said

Automatic credit card filling is disabled because this form does not use a secure connection

So my question is how to make a form secure using redux-form?

This is the code where I input the Payment redux-form

import React from 'react'
import { connect } from 'react-redux'
import PaymentView from './Payment.js'
import { reduxForm } from 'redux-form'

class Payment extends React.Component{

    render() {
        const { cardDetail } = this.props
        return(<PaymentView onCheckOut={()=>console.log(cardDetail)} />)
    }
}

Payment = reduxForm({
    form: 'payment'
})(Payment)

const mapStateToProps = state => ({
    cardDetail : state.form.payment ? state.form.payment.values : null
})

export default connect(mapStateToProps)(Payment)

This is the code for my Payment View

import React from 'react'
import { Panel, Button, Row, Col } from 'react-bootstrap'
import { TextInput } from '.Form'

export default ({onCheckOut})=>

    <Row>
        <Col sm={12} md={8} lg={6} mdOffset={2} lgOffset={3}>
            <Panel className="scb" header="bank transfer">
                123-456-789
            </Panel>
        </Col>
    </Row>
    <Row>
        <Col sm={12} md={8} mdOffset={2} lg={6} lgOffset={3}>
        <Panel className="credit-card" header="credit card" >
            <Row>
                <Col sm={12} md={8} lg={6}>
                <TextInput
                    name="creditCard"
                    label="credit card number"
                    type="text"
                    validateState="success"
                    controlId="credit-card"
                    value="12345678910111213"
                    placeholder="xxxx xxxx xxxx xxxx"
                    onChange={()=>{}}
                    helptext="16card number"
                >
                    card number
                </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={8} lg={6}>
                    <TextInput
                        name="name"
                        label="name"
                        type="text"
                        validateState="success"
                        controlId="name-card"
                        value="steve jobs"
                        placeholder="steve jobs"
                        onChange={()=>{}}
                        helptext="name on card"
                    >
                        Name on Card
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={8} md={8} lg={8}>

Expiry Date

                </Col>
            </Row>
            <Row>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="month"
                        label="month"
                        type="text"
                        validateState="success"
                        controlId="month"
                        value="12"
                        placeholder="01"
                        onChange={()=>{}}
                        helptext="month"
                    >
                        month
                    </TextInput>
                </Col>
                <Col sm={4} md={2} lg={2}>
                    <TextInput
                        name="year"
                        label="year"
                        type="text"
                        validateState="success"
                        controlId="year"
                        value="18"
                        placeholder="18"
                        onChange={()=>{}}
                        helptext="year"
                    >
                        Year
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <TextInput
                        name="cvv"
                        label="cvv"
                        type="text"
                        validateState="cvv"
                        controlId="cvv"
                        value="123"
                        placeholder="123"
                        onChange={()=>{}}
                        helptext="cvv"
                    >
                        Cvv
                    </TextInput>
                </Col>
            </Row>
            <Row>
                <Col sm={12} md={4} lg={4}>
                    <Button bsStyle="primary" bsSize="large" block onClick={onCheckOut}>
                        Pay Now
                    </Button>
                </Col>
            </Row>
        </Panel>
        </Col>
    </Row>

This is my TextInput

export const TextInput = (
    {
        type,
        name,
        placeholder,
        helpTextArray,
        status,
        label,
        value
    }
) =>
<FormGroup
    name="formBasicText"
    validationState={status || null}
>
    <ControlLabel>{label}</ControlLabel>
    <Field
        className="form-control"
        id="formBasicText"
        name={name}
        component="input"
        type={type}
        placeholder={placeholder}
    />
    <FormControl.Feedback />
    {
        value !== null?
        helpTextArray.map( (helpText, key) =>
            <HelpBlock key={key}>{helpText}</HelpBlock>
        ): null
    }
</FormGroup>


来源: stackexchange

问:
Correct Routing for :has_many :through
Ok so.. I have a site with several dropdown menus in my navbar. It goes a little like this:

Gran Turismo (First title drops down to: )

PS4

PS3 etc.

Forza (Second title drops down to: )

PS4

PS3 etc..

My goal is when I click on one of the drop downs it will display a Show page using the routes:

```<code>www.mysite.com/forza/ps4
</code>```

Everyone tells me that I should use a has_many :through to a third model which I have called Platform.

My models are therefore this:

class Game < ApplicationRecord
  has_many :platforms
  has_many :consoles, through: :platforms
end

class Console < ApplicationRecord
  has_many :platforms
  has_many :games, through: :platforms
end

class Platform < ApplicationRecord
  belongs_to :game
  belongs_to :console
end
```

<p>And my routes are this:</p>

```  resources :platforms, only: [:show] do
    resources :games do
      resources :consoles
    end
  end
```

<p>Ideally, on the final show.html.erb which im guessing would be the platforms show, I would like to display the product I am selling specifically for the game Forza on the platform PS4 which I chose my selecting the dropdown menu of my choosing..</p>

<p>However my routes are coming up like this instead:</p>

```/platforms/:platform_id/games/:game_id/consoles/:id(.:format)
```

Any ideas where I'm going wrong? And if there's a much easier way around this?

Many thanks!

Update:

"Platform" could be slightly confusing. Perhaps "MarketPlace" would be better suited. Although reading it through now, maybe I shouldn't have a third model and just end it at Console.

I just want the final show page to be slightly different if a different Game is selected.

答:
You could achieve the exact route you want (e.g. www.mysite.com/forza/ps4) using a custom route, like this:

```<code>get "/:game/:console", to: "games#show"
</code>```

In GamesController you could retrieve both parameters and search for the Game you want to display, something like this:

```<code>def show
  @console = Console.find_by(name: params[:console])
  @game    = Game.find_by(name: params[:game])
  # ...
end
</code>```

Keep in mind that this will work consistently only if all of the following conditions are met:

Game model contains unique names (or whatever column you chose to use as slug).

You have no other routes with the same pattern (e.g. /:other/:route).

Game names are different from any model name (unless that model has custom routes to handle the conflict, or not routes at all).

The route is defined at the end of your routes so it won't interfere with other routes.

ContentLicense: CC BY-SA 3.0

Title: Correct Routing for :has_many :through

Body:
Ok so.. I have a site with several dropdown menus in my navbar. It goes a little like this:

Gran Turismo (First title drops down to: )

PS4

PS3 etc.

Forza (Second title drops down to: )

PS4

PS3 etc..

My goal is when I click on one of the drop downs it will display a Show page using the routes:

www.mysite.com/forza/ps4

Everyone tells me that I should use a has_many :through to a third model which I have called Platform.

My models are therefore this:

class Game < ApplicationRecord
  has_many :platforms
  has_many :consoles, through: :platforms
end

class Console < ApplicationRecord
  has_many :platforms
  has_many :games, through: :platforms
end

class Platform < ApplicationRecord
  belongs_to :game
  belongs_to :console
end

And my routes are this:

  resources :platforms, only: [:show] do
    resources :games do
      resources :consoles
    end
  end

Ideally, on the final show.html.erb which im guessing would be the platforms show, I would like to display the product I am selling specifically for the game Forza on the platform PS4 which I chose my selecting the dropdown menu of my choosing..

However my routes are coming up like this instead:

/platforms/:platform_id/games/:game_id/consoles/:id(.:format)

Any ideas where I'm going wrong? And if there's a much easier way around this?

Many thanks!

Update:

"Platform" could be slightly confusing. Perhaps "MarketPlace" would be better suited. Although reading it through now, maybe I shouldn't have a third model and just end it at Console.

I just want the final show page to be slightly different if a different Game is selected.

Body:
You could achieve the exact route you want (e.g. www.mysite.com/forza/ps4) using a custom route, like this:

get "/:game/:console", to: "games#show"

In GamesController you could retrieve both parameters and search for the Game you want to display, something like this:

def show
  @console = Console.find_by(name: params[:console])
  @game    = Game.find_by(name: params[:game])
  # ...
end

Keep in mind that this will work consistently only if all of the following conditions are met:

Game model contains unique names (or whatever column you chose to use as slug).

You have no other routes with the same pattern (e.g. /:other/:route).

Game names are different from any model name (unless that model has custom routes to handle the conflict, or not routes at all).

The route is defined at the end of your routes so it won't interfere with other routes.


问:
Updating LINQ to SQL but the query i have is from a join? Can't update using query that uses a join?
I have a query that returns IQueryable, my query consists of join. the end user needs to be able to update certain fields. Rememeber that the fields don't come from 1 table but are the result of 2 joins.

Hence how do i use the data that i returned from my query and change it and update back to the database?

Do i need to do a futher 2 select queries which would obviosly return an LINQ2SQL CLASS so i can then just change the values in the class and then update the database?

I am little confused the best way around this problem.

答:
If there is some way to pass with the grouped query the original LINQ objects, the objects could be updated there and the changes persisted to the database.  Otherwise, no you cannot persist grouped results back to the DB, and would require querying the objects you want to update as you mentioned.

HTH.

ContentLicense: CC BY-SA 2.5


问:
Modelsim - Object not logged & no signal data while simulating verilog clock divider code
What I'm trying to do: I wish to count numbers from 0 to hexadecimal F and display these on my FPGA board at different frequencies - my board's clock (CLOCK_50) is at 50 MHz and I wish to alter the frequency/speed of the counting based on two input switches on my board (SW[1:0]).

Verilog Code for top-module & clock divider module:

```<code>//top level module

module rate_divider (input CLOCK_50, input [1:0] SW, input [1:0] KEY,output [6:0] HEX0);

//Declare parameters that define the # of clock cycles needed to generate an enable pulse
according to the desired frequency.

    parameter FREQ_5MHz = 4'd9; //To divide to 5 MHz we need (10-1) cycles,
                                //since the pulse needs to start at the 9th cycle.
    parameter FULL50_MHz = (4'd1);  //The CLOCK_50's Frequency.

//Select the desired parameter based on the input switches

    reg [3:0] cycles_countdown;
    wire enable_display_count;
    wire [3:0] selected_freq;

    always @(*)
            case (SW)
                2'b00: cycles_countdown = FULL50_MHz;
                2'b01: cycles_countdown = FREQ_5MHz;
                default : cycles_countdown = FULL50_MHz;
            endcase

    assign selected_freq = cycles_countdown;

//wire that is the output of the display_counter and input to the 7 segment

    wire [3:0] hex_value;

// instantiate my other modules

    clock_divider_enable freq_divider (.d(selected_freq), .clk(CLOCK_50), .reset(KEY[0]),
                                                    .enable(enable_display_count));

    display_counter count_hex (.enable(enable_display_count), .clk(CLOCK_50), .hex_out(hex_value), .reset(KEY[1]));

    hex_decoder HX0 (.hex_digit(hex_value), .segments(HEX0[6:0]));

endmodule

//the clock_divider sub-circuit.

module clock_divider_enable (input [3:0] d, input clk, reset,
                                        output enable);

    reg [3:0] q;

    always @(posedge clk)
        begin
            if (!reset || !q)
                q <= d;
            else
                q <= q - 4'd1;
        end

    assign enable = (q == 4'h0) ? 1'b1 : 1'b0;

endmodule
</code>```

ModelSim Code:

```<code>vlib work
vlog rate_divider.v
vsim rate_divider
log {/*}
add wave {/*}

#initial reset - using KEY[1:0]. Note: active low synchronous reset.

force {CLOCK_50} 1
force {KEY[0]} 0
force {KEY[1]} 0
run 10ns

#choose 5 MHz as the desired frequency - turn SW[0] high.

force {CLOCK_50} 0 0ns, 1 {10ns} -r 20ns
force {KEY[0]} 1
force {KEY[1]} 1
force {SW[0]} 1
force {SW[1]} 0
run 600ns
</code>```

Problems I am facing:

Here's the thing - when I don't use the always block to select a parameter, and pass a desired parameter to the wire selected_freq, my simulation works fine - I can see the expected enable pulse.

HOWEVER, if I use the always block, the reg cycles_countdown does get the correct value assigned, BUT for some reason the enable signal is just a red line. When I select my clock_divider_enable module and add it's 'q' signal onto my waveform, it is red too and shows no data, and the object q is "not logged". As such, I'm unable to debug and figure out what exactly the problem with my code is.

It'd be great if someone could help with how to fix the simulation issue rather than just point out the issue with my Verilog code since I want to learn how to use ModelSim efficiently so that in the future debugging will be easier for me.

Equipment Used:

FPGA: Altera De-1-SoC, Cyclone V chip

CAD/Simulation Tools: Altera Quartus II Lite 17.0 + ModelSim Starter Edition

答:
SW wasn't given an initial value, therefore it is high-Z (X if connected to a reg).

I'm guessing when you used the parameter approach you were parameterizing cycles_countdown. Some simulators do not trigger @* at time-0. So if there isn't a change on the senctivity list, then the block may not execute; leaving cycles_countdown as its initial value (4'hX).

Instead of driving your test with TCL commands, you can use create a testbench in with verilog. This testbench should only be used in simulation, not synthesis.

```<code>module rate_devider_tb;
  reg CLOCK_50;
  reg [1:0] SW;
  reg [1:0] KEY;
  wire [6:0] HEX0;

  rate_divider dut( .CLOCK_50(CLOCK_50), .SW(SW), .KEY(KEY), .HEX0(HEX0));

  always begin
    CLOCK_50 = 1'b1;
    #10;
    CLOCK_50 = 1'b0;
    #10;
  end
  initial begin
    // init input signals
    SW <= 2'b01;
    KEY <= 2'b00;

    // Log file reporting
    $monitor("SW:%b KEY:%b HEX0:%h  @ %t", SW, KEY, HEX0, $time);
    // waveform dumping
    $dumpfile("test.vcd");
    $dumpvars(0, rate_devider_tb);

    wait(CLOCK_50 === 1'b0); // initialization x->1 will trigger an posedge
    @(posedge CLOCK_50);
    KEY <= 2'b01; // remove reset after SW was sampled
    #600; // 600ns assuming timescale is in 1ns steps
    $finish();
  end
</code>```

Body:
What I'm trying to do: I wish to count numbers from 0 to hexadecimal F and display these on my FPGA board at different frequencies - my board's clock (CLOCK_50) is at 50 MHz and I wish to alter the frequency/speed of the counting based on two input switches on my board (SW[1:0]).

Verilog Code for top-module & clock divider module:

//top level module

module rate_divider (input CLOCK_50, input [1:0] SW, input [1:0] KEY,output [6:0] HEX0);

//Declare parameters that define the # of clock cycles needed to generate an enable pulse
according to the desired frequency.

    parameter FREQ_5MHz = 4'd9; //To divide to 5 MHz we need (10-1) cycles,
                                //since the pulse needs to start at the 9th cycle.
    parameter FULL50_MHz = (4'd1);  //The CLOCK_50's Frequency.

//Select the desired parameter based on the input switches

    reg [3:0] cycles_countdown;
    wire enable_display_count;
    wire [3:0] selected_freq;

    always @(*)
            case (SW)
                2'b00: cycles_countdown = FULL50_MHz;
                2'b01: cycles_countdown = FREQ_5MHz;
                default : cycles_countdown = FULL50_MHz;
            endcase

    assign selected_freq = cycles_countdown;

//wire that is the output of the display_counter and input to the 7 segment

    wire [3:0] hex_value;

// instantiate my other modules

    clock_divider_enable freq_divider (.d(selected_freq), .clk(CLOCK_50), .reset(KEY[0]),
                                                    .enable(enable_display_count));

    display_counter count_hex (.enable(enable_display_count), .clk(CLOCK_50), .hex_out(hex_value), .reset(KEY[1]));

    hex_decoder HX0 (.hex_digit(hex_value), .segments(HEX0[6:0]));

endmodule

//the clock_divider sub-circuit.

module clock_divider_enable (input [3:0] d, input clk, reset,
                                        output enable);

    reg [3:0] q;

    always @(posedge clk)
        begin
            if (!reset || !q)
                q <= d;
            else
                q <= q - 4'd1;
        end

    assign enable = (q == 4'h0) ? 1'b1 : 1'b0;

endmodule

ModelSim Code:

vlib work
vlog rate_divider.v
vsim rate_divider
log {/*}
add wave {/*}

#initial reset - using KEY[1:0]. Note: active low synchronous reset.

force {CLOCK_50} 1
force {KEY[0]} 0
force {KEY[1]} 0
run 10ns

#choose 5 MHz as the desired frequency - turn SW[0] high.

force {CLOCK_50} 0 0ns, 1 {10ns} -r 20ns
force {KEY[0]} 1
force {KEY[1]} 1
force {SW[0]} 1
force {SW[1]} 0
run 600ns

Problems I am facing:

Here's the thing - when I don't use the always block to select a parameter, and pass a desired parameter to the wire selected_freq, my simulation works fine - I can see the expected enable pulse.

HOWEVER, if I use the always block, the reg cycles_countdown does get the correct value assigned, BUT for some reason the enable signal is just a red line. When I select my clock_divider_enable module and add it's 'q' signal onto my waveform, it is red too and shows no data, and the object q is "not logged". As such, I'm unable to debug and figure out what exactly the problem with my code is.

It'd be great if someone could help with how to fix the simulation issue rather than just point out the issue with my Verilog code since I want to learn how to use ModelSim efficiently so that in the future debugging will be easier for me.

Equipment Used:

FPGA: Altera De-1-SoC, Cyclone V chip

CAD/Simulation Tools: Altera Quartus II Lite 17.0 + ModelSim Starter Edition

Body:
SW wasn't given an initial value, therefore it is high-Z (X if connected to a reg).

I'm guessing when you used the parameter approach you were parameterizing cycles_countdown. Some simulators do not trigger @* at time-0. So if there isn't a change on the senctivity list, then the block may not execute; leaving cycles_countdown as its initial value (4'hX).

Instead of driving your test with TCL commands, you can use create a testbench in with verilog. This testbench should only be used in simulation, not synthesis.

module rate_devider_tb;
  reg CLOCK_50;
  reg [1:0] SW;
  reg [1:0] KEY;
  wire [6:0] HEX0;

  rate_divider dut( .CLOCK_50(CLOCK_50), .SW(SW), .KEY(KEY), .HEX0(HEX0));

  always begin
    CLOCK_50 = 1'b1;
    #10;
    CLOCK_50 = 1'b0;
    #10;
  end
  initial begin
    // init input signals
    SW <= 2'b01;
    KEY <= 2'b00;

    // Log file reporting
    $monitor("SW:%b KEY:%b HEX0:%h  @ %t", SW, KEY, HEX0, $time);
    // waveform dumping
    $dumpfile("test.vcd");
    $dumpvars(0, rate_devider_tb);

    wait(CLOCK_50 === 1'b0); // initialization x->1 will trigger an posedge
    @(posedge CLOCK_50);
    KEY <= 2'b01; // remove reset after SW was sampled
    #600; // 600ns assuming timescale is in 1ns steps
    $finish();
  end


问:
Is it wise to use animations in place of style for some of elements?
Just curious, it doesn't seem to be very smart, but at the same time, what if? Will it be a bad practice or just unnecessary one?

For example, take a div element and describe all its states (including hover and focus and etc) in separated animation file. While in a component file and its html write logic for when implementing each state?

答:
The only question you need to ask yourself is: "Can it be done easily with CSS?"

If the answer is yes, then by all means. Angular binding makes changing style, and animating with CSS, quick and easy. No point adding a dependency to the Angular-Animation module if none are needed.

What Angular-Animation module provide is a way to deal with more complex animations that requires many states or specific events such as when animation ends or begins. You can use the Angular-Animation module to create powerful dynamic animation queuing system by queuing up different states in an array and moving to the next state once an animation as ended for a certain component.

A simple example of that would be a box in the middle of the screen with 4 arrows button at the bottom of the screen that control the box position. Everytime you click a button, it moves the box for 1 second in the direction designated by the button. The problem here is that you want the movement to finish before the box start moving in the next direction selected.

For this, all you have to do is push into an array the new state of the box (Left, Right, Up, Down) everytime you press a button and, using Angular-Animation module, change the state of the box to the first state in the array when both these conditions are met: A) There is a state in the array. B) The current animation has ended.

Angular-Animations module can allow you to make dynamic changes on animation ending or beginning, allowing you to slice the state out of the array at the beginning and applying the new state at the end.


问:
How can I throttle a large array of async workflows passed to Async.Parallel
I have an array holding a large number of small async database queries; for example:

```<code>// I actually have a more complex function that
// accepts name/value pairs for query parameters.
let runSql connString sql = async {
    use connection = new SqlConnection(connString)
    use command = new SqlCommand(sql, connection)
    do! connection.OpenAsync() |> Async.AwaitIAsyncResult |> Async.Ignore
    return! command.ExecuteScalarAsync() |> Async.AwaitTask
    }

let getName (id:Guid) = async {
    // I actually use a parameterized query
    let querySql = "SELECT Name FROM Entities WHERE ID = '" + id.ToString() + "'"
    return! runSql connectionString querySql
    }

let ids : Guid array = getSixtyThousandIds()

let asyncWorkflows = ids |> Array.map getName
//...
</code>```

Now, the problem: The next expression runs all 60K workflows at once, flooding the server.  This leads to many of the SqlCommands timing out; it also typically causes out of memory exceptions in the client (which is F# interactive) for reasons I do not understand and (not needing to understand them) have not investigated:

```<code>//...
let names =
    asyncWorkflows
    |> Async.Parallel
    |> Async.RunSynchronously
</code>```

I've written a rough-and-ready function to batch the requests:

```<code>let batch batchSize asyncs = async {
    let batches = asyncs
                  |> Seq.mapi (fun i a -> i, a)
                  |> Seq.groupBy (fst >> fun n -> n / batchSize)
                  |> Seq.map (snd >> Seq.map snd)
                  |> Seq.map Async.Parallel
    let results = ref []
    for batch in batches do
        let! result = batch
        results := (result :: !results)
    return (!results |> List.rev |> Seq.collect id |> Array.ofSeq)
}
</code>```

To use this function, I replace Async.Parallel with batch 20 (or another integer value):

```<code>let names =
    asyncWorkflows
    |> batch 20
    |> Async.RunSynchronously
</code>```

This works reasonably well, but I would prefer to have a system that starts each new async as soon as one completes, so rather than successive batches of size N starting after each previous batch of size N has finished, I am always awaiting N active SqlCommands (until I get to the end, of course).

Questions:

Am I reinventing the wheel?  In other words, are there library functions that do this already?  (Would it be profitable to look into exploiting ParallelEnumerable.WithDegreeOfParallelism somehow?)

If not, how should I implement a continuous queue instead of a series of discrete batches?

I am not primarily seeking suggestions to improve the existing code, but such suggestions will nonetheless be received with interest and gratitude.

答: FSharpx.Control offers an Async.ParallelWithThrottle function. I'm not sure if it is the best implementation as it uses SemaphoreSlim. But the ease of use is great and since my application doesn't need top performance it works well enough for me. Although since it is a library if someone knows how to make it better it is always a nice thing to make libraries top performers out of the box so the rest of us can just use the code that works and just get our work done!

Body:
I have an array holding a large number of small async database queries; for example:

// I actually have a more complex function that
// accepts name/value pairs for query parameters.
let runSql connString sql = async {
    use connection = new SqlConnection(connString)
    use command = new SqlCommand(sql, connection)
    do! connection.OpenAsync() |> Async.AwaitIAsyncResult |> Async.Ignore
    return! command.ExecuteScalarAsync() |> Async.AwaitTask
    }

let getName (id:Guid) = async {
    // I actually use a parameterized query
    let querySql = "SELECT Name FROM Entities WHERE ID = '" + id.ToString() + "'"
    return! runSql connectionString querySql
    }

let ids : Guid array = getSixtyThousandIds()

let asyncWorkflows = ids |> Array.map getName
//...

Now, the problem: The next expression runs all 60K workflows at once, flooding the server.  This leads to many of the SqlCommands timing out; it also typically causes out of memory exceptions in the client (which is F# interactive) for reasons I do not understand and (not needing to understand them) have not investigated:

//...
let names =
    asyncWorkflows
    |> Async.Parallel
    |> Async.RunSynchronously

I've written a rough-and-ready function to batch the requests:

let batch batchSize asyncs = async {
    let batches = asyncs
                  |> Seq.mapi (fun i a -> i, a)
                  |> Seq.groupBy (fst >> fun n -> n / batchSize)
                  |> Seq.map (snd >> Seq.map snd)
                  |> Seq.map Async.Parallel
    let results = ref []
    for batch in batches do
        let! result = batch
        results := (result :: !results)
    return (!results |> List.rev |> Seq.collect id |> Array.ofSeq)
}

To use this function, I replace Async.Parallel with batch 20 (or another integer value):

let names =
    asyncWorkflows
    |> batch 20
    |> Async.RunSynchronously

This works reasonably well, but I would prefer to have a system that starts each new async as soon as one completes, so rather than successive batches of size N starting after each previous batch of size N has finished, I am always awaiting N active SqlCommands (until I get to the end, of course).

Questions:

Am I reinventing the wheel?  In other words, are there library functions that do this already?  (Would it be profitable to look into exploiting ParallelEnumerable.WithDegreeOfParallelism somehow?)

If not, how should I implement a continuous queue instead of a series of discrete batches?

I am not primarily seeking suggestions to improve the existing code, but such suggestions will nonetheless be received with interest and gratitude.


问:
Assign Column Name for Simple Coalesce Statement
While attempting to create a list of all ID's made since _____ I am able to get the results I want from the following:

```<code>DECLARE @BoID varchar(max)

SELECT @BoID = COALESCE(@BoID + ', ', '') +
   CAST(ApplicationID AS varchar(10))
FROM BoList as "ID"
WHERE CreatedDate > '2017-07-01 18:14:09.210'
</code>```

However, I am having issues with establishing a column name for the above statement. Where does the as "ID" need to be located at in order to give the above result a column name of "ID"?

答:
As the query stands now, you are giving the table BoList an alias of "ID" instead of the column.  Since you are selecting the value into a variable there is no output.  You can do it like this...

```<code>SELECT COALESCE(@BoID + ', ', '') +
   CAST(ApplicationID AS varchar(10)) as "ID"
FROM BoList
WHERE CreatedDate > '2017-07-01 18:14:09.210'
</code>```

Or if you really do need to stash the value in a variable to return later as part of another query...

```<code>DECLARE @BoID varchar(max)

SELECT @BoID = COALESCE(@BoID + ', ', '') +
   CAST(ApplicationID AS varchar(10))
FROM BoList
WHERE CreatedDate > '2017-07-01 18:14:09.210'

SELECT @BoID AS "ID", other columns... FROM whatever
</code>```

Body:
While attempting to create a list of all ID's made since _____ I am able to get the results I want from the following:

DECLARE @BoID varchar(max)

SELECT @BoID = COALESCE(@BoID + ', ', '') +
   CAST(ApplicationID AS varchar(10))
FROM BoList as "ID"
WHERE CreatedDate > '2017-07-01 18:14:09.210'

However, I am having issues with establishing a column name for the above statement. Where does the as "ID" need to be located at in order to give the above result a column name of "ID"?

Body:
As the query stands now, you are giving the table BoList an alias of "ID" instead of the column.  Since you are selecting the value into a variable there is no output.  You can do it like this...

SELECT COALESCE(@BoID + ', ', '') +
   CAST(ApplicationID AS varchar(10)) as "ID"
FROM BoList
WHERE CreatedDate > '2017-07-01 18:14:09.210'

Or if you really do need to stash the value in a variable to return later as part of another query...

DECLARE @BoID varchar(max)

SELECT @BoID = COALESCE(@BoID + ', ', '') +
   CAST(ApplicationID AS varchar(10))
FROM BoList
WHERE CreatedDate > '2017-07-01 18:14:09.210'

SELECT @BoID AS "ID", other columns... FROM whatever


问:
Creation of PDF file using itextSharp
Hi
 I am creating an ASP.net website where some articles can be uploaded. I need that my users can get PDF version of it by clicking on a button. For this functionality I am using itextSharp.
    I am considering the following two options.
1. I will create the PDF file once(on first request) and reuse it always by checking for the existence of it.
2. I will create it on the fly and delete it as soon as the PDF file is delivered to the client.
The first approach will lead to faster PDF delivery where as the second approach will lead to saving space. Can anyone please tell me which of the options is better?

I am also wondering if this can be possible without saving the PDF on the server in the first place. So can anyone reply me as soon as possible.

Thanks
Dipa

答:
You can definitely create the PDF on the fly without writing it to disk. Instead of using a FileStream use a MemoryString:

```<code>        'PDF Document'
        Dim document As New Document(PageSize.LETTER)
        'Use a memory string so we don't need to write to disk
        Using outputStream As New MemoryStream()
            'Associate the PDF with the stream
            Dim w = PdfWriter.GetInstance(document, outputStream)

            'Open the PDF for writing'
            document.Open()

            'Do PDF stuff Here'

            'Close the PDF'
            document.Close()
            'Clear the response buffer'
            Response.Clear()
            'Set the output type as a PDF'
            Response.ContentType = "application/pdf"
            'Disable caching'
            Response.AddHeader("Expires", "0")
            Response.AddHeader("Cache-Control", "")
            'Set the filename'
            Response.AddHeader("Content-Disposition", "attachment; filename=" & OutputFileName)
            'Set the length of the file so the browser can display an accurate progress bar'
            Response.AddHeader("Content-length", outputStream.GetBuffer().Length.ToString())
            'Write the contents of the memory stream'
            Response.OutputStream.Write(outputStream.GetBuffer(), 0, outputStream.GetBuffer().Length)
            'Close the response stream'
            Response.End()

        End Using
</code>```

iTextSharp is very, very fast for me. I'm on a shared host and I can generate fairly complex PDFs of dozens of pages without noticing any sluggishness.

EDIT
Here's the code converted using the VB.Net to C# converter. I haven't tested it and you might have to clean up a couple of things but it should be pretty straight forward.

```<code>Document document = new Document(PageSize.LETTER);
//Use a memory string so we don't need to write to disk
using (MemoryStream outputStream = new MemoryStream()) {
    //Associate the PDF with the stream
    dynamic w = PdfWriter.GetInstance(document, outputStream);

    //Open the PDF for writing'
    document.Open();

    //Do PDF stuff Here'

    //Close the PDF'
    document.Close();
    //Clear the response buffer'
    Response.Clear();
    //Set the output type as a PDF'
    Response.ContentType = "application/pdf";
    //Disable caching'
    Response.AddHeader("Expires", "0");
    Response.AddHeader("Cache-Control", "");
    //Set the filename'
    Response.AddHeader("Content-Disposition", "attachment; filename=" + OutputFileName);
    //Set the length of the file so the browser can display an accurate progress bar'
    Response.AddHeader("Content-length", outputStream.GetBuffer().Length.ToString());
    //Write the contents of the memory stream'
    Response.OutputStream.Write(outputStream.GetBuffer(), 0, outputStream.GetBuffer().Length);
    //Close the response stream'
    Response.End();

}
</code>```

To open a PDF in a new window have your link button point to a page such as "CreatePDF.aspx". That page should have this code in it.

Title: Creation of PDF file using itextSharp

Body:
You can definitely create the PDF on the fly without writing it to disk. Instead of using a FileStream use a MemoryString:

        'PDF Document'
        Dim document As New Document(PageSize.LETTER)
        'Use a memory string so we don't need to write to disk
        Using outputStream As New MemoryStream()
            'Associate the PDF with the stream
            Dim w = PdfWriter.GetInstance(document, outputStream)

            'Open the PDF for writing'
            document.Open()

            'Do PDF stuff Here'

            'Close the PDF'
            document.Close()
            'Clear the response buffer'
            Response.Clear()
            'Set the output type as a PDF'
            Response.ContentType = "application/pdf"
            'Disable caching'
            Response.AddHeader("Expires", "0")
            Response.AddHeader("Cache-Control", "")
            'Set the filename'
            Response.AddHeader("Content-Disposition", "attachment; filename=" & OutputFileName)
            'Set the length of the file so the browser can display an accurate progress bar'
            Response.AddHeader("Content-length", outputStream.GetBuffer().Length.ToString())
            'Write the contents of the memory stream'
            Response.OutputStream.Write(outputStream.GetBuffer(), 0, outputStream.GetBuffer().Length)
            'Close the response stream'
            Response.End()

        End Using

iTextSharp is very, very fast for me. I'm on a shared host and I can generate fairly complex PDFs of dozens of pages without noticing any sluggishness.

EDIT
Here's the code converted using the VB.Net to C# converter. I haven't tested it and you might have to clean up a couple of things but it should be pretty straight forward.

Document document = new Document(PageSize.LETTER);
//Use a memory string so we don't need to write to disk
using (MemoryStream outputStream = new MemoryStream()) {
    //Associate the PDF with the stream
    dynamic w = PdfWriter.GetInstance(document, outputStream);

    //Open the PDF for writing'
    document.Open();

    //Do PDF stuff Here'

    //Close the PDF'
    document.Close();
    //Clear the response buffer'
    Response.Clear();
    //Set the output type as a PDF'
    Response.ContentType = "application/pdf";
    //Disable caching'
    Response.AddHeader("Expires", "0");
    Response.AddHeader("Cache-Control", "");
    //Set the filename'
    Response.AddHeader("Content-Disposition", "attachment; filename=" + OutputFileName);
    //Set the length of the file so the browser can display an accurate progress bar'
    Response.AddHeader("Content-length", outputStream.GetBuffer().Length.ToString());
    //Write the contents of the memory stream'
    Response.OutputStream.Write(outputStream.GetBuffer(), 0, outputStream.GetBuffer().Length);
    //Close the response stream'
    Response.End();

}

To open a PDF in a new window have your link button point to a page such as "CreatePDF.aspx". That page should have this code in it.


问:
Proper disposal of powershell pipeline objects
This script snippet is accessing a SharePoint site (web) within a function. It creates a SPWeb object that should get disposed of by the end of the function to avoid a memory leak. Usually the way to dispose of an object is something like $web.dispose(). In this case the SPWeb object is created and used in a pipeline but doesn't have a name.

Here is the code:

```<code>function foobar {
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" |
         ForEach-Object {$_.Lists | Where {$_.Title -EQ "someLibrary"} |
         Select ID }
}
</code>```

I suspect that the SPWeb object is not automatically disposed of at the end of the pipeline and is causing a memory leak.

How do I dispose of objects created in a pipeline? Do I even need to?

FYI: $x does not have a method named 'Dispose', so $x.Dispose() does not work.

答:
More in keeping with PowerShell vernacular is to maintain the pipeline by using Start-SPAssignment and Stop-SPAssignment, eg

```<code>function foobar {
    $assig = Start-SPAssignment
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" -AssignmentCollection $assign |
         ForEach-Object {$_.Lists | Where {$_.Title -EQ "someLibrary"} |
         Select ID }
    Stop-SPAssignment $assign
}
</code>```

This is only an illustration not a verified code sample as I don't have a SharePoint server handy at the moment to test it, but it gives you the idea. If I get a chance I'll test it and edit my answer accordingly.

A further refinement is to collapse the ForEach into the pipeline

```<code>function foobar {
    $assig = Start-SPAssignment
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" -AssignmentCollection $assign |
         Select-Object -ExpandProperty Lists |
         Where {$_.Title -EQ "someLibrary"} |
         Select ID
    Stop-SPAssignment $assign
}
</code>```

Once again only an illustration not a verified code sample.

The following blog post gives a good tutorial on the assignment object, PowerShell, SharePoint and Memory Leaks (Start-SPAssignment).

Body:
This script snippet is accessing a SharePoint site (web) within a function. It creates a SPWeb object that should get disposed of by the end of the function to avoid a memory leak. Usually the way to dispose of an object is something like $web.dispose(). In this case the SPWeb object is created and used in a pipeline but doesn't have a name.

Here is the code:

function foobar {
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" |
         ForEach-Object {$_.Lists | Where {$_.Title -EQ "someLibrary"} |
         Select ID }
}

I suspect that the SPWeb object is not automatically disposed of at the end of the pipeline and is causing a memory leak.

How do I dispose of objects created in a pipeline? Do I even need to?

FYI: $x does not have a method named 'Dispose', so $x.Dispose() does not work.

Body:
More in keeping with PowerShell vernacular is to maintain the pipeline by using Start-SPAssignment and Stop-SPAssignment, eg

function foobar {
    $assig = Start-SPAssignment
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" -AssignmentCollection $assign |
         ForEach-Object {$_.Lists | Where {$_.Title -EQ "someLibrary"} |
         Select ID }
    Stop-SPAssignment $assign
}

This is only an illustration not a verified code sample as I don't have a SharePoint server handy at the moment to test it, but it gives you the idea. If I get a chance I'll test it and edit my answer accordingly.

A further refinement is to collapse the ForEach into the pipeline

function foobar {
    $assig = Start-SPAssignment
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" -AssignmentCollection $assign |
         Select-Object -ExpandProperty Lists |
         Where {$_.Title -EQ "someLibrary"} |
         Select ID
    Stop-SPAssignment $assign
}

Once again only an illustration not a verified code sample.

The following blog post gives a good tutorial on the assignment object, PowerShell, SharePoint and Memory Leaks (Start-SPAssignment).


问:
PostgresQL Foreign Key Syntax Error
When attempting to create the second table in this respective database, I'm getting the following error message:

```<code>ERROR:  syntax error at or near "REFERENCES"
LINE 3: master_directory REFERENCES auth_table (directory),
</code>```

Here's the database structure that I attempted to create:

```<code>CREATE TABLE auth_table (
id SERIAL PRIMARY KEY,
directory VARCHAR,
image VARCHAR
)

CREATE TABLE master_table (
id SERIAL PRIMARY KEY,
master_directory references auth_table (directory),
master_image references auth_table (image)
)
</code>```

Any reason why I'm receiving that error? Any help would be appreciated!

答:
You've left the data type off, but that syntax error is the least of your problems.

Your foreign key references need to refer to unique column(s). So "auth_table" probably needs to be declared one of these ways. (And you probably want the second one, if your table has something to do with the paths to files.)

```<code>CREATE TABLE auth_table (
  id SERIAL PRIMARY KEY,
  directory VARCHAR not null unique,
  image VARCHAR not null unique
);

CREATE TABLE auth_table (
  id SERIAL PRIMARY KEY,
  directory VARCHAR not null,
  image VARCHAR not null,
  unique (directory, image)
);
</code>```

Those unique constraints mean quite different things, and each requires a different foreign key reference. Assuming that you want to declare "auth_table" the second way, "master_table" probably ought to be declared like one of these. (Deliberately ignoring cascading updates and deletes.)

```<code>CREATE TABLE master_table (
  master_directory varchar not null,
  master_image varchar not null,
  primary key (master_directory, master_image),
  foreign key (master_directory, master_image)
    references auth_table (directory, image)
);

CREATE TABLE master_table (
  id integer primary key,
  foreign key (id) references auth_table (id)
);
</code>```

Title: PostgresQL Foreign Key Syntax Error

Body:
When attempting to create the second table in this respective database, I'm getting the following error message:

ERROR:  syntax error at or near "REFERENCES"
LINE 3: master_directory REFERENCES auth_table (directory),

Here's the database structure that I attempted to create:

CREATE TABLE auth_table (
id SERIAL PRIMARY KEY,
directory VARCHAR,
image VARCHAR
)

CREATE TABLE master_table (
id SERIAL PRIMARY KEY,
master_directory references auth_table (directory),
master_image references auth_table (image)
)

Any reason why I'm receiving that error? Any help would be appreciated!

Body:
You've left the data type off, but that syntax error is the least of your problems.

Your foreign key references need to refer to unique column(s). So "auth_table" probably needs to be declared one of these ways. (And you probably want the second one, if your table has something to do with the paths to files.)

CREATE TABLE auth_table (
  id SERIAL PRIMARY KEY,
  directory VARCHAR not null unique,
  image VARCHAR not null unique
);

CREATE TABLE auth_table (
  id SERIAL PRIMARY KEY,
  directory VARCHAR not null,
  image VARCHAR not null,
  unique (directory, image)
);

Those unique constraints mean quite different things, and each requires a different foreign key reference. Assuming that you want to declare "auth_table" the second way, "master_table" probably ought to be declared like one of these. (Deliberately ignoring cascading updates and deletes.)

CREATE TABLE master_table (
  master_directory varchar not null,
  master_image varchar not null,
  primary key (master_directory, master_image),
  foreign key (master_directory, master_image)
    references auth_table (directory, image)
);

CREATE TABLE master_table (
  id integer primary key,
  foreign key (id) references auth_table (id)
);


问:
Transaction isolation - INSERTS dependant on previous records values
This question is related/came from discussion about another thing:
What is the correct isolation level for Order header - Order lines transactions?

Imagine scenario where we have usual Orders_Headers and Orders_LineItems tables. Lets say also that we have a special business rules that say:

Each order has Discount field which is calculated based on time passed from last order entered

Each next order Discount field is calculated specially if there has been more than X order in last Y hours.

Each next order Discount field is calculated specially if average frequency of last 10 orders was higher than x per minute.

Each next order Discount field is calculated specially

Point here is to show that every Order is dependant on previous ones and isolation level is crucial.

We have a transaction (just logic of the code shown):

```<code>BEGIN TRANSACTION

INSERT INTO Order_Headers...

SET @Id = SCOPE_IDENTITY()

INSERT INTO Order_LineItems...(using @Id)

DECLARE @SomeVar INT

--just example to show selecting previous x orders
--needed to calculate Discount value for new Order
SELECT @SomeVar = COUNT(*) Order_Headers
WHERE ArbitraryCriteria

UPDATE Order_Headers
SET Discount= UDF(@SomeVar)
WHERE Id = @Id

COMMIT

END TRANSACTION
</code>```

We also have another transaction to read orders:

```<code>SELECT TOP 10 * FROM Order_Headers
ORDER BY Id DESC
</code>```

QUESTIONS

Is SNAPSHOT isolation level for first transaction and READ COMMITED for second appropriate levels?

Is there a better way of approaching CREATE/UPDATE transaction or is this the way to do it?

答:
The problem with snapshot is not about inserting/reading (which i assume you decided to use). Its about updates, that you should be a concerned.

Snapshot isolation levels are using row versioning. Which means any time you insert/update/delete row, those rows get duplicated in tempdb(version store, location for those kinds of rows), and increase its size by 14 bytes with a versioning tag so that your newly started transaction can read a row from the last committed transaction. Keep in mind that these resized rows will stay as they are until you rebuild the index.

This should be an indicator ,that if your table is really busy, your indexes will be defragmented much faster and it will add certain amount of % overhead on your temp.So keep that in mind.

What is even bigger concern here are updates, as i mentioned.

Any time you insert/delete/update row, you will get exclusive locks on those rows (object later),and since you snapshot is using row versioning, inserts from another transaction are adding exclusive locks on a NEW row, and that is not a problem.However if you try to update an existing row and session 2 tries to acquire X lock on that row, it will fail because session 1 already has X lock on it, and this is where you will get this message:

Read Committed and Serializable have covered these issues well, so you might wanna take that approach and test all solutions before you actually implement it. Remember all transactions will cause blocking on updates, and snapshot/read comitted snapshot will simply fail.

Me personally would`ve used read committed snapshot and altered procedure , to rerun in catch block N amount of times, but hey that has flaws as well !

Body:
This question is related/came from discussion about another thing:
What is the correct isolation level for Order header - Order lines transactions?

Imagine scenario where we have usual Orders_Headers and Orders_LineItems tables. Lets say also that we have a special business rules that say:

Each order has Discount field which is calculated based on time passed from last order entered

Each next order Discount field is calculated specially if there has been more than X order in last Y hours.

Each next order Discount field is calculated specially if average frequency of last 10 orders was higher than x per minute.

Each next order Discount field is calculated specially

Point here is to show that every Order is dependant on previous ones and isolation level is crucial.

We have a transaction (just logic of the code shown):

BEGIN TRANSACTION

INSERT INTO Order_Headers...

SET @Id = SCOPE_IDENTITY()

INSERT INTO Order_LineItems...(using @Id)

DECLARE @SomeVar INT

--just example to show selecting previous x orders
--needed to calculate Discount value for new Order
SELECT @SomeVar = COUNT(*) Order_Headers
WHERE ArbitraryCriteria

UPDATE Order_Headers
SET Discount= UDF(@SomeVar)
WHERE Id = @Id

COMMIT

END TRANSACTION

We also have another transaction to read orders:

SELECT TOP 10 * FROM Order_Headers
ORDER BY Id DESC

QUESTIONS

Is SNAPSHOT isolation level for first transaction and READ COMMITED for second appropriate levels?

Is there a better way of approaching CREATE/UPDATE transaction or is this the way to do it?


问:
How to add md-switch to angular 4
i want to add md-switch from AngularJS Material to my angular4 project, but i'm getting the following error:

```<code>Uncaught Error: Template parse errors:
'md-switch' is not a known element:
1. If 'md-switch' is an Angular component, then verify that it is part of this module.
2. If 'md-switch' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message
</code>```

===============================

UPDATE

test.component.html:

```<code><md-slide-toggle>Slide me!</md-slide-toggle>
</code>```

test.component.ts:

```<code>@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
</code>```

test.module.ts

```<code>import { MaterialModule, MdButtonModule, MdSlideToggleModule} from '@angular/material';
import { NgModule } from '@angular/core';
import { TestComponent } from './test.component';

@NgModule({
  declarations: [
    TestComponent
  ],
  imports: [
    MaterialModule, MdSlideToggleModule,
  ],
})
export class TestModule { }
</code>```

package.json

```<code>{
  "name": "web-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.7",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.3",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}
</code>```

What am i missing?

答:
First of all angularjs material is not compatible with angular 4  instead use angular material 2. And before adding angular material ,Check this issue:

https://github.com/angular/material2/issues/4137

Treeshaking is not happening in angular material. Even if you use one module it will import everything and it will increase your build size, hence decrease the performance. So, I would recommend to either use any other library or write your own custom css.

Some of the material libraires that you can use are:

Prime NG

Md2 by promact

Title: How to add md-switch to angular 4

Body:
i want to add md-switch from AngularJS Material to my angular4 project, but i'm getting the following error:

Uncaught Error: Template parse errors:
'md-switch' is not a known element:
1. If 'md-switch' is an Angular component, then verify that it is part of this module.
2. If 'md-switch' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message

===============================

UPDATE

test.component.html:

<md-slide-toggle>Slide me!</md-slide-toggle>

test.component.ts:

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})

test.module.ts

import { MaterialModule, MdButtonModule, MdSlideToggleModule} from '@angular/material';
import { NgModule } from '@angular/core';
import { TestComponent } from './test.component';

@NgModule({
  declarations: [
    TestComponent
  ],
  imports: [
    MaterialModule, MdSlideToggleModule,
  ],
})
export class TestModule { }

package.json

{
  "name": "web-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.7",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.3",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

What am i missing?


问:
WPF How To Bind Two Nested Usercontrols
I need to bind a user control data context with other control property :

```<code>    <StackPanel>
        <custom:UserControl1 x:Name="UC1"/>
    </StackPanel>

    <StackPanel>
        <custom:UserControl2 DataContext="{Binding ElementName=UC1, Path=MySelectedValue}"/>
    </StackPanel>
</code>```

Of course i have implemented a dependency property 'MySelectedValue' on UserControl1.
The following does not work. I guess because it searches the ElementName on the visual tree and could not find it because both controls are parallel nested.

How could i get the above to work?

Thanks,

答: How did you define the MySelectedValue DependencyProperty (is it set to BindsTwoWayByDefault)?</p>

Title: WPF How To Bind Two Nested Usercontrols

Body:
I need to bind a user control data context with other control property :

    <StackPanel>
        <custom:UserControl1 x:Name="UC1"/>
    </StackPanel>

    <StackPanel>
        <custom:UserControl2 DataContext="{Binding ElementName=UC1, Path=MySelectedValue}"/>
    </StackPanel>

Of course i have implemented a dependency property 'MySelectedValue' on UserControl1.
The following does not work. I guess because it searches the ElementName on the visual tree and could not find it because both controls are parallel nested.

How could i get the above to work?

Thanks,


问:
Selecting top of word document using VBA
I am using excel VBA to populate data onto a word template from an excel spreadsheet. The problem I am having is selecting the top of the word document so the information goes into the right spot.

I have tried using Selection.HomeKey wd:=Story and Selection.MoveUp Unit:=wdScreen, count:=1 both with no success as I am consistently getting

runtime error 4120

答:
Please try

```<code>ActiveDocument.Bookmarks("\StartOfDoc").Select
</code>```

It makes use of a pre-defined, implicit bookmark to take you to the beginning of the document.

I just tested in Word 2016 and it works.

Body:
Please try

ActiveDocument.Bookmarks("\StartOfDoc").Select

It makes use of a pre-defined, implicit bookmark to take you to the beginning of the document.

I just tested in Word 2016 and it works.


问:
"Throttled" async download in F#
I'm trying to download the 3000+ photos referenced from the xml backup of my blog. The problem I came across is that if just one of those photos is no longer available, the whole async gets blocked because AsyncGetResponse doesn't do timeouts.

ildjarn helped me to put together a version of AsyncGetResponse which does fail on timeout, but using that gives a lot more timeouts - as though requests that are just queued timeout. It seems like all the WebRequests are launched 'immediately', the only way to make it work is to set the timeout to the time required to download all of them combined: which isn't great because it means I have adjust the timeout depending on the number of images.

Have I reached the limits of vanilla async? Should I be looking at reactive extensions instead?

This is a bit embarassing, because I've already asked two questions here on this particular bit of code, and I still haven't got it working the way I want!

答:
Here's an out of the box solution:

FSharpx.Control offers an Async.ParallelWithThrottle function. I'm not sure if it is the best implementation as it uses SemaphoreSlim. But the ease of use is great and since my application doesn't need top performance it works well enough for me. Although since it is a library if someone knows how to make it better it is always a nice thing to make libraries top performers out of the box so the rest of us can just use the code that works and just get our work done!

Title: "Throttled" async download in F#


问:
output differences between 2 texts when lines are dissimilar
I am relatively new to Python so apologies in advance for sounding a bit ditzy sometimes. I'll try took google and attempt your tips as much as I can before asking even more questions.
Here is my situation: I am working with R and stylometry to find out the (likely) authorship of a text. What I'd like to do is see if there is a difference in the stylometry of a novel in the second edition, after one of the (assumed) co-authors died and therefore could not have contributed. In order to research that I need

Text edition 1

Text edition 2

and for python to output

words that appear in text 1 but not in text 2

words that appear in text 2 but not in text 1

And I would like to have the words each time they appear so not just 'the' once, but every time the program encounters it when it differs from the first edition (yep I know I'm asking for a lot sorry)

I have tried approaching this via

```<code>file1 = open("FRANKENST18.txt", "r")
file2 = open("FRANKENST31.txt", "r")
file3 = open("frankoutput.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1:
    for j in list2:
        if  i==j:
            file3.write(i)
</code>```

but of course this doesn't work because the texts are two giant balls of texts and not separate lines that can be compared, plus the first text has far more lines than the second one. Is there a way to go from lines to 'words' or the text in general to overcome that? Can I put an entire novel in a string lol? I assume not.
I have also attempted to use difflib, but I've only started coding a few weeks ago and I find it quite complicated. For example, I used fraxel's script as a base for:

```<code>from difflib import Differ

s1 = open("FRANKENST18.txt", "r")
s1 = open("FRANKENST31.txt", "r")

def appendBoldChanges(s1, s2):
#"Adds <b></b> tags to words that are changed"
    l1 = s1.split(' ')
    l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join(['<b>'+i[2:]+'</b>' if i[:1] == '+' else i[2:] for i in dif
                                                       if not i[:1] in '-?'])

print appendBoldChanges
</code>```

but I couldn't get it to work.

So my question is is there any way to output the differences between texts that are not similar in lines like this? It sounded quite do-able but I've greatly underestimated how difficult I found Python haha.
Thanks for reading, any help is appreciated!

EDIT: posting my current code just in case it might help fellow learners that are googling for answers:

```<code>file1 = open("1stein.txt")
originaltext1 = file1.read()
wordlist1={}

import string
text1 = [x.strip(string.punctuation) for x in originaltext1.split()]
text1 = [x.lower() for x in text1]

for word1 in text1:
    if word1 not in wordlist1:
        wordlist1[word1] = 1
    else:
        wordlist1[word1] += 1

for k,v in sorted(wordlist1.items()):
    #print "%s %s" % (k, v)
    col1 = ("%s %s" % (k, v))
    print col1

file2 = open("2stein.txt")
originaltext2 = file2.read()
wordlist2={}

import string
text2 = [x.strip(string.punctuation) for x in originaltext2.split()]
text2 = [x.lower() for x in text2]

for word2 in text2:
    if word2 not in wordlist2:
        wordlist2[word2] = 1
    else:
        wordlist2[word2] += 1

for k,v in sorted(wordlist2.items()):
    #print "%s %s" % (k, v)
    col2 = ("%s %s" % (k, v))
    print col2
</code>```

what I hope still to edit and output is something like this:
using the dictionaries' key and value system (applied to col1 and col2): {apple 3, bridge 7, chair 5} - {apple 1, bridge 9, chair 5} = {apple 2, bridge -2, chair 5}?

答:
Let me know if this isn't exactly what you're looking for, but it seems like you want to iterate through lines of a file, which you can do very easily in python. Here's an example, where I omit the newline character at the end of each line, and add the lines to a list:

```<code>f = open("filename.txt", 'r')
lines = []
for line in f:
    lines.append(f[:-1])
</code>```

Hope this helps!

Body:
I am relatively new to Python so apologies in advance for sounding a bit ditzy sometimes. I'll try took google and attempt your tips as much as I can before asking even more questions.
Here is my situation: I am working with R and stylometry to find out the (likely) authorship of a text. What I'd like to do is see if there is a difference in the stylometry of a novel in the second edition, after one of the (assumed) co-authors died and therefore could not have contributed. In order to research that I need

Text edition 1

Text edition 2

and for python to output

words that appear in text 1 but not in text 2

words that appear in text 2 but not in text 1

And I would like to have the words each time they appear so not just 'the' once, but every time the program encounters it when it differs from the first edition (yep I know I'm asking for a lot sorry)

I have tried approaching this via

file1 = open("FRANKENST18.txt", "r")
file2 = open("FRANKENST31.txt", "r")
file3 = open("frankoutput.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1:
    for j in list2:
        if  i==j:
            file3.write(i)

but of course this doesn't work because the texts are two giant balls of texts and not separate lines that can be compared, plus the first text has far more lines than the second one. Is there a way to go from lines to 'words' or the text in general to overcome that? Can I put an entire novel in a string lol? I assume not.
I have also attempted to use difflib, but I've only started coding a few weeks ago and I find it quite complicated. For example, I used fraxel's script as a base for:

from difflib import Differ

s1 = open("FRANKENST18.txt", "r")
s1 = open("FRANKENST31.txt", "r")

def appendBoldChanges(s1, s2):
#"Adds  tags to words that are changed"
    l1 = s1.split(' ')
    l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join([''+i[2:]+'' if i[:1] == '+' else i[2:] for i in dif
                                                       if not i[:1] in '-?'])

print appendBoldChanges

but I couldn't get it to work.

So my question is is there any way to output the differences between texts that are not similar in lines like this? It sounded quite do-able but I've greatly underestimated how difficult I found Python haha.
Thanks for reading, any help is appreciated!

EDIT: posting my current code just in case it might help fellow learners that are googling for answers:

file1 = open("1stein.txt")
originaltext1 = file1.read()
wordlist1={}

import string
text1 = [x.strip(string.punctuation) for x in originaltext1.split()]
text1 = [x.lower() for x in text1]

for word1 in text1:
    if word1 not in wordlist1:
        wordlist1[word1] = 1
    else:
        wordlist1[word1] += 1

for k,v in sorted(wordlist1.items()):
    #print "%s %s" % (k, v)
    col1 = ("%s %s" % (k, v))
    print col1

file2 = open("2stein.txt")
originaltext2 = file2.read()
wordlist2={}

import string
text2 = [x.strip(string.punctuation) for x in originaltext2.split()]
text2 = [x.lower() for x in text2]

for word2 in text2:
    if word2 not in wordlist2:
        wordlist2[word2] = 1
    else:
        wordlist2[word2] += 1

for k,v in sorted(wordlist2.items()):
    #print "%s %s" % (k, v)
    col2 = ("%s %s" % (k, v))
    print col2

what I hope still to edit and output is something like this:
using the dictionaries' key and value system (applied to col1 and col2): {apple 3, bridge 7, chair 5} - {apple 1, bridge 9, chair 5} = {apple 2, bridge -2, chair 5}?

Body:
Let me know if this isn't exactly what you're looking for, but it seems like you want to iterate through lines of a file, which you can do very easily in python. Here's an example, where I omit the newline character at the end of each line, and add the lines to a list:

f = open("filename.txt", 'r')
lines = []
for line in f:
    lines.append(f[:-1])

Hope this helps!


问:
Unbind - Remove - Kill a jQuery plugin
Is there a way to "unbind" a jQuery plugin from a jquery selector?</p>

Title: Unbind - Remove - Kill a jQuery plugin

Body: $("#selector").unbind().removeData();


问:
How big can an Angular single-page-app grow?
I have been developing a quite big web based application, using Angular 1.5.x and, amongst others, the awesome module ui.route, in order to simpify the single page application approach. I get all my stuff from a backend API, using RestAngular. Works really neat - so far. Not really that many 3rd party module beyond that, apart from ui.tree and momentjs.

My concerns are: how well will this work IRL? In some parts of the app, I have recordsets of around 1000 items. In other parts (meaning: different controllers in different modules) I have to add watchers for certain conditions to kick in. I have around 10 directives I use across the app. Every single part is its own module, controller and/or service, external html files as templates for the different routes. And a websockets connection that listens to incoming messages. Most models are basically divided into two parts: list the overview, and creste/update/delete an item. Some detail views are a bit more complex, eg they have nested items which are editable as well, must fetch additional information as everything is backed up by an id-based API.

To me, this is quite an app. With the test data, all's good. Is there something to be concerned about? Do I need to "clear" any memory once I leave a controller for another one, stuff like that.

Not sure if I expect a "yes" or "no" on this one, but one might have more experience in this field which could be a good-to-share.

Thanks.

答: Angular apps can be very big. The thing is, you don't have to show everything all at once, that's where the issues come in. Angular change detection works with something called watchers, which performs data comparisons at every digest loop. If you have 1000 elements on screen, it will check every single element at every digest cycle, which is pretty often. For modern browsers, the upper limit seems to be about 4000 items on screen, but think of it this way: people don't actually look at 4000 things on the screen at a time. So, most of the watchers aren't actually needed. Techniques such as pagination, and virtual repeat will drastically cut down on the demand angular places on the browser, and will let your app grow very very big. Clearing memory is usually not necessary. Modern browsers will let a web page take up as much memory as needed, I think up to 500MB with Google Chrome. As long as you keep your data structures well groomed, I doubt you'll ever run into trouble with memory.</p>


问:
Hibernate ManyToOne association in a Spring Form
I have two entities with a @ManyToOne association, and a form which adds a product. Everything is working fine except for the category and the manufacturer attribute. Any Idea ?

Here is the Product class :

```<code>@Entity
public class Product implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotEmpty(message = "Le champ nom ne peut être vide")
private String name;

@NotEmpty(message = "Le champ description ne peut être vide")
private String description;

@Min(value = 0, message = "Le prix du produit ne peux pas être négatif")
@NotNull(message = "Le champ prix ne peut pas être vide")
private Double price;

@ManyToOne
private Category category;

@Min(value = 0, message = "Le stock du produit ne peut pas être négatif")
@NotNull(message = "Le champ stock ne peut pas être vide")
private Long stock;

@ManyToOne
private Manufacturer manufacturer;

@Transient
private MultipartFile image;
</code>```

Here is the Category class :

```<code>@Entity
public class Category {
@Id
private Long id;

@NotEmpty(message = "Le champ nom est vide.")
private String name;

private String description;
private String picture;
</code>```

Here is the controller :

```<code>@RequestMapping(value = "admin/inventaire/ajout", method = RequestMethod.POST)
public String ajoutProduitPost(@Valid @ModelAttribute("product") Product product,
        BindingResult result, HttpServletRequest request) {

    if (result.hasErrors()) {
        return "addProduct";
    }

    productDao.addProduct(product);

    MultipartFile productImage = product.getImage();
    String contextPath = context.getRealPath("/");

    Path path = Paths.get(contextPath + "/WEB-INF/resources/images/product   /"+product.getId()+".png");

    if (productImage != null && !productImage.isEmpty()) {
        try {
            productImage.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Product image saving failed", e);
        }
    }

    return "redirect:/admin/inventaire";
}
</code>```

And finally the JSP :

```<code>    <%@include file="/WEB-INF/views/template/header.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<div class="container-wrapper">
    <div class ="container">

        <div class="page-header">
            <h1>Ajout d'un nouveau produit</h1>
        </div>
        <form:form action="${pageContext.request.contextPath}/admin/inventaire/ajout" method="post"
                   modelAttribute="product" enctype="multipart/form-data">
            <!-- NOM -->
            <div class="form-group" >
                <label for = "productName">Name</label>
                <form:input path="name" id="productName" class="form-control "/> <form:errors path="name" cssStyle="color:#ff0000;"/>
            </div>
            <!-- DESCRIPTION -->
            <div class = "form-group">
                <label for = "description">Description</label>
                <form:textarea path = "description" id="description" class ="form-control"/> <form:errors path="description" cssStyle="color:#ff0000;"/>
            </div>
            <!-- STOCK -->
            <div class="form-group">
                <label for="stock">Quantité en stock</label>
                <form:input path="stock" id="stock" class="form-control"/> <form:errors path="stock" cssStyle="color:#ff0000;"/>
            </div>
            <!-- PRIX -->
            <div class="form-group">
                <label for="price">Prix</label>
                <form:input path="price" id="price" class="form-control"/> <form:errors path="price" cssStyle="color:#ff0000;"/>
            </div>
            <!-- CATEGORY -->
            <div class="form-group">
                <label for="category">Catégorie</label>
                <form:select path="category">
                    <form:option value="-" label="--Please Select"/>
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name"/>
                </form:select>
            </div>
            <!-- FABRICANT -->

            <!-- IMAGE -->
            <div class="form-group">
                <label class = "control-label" for= "image">Image</label>
                <form:input id="image" path = "image" type="file" class="form:input-large"/>
            </div>

            <input type="submit" value="Envoyer" class="btn btn-default">
            <a href="<c:url value="/admin/inventaire" />" class="btn btn-default">Annuler</a>

        </form:form>
    </div>
</div>
    <%@include file="/WEB-INF/views/template/footer.jsp" %>
</code>```

I think the problem is that the form sends the id of the category to the controller, but it expects the object Category instead. I can't find a solution around it.

答:
```<code><form:select path="category.id">
</code>```

As pointed by Mayank Add @JoinColumn(name="mapped_table_column_id") annotation to both Category and Manufacturer

Body:
I have two entities with a @ManyToOne association, and a form which adds a product. Everything is working fine except for the category and the manufacturer attribute. Any Idea ?

Here is the Product class :

@Entity
public class Product implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotEmpty(message = "Le champ nom ne peut être vide")
private String name;

@NotEmpty(message = "Le champ description ne peut être vide")
private String description;

@Min(value = 0, message = "Le prix du produit ne peux pas être négatif")
@NotNull(message = "Le champ prix ne peut pas être vide")
private Double price;

@ManyToOne
private Category category;

@Min(value = 0, message = "Le stock du produit ne peut pas être négatif")
@NotNull(message = "Le champ stock ne peut pas être vide")
private Long stock;

@ManyToOne
private Manufacturer manufacturer;

@Transient
private MultipartFile image;

Here is the Category class :

@Entity
public class Category {
@Id
private Long id;

@NotEmpty(message = "Le champ nom est vide.")
private String name;

private String description;
private String picture;

Here is the controller :

@RequestMapping(value = "admin/inventaire/ajout", method = RequestMethod.POST)
public String ajoutProduitPost(@Valid @ModelAttribute("product") Product product,
        BindingResult result, HttpServletRequest request) {

    if (result.hasErrors()) {
        return "addProduct";
    }

    productDao.addProduct(product);

    MultipartFile productImage = product.getImage();
    String contextPath = context.getRealPath("/");

    Path path = Paths.get(contextPath + "/WEB-INF/resources/images/product   /"+product.getId()+".png");

    if (productImage != null && !productImage.isEmpty()) {
        try {
            productImage.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Product image saving failed", e);
        }
    }

    return "redirect:/admin/inventaire";
}

And finally the JSP :

    <%@include file="/WEB-INF/views/template/header.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Ajout d'un nouveau produit

        <form:form action="${pageContext.request.contextPath}/admin/inventaire/ajout" method="post"
                   modelAttribute="product" enctype="multipart/form-data">

                Name
                <form:input path="name" id="productName" class="form-control "/> <form:errors path="name" cssStyle="color:#ff0000;"/>

                Description
                <form:textarea path = "description" id="description" class ="form-control"/> <form:errors path="description" cssStyle="color:#ff0000;"/>

                Quantité en stock
                <form:input path="stock" id="stock" class="form-control"/> <form:errors path="stock" cssStyle="color:#ff0000;"/>

                Prix
                <form:input path="price" id="price" class="form-control"/> <form:errors path="price" cssStyle="color:#ff0000;"/>

                Catégorie
                <form:select path="category">
                    <form:option value="-" label="--Please Select"/>
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name"/>
                </form:select>

                Image
                <form:input id="image" path = "image" type="file" class="form:input-large"/>

            <input type="submit" value="Envoyer" class="btn btn-default">
            <a href="<c:url value="/admin/inventaire" />" class="btn btn-default">Annuler

        </form:form>

    <%@include file="/WEB-INF/views/template/footer.jsp" %>

I think the problem is that the form sends the id of the category to the controller, but it expects the object Category instead. I can't find a solution around it.

Body:
<form:select path="category.id">

As pointed by Mayank Add @JoinColumn(name="mapped_table_column_id") annotation to both Category and Manufacturer


问:
git merge does not merge
I have a master and "PersonalSite" branch for a codebase I'm working on.  I have been repeatedly trying to merge the master into the PersonalSite branch to no avail.

This time, I thought I had everything straightened out, so I did:

```<code>git checkout master
git pull
git checkout PersonalSite
git pull
git merge master
</code>```

It looked like everything was working, and it listed the set of files I would have expected, but there was a conflict.  The conflict was correct and was as expected, so I fixed it, did "git add", "git commit", then "git push".  But now, when I look at my git log, it just shows a commit with no code changes but a single conflict.

Now, when I run "git merge master" from the "PersonalSite" branch it says "Already up-to-date." but this clearly is not the case, as none of the changes I tried to merge actually merged.  What exactly do I do to get master to actually merge at this point?

答:
I realize that this is an older question now, but I was just having what I believe is the same problem. I couldn't get it resolved with any combination of the commands in other answers, but I did resolve it by running in the branch that I want merges into:

```<code>git checkout <desired_branch_name> -- .
</code>```

So for you:

```<code>git checkout master -- .
</code>```

I found this answer here:
git: checkout files from another branch into current branch (don't switch HEAD to the other branch)

Title: git merge does not merge

Body:
I have a master and "PersonalSite" branch for a codebase I'm working on.  I have been repeatedly trying to merge the master into the PersonalSite branch to no avail.

This time, I thought I had everything straightened out, so I did:

git checkout master
git pull
git checkout PersonalSite
git pull
git merge master

It looked like everything was working, and it listed the set of files I would have expected, but there was a conflict.  The conflict was correct and was as expected, so I fixed it, did "git add", "git commit", then "git push".  But now, when I look at my git log, it just shows a commit with no code changes but a single conflict.

Now, when I run "git merge master" from the "PersonalSite" branch it says "Already up-to-date." but this clearly is not the case, as none of the changes I tried to merge actually merged.  What exactly do I do to get master to actually merge at this point?

Body:
I realize that this is an older question now, but I was just having what I believe is the same problem. I couldn't get it resolved with any combination of the commands in other answers, but I did resolve it by running in the branch that I want merges into:

git checkout <desired_branch_name> -- .

So for you:

git checkout master -- .

I found this answer here:
git: checkout files from another branch into current branch (don't switch HEAD to the other branch)


问:
how to combine two same scene images for image registration
I try to do image registration on two grayscale images where the images were taken twice with different views. The images were taking by myself using a Lifecam camera.

To register these images, I used template matching method and normalized cross correlation as similarity measure and found the right location. But the result after combination of these two images was not good as I wish. I don't know how to fix it. Do I need to do some rotation or translation first before combine it? If so, I have no idea how to get the real angle for rotation. Or do you have any idea how to fix the image result without applying any rotation?

Input image 1:

Input Image 2:

Result:

This my code:

```<code>A = imread('image1.jpg');
B = imread('image2.jpg');

[M1, N1] = size(A);      % size imej A n B
[M2, N2] = size(B);
%% finding coordinated of (r2,c2)
r1 = size(A,1)/2;        % midpoint of image A as coordinate
c1 = size(A,2
template = imcrop(A,[(c1-20) (r1-20) 40 40]);
[r2, c2] = normcorr(temp,B);     % Normalized cross correlation

%% count distance of coordinate (r1,c1) in image A and (r2,c2)in image B
UA = r1;           % distance of coordinate (r1,c1) from top in image A
BA = M1 - r1;      % distance of coordinate (r1,c1) from bottom
LA = c1;           % left distance from (r1,c1)
RA = N1 - c1;      % right distance from (r1,c1)

UB = r2;           % finding distance of coordinate (r2,c2) from top,
BB = M2 - r2;      % bottom, left and right in image B
LB = c2;
RB = N2 - c2;
%% zero padding for both image
if LA > LB
L_diff = LA - LB;           % value of columns need to pad with zero on left side
B = [zeros(M2,L_diff),B];
else
L_diff = LB - LA;
 A = [zeros(M1,L_diff),A];
end
if RA > RB
 R_diff = RA - RB;          % value of columns need to pad with zero on right side
 B = [B, zeros(M2,R_diff)];
else
 R_diff = RB - RA;
 A = [A, zeros(M1,R_diff)];
end
N1 = size(A, 2);                    % renew value column image A and B
N2 = size(B, 2);
if UA > UB
 U_diff = UA - UB;                  % value of rows need to pad with zero on top
 B = [zeros(U_diff,N2);B];
else
 U_diff = UB - UA;
 A = [zeros(U_diff,N1);A];
end
if BA > BB
 B_diff = BA - BB;         % value of rows need to pad with zero on bottom
 B = [B; zeros(B_diff,N2)];
else
 B_diff = BB - BA;
 A = [A; zeros(B_diff,N1)];
end
%% find coordinate that have double value
if LA > LB
 r = r1;
 c = c1;
else
 r = r2;
 c = c2;
end
if UA >= UB
 i_Start = r - UB + 1;
else
 i_Start = r - UA + 1;
end
if BA >= BB
 i_Stop = r + BB ;
else
 i_Stop = r + BA;
end
 if LA >= LB
 j_Start = c - c2 + 1;
else
 j_Start = c - c1 + 1;
end
if RA >= RB
 j_Stop = c + RB;
else
 j_Stop = c + RA;
end
%% add image A and B
A = im2double(A);
B = im2double(B);
final_im = A + B;
for i = i_Start:i_Stop
 for j = j_Start:j_Stop
     final_im(i,j) = final_im(i,j)/2;
 end
end

final_im = im2uint8(final_im);
</code>```

答:
The answer from rayryeng in Ryan L's first link is quite applicable here. Cross-correlation likely won't provide a close enough match between the two images since the transformation between the two images is more accurately described as a homography than a 2D rigid transform.

Accurate image registration requires that you find this projective transformation. To do so you can find a set of corresponding points in the two images (using SURF, as mentioned above, usually works well) and then use RANSAC to obtain the homography's parameters from the corresponding points. RANSAC does a nice job even when some of the "corresponding" features in your two images are actually not correct matches. Once found, you can use the transformation to move one of your images to the other's point of view and fuse.

Here's a nice explanation of feature matching, RANSAC, and fusing two images with some Matlab code samples. The lecture uses SIFT features, but the idea still works for SURF.

Body:
I try to do image registration on two grayscale images where the images were taken twice with different views. The images were taking by myself using a Lifecam camera.

To register these images, I used template matching method and normalized cross correlation as similarity measure and found the right location. But the result after combination of these two images was not good as I wish. I don't know how to fix it. Do I need to do some rotation or translation first before combine it? If so, I have no idea how to get the real angle for rotation. Or do you have any idea how to fix the image result without applying any rotation?

Input image 1:

Input Image 2:

Result:

This my code:

A = imread('image1.jpg');
B = imread('image2.jpg');

[M1, N1] = size(A);      % size imej A n B
[M2, N2] = size(B);
%% finding coordinated of (r2,c2)
r1 = size(A,1)/2;        % midpoint of image A as coordinate
c1 = size(A,2
template = imcrop(A,[(c1-20) (r1-20) 40 40]);
[r2, c2] = normcorr(temp,B);     % Normalized cross correlation

%% count distance of coordinate (r1,c1) in image A and (r2,c2)in image B
UA = r1;           % distance of coordinate (r1,c1) from top in image A
BA = M1 - r1;      % distance of coordinate (r1,c1) from bottom
LA = c1;           % left distance from (r1,c1)
RA = N1 - c1;      % right distance from (r1,c1)

UB = r2;           % finding distance of coordinate (r2,c2) from top,
BB = M2 - r2;      % bottom, left and right in image B
LB = c2;
RB = N2 - c2;
%% zero padding for both image
if LA > LB
L_diff = LA - LB;           % value of columns need to pad with zero on left side
B = [zeros(M2,L_diff),B];
else
L_diff = LB - LA;
 A = [zeros(M1,L_diff),A];
end
if RA > RB
 R_diff = RA - RB;          % value of columns need to pad with zero on right side
 B = [B, zeros(M2,R_diff)];
else
 R_diff = RB - RA;
 A = [A, zeros(M1,R_diff)];
end
N1 = size(A, 2);                    % renew value column image A and B
N2 = size(B, 2);
if UA > UB
 U_diff = UA - UB;                  % value of rows need to pad with zero on top
 B = [zeros(U_diff,N2);B];
else
 U_diff = UB - UA;
 A = [zeros(U_diff,N1);A];
end
if BA > BB
 B_diff = BA - BB;         % value of rows need to pad with zero on bottom
 B = [B; zeros(B_diff,N2)];
else
 B_diff = BB - BA;
 A = [A; zeros(B_diff,N1)];
end
%% find coordinate that have double value
if LA > LB
 r = r1;
 c = c1;
else
 r = r2;
 c = c2;
end
if UA >= UB
 i_Start = r - UB + 1;
else
 i_Start = r - UA + 1;
end
if BA >= BB
 i_Stop = r + BB ;
else
 i_Stop = r + BA;
end
 if LA >= LB
 j_Start = c - c2 + 1;
else
 j_Start = c - c1 + 1;
end
if RA >= RB
 j_Stop = c + RB;
else
 j_Stop = c + RA;
end
%% add image A and B
A = im2double(A);
B = im2double(B);
final_im = A + B;
for i = i_Start:i_Stop
 for j = j_Start:j_Stop
     final_im(i,j) = final_im(i,j)/2;
 end
end

final_im = im2uint8(final_im);