问:
Textfields component number validation React js
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (
      <div className={cr.container}>
        <div className ={cr.boton}>
          <Divider/>
          <br/>
        </div>

        <div className={cr.rows}>
          <div>
            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />
          </div>
        </div>

        <div className={cr.botonSet}>
          <div className={cr.botonMargin}>
            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>
          </div>
          <div>
            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />
          </div>
        </div>
      </div>
    );
  }
}
</code>```

Can someone help me on this please.

Thanks in advance.

答:
You can prevent users from input text by using this : </p>

```<code><TextField
    onChange={(e) => {
        if(e.target.value === '' || /^\d+$/.test(e.target.value)) {
            this.setState({and_: e.target.value})
        } else {
            return false;
        }
    }}
    value={this.state.and_}
    errorText={this.state.and_error}
    floatingLabelText="And"
/>
</code>```

Body:
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (

          <Divider/>

            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />

            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />

            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />

            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>

            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />

    );
  }
}

Can someone help me on this please.

Thanks in advance.

Body:
You can prevent users from input text by using this :

<TextField
    onChange={(e) => {
        if(e.target.value === '' || /^\d+$/.test(e.target.value)) {
            this.setState({and_: e.target.value})
        } else {
            return false;
        }
    }}
    value={this.state.and_}
    errorText={this.state.and_error}
    floatingLabelText="And"
/>


来源: stackexchange

问:
e.target.value shows values one key 'behind'
Input type with id 'typehere'. There is a keydown event set on typhere. The simple problem is that e.srcElement.value seems to have a value one key behind. i.e. if the value should 's' , its consoled'logged as blank '' . If I type 'ss' , the value shown is 's' . I can't seem to figure this one out.

console.log(e), shows the correct value of e.srcElement.value (in the console), but console.log(e.srcElement.value) shows the wrong value. Why?

```<code><script type="text/javascript">
            var xmlHttp = createXmlHttpRequestObject();
            selectOption = document.getElementById('choose_colony') ;

            document.body.onload = function () {
                typehere = document.getElementById('typehere') ;

                addAnEvent(typehere,"keydown",handleKeyDownevent,false )  ;
            }

            function handleKeyDownevent (e) {
                e = e || window.event ;
                if (xmlHttp) {
                    try {
                        //xmlHttp.open('GET' , 'async.txt', true ) ;
                           console.log(e.srcElement.value ) ;
                       var target=  e.target || e.srcElement ;
                        var typed = target.value      ;
                        if (typed != ""){
                            console.log('sennding request') ;
                            //ajax request
                        }
                        else {
                            console.log(e.srcElement.value + "is blank") ;
                        }
                    }
                    catch(e) {
                        console.log('could not connect to server') ;
                    }
                }

            }
</script>
</code>```

The script tag are before the  tag btw

答:
The simple answer lies in the fact that when you are trying to determine the value of a variable that is within an event, it is processed by an event handler, and therefore it is best to simply log the event itself.  So you could try modifying your code to accommodate for that, to see if helps.  Also, I disagree with above answer about needing to set/include a time-out (function), unless you are trying to cancel any keystrokes, etc. To clarify:

```<code><script type="text/javascript">
        var xmlHttp = createXmlHttpRequestObject();
        selectOption = document.getElementById('choose_colony') ;

        document.body.onload = function () {
            typehere = document.getElementById('typehere');
            addAnEvent(typehere, "keydown", function(e) {
                e = e || window.event;
                handleKeyDownevent(e);}, false);
        }
function handleKeyDownevent (e) {
            e = e || window.event ;
            if (xmlHttp) {
                try {
                    //xmlHttp.open('GET' , 'async.txt', true ) ;
                       console.log(e.srcElement.value ) ;
                   var target=  e.target || e.srcElement ;
                    var typed = target.value      ;
                    if (typed != ""){
                        console.log('sennding request') ;
                        //ajax request
                    }
                    else {
                        console.log(e.srcElement.value + "is blank") ;
                    }
                }
                catch(e) {
                    console.log('could not connect to server') ;
                }
            }
          return true;
        }
</script>
</code>```

I hope that helps you out.  The return true at the bottom allows the browser's default response.

ContentLicense: CC BY-SA 4.0

Body:
Input type with id 'typehere'. There is a keydown event set on typhere. The simple problem is that e.srcElement.value seems to have a value one key behind. i.e. if the value should 's' , its consoled'logged as blank '' . If I type 'ss' , the value shown is 's' . I can't seem to figure this one out.

console.log(e), shows the correct value of e.srcElement.value (in the console), but console.log(e.srcElement.value) shows the wrong value. Why?

The script tag are before the  tag btw

Body:
The simple answer lies in the fact that when you are trying to determine the value of a variable that is within an event, it is processed by an event handler, and therefore it is best to simply log the event itself.  So you could try modifying your code to accommodate for that, to see if helps.  Also, I disagree with above answer about needing to set/include a time-out (function), unless you are trying to cancel any keystrokes, etc. To clarify:

<script type="text/javascript">
        var xmlHttp = createXmlHttpRequestObject();
        selectOption = document.getElementById('choose_colony') ;

        document.body.onload = function () {
            typehere = document.getElementById('typehere');
            addAnEvent(typehere, "keydown", function(e) {
                e = e || window.event;
                handleKeyDownevent(e);}, false);
        }
function handleKeyDownevent (e) {
            e = e || window.event ;
            if (xmlHttp) {
                try {
                    //xmlHttp.open('GET' , 'async.txt', true ) ;
                       console.log(e.srcElement.value ) ;
                   var target=  e.target || e.srcElement ;
                    var typed = target.value      ;
                    if (typed != ""){
                        console.log('sennding request') ;
                        //ajax request
                    }
                    else {
                        console.log(e.srcElement.value + "is blank") ;
                    }
                }
                catch(e) {
                    console.log('could not connect to server') ;
                }
            }
          return true;
        }
</script>

I hope that helps you out.  The return true at the bottom allows the browser's default response.

ContentLicense: CC BY-SA 3.0


问:
(Ecto.ChangeError) value xxx for xxx does not match type :float
I have a function to add a product to the database (product is a map):

```<code>  @derive {Poison.Encoder, only: [:s_id, :p_id]}
  schema "product_shops" do
    field :s_id, :integer
    field :p_id, :integer
    field :not_in_shop_count, :integer
    field :price, :float
  end

  def changeset(product_shop, params \\ %{}) do
    product_shop
    |> cast(params, [:s_id, :p_id, :price, :not_in_shop_count])
    |> validate_required([:s_id, :p_id])
    |> unique_constraint(:s_id, name: :unique_product_shop)
  end

  def insert_product_shop(conn, product_id, shop_id, price) do
    IO.inspect(price, label: "price")
    changeset = Api.ProductShop.changeset(%Api.ProductShop{p_id: product_id, s_id: shop_id, not_in_shop_count: 0, price: price})
    errors = changeset.errors
    valid = changeset.valid?
    case insert(changeset) do
      {:ok, product_shop} ->
        {:ok, product_shop}
      {:error, changeset} ->
        {:error, :failure}
    end
  end
</code>```

The IO.inspect shows:

```<code>price: 52
</code>```

But I get this error:

```<code>(Ecto.ChangeError) value `24` for `Api.ProductShop.price` in `insert` does not match type :float
</code>```

So price is an int but needs to be a float.

this is the log from IO.inspect(product)

```<code>%{"brand" => "if",
  "categories" => [%{"categoryId" => 1, "label" => "Meat",
     "selectedAdd" => true, "selectedSearch" => false, "value" => 1}],
  "description" => "kcjcufujdifgkv. ckcfickc", "name" => "car",
  "not_vegan_count" => 0, "number_of_votes" => 0, "price" => 24,
  "rating" => nil,
  "shop" => %{"latitude" => -37.6739483, "longitude" => 176.1662587,
    "name" => "Rebel Sport", "place_id" => "ChIJgRN1iu_bbW0Rsb-fET0z81Y"}}
</code>```

Convert price to float attempt (using this resource):

```<code>  def insert_product(conn, product) do
  IO.puts("the product price")
  IO.inspect(Map.fetch(product, "price"))
  %{product | "price" => "price" / 1}
  IO.puts("the product price as a float")
  IO.inspect(Map.fetch(product, "price"))
</code>```

It logs this:

```<code>the product price
{:ok, 24}
</code>```

with error:

```<code>** (ArithmeticError) bad argument in arithmetic expression
</code>```

How can I get price in the map to be a float?

答:
Answering the question stated:

```<code>iex(1)> map = %{"foo" => 42}
%{"foo" => 42}
iex(2)> %{map | "foo" => map["foo"] / 1}
%{"foo" => 42.0}
</code>```

Please note, that in Elixir terms are all immutable, and hence even correct clause:

```<code>%{product | "price" => product["price"] / 1}
</code>```

is a NOOP. The result is immediately discarded. One must rebind product to use it later:

```<code>product = %{product | "price" => product["price"] / 1}
</code>```

It in general should be done with Ecto.Changeset.cast/4, not explicitly.

If for some reason one needs to cast the value manually, Ecto.Type.cast/2 comes to the rescue:

```<code>Ecto.Type.cast(:float, 1)
#⇒ 1.0
</code>```

Sidenote: IO.inspect/2 accepts a second parameter opts:

```<code>IO.inspect(product, label: "the product")
</code>```

Body:
I have a function to add a product to the database (product is a map):

  @derive {Poison.Encoder, only: [:s_id, :p_id]}
  schema "product_shops" do
    field :s_id, :integer
    field :p_id, :integer
    field :not_in_shop_count, :integer
    field :price, :float
  end

  def changeset(product_shop, params \\ %{}) do
    product_shop
    |> cast(params, [:s_id, :p_id, :price, :not_in_shop_count])
    |> validate_required([:s_id, :p_id])
    |> unique_constraint(:s_id, name: :unique_product_shop)
  end

  def insert_product_shop(conn, product_id, shop_id, price) do
    IO.inspect(price, label: "price")
    changeset = Api.ProductShop.changeset(%Api.ProductShop{p_id: product_id, s_id: shop_id, not_in_shop_count: 0, price: price})
    errors = changeset.errors
    valid = changeset.valid?
    case insert(changeset) do
      {:ok, product_shop} ->
        {:ok, product_shop}
      {:error, changeset} ->
        {:error, :failure}
    end
  end

The IO.inspect shows:

price: 52

But I get this error:

(Ecto.ChangeError) value `24` for `Api.ProductShop.price` in `insert` does not match type :float

So price is an int but needs to be a float.

this is the log from IO.inspect(product)

%{"brand" => "if",
  "categories" => [%{"categoryId" => 1, "label" => "Meat",
     "selectedAdd" => true, "selectedSearch" => false, "value" => 1}],
  "description" => "kcjcufujdifgkv. ckcfickc", "name" => "car",
  "not_vegan_count" => 0, "number_of_votes" => 0, "price" => 24,
  "rating" => nil,
  "shop" => %{"latitude" => -37.6739483, "longitude" => 176.1662587,
    "name" => "Rebel Sport", "place_id" => "ChIJgRN1iu_bbW0Rsb-fET0z81Y"}}

Convert price to float attempt (using this resource):

  def insert_product(conn, product) do
  IO.puts("the product price")
  IO.inspect(Map.fetch(product, "price"))
  %{product | "price" => "price" / 1}
  IO.puts("the product price as a float")
  IO.inspect(Map.fetch(product, "price"))

It logs this:

the product price
{:ok, 24}

with error:

** (ArithmeticError) bad argument in arithmetic expression

How can I get price in the map to be a float?

Body:
Answering the question stated:

iex(1)> map = %{"foo" => 42}
%{"foo" => 42}
iex(2)> %{map | "foo" => map["foo"] / 1}
%{"foo" => 42.0}

Please note, that in Elixir terms are all immutable, and hence even correct clause:

%{product | "price" => product["price"] / 1}

is a NOOP. The result is immediately discarded. One must rebind product to use it later:

product = %{product | "price" => product["price"] / 1}

It in general should be done with Ecto.Changeset.cast/4, not explicitly.

If for some reason one needs to cast the value manually, Ecto.Type.cast/2 comes to the rescue:

Ecto.Type.cast(:float, 1)
#⇒ 1.0

Sidenote: IO.inspect/2 accepts a second parameter opts:

IO.inspect(product, label: "the product")


问:
Why is my code so slow?
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

```<code>loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop
</code>```

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

```
   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();
```

update:

```
Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;

```

答:
Additionally to Larry Lustig points:

In general, FieldByName is comparably slow method. You are calling it in loop for the same fields. Move the getting of field references out of the loop and store references in the variables. Like: InputTempField := ADODataSet.FieldByname('inputTemperature');

You are resizing the grid in the loop TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1. That is the case, when you should use ADODataSet.RecordCount before the loop: TestRunDataStringGrid.RowCount := ADODataSet.RecordCount.

That is a good practice to call ADODataSet.DisableControls before loop and ADODataSet.EnableControls after loop. Even more actual that is for ADO dataset, which has not optimal implementation and those calls help.

Depending on a DBMS you are using, you can improve the fetching performance by setting a larger "rowset size". Not sure, how it control in ADO, probably setting ADODataSet.CacheSize to a greater value will help. Also, there are cursor settings :)

ContentLicense: CC BY-SA 2.5

Title: Why is my code so slow?

Body:
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();

update:

Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;


问:
can't run eclipse, keep getting errors?
I'm having trouble with eclipse.
Somehow I always get an error..
I´m trying to learn java programming and want to move on as fast as possible.

Here is the error log.
If anyone can help me, that would be awesome because even the people who run the java programming course are letting me down.

Thank you  very much!
Jarne Bartray

```<code>**!SESSION 2013-09-24 11:11:10.783 -----------------------------------------------
eclipse.buildId=M20070212-1330
java.version=1.7.0_40
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=nl_NL
Command-line arguments:  -os win32 -ws win32 -arch x86
!ENTRY org.eclipse.equinox.common 4 0 2013-09-24 11:11:11.230
!MESSAGE FrameworkEvent.ERROR
!STACK 0
org.osgi.framework.BundleException: The bundle could not be resolved. Reason: Missing Constraint: Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,J2SE-1.3
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:294)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:329)
    at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1046)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:573)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:495)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:275)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:455)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:189)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:291)
!ENTRY org.eclipse.update.configurator 4 0 2013-09-24 11:11:11.231
!MESSAGE FrameworkEvent.ERROR
!STACK 0
org.osgi.framework.BundleException: The bundle could not be resolved. Reason: Missing Constraint: Bundle-RequiredExecutionEnvironment: J2SE-1.4,CDC-1.0/Foundation-1.0,J2SE-1.3
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:294)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:329)
    at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1046)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:573)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:495)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:275)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:455)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:189)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:291)
!ENTRY org.eclipse.core.runtime 4 0 2013-09-24 11:11:11.232
!MESSAGE FrameworkEvent.ERROR
!STACK 0
org.osgi.framework.BundleException: The bundle could not be resolved. Reason: Missing Constraint: Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,J2SE-1.3
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:294)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:329)
    at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1046)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:573)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:495)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:275)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:455)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:189)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:291)
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.235
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.equinox.common_3.2.0.v20060603.jar/ was not resolved.
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.235
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.update.configurator_3.2.2.R32x_v20070111.jar/ was not resolved.
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.235
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.core.runtime_3.2.0.v20060603.jar/ was not resolved.
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.237
!MESSAGE Application error
!STACK 1
java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:65)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:400)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:177)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.core.launcher.Main.invokeFramework(Main.java:336)
    at org.eclipse.core.launcher.Main.basicRun(Main.java:280)
    at org.eclipse.core.launcher.Main.run(Main.java:977)
    at org.eclipse.core.launcher.Main.main(Main.java:952)
!ENTRY org.eclipse.osgi 2 0 2013-09-24 11:11:11.242
!MESSAGE One or more bundles are not resolved because the following root constraints are not resolved:
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.242
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.update.configurator_3.2.2.R32x_v20070111.jar/ was not resolved.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package org.w3c.dom_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package org.xml.sax_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package javax.xml.parsers_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package org.xml.sax.helpers_0.0.0.
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.242
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.core.runtime_3.2.0.v20060603.jar/ was not resolved.
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.equinox.registry_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.core.jobs_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.equinox.preferences_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.core.contenttype_[3.2.0,4.0.0).
!ENTRY org.eclipse.osgi 2 0 2013-09-24 11:11:11.244
!MESSAGE The following is a complete list of bundles which are not resolved, see the prior log entry for the root cause if it exists:
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.244
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.equinox.common_3.2.0.v20060603.jar/ [1] was not resolved.
!SUBENTRY 2 org.eclipse.equinox.common 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing Constraint: Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,J2SE-1.3
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.244
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.update.configurator_3.2.2.R32x_v20070111.jar/ [2] was not resolved.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing required bundle org.eclipse.equinox.common_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing imported package javax.xml.parsers_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing imported package org.w3c.dom_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing imported package org.xml.sax_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing imported package org.xml.sax.helpers_0.0.0.
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.245
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.core.runtime_3.2.0.v20060603.jar/ [3] was not resolved.
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.equinox.common_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.core.jobs_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.equinox.registry_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.equinox.preferences_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.core.contenttype_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing optionally required bundle org.eclipse.core.runtime.compatibility.auth_[3.2.0,4.0.0).**
</code>```

答: Verify the Java version running on the system. I had the same issue with java 9 while working with oxygen / kepler / juno. Reverted to older version of Java 8, and it seems to have fixed it.</p>

Title: can't run eclipse, keep getting errors?

Body:
I'm having trouble with eclipse.
Somehow I always get an error..
I´m trying to learn java programming and want to move on as fast as possible.

Here is the error log.
If anyone can help me, that would be awesome because even the people who run the java programming course are letting me down.

Thank you  very much!
Jarne Bartray

**!SESSION 2013-09-24 11:11:10.783 -----------------------------------------------
eclipse.buildId=M20070212-1330
java.version=1.7.0_40
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=nl_NL
Command-line arguments:  -os win32 -ws win32 -arch x86
!ENTRY org.eclipse.equinox.common 4 0 2013-09-24 11:11:11.230
!MESSAGE FrameworkEvent.ERROR
!STACK 0
org.osgi.framework.BundleException: The bundle could not be resolved. Reason: Missing Constraint: Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,J2SE-1.3
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:294)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:329)
    at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1046)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:573)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:495)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:275)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:455)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:189)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:291)
!ENTRY org.eclipse.update.configurator 4 0 2013-09-24 11:11:11.231
!MESSAGE FrameworkEvent.ERROR
!STACK 0
org.osgi.framework.BundleException: The bundle could not be resolved. Reason: Missing Constraint: Bundle-RequiredExecutionEnvironment: J2SE-1.4,CDC-1.0/Foundation-1.0,J2SE-1.3
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:294)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:329)
    at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1046)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:573)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:495)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:275)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:455)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:189)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:291)
!ENTRY org.eclipse.core.runtime 4 0 2013-09-24 11:11:11.232
!MESSAGE FrameworkEvent.ERROR
!STACK 0
org.osgi.framework.BundleException: The bundle could not be resolved. Reason: Missing Constraint: Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,J2SE-1.3
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:294)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:329)
    at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1046)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:573)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:495)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:275)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:455)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:189)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:291)
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.235
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.equinox.common_3.2.0.v20060603.jar/ was not resolved.
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.235
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.update.configurator_3.2.2.R32x_v20070111.jar/ was not resolved.
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.235
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.core.runtime_3.2.0.v20060603.jar/ was not resolved.
!ENTRY org.eclipse.osgi 4 0 2013-09-24 11:11:11.237
!MESSAGE Application error
!STACK 1
java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:65)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:400)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:177)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.core.launcher.Main.invokeFramework(Main.java:336)
    at org.eclipse.core.launcher.Main.basicRun(Main.java:280)
    at org.eclipse.core.launcher.Main.run(Main.java:977)
    at org.eclipse.core.launcher.Main.main(Main.java:952)
!ENTRY org.eclipse.osgi 2 0 2013-09-24 11:11:11.242
!MESSAGE One or more bundles are not resolved because the following root constraints are not resolved:
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.242
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.update.configurator_3.2.2.R32x_v20070111.jar/ was not resolved.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package org.w3c.dom_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package org.xml.sax_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package javax.xml.parsers_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing imported package org.xml.sax.helpers_0.0.0.
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.242
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.core.runtime_3.2.0.v20060603.jar/ was not resolved.
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.equinox.registry_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.core.jobs_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.equinox.preferences_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.242
!MESSAGE Missing required bundle org.eclipse.core.contenttype_[3.2.0,4.0.0).
!ENTRY org.eclipse.osgi 2 0 2013-09-24 11:11:11.244
!MESSAGE The following is a complete list of bundles which are not resolved, see the prior log entry for the root cause if it exists:
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.244
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.equinox.common_3.2.0.v20060603.jar/ [1] was not resolved.
!SUBENTRY 2 org.eclipse.equinox.common 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing Constraint: Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,J2SE-1.3
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.244
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.update.configurator_3.2.2.R32x_v20070111.jar/ [2] was not resolved.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing required bundle org.eclipse.equinox.common_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing imported package javax.xml.parsers_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.244
!MESSAGE Missing imported package org.w3c.dom_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing imported package org.xml.sax_0.0.0.
!SUBENTRY 2 org.eclipse.update.configurator 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing imported package org.xml.sax.helpers_0.0.0.
!SUBENTRY 1 org.eclipse.osgi 2 0 2013-09-24 11:11:11.245
!MESSAGE Bundle initial@reference:file:plugins/org.eclipse.core.runtime_3.2.0.v20060603.jar/ [3] was not resolved.
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.equinox.common_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.core.jobs_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.equinox.registry_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.equinox.preferences_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing required bundle org.eclipse.core.contenttype_[3.2.0,4.0.0).
!SUBENTRY 2 org.eclipse.core.runtime 2 0 2013-09-24 11:11:11.245
!MESSAGE Missing optionally required bundle org.eclipse.core.runtime.compatibility.auth_[3.2.0,4.0.0).**


问:
Entity Framework cast selected fields to varchar and concat them
I want do below query in Entity Framework</p>

```<code>select
    cast(p_min as varchar) + '' + cast(p_max as varchar)
from
    user_behave_fact
where
    beef_dairy_stat = 'True' and param_id = 2
group by
    p_min,p_max
go
</code>```

答:
Since you have not mentioned a language, I am writing code in C#.

Try this:

```<code>using (var dbContext = new DatabaseContext())
{
   var output = (
                 from fact in dbContext.user_behave_facts
                 where fact.beef_dairy_stat == "True" && fact.param_id == 2
                 group fact by new {fact.p_min, fact.p_max} in grp
                 select new
                 {
                    ColName = grp.Key.p_min.ToString() + " " + grp.Key.p_max.ToString()
                 }
                 ).ToList();
}
</code>```

.ToList() can be changed according to your expectations

Body:
I want do below query in Entity Framework

select
    cast(p_min as varchar) + '' + cast(p_max as varchar)
from
    user_behave_fact
where
    beef_dairy_stat = 'True' and param_id = 2
group by
    p_min,p_max
go

Body:
Since you have not mentioned a language, I am writing code in C#.

Try this:

using (var dbContext = new DatabaseContext())
{
   var output = (
                 from fact in dbContext.user_behave_facts
                 where fact.beef_dairy_stat == "True" && fact.param_id == 2
                 group fact by new {fact.p_min, fact.p_max} in grp
                 select new
                 {
                    ColName = grp.Key.p_min.ToString() + " " + grp.Key.p_max.ToString()
                 }
                 ).ToList();
}

.ToList() can be changed according to your expectations


问:
react-native type check on component
I have a component that I want to be able to handle two kinds of components. One is a Text component, the other Image component.

I have some default styles like the color I want to be able to apply that to both components, however, a text element can use the key of color in its styles, but on an Image, it has to be tintColor key.

Is there any way I can check for which element I have so I can set the appropriate styles to each one?

答:
You can find many components have such behavior, including some official ones.

e.g: <ScrollView /> with style, contentContainerStyle, indicatorStyle.

For your component, it could be:

<CompositeComponent
  style={{backgroundColor: 'red'}}
  textStyle={{color: 'black'}}
  imageStyle={{tintColor: 'black'}}
  />
```

<p>and in your <code>render()</code> function,</p>

<pre class="lang-js prettyprint-override"><code>render() {
  return (
    <View>
      <Text style={{[this.props.style, this.props.textStyle]}} />
      <Image style={{[this.props.style, this.props.imageStyle]}} />
    </View>
  );
}
</code>```

This way <Text /> and <Image /> share the same style, and then overwritten each with textStyle or imageStyle.

Title: react-native type check on component

Body:
You can find many components have such behavior, including some official ones.

e.g: <ScrollView /> with style, contentContainerStyle, indicatorStyle.

For your component, it could be:

<CompositeComponent
  style={{backgroundColor: 'red'}}
  textStyle={{color: 'black'}}
  imageStyle={{tintColor: 'black'}}
  />

and in your render() function,

render() {
  return (
    <View>
      <Text style={{[this.props.style, this.props.textStyle]}} />
      <Image style={{[this.props.style, this.props.imageStyle]}} />
    </View>
  );
}

This way <Text /> and <Image /> share the same style, and then overwritten each with textStyle or imageStyle.


问:
How to create pie chart in iPhone?
I want to show pie chart of my category by percentage.

How can I create pie chart of category percentage ?

答:
You have to implement a class which overrides the drawRect: method and draw the pie yourself. You'd use UIBezierPath class, specifically look into the addArcWithCenter:radius:startAngle:endAngle:clockwise: method to draw a part of a circle.

See also this article and this article.

Title: How to create pie chart in iPhone?


问:
how to link the cells with numbers? python 3 (I tried zip function and another ways)
I'm attempting to replace each zero into the specific odd number in ascending order. For instance: I have a raw with this list of lists [[0], [0, 0], [0,0,0] and etc.] and I need to get this: [[1], [3,5], [7,9,11], [13,15,17,19] and etc.]

```<code>def x(n):
    obj = iter(list(range(1, 100, 2)))
    odds = list(range(1, 100, 2))
    a =[y*[0] for y,x in enumerate(odds,1)]
    for i in range(0,50):
        a[i] = next(obj)
    return odds
print(x(10))
</code>```

I need a small hint. How continue/fix this code.

答:
You could just do something as simple as this:

```<code>zeroes = [[0], [0, 0], [0,0,0], [0,0,0,0]]

count = 1
for lst in zeroes:
    for i in range(len(lst)):
        lst[i] = count
        count += 2

print(zeroes)
# [[1], [3, 5], [7, 9, 11], [13, 15, 17, 19]]
</code>```

Which just updates the nested list of zeroes with odd numbers, based off a counter that increments in 2.

You could also do something more complicated like this, which uses iterators and itertools functions:

```<code>import itertools

def x(n):
    # get the zeroes sublists
    zeroes = [i * [0] for i in range(1, n+1)]

    # get the length of the flattened list above
    odd_len = len(list(itertools.chain.from_iterable(zeroes)))

    # get the odd numbers
    odd_numbers = [i for i in range(1, odd_len * 2, 2)]

    # check they are the same length
    assert(len(odd_numbers) == odd_len)

    # convert to iterator
    odd_numbers = iter(odd_numbers)

    # loop over the zeroes
    for lst in zeroes:

        for i in range(len(lst)):

            # update the zeroes with the odd numbers
            lst[i] = next(odd_numbers)

    return zeroes

>>> print(x(4))
[[1], [3, 5], [7, 9, 11], [13, 15, 17, 19]]

>>> print(x(10))
[[1], [3, 5], [7, 9, 11], [13, 15, 17, 19], [21, 23, 25, 27, 29], [31, 33, 35, 37, 39, 41], [43, 45, 47, 49, 51, 53, 55], [57, 59, 61, 63, 65, 67, 69, 71], [73, 75, 77, 79, 81, 83, 85, 87, 89], [91, 93, 95, 97, 99, 101, 103, 105, 107, 109]]
</code>```

Body:
I'm attempting to replace each zero into the specific odd number in ascending order. For instance: I have a raw with this list of lists [[0], [0, 0], [0,0,0] and etc.] and I need to get this: [[1], [3,5], [7,9,11], [13,15,17,19] and etc.]

def x(n):
    obj = iter(list(range(1, 100, 2)))
    odds = list(range(1, 100, 2))
    a =[y*[0] for y,x in enumerate(odds,1)]
    for i in range(0,50):
        a[i] = next(obj)
    return odds
print(x(10))

I need a small hint. How continue/fix this code.

Body:
You could just do something as simple as this:

zeroes = [[0], [0, 0], [0,0,0], [0,0,0,0]]

count = 1
for lst in zeroes:
    for i in range(len(lst)):
        lst[i] = count
        count += 2

print(zeroes)
# [[1], [3, 5], [7, 9, 11], [13, 15, 17, 19]]

Which just updates the nested list of zeroes with odd numbers, based off a counter that increments in 2.

You could also do something more complicated like this, which uses iterators and itertools functions:

import itertools

def x(n):
    # get the zeroes sublists
    zeroes = [i * [0] for i in range(1, n+1)]

    # get the length of the flattened list above
    odd_len = len(list(itertools.chain.from_iterable(zeroes)))

    # get the odd numbers
    odd_numbers = [i for i in range(1, odd_len * 2, 2)]

    # check they are the same length
    assert(len(odd_numbers) == odd_len)

    # convert to iterator
    odd_numbers = iter(odd_numbers)

    # loop over the zeroes
    for lst in zeroes:

        for i in range(len(lst)):

            # update the zeroes with the odd numbers
            lst[i] = next(odd_numbers)

    return zeroes

>>> print(x(4))
[[1], [3, 5], [7, 9, 11], [13, 15, 17, 19]]

>>> print(x(10))
[[1], [3, 5], [7, 9, 11], [13, 15, 17, 19], [21, 23, 25, 27, 29], [31, 33, 35, 37, 39, 41], [43, 45, 47, 49, 51, 53, 55], [57, 59, 61, 63, 65, 67, 69, 71], [73, 75, 77, 79, 81, 83, 85, 87, 89], [91, 93, 95, 97, 99, 101, 103, 105, 107, 109]]


问:
Bottom navigation not working in android?
I have create a custom bottom navigation menu like below

```<code>    <item
        android:id="@+id/ic_home"
        android:icon="@drawable/ic_home"
        android:title="">
    </item>

    <item
        android:id="@+id/ic_search"
        android:icon="@drawable/ic_search"
        android:title="">
    </item>

    <item
        android:id="@+id/ic_camera"
        android:icon="@drawable/ic_camera"
        android:title="">
    </item>
</code>```

I have include that in my main activity and I have use a frame layout to go create fragments when i click item it will change

activity_main.xml file like below

```<code>       <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="53dp">

        </FrameLayout>

        <!--bottom navigartion-->
        <include layout="@layout/layout_bottom_navigation_view" />
</code>```

my MainActivity.java file like below what did I do wrong

```<code>public class MainActivity extends AppCompatActivity {

    BottomNavigationViewEx bottomNavigationViewEx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottom_nav_view_bar);
        BottomNavigationViewHelper.setupBottmNavigationView(bottomNavigationViewEx);

        BottomNavigationViewEx.OnNavigationItemSelectedListener onNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();

                switch (item.getItemId()) {
                    case R.id.ic_home :
                        transaction.replace(R.id.container, new HomeFragment()).commit();
                        return true;
                    case R.id.ic_search :
                        transaction.replace(R.id.container, new SearchFragment()).commit();
                        return true;
                    case R.id.ic_camera :
                        transaction.replace(R.id.container, new CameraFragment()).commit();
                        return true;
                    case R.id.ic_alert :
                        transaction.replace(R.id.container, new AlertFragment()).commit();
                        return true;
                    case R.id.ic_user :
                        transaction.replace(R.id.container, new UserFragment()).commit();
                        return true;
                }
                return false;
            }
        };

    }
}
</code>```

Any help?

答:
Include layout_bottom_navigation_view  inside the  frame layout or another way is set fragmelayout margin bottom  is height of layout_bottom_navigation_view

```<code>  <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="53dp">
      <include layout="@layout/layout_bottom_navigation_view" />
    </FrameLayout>
</code>```

Edited : bottomNavigationViewEx use instead of BottomNavigationViewEx then onclick will be work

```<code> bottomNavigationViewEx.OnNavigationItemSelectedListener onNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
   }
</code>```

Body:
I have create a custom bottom navigation menu like below

    <item
        android:id="@+id/ic_home"
        android:icon="@drawable/ic_home"
        android:title="">
    </item>

    <item
        android:id="@+id/ic_search"
        android:icon="@drawable/ic_search"
        android:title="">
    </item>

    <item
        android:id="@+id/ic_camera"
        android:icon="@drawable/ic_camera"
        android:title="">
    </item>

I have include that in my main activity and I have use a frame layout to go create fragments when i click item it will change

activity_main.xml file like below

       <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="53dp">

        </FrameLayout>

        <include layout="@layout/layout_bottom_navigation_view" />

my MainActivity.java file like below what did I do wrong

public class MainActivity extends AppCompatActivity {

    BottomNavigationViewEx bottomNavigationViewEx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottom_nav_view_bar);
        BottomNavigationViewHelper.setupBottmNavigationView(bottomNavigationViewEx);

        BottomNavigationViewEx.OnNavigationItemSelectedListener onNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();

                switch (item.getItemId()) {
                    case R.id.ic_home :
                        transaction.replace(R.id.container, new HomeFragment()).commit();
                        return true;
                    case R.id.ic_search :
                        transaction.replace(R.id.container, new SearchFragment()).commit();
                        return true;
                    case R.id.ic_camera :
                        transaction.replace(R.id.container, new CameraFragment()).commit();
                        return true;
                    case R.id.ic_alert :
                        transaction.replace(R.id.container, new AlertFragment()).commit();
                        return true;
                    case R.id.ic_user :
                        transaction.replace(R.id.container, new UserFragment()).commit();
                        return true;
                }
                return false;
            }
        };

    }
}

Any help?

Body:
Include layout_bottom_navigation_view  inside the  frame layout or another way is set fragmelayout margin bottom  is height of layout_bottom_navigation_view

  <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="53dp">
      <include layout="@layout/layout_bottom_navigation_view" />
    </FrameLayout>

Edited : bottomNavigationViewEx use instead of BottomNavigationViewEx then onclick will be work

 bottomNavigationViewEx.OnNavigationItemSelectedListener onNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
   }


问:
Child Components are not being re-rendered
I'm new to React. As a learning exercise I'm building an chess application

I want to change the DOM of child based on state in parent. Currently there is no change in child components on change of state in parent.

Parent Component

```<code>class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                board_position = { 'One' : ''}
            }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })

        //this.forceUpdate(); // Just trying different methods to make it work
    }

    render(){
        return(
            <div onClick={(e) => this.handleClick(e) }>
                <Piece {...this.state.game.board_position} />
            </div>
        )
    }
}
</code>```

Child Component

```<code>Class Piece extends Component{

    constructor(){
        super(props);
        this.state = {
            clr : ''
        }
    }

    componentWillMount(){
        let c;

        // some computations that change value of c based on props
        if( typeof ( this.props.game.one) == number ){
            c = 'Red'
        } else {
            c = 'Blue'
        }

        this.setState({
            clr : c
        })

    }

    render(){
        return(
            <span>{this.state.clr}</span>
        )
    }
}
</code>```

On call of handle click method, there is a change in state of the game. However, subsequent changes in Child are not seen.

Can anyone please help me out? Where am I going wrong?

I'm not sure how to implement ref as suggested over here. However, I don't think that is a good solution. Probably I'm having some conceptual misunderstanding.

PS: Please ignore any syntax error. This code is a strip down of real code.
If you want to take a look at full code - go over here

答:
A component re render when it's props or states get changed. There will be certain life cycle methods get invoked based on the values of props and own states.

The way you accessed your **props is wrong.**
It should be

```<code>this.props.One
</code>```

Life cycle method you should have used is componentWillReciveProps(nextProps). In that case you should access the relevant prop like below

```<code>nextProps.One
</code>```

I have created a working fiddle (your code had errors if you fixed those and looked at your log you could have easily figure out where the error is)

Body:
I'm new to React. As a learning exercise I'm building an chess application

I want to change the DOM of child based on state in parent. Currently there is no change in child components on change of state in parent.

Parent Component

class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                board_position = { 'One' : ''}
            }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })

        //this.forceUpdate(); // Just trying different methods to make it work
    }

    render(){
        return(

 this.handleClick(e) }>
                <Piece {...this.state.game.board_position} />

        )
    }
}

Child Component

Class Piece extends Component{

    constructor(){
        super(props);
        this.state = {
            clr : ''
        }
    }

    componentWillMount(){
        let c;

        // some computations that change value of c based on props
        if( typeof ( this.props.game.one) == number ){
            c = 'Red'
        } else {
            c = 'Blue'
        }

        this.setState({
            clr : c
        })

    }

    render(){
        return(
            {this.state.clr}
        )
    }
}

On call of handle click method, there is a change in state of the game. However, subsequent changes in Child are not seen.

Can anyone please help me out? Where am I going wrong?

I'm not sure how to implement ref as suggested over here. However, I don't think that is a good solution. Probably I'm having some conceptual misunderstanding.

PS: Please ignore any syntax error. This code is a strip down of real code.
If you want to take a look at full code - go over here

Body:
A component re render when it's props or states get changed. There will be certain life cycle methods get invoked based on the values of props and own states.

The way you accessed your **props is wrong.**
It should be

this.props.One

Life cycle method you should have used is componentWillReciveProps(nextProps). In that case you should access the relevant prop like below

nextProps.One

I have created a working fiddle (your code had errors if you fixed those and looked at your log you could have easily figure out where the error is)


问:
Promisifying Node SSH2 SFTP with Bluebird
I am using https://github.com/mscdex/ssh2 for my FTP requirements.
I tried below mentioned code:

```<code>'use strict';

global.Promise = require("bluebird");
global._ = require('lodash');

var Client = Promise.promisifyAll(require('ssh2').Client);
Promise.promisifyAll(Client.prototype);

var clientObject, conn;

function getClient() {
    return new Promise((resolve, reject) => {
        if (clientObject) resolve(clientObject);

        let authObj = {
            host: 'abc',
            port: 22,
            username: 'name',
            password: 'password'
        };

        conn = new Client();
        conn.connect(authObj);

        conn.on('ready', () => {
            conn.sftp((err, sftp) => {
                if (err) reject(err);
                clientObject = sftp;
                resolve(clientObject)
            });
        });

        conn.on('error', (err) => { reject(err) });
    });
}

function getList(){
    getClient().then((cObj)=>{
        cObj.readdir('.').then((list)=>{
            _.each(list, (file)=>{console.log(file.filename)});
        });
    });
}

getList();
</code>```

Above is given errors as:

```<code>Unhandled rejection TypeError: cObj.readdir(...).then is not a function
.
.
.
/home/nk/test/node_modules/ssh2-streams/lib/sftp.js:1583
            cb(undefined, entries);
            ^

TypeError: cb is not a function
    at /home/nk/test/node_modules/ssh2-streams/lib/sftp.js:1583:13
</code>```

From above error; it looks like it is pointing to this line https://github.com/mscdex/ssh2-streams/blob/master/lib/sftp.js#L1583

Is it possible to achieve ?

答: I have created a ssh2-promise npm package for catering the same. I have promisified SSH2 and SFTP item. Hopefully, it will help</p>

Body:
I am using https://github.com/mscdex/ssh2 for my FTP requirements.
I tried below mentioned code:

'use strict';

global.Promise = require("bluebird");
global._ = require('lodash');

var Client = Promise.promisifyAll(require('ssh2').Client);
Promise.promisifyAll(Client.prototype);

var clientObject, conn;

function getClient() {
    return new Promise((resolve, reject) => {
        if (clientObject) resolve(clientObject);

        let authObj = {
            host: 'abc',
            port: 22,
            username: 'name',
            password: 'password'
        };

        conn = new Client();
        conn.connect(authObj);

        conn.on('ready', () => {
            conn.sftp((err, sftp) => {
                if (err) reject(err);
                clientObject = sftp;
                resolve(clientObject)
            });
        });

        conn.on('error', (err) => { reject(err) });
    });
}

function getList(){
    getClient().then((cObj)=>{
        cObj.readdir('.').then((list)=>{
            _.each(list, (file)=>{console.log(file.filename)});
        });
    });
}

getList();

Above is given errors as:

Unhandled rejection TypeError: cObj.readdir(...).then is not a function
.
.
.
/home/nk/test/node_modules/ssh2-streams/lib/sftp.js:1583
            cb(undefined, entries);
            ^

TypeError: cb is not a function
    at /home/nk/test/node_modules/ssh2-streams/lib/sftp.js:1583:13

From above error; it looks like it is pointing to this line https://github.com/mscdex/ssh2-streams/blob/master/lib/sftp.js#L1583

Is it possible to achieve ?


问:
zsh alias expansion
Is it possible to configure zsh to expand global aliases during tab completion?  For example, I have the common aliases:

```<code>alias -g '...'='../..'
alias -g '....'='../../..'
</code>```

but when I type, for example, cd .../some<tab> it won't expand to cd .../something or cd ../../something.  Consequently, I frequently won't use these handy aliases because they are incompatible with tab completion.

答:
I'm a user of Mikael Magnusson's rationalise-dot. From my zshrc:

```<code># This was written entirely by Mikael Magnusson (Mikachu)
# Basically type '...' to get '../..' with successive .'s adding /..
function rationalise-dot {
    local MATCH # keep the regex match from leaking to the environment
    if [[ $LBUFFER =~ '(^|/| |      |'$'\n''|\||;|&)\.\.$' ]]; then
      LBUFFER+=/
      zle self-insert
      zle self-insert
    else
      zle self-insert
    fi
}
zle -N rationalise-dot
bindkey . rationalise-dot
# without this, typing a . aborts incremental history search
bindkey -M isearch . self-insert
</code>```

Title: zsh alias expansion

Body:
Is it possible to configure zsh to expand global aliases during tab completion?  For example, I have the common aliases:

alias -g '...'='../..'
alias -g '....'='../../..'

but when I type, for example, cd .../some<tab> it won't expand to cd .../something or cd ../../something.  Consequently, I frequently won't use these handy aliases because they are incompatible with tab completion.

Body:
I'm a user of Mikael Magnusson's rationalise-dot. From my zshrc:

# This was written entirely by Mikael Magnusson (Mikachu)
# Basically type '...' to get '../..' with successive .'s adding /..
function rationalise-dot {
    local MATCH # keep the regex match from leaking to the environment
    if [[ $LBUFFER =~ '(^|/| |      |'$'\n''|\||;|&)\.\.$' ]]; then
      LBUFFER+=/
      zle self-insert
      zle self-insert
    else
      zle self-insert
    fi
}
zle -N rationalise-dot
bindkey . rationalise-dot
# without this, typing a . aborts incremental history search
bindkey -M isearch . self-insert


问:
Internet Explorer is opening when redirecting to my browser
I have a problem. I have created WebBrowser in C++. I am opening the site (for Example: http://google.com) and click to the link it's opening an Internet bRowser with that uri but I want to open the link  in the my program. How to do that?</p>

答:
Change the default program to access the web content. To do so, do following:

Control Panel -> Programs -> Default Programs

Here set your provide your program(.EXE) path for appropriate content type.


问:
Add more field into header using interceptor of spring boot not work
I'm using spring boot.
I want to add a field into header of every response. So that, i using interceptor. The code is:

```<code>@Component
public class ApiVersionInterceptor extends HandlerInterceptorAdapter{
    private final Logger log = LoggerFactory.getLogger(ApiVersionInterceptor.class);

    @Autowired
    private Environment environment;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception arg3) throws Exception {
        String apiVersion = environment.getProperty(ApiVersion.VERSION_KEY.getKey());
        log.debug("api-version:"+apiVersion);
        response.addHeader("Api-Version", apiVersion);
    }
}
</code>```

And the configuration is:

```<code>@Configuration
public class InterceptorsConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private ApiVersionInterceptor apiVersionInterceptor;

    /**
     * Add interceptor
     */
    @Override
    public void addInterceptors(final InterceptorRegistry registry) {

        //Add api-version field to header of response
        registry.addInterceptor(apiVersionInterceptor);
    }

}
</code>```

To make sure this snipped code is run because of:

```<code>2017-12-06 02:35:10,392 DEBUG [] [http-nio-8080-exec-7] ApiVersionInterceptor: api-version:1.9.0
</code>```

But i don't understand, i don't see this field in the header of any response.

Update

My app use Restful webservice, so don't have view phase.

Thanks for help.

答: You should add header in a earlier phase, override the preHandle method in your ApiVersionInterceptor. Because in afterCompletion response is already committed and skip header changes.

Body:
I'm using spring boot.
I want to add a field into header of every response. So that, i using interceptor. The code is:

@Component
public class ApiVersionInterceptor extends HandlerInterceptorAdapter{
    private final Logger log = LoggerFactory.getLogger(ApiVersionInterceptor.class);

    @Autowired
    private Environment environment;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception arg3) throws Exception {
        String apiVersion = environment.getProperty(ApiVersion.VERSION_KEY.getKey());
        log.debug("api-version:"+apiVersion);
        response.addHeader("Api-Version", apiVersion);
    }
}

And the configuration is:

@Configuration
public class InterceptorsConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private ApiVersionInterceptor apiVersionInterceptor;

    /**
     * Add interceptor
     */
    @Override
    public void addInterceptors(final InterceptorRegistry registry) {

        //Add api-version field to header of response
        registry.addInterceptor(apiVersionInterceptor);
    }

}

To make sure this snipped code is run because of:

2017-12-06 02:35:10,392 DEBUG [] [http-nio-8080-exec-7] ApiVersionInterceptor: api-version:1.9.0

But i don't understand, i don't see this field in the header of any response.

Update

My app use Restful webservice, so don't have view phase.

Thanks for help.


问:
How do you create Tuples from two lists so that one list elements repeat
I'm trying to join 2 list such that the values in the first list get joined to the values in the second list in order and then join again when the list one items have exhausted...

```<code>worker_tables=['table1','table2']

mylist = [['val1','val2'], ['val3','val4'],['val5','val6'],['val7','val8'],['val9','val10']]

mylist_tup = zip(mylist, worker_tables)
</code>```

the result i'm getting is--

```<code>print mylist_tup

[(['val1', 'val2'], 'table1'), (['val3', 'val4'], 'table2')]
</code>```

as you see, it's not joining back to table1 and table2 fields from the first list..

desired output=

```<code> [(['val1', 'val2'], 'table1'),(['val3', 'val4'], 'table2'), (['val5', 'val6'], 'table1'),(['val7', 'val8'], 'table2'), (['val9', 'val10'], 'table1')]
</code>```

答:
You can use itertools.cycle to achieve the desired result:

```<code>from itertools import cycle

mylist_tup = zip(mylist, cycle(worker_tables))
</code>```

This will cycle through the values of worker_tables as many times as needed.

Body:
I'm trying to join 2 list such that the values in the first list get joined to the values in the second list in order and then join again when the list one items have exhausted...

worker_tables=['table1','table2']

mylist = [['val1','val2'], ['val3','val4'],['val5','val6'],['val7','val8'],['val9','val10']]

mylist_tup = zip(mylist, worker_tables)

the result i'm getting is--

print mylist_tup

[(['val1', 'val2'], 'table1'), (['val3', 'val4'], 'table2')]

as you see, it's not joining back to table1 and table2 fields from the first list..

desired output=

 [(['val1', 'val2'], 'table1'),(['val3', 'val4'], 'table2'), (['val5', 'val6'], 'table1'),(['val7', 'val8'], 'table2'), (['val9', 'val10'], 'table1')]

Body:
You can use itertools.cycle to achieve the desired result:

from itertools import cycle

mylist_tup = zip(mylist, cycle(worker_tables))

This will cycle through the values of worker_tables as many times as needed.


问:
DataAnnotations and multi lingual web applications
ASP.NET MVC has a nice feature called DataAnnotations that can simplify validation of user input. I couldn't find a way to work with the builtin data annotations so that the validation message will change if the user is running the spanish version of my application. Can someone put an example that takes multiple languages into account?</p>

答:
It will get quite ugly fast.

```<code>public class User
{
    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
    public int Id { get; set; }

    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
    [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
    public string FirstName { get; set; }

    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
    [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
    public string LastName { get; set; }
}
</code>```

I got a prettier solution in my blog: http://blog.gauffin.org/2010/11/simplified-localization-for-dataannotations/

Body:
It will get quite ugly fast.

public class User
{
    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
    public int Id { get; set; }

    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
    [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
    public string FirstName { get; set; }

    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
    [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
    public string LastName { get; set; }
}

I got a prettier solution in my blog: http://blog.gauffin.org/2010/11/simplified-localization-for-dataannotations/


问:
Apply a particular style to all child elements of a Xamarin.Forms element
I have a Style with target type Grid. I want all Entry child elements within a grid of this style to automatically acquire a particular style.

I've had a look at these:

Styling nested elements in WPF

Apply Style to all child-elements of specific type

The only solution appears to be setting Resources within the parent Style, so this is what I've done:

```<code><Style x:Key="BuggyGrid" TargetType="Grid">
    <!-- bunch of property setters -->
    <Style.Resources>
        <Style TargetType="Entry">
            <Setter Property="FontFamily" Value="Arial" />
        </Style>
    </Style.Resources>
</Style>
</code>```

However, I get a build error:
"No property, bindable property, or event found for 'Resources'".

Why do I get this error?

I'm using Xamarin.Forms 2.3.2.

答:
The links you have referenced are specific to WPF XAML and do not apply to Xamarin.Forms XAML.

I'm not sure how you would achieve nested styles in Xamarin.Forms.

The only possibility is XamlCSS which I haven't personally used.

https://www.nuget.org/packages/XamlCSS.xamarinforms/2.0.0-pre1

Body:
I have a Style with target type Grid. I want all Entry child elements within a grid of this style to automatically acquire a particular style.

I've had a look at these:

Styling nested elements in WPF

Apply Style to all child-elements of specific type

The only solution appears to be setting Resources within the parent Style, so this is what I've done:

    </Style.Resources>
</Style>

However, I get a build error:
"No property, bindable property, or event found for 'Resources'".

Why do I get this error?

I'm using Xamarin.Forms 2.3.2.


答:
You can repeat the worker_table list items out to the length of mylist:</p>

```<code>worker_tables=['table1','table2']

mylist = [['val1','val2'], ['val3','val4'],['val5','val6'],['val7','val8'],['val9','val10']]

mylist_tup = zip(mylist, worker_tables * int(len(mylist) / len(worker_tables)))
</code>```

Title: How do you create Tuples from two lists so that one list elements repeat

Body:
You can repeat the worker_table list items out to the length of mylist:

worker_tables=['table1','table2']

mylist = [['val1','val2'], ['val3','val4'],['val5','val6'],['val7','val8'],['val9','val10']]

mylist_tup = zip(mylist, worker_tables * int(len(mylist) / len(worker_tables)))


问:
Azure functions post issue
Hi Iam new to Azure functions i am using VS 2017 15.4 and running helloworld function app on local. i was able to do get request on this function but when i perform post on same uri it gives.

mscorlib: Exception while executing function: HelloWorld. System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'application/octet-stream'.

can you tell me what i forgot bold line is giving problem in post request, i tried with contentType and without ContentType; with body and without body.

How can i parse Json object in request body in azure function. one way i could was to parse it in string then deserialized using jsonconvert. is their any better way of doing it like valueproviders modelbinders etc.

```<code>[FunctionName("HelloWorld")]
public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");

        // parse query parameter
        string name = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
            .Value;

        // Get request body
        *dynamic data = await req.Content.ReadAsAsync<object>();*

        // Set name to query string or body data
        name = name ?? data?.name;

        return name == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }.
</code>```

答:
As Connor said as long as the Content-Type header is set to application/json in your request this code will work fine. An issue I have run into though is that the add header functionality when testing azure functions in azure portal doesn't seem to work in this case.

If you can send a request to your function from outside of the test section of azure functions this should work fine.

Title: Azure functions post issue

Body:
Hi Iam new to Azure functions i am using VS 2017 15.4 and running helloworld function app on local. i was able to do get request on this function but when i perform post on same uri it gives.

mscorlib: Exception while executing function: HelloWorld. System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'application/octet-stream'.

can you tell me what i forgot bold line is giving problem in post request, i tried with contentType and without ContentType; with body and without body.

How can i parse Json object in request body in azure function. one way i could was to parse it in string then deserialized using jsonconvert. is their any better way of doing it like valueproviders modelbinders etc.

[FunctionName("HelloWorld")]
public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");

        // parse query parameter
        string name = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
            .Value;

        // Get request body
        *dynamic data = await req.Content.ReadAsAsync<object>();*

        // Set name to query string or body data
        name = name ?? data?.name;

        return name == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }.


问:
How can I align multiple plots by their titles instead of plot area?
I'm using egg to align multiple plots on a page. I'm wondering if it's possible to align two columns by the titles a) and c) instead of plot area? Thanks!

Code:

```<code>library(egg)
library(grid)

p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)")
p1

p2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_wrap(~ cyl, ncol = 2, scales = "free") +
  guides(colour = "none") +
  theme() + ggtitle("b)")
p2

p3 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_grid(. ~ am, scales = "free") + guides(colour="none") +
  ggtitle("c)")
p3

g1 <- ggplotGrob(p1)

g2 <- ggplotGrob(p2)

g3 <- ggplotGrob(p3)

fg1 <- gtable_frame(g1, debug = TRUE)
fg2 <- gtable_frame(g2, debug = TRUE)
fg12 <- gtable_frame(gtable_rbind(fg1, fg2),
                     width = unit(2, "null"),
                     height = unit(1, "null"))
fg3 <-
  gtable_frame(
    g3,
    width = unit(2, "null"),
    height = unit(1, "null"),
    debug = TRUE
  )
grid.newpage()
combined <- gtable_cbind(fg12, fg3)
grid.draw(combined)
</code>```

Plot:

答:
Adding a blank dummy faceting variable to plot p1/ a) seems like the easiest solution

```<code>p1 <- ggplot(data.frame(mtcars, dummy=''),
             aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)") +
  facet_wrap(~dummy)
</code>```

Body:
I'm using egg to align multiple plots on a page. I'm wondering if it's possible to align two columns by the titles a) and c) instead of plot area? Thanks!

Code:

library(egg)
library(grid)

p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)")
p1

p2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_wrap(~ cyl, ncol = 2, scales = "free") +
  guides(colour = "none") +
  theme() + ggtitle("b)")
p2

p3 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_grid(. ~ am, scales = "free") + guides(colour="none") +
  ggtitle("c)")
p3

g1 <- ggplotGrob(p1)

g2 <- ggplotGrob(p2)

g3 <- ggplotGrob(p3)

fg1 <- gtable_frame(g1, debug = TRUE)
fg2 <- gtable_frame(g2, debug = TRUE)
fg12 <- gtable_frame(gtable_rbind(fg1, fg2),
                     width = unit(2, "null"),
                     height = unit(1, "null"))
fg3 <-
  gtable_frame(
    g3,
    width = unit(2, "null"),
    height = unit(1, "null"),
    debug = TRUE
  )
grid.newpage()
combined <- gtable_cbind(fg12, fg3)
grid.draw(combined)

Plot:

Body:
Adding a blank dummy faceting variable to plot p1/ a) seems like the easiest solution

p1 <- ggplot(data.frame(mtcars, dummy=''),
             aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)") +
  facet_wrap(~dummy)


问:
java integer not working as expected

Here is my code
this should output (8477559501395327) but it is giving(2084842641)
whats the problem here. I tried long instead of int but it gives some different answer </p>

```<code>    int counter = 0;
    int counter2 =0;
    int k=203903;
    int result=0;
    int countequalk =0;
    int i=0;

   while(true){

        if( i % 2 != 0){
            counter++;
            if(counter<k){
                counter2=counter2+counter;
            }
            //System.out.println(counter+" "+i);

           if(counter>counter2&&counter<=counter2+k){

               result = result+i;
               countequalk++;
           }
           if(countequalk==k){
               break;
           }
        }
        i++;

    }

    System.out.println(result);
</code>```

答: The number 8477559501395327 doesn't fit into an int - which supports values up to 2^31 - 1, as specified by Integer.MAX_VALUE. try using a long instead, which has a maximum value of 2^63 - 1, as indicated by Long.MAX_VALUE. This value is greater than 8477559501395327, so it fits. For even bigger numbers, better use BigInteger.

Title: java integer not working as expected

Body:
Here is my code
this should output (8477559501395327) but it is giving(2084842641)
whats the problem here. I tried long instead of int but it gives some different answer

    int counter = 0;
    int counter2 =0;
    int k=203903;
    int result=0;
    int countequalk =0;
    int i=0;

   while(true){

        if( i % 2 != 0){
            counter++;
            if(counter<k){
                counter2=counter2+counter;
            }
            //System.out.println(counter+" "+i);

           if(counter>counter2&&counter<=counter2+k){

               result = result+i;
               countequalk++;
           }
           if(countequalk==k){
               break;
           }
        }
        i++;

    }

    System.out.println(result);


问:
select products from specific category codeigniter
Products are available in following categories

```<code>product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5
</code>```

I want to select products of specific category e.g. all products from category 2. what will be sql syntax

答:
You can use a simple SQL query & use this in your model.

```<code>public function get_product_category($category_id)
{
     $query = "SELECT * FROM product_table WHERE category_id LIKE '%$categoryid%'";
     return $this->db->query($query, $category_id)->result();
}
</code>```

It will find in your product table where category_id contain example 2.

But, like M Khalid Junaid said, you better learn about database normalization.

For example : Normalization Table

This is your table before normalized, the product ID is duplicated on 2 how can if that is a primary key ? So, try to change your table to normalized table, it will help you so much.

```<code>product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5
</code>```

This is a new table are normalized after creating a table named group_table or whatever. Then set group_id as a primary_key

```<code>group_id       product_id       category_id
    1               2                 1
    2               2                 2
    3               3                 1
    4               3                 3
    5               4                 1
    6               4                 13
    7               2                 5
</code>```

The query for find the product from category_id is more simple, just

SELECT * FROM group_table WHERE category_id = $category_id

or any condition that you wanted to create. Like if you wanted to get product name just JOIN the table from product_table

Body:
Products are available in following categories

product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5

I want to select products of specific category e.g. all products from category 2. what will be sql syntax

Body:
You can use a simple SQL query & use this in your model.

public function get_product_category($category_id)
{
     $query = "SELECT * FROM product_table WHERE category_id LIKE '%$categoryid%'";
     return $this->db->query($query, $category_id)->result();
}

It will find in your product table where category_id contain example 2.

But, like M Khalid Junaid said, you better learn about database normalization.

For example : Normalization Table

This is your table before normalized, the product ID is duplicated on 2 how can if that is a primary key ? So, try to change your table to normalized table, it will help you so much.

product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5

This is a new table are normalized after creating a table named group_table or whatever. Then set group_id as a primary_key

group_id       product_id       category_id
    1               2                 1
    2               2                 2
    3               3                 1
    4               3                 3
    5               4                 1
    6               4                 13
    7               2                 5

The query for find the product from category_id is more simple, just

SELECT * FROM group_table WHERE category_id = $category_id

or any condition that you wanted to create. Like if you wanted to get product name just JOIN the table from product_table


问:
Issue when using string operation and pipe together
I have a HTML in a Angular 2.0 template like following:

```<code><span> Total Employee {{employeeCount> 0 ? '(' + employeeCount+ ')' : ''}} ></span>
</code>```

My customFormatter takes a value and format it with coma separator if its a number.

It works fine. Now I want to use a custom pipe to format the employee count and I have used the following code:

```<code><span>
   Total Employee {{employeeCount> 0 ? '(' + employeeCount | customFormatter + ')' : ''}} >
</span>
</code>```

But it gives syntax error: "Error: Template parse errors: Parser Error: Conditional expression..."

The pipe is working when I use as following:

```<code><span> Total Employee {{employeeCount | customFormatter }} ></span>
</code>```

How can I solve my issue?

答:
You should be writing this logic inside your customFormatter pipe

```<code>export class CustomFormatterPipe implements PipeTransform{

     transform(employeeCount){
      if({employeeCount> 0){
          // your logic here
      } else {
           return '';
      }

}
</code>```

Body:
I have a HTML in a Angular 2.0 template like following:

 Total Employee {{employeeCount> 0 ? '(' + employeeCount+ ')' : ''}} >

My customFormatter takes a value and format it with coma separator if its a number.

It works fine. Now I want to use a custom pipe to format the employee count and I have used the following code:

   Total Employee {{employeeCount> 0 ? '(' + employeeCount | customFormatter + ')' : ''}} >

But it gives syntax error: "Error: Template parse errors: Parser Error: Conditional expression..."

The pipe is working when I use as following:

 Total Employee {{employeeCount | customFormatter }} >

How can I solve my issue?

Body:
You should be writing this logic inside your customFormatter pipe

export class CustomFormatterPipe implements PipeTransform{

     transform(employeeCount){
      if({employeeCount> 0){
          // your logic here
      } else {
           return '';
      }

}


问:
How do I do full-text searching in Ruby on Rails?
I would like to do full-text searching of data in my Ruby on Rails application.  What options exist?</p>

答: I can recommend Sphinx. Ryan Bates has a great screencast on using the Thinking Sphinx plugin to create a full-text search solution.</p>

OwnerDisplayName: sock

OwnerDisplayName: John Topley


问:
How to get rid of Javascript Runtime Errors when running PDT + XDebug in Eclipse?
I am currently developing a Drupal webpage using PDT. When running without XDebug, the site works fine.

When I enable XDebug, the site works fine but opens up tons of Javascript errors that I need to click through.

Example:

A Runtime Error has occurred.
Do you wish to Debug?

Line: 1
Error: Syntax error

--

It seems to only be a problem when XDebug/PDT uses Firefox as its browser, this problem does not occur when using IE. Could it be some incompatability with Firebug?

答:
here is how to solve this problem:

Turn off XDebug output capture:

Window -> Preferences, expand PHP, expand Debug, select "Installed Debuggers", choose "XDebug", click "Configure" on the right to bring up the configure dialog. In the middle "Output Capture Settings", set "Capture stdout" to "Off".

OwnerDisplayName: Matthew