问:
Why Erlang Dialyzer cannot find type error in the following code?
free_vars_in_dterm({var, V}) -> {var, V}; obviously cannot type check, however, dialyzer says everything is OK.

```<code>$ dialyzer *erl
  Checking whether the PLT ~/.dialyzer_plt is up-to-date... yes
  Proceeding with analysis... done in 0m0.66s
done (passed successfully)
</code>```

Code is as below:

```<code>-module(formulas).

-type formulas() :: {predicate(), [dterm()]}
                  | {'~', formulas()}
                  | {'&', formulas(), formulas()}
                  | {'|', formulas(), formulas()}
                  | {'->', formulas(), formulas()}
                  | {'<->', formulas(), formulas()}
                  | {'exist', variable(), formulas()}
                  | {'any', variable(), formulas()}.

-type dterm() :: constant()
               | variable()
               | {func(), [dterm()]}.

-type constant() :: {const, atom()}
                  | {const, integer()}.

-type variable() :: {var, atom()}.

-type func() :: {function,
                 Function_name::atom(),
                 Arity::integer()}.

-type predicate() :: {predicate,
                      Predicate_name::atom(),
                      Arity::integer()}.

-include_lib("eunit/include/eunit.hrl").

-export([is_ground/1, free_vars/1, is_sentence/1]).

-spec is_ground(formulas()) -> boolean().
is_ground({_, {var, _}, _}) -> false;
is_ground({{predicate, _, _}, Terms}) ->
    lists:all(fun is_ground_term/1, Terms);
is_ground(Formulas) ->
    Ts = tuple_size(Formulas),
    lists:all(fun is_ground/1, [element(I, Formulas)
                                || I <- lists:seq(2, Ts)]).

-spec is_ground_term(dterm()) -> boolean().
is_ground_term({const, _}) -> true;
is_ground_term({var, _}) -> false;
is_ground_term({{function, _, _}, Terms}) ->
    lists:all(fun is_ground_term/1, Terms).

-spec is_sentence(formulas()) -> boolean().
is_sentence(Formulas) ->
    sets:size(free_vars(Formulas)) =:= 0.

-spec free_vars(formulas()) -> sets:set(variable()).
free_vars({{predicate, _, _}, Dterms}) ->
    join_sets([free_vars_in_dterm(Dterm)
               || Dterm <- Dterms]);
free_vars({_Qualify, {var, V}, Formulas}) ->
    sets:del_element({var, V}, free_vars(Formulas));
free_vars(Compound_formulas) ->
    Tp_size = tuple_size(Compound_formulas),
    join_sets([free_vars(element(I, Compound_formulas))
               || I <- lists:seq(2, Tp_size)]).

-spec free_vars_in_dterm(dterm()) -> sets:set(variable()).
free_vars_in_dterm({const, _}) -> sets:new();
free_vars_in_dterm({var, V}) -> {var, V};
free_vars_in_dterm({{function, _, _}, Dterms}) ->
    join_sets([free_vars_in_dterm(Dterm)
               || Dterm <- Dterms]).

-spec join_sets([sets:set(T)]) -> sets:set(T).
join_sets(Set_list) ->
    lists:foldl(fun (T, Acc) -> sets:union(T, Acc) end,
                sets:new(),
                Set_list).
</code>```

答:
First a short answer, using Dialyzer's maxims :

Dialyzer is never wrong. (recited very often by Erlang programmers)

Dialyzer never promised to find all errors in your code. (not so famous)

Maxim number 2 is the (admittedly not very satisfying) "standard" answer to any "Why Dialyzer didn't catch this error" question.

More explanatory answer:

Dialyzer's analysis for return values of functions is frequently doing over-approximations. As a result, any value included in the types should be considered to be a "maybe returned" value. This has the unfortunate side-effect that sometimes values that are certainly going to be returned (such as your {var, V} tuple) are also considered "maybe returned". Dialyzer must guarantee maxim 1 (never be wrong), so in cases where an unexpected value "may be returned" it will not give a warning, unless none of the actually specified values can be returned. This last part is checked at the level of the entire function, and since in your example some of the clauses indeed return sets, no warnings are generated.

Body:
free_vars_in_dterm({var, V}) -> {var, V}; obviously cannot type check, however, dialyzer says everything is OK.

$ dialyzer *erl
  Checking whether the PLT ~/.dialyzer_plt is up-to-date... yes
  Proceeding with analysis... done in 0m0.66s
done (passed successfully)

Code is as below:

-module(formulas).

-type formulas() :: {predicate(), [dterm()]}
                  | {'~', formulas()}
                  | {'&', formulas(), formulas()}
                  | {'|', formulas(), formulas()}
                  | {'->', formulas(), formulas()}
                  | {'<->', formulas(), formulas()}
                  | {'exist', variable(), formulas()}
                  | {'any', variable(), formulas()}.

-type dterm() :: constant()
               | variable()
               | {func(), [dterm()]}.

-type constant() :: {const, atom()}
                  | {const, integer()}.

-type variable() :: {var, atom()}.

-type func() :: {function,
                 Function_name::atom(),
                 Arity::integer()}.

-type predicate() :: {predicate,
                      Predicate_name::atom(),
                      Arity::integer()}.

-include_lib("eunit/include/eunit.hrl").

-export([is_ground/1, free_vars/1, is_sentence/1]).

-spec is_ground(formulas()) -> boolean().
is_ground({_, {var, _}, _}) -> false;
is_ground({{predicate, _, _}, Terms}) ->
    lists:all(fun is_ground_term/1, Terms);
is_ground(Formulas) ->
    Ts = tuple_size(Formulas),
    lists:all(fun is_ground/1, [element(I, Formulas)
                                || I <- lists:seq(2, Ts)]).

-spec is_ground_term(dterm()) -> boolean().
is_ground_term({const, _}) -> true;
is_ground_term({var, _}) -> false;
is_ground_term({{function, _, _}, Terms}) ->
    lists:all(fun is_ground_term/1, Terms).

-spec is_sentence(formulas()) -> boolean().
is_sentence(Formulas) ->
    sets:size(free_vars(Formulas)) =:= 0.

-spec free_vars(formulas()) -> sets:set(variable()).
free_vars({{predicate, _, _}, Dterms}) ->
    join_sets([free_vars_in_dterm(Dterm)
               || Dterm <- Dterms]);
free_vars({_Qualify, {var, V}, Formulas}) ->
    sets:del_element({var, V}, free_vars(Formulas));
free_vars(Compound_formulas) ->
    Tp_size = tuple_size(Compound_formulas),
    join_sets([free_vars(element(I, Compound_formulas))
               || I <- lists:seq(2, Tp_size)]).

-spec free_vars_in_dterm(dterm()) -> sets:set(variable()).
free_vars_in_dterm({const, _}) -> sets:new();
free_vars_in_dterm({var, V}) -> {var, V};
free_vars_in_dterm({{function, _, _}, Dterms}) ->
    join_sets([free_vars_in_dterm(Dterm)
               || Dterm <- Dterms]).

-spec join_sets([sets:set(T)]) -> sets:set(T).
join_sets(Set_list) ->
    lists:foldl(fun (T, Acc) -> sets:union(T, Acc) end,
                sets:new(),
                Set_list).


来源: stackexchange

问:
Overloaded Equals method and putVal method in HashMap
I have two methods in my Emp class

```<code>class Emp
{
  String empId;
  public boolean equals(Emp e){..}
  public boolean equals(Object o){..}
  public int hashCode(){
  return empId.hashCode();
 }
}
</code>```

Now if a am trying to add Emp objects to a HashSet<Emp>.

If i look at the code of HashMap's putVal method which is used to compare and put values to the set. The code never casts your passed object to java.lang.Object.So every time the equals(Emp) version should get called.

But every time equals(Object o) gets called.I want to know when is this Emp converted to java.lang.Object so that everyTime the equals(Object o) gets called.

Below is the putval snippet i am using:

```<code> final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                        boolean evict) {
   Node<K,V>[] tab; Node<K,V> p; int n, i;
   if ((tab = table) == null || (n = tab.length) == 0)
     n = (tab = resize()).length;
   if ((p = tab[i = (n - 1) & hash]) == null)
     tab[i] = newNode(hash, key, value, null);
   else {
     Node<K,V> e; K k;
     if (p.hash == hash &&
          ((k = p.key) == key || (key != null && key.equals(k))))
       e = p;
     else if (p instanceof TreeNode)
       e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                     ....
    }
</code>```

答:
Beyond the correct argument from Eran; the point is don't do that.

Do not overload public boolean equals(Object)!

This is a method with a very defined and clear and known contract in Java. Adding your own public equals(Emp) only increases your risks of creating bugs.

If at all, make that method private; and call it from within the equals(Object) method.

You see, overloading is a concept that should be used really carefully, as all of that happens at compile time; and especially when combining it with polymorphism, unexpected things can happen at runtime (as you just learned).

ContentLicense: CC BY-SA 3.0

Body:
I have two methods in my Emp class

class Emp
{
  String empId;
  public boolean equals(Emp e){..}
  public boolean equals(Object o){..}
  public int hashCode(){
  return empId.hashCode();
 }
}

Now if a am trying to add Emp objects to a HashSet<Emp>.

If i look at the code of HashMap's putVal method which is used to compare and put values to the set. The code never casts your passed object to java.lang.Object.So every time the equals(Emp) version should get called.

But every time equals(Object o) gets called.I want to know when is this Emp converted to java.lang.Object so that everyTime the equals(Object o) gets called.

Below is the putval snippet i am using:

 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                        boolean evict) {
   Node<K,V>[] tab; Node<K,V> p; int n, i;
   if ((tab = table) == null || (n = tab.length) == 0)
     n = (tab = resize()).length;
   if ((p = tab[i = (n - 1) & hash]) == null)
     tab[i] = newNode(hash, key, value, null);
   else {
     Node<K,V> e; K k;
     if (p.hash == hash &&
          ((k = p.key) == key || (key != null && key.equals(k))))
       e = p;
     else if (p instanceof TreeNode)
       e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                     ....
    }


问:
Write data in Excel using POI. It delete my entire WorkBook?
I am new in Selenium. I am trying to write data in Excel file, by getting activeRow and search the column Heading.

My Code in Driver Script Class is like :

```<code>int activeRow = cnfig.isScenarioAvailable("New", cn);
    if (activeRow != 0) {
        String[] colHeading = new String[cnfig.getcolumnCount("New")];
        colHeading = cnfig.getcolumnHeadinginArray("New");

for (int counter = 0; counter < cnfig.getcolumnCount("New"); counter++) {
    if (colHeading[counter].equals("Name")) {
        inName = cn + " Test" + cmnfnc.getRandomNumber(5000, 100);
        cnfig.setData(activeRow, counter, "Name", inName);
    }
</code>```

And The Code in my Config Class is

```<code> XSSFWorkbook wb;
 XSSFSheet sht;

 File fl;
 FileInputStream fis;
 FileOutputStream fout;

 public ExcelConfig(String filePath) {
    try {
        fl = new File(filePath);
        fis = new FileInputStream(fl);
        wb = new XSSFWorkbook(fis);
        fout = new FileOutputStream(fl);

    }

public void setData(int activeRow, int activeCol, String sheetName, String value) {
    try {
        sht = wb.getSheet(sheetName);
        sht.getRow(activeRow).createCell(activeCol).setCellValue(value);
        wb.write(fout);
    }
</code>```

答:
This is not a selenium question kindly remove the selenium tag.

If you want to edit an excel workbook with poi you must 1st load your file inputstream

```<code>public void setData(int activeRow, int activeCol, String sheetName, String value) {

    try {
        FileInputStream in = new FileInputStream(yourFileLocation);
        XSSFWorkbook wb    = new XSSFWorkbook(in);  //I know this line is not suppose to be here, but I hope you get the general idea
        sht                = wb.getSheet(sheetName);

        sht.getRow(activeRow).createCell(activeCol).setCellValue(value);
        wb.write(fout);
    }
}
</code>```

Body:
I am new in Selenium. I am trying to write data in Excel file, by getting activeRow and search the column Heading.

My Code in Driver Script Class is like :

int activeRow = cnfig.isScenarioAvailable("New", cn);
    if (activeRow != 0) {
        String[] colHeading = new String[cnfig.getcolumnCount("New")];
        colHeading = cnfig.getcolumnHeadinginArray("New");

for (int counter = 0; counter < cnfig.getcolumnCount("New"); counter++) {
    if (colHeading[counter].equals("Name")) {
        inName = cn + " Test" + cmnfnc.getRandomNumber(5000, 100);
        cnfig.setData(activeRow, counter, "Name", inName);
    }

And The Code in my Config Class is

 XSSFWorkbook wb;
 XSSFSheet sht;

 File fl;
 FileInputStream fis;
 FileOutputStream fout;

 public ExcelConfig(String filePath) {
    try {
        fl = new File(filePath);
        fis = new FileInputStream(fl);
        wb = new XSSFWorkbook(fis);
        fout = new FileOutputStream(fl);

    }

public void setData(int activeRow, int activeCol, String sheetName, String value) {
    try {
        sht = wb.getSheet(sheetName);
        sht.getRow(activeRow).createCell(activeCol).setCellValue(value);
        wb.write(fout);
    }

Body:
This is not a selenium question kindly remove the selenium tag.

If you want to edit an excel workbook with poi you must 1st load your file inputstream

public void setData(int activeRow, int activeCol, String sheetName, String value) {

    try {
        FileInputStream in = new FileInputStream(yourFileLocation);
        XSSFWorkbook wb    = new XSSFWorkbook(in);  //I know this line is not suppose to be here, but I hope you get the general idea
        sht                = wb.getSheet(sheetName);

        sht.getRow(activeRow).createCell(activeCol).setCellValue(value);
        wb.write(fout);
    }
}


问:
UILabel Text with Multiple Font Colors
Is there a way to have the textColor property of a UILabel be two different UIColors? Basically I'm trying to make the first character in the UILabel text property to be greenColor and the rest be blackColor. I would like to avoid using two different UILabels because I may want to change the position in the text of the green character.

答: Another alternative way is to create multiple labels with difference color and layout them next to each other. Try to make the label's background color transparent. It may be tedious but should work.</p>

Title: UILabel Text with Multiple Font Colors

ContentLicense: CC BY-SA 2.5


问:
Slim 3 multiple routes to one function?
I've been looking all over online and can't find anything that tells you how to assign multiple routes to one callback. For example I want to move:

```<code>$app->get('/sign-in', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

$app->get('/login', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});
</code>```

into something like:

```<code>$app->get(['/sign-in', '/login'], function($request, $response) {
    return $this->view->render($response, 'home.twig');
});
</code>```

Is there a way to do this with Slim 3? I found online that in Slim 2 you could use the conditions([]); function on the end to chain multiple routes to one callback.

答:
FastRoute doesn't do what you want, however, you can use a parameter that is limited via regex to the list of urls that you want to use:

```<code>$app->get("/{_:sign-in|login}", function ($request, $response) {
    $response->write("Hello!");
    return $response;
});
</code>```

Note that you have to have an argument name, so I've use _ as it's inoffensive.

Title: Slim 3 multiple routes to one function?

Body:
I've been looking all over online and can't find anything that tells you how to assign multiple routes to one callback. For example I want to move:

$app->get('/sign-in', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

$app->get('/login', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

into something like:

$app->get(['/sign-in', '/login'], function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

Is there a way to do this with Slim 3? I found online that in Slim 2 you could use the conditions([]); function on the end to chain multiple routes to one callback.

Body:
FastRoute doesn't do what you want, however, you can use a parameter that is limited via regex to the list of urls that you want to use:

$app->get("/{_:sign-in|login}", function ($request, $response) {
    $response->write("Hello!");
    return $response;
});

Note that you have to have an argument name, so I've use _ as it's inoffensive.


问:
How to pass form values as FormData in reactjs on submit function
I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.</p>
```<code>var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (
          <div className={group.Type}>
            <div for="let value of group.Values">
              {group.Values.map(el=> (
                <label><input name="radios"/>{el.Value}</label>
              ))}
            </div>
          </div>
        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (
        <div>
          <label for={group.Label}>{group.Label}</label>
          <div>
            {this._renderElement(group)}
          </div>
        </div>
      )
    });
  },

  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (
      <div className="container">
        <br/>
        <div className="panel panel-primary">
          <div className="panel-heading">Form</div>
          <div className="panel-body">
            <form>
              <div className="form-group">
                <div className="col-xs-5">
                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));
</code>```

答:
To post the FormData using axios, you need specify in header that you are sending FormData, for that content-type should be multipart/form-data.

Check this, how to use FormData with axios:

```<code>let formData = new FormData();    //formdata object

formData.append('name', 'ABC');   //append the values with key, value pair
formData.append('age', 20);

const config = {
    headers: { 'content-type': 'multipart/form-data' }
}

axios.post(url, formData, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.

var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (

              {group.Values.map(el=> (
                <input name="radios"/>{el.Value}
              ))}

        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (

          {group.Label}

            {this._renderElement(group)}

      )
    });
  },

  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (

Form

            <form>

                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>

            </form>

    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));

Body:
To post the FormData using axios, you need specify in header that you are sending FormData, for that content-type should be multipart/form-data.

Check this, how to use FormData with axios:

let formData = new FormData();    //formdata object

formData.append('name', 'ABC');   //append the values with key, value pair
formData.append('age', 20);

const config = {
    headers: { 'content-type': 'multipart/form-data' }
}

axios.post(url, formData, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });


问:
How can access random .csv file on my computer for further manipulations?
I am only at the beginning of my python programming way.

```<code>f = csv.reader(open('andr.csv'), delimiter=',')
andr=[]
for row in f:
</code>```

This is for specific .csv file in my comp. I want to INPUT random file

```<code>file=print(input('File to analyze: '))
f = csv.reader(open(file), delimiter=',')
andr=[]
for row in f:
</code>```

This obviously doesn't work. As I've already told, I am just starting to study python and it is probably very easy, but I am stuck here. I appreciate any help.

答:
You can use glob module to get any filenames with specific extension(.csv) from any directory.

Then by using Random module you can randomly select any one file,

Please try this code,

```<code>import random
import glob

#total_files contains all CSV file names.
total_files = glob.glob(('*.csv'))

#randomly selecting one csv file.
file = random.choice(filee)

f = csv.reader(open(file), delimiter=',')
andr=[]
for row in f:
</code>```

Please let me know in terms of any queries.

Body:
I am only at the beginning of my python programming way.

f = csv.reader(open('andr.csv'), delimiter=',')
andr=[]
for row in f:

This is for specific .csv file in my comp. I want to INPUT random file

file=print(input('File to analyze: '))
f = csv.reader(open(file), delimiter=',')
andr=[]
for row in f:

This obviously doesn't work. As I've already told, I am just starting to study python and it is probably very easy, but I am stuck here. I appreciate any help.

Body:
You can use glob module to get any filenames with specific extension(.csv) from any directory.

Then by using Random module you can randomly select any one file,

Please try this code,

import random
import glob

#total_files contains all CSV file names.
total_files = glob.glob(('*.csv'))

#randomly selecting one csv file.
file = random.choice(filee)

f = csv.reader(open(file), delimiter=',')
andr=[]
for row in f:

Please let me know in terms of any queries.


问:
What is difference between isValid() and _isValid in moment.js?
I want to check whether moment object is valid or not, so i used both isValid() and _isValid in different places. Both are giving same results. So i want to know purpose of using both.

Note: I know basic diff that one is function and other one is attribute.

答:
isValid() is documented and so using it in prodution code is fine. It tells you whether the Moment instance contains a valid date/time.

_isValid is not documented and so using it in production code is a bad idea. It doesn't officially tell you anything. Its meaning could change, or it could disappear entirely, from one Moment to the next (see what I did there? ;-) ).

In general, in JavaScript, when you see a property name prefixed with _ it means "this is internal, pretend you don't see it."


问:
How to ignore certain files in Git
I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated.

I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked.

How can I make Git ignore Hello.class?

答:
Add the following line to file .gitignore:

```<code>/Hello.class
</code>```

This will exclude Hello.class from Git.  If you have already committed it, run the following command:

```<code>git rm Hello.class
</code>```

If you want to exclude all class files from Git, add the following line to .gitignore:

```<code>*.class
</code>```

Title: How to ignore certain files in Git

Body:
Add the following line to file .gitignore:

/Hello.class

This will exclude Hello.class from Git.  If you have already committed it, run the following command:

git rm Hello.class

If you want to exclude all class files from Git, add the following line to .gitignore:

*.class


问:
How to get previous LI in multi-level UL/LI elements
I have following html code:

```<code><ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul>
</code>```

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

答:
Try this :</p>

```<code>$('ul li').click(function(e) {
var element = $(this);
if(element.prevAll('li').length > 0) {
   element.prev('li').text();
} else {
   element.closest('ul').parent('li').text();
}
e.stopImmediatePropagation();
});
</code>```

Body:
I have following html code:

Parameter1

Group1

Parameter2

Parameter3

Parameter4

Group2

Parameter5

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

Body:
Try this :

$('ul li').click(function(e) {
var element = $(this);
if(element.prevAll('li').length > 0) {
   element.prev('li').text();
} else {
   element.closest('ul').parent('li').text();
}
e.stopImmediatePropagation();
});


问:
Showing toast causes app to crash
My class extends AppCompatActivity

This is my class

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

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

        final Button loginBtn = (Button) findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                Login login = new Login();
                try {
                    login.getAccessCode();
                }
                catch (IOException e){
                    Log.e("LOGIN", "I got an error", e);
                }

            }
        });
    }

    public void getAccessCode() throws IOException {
        RequestParams params = new RequestParams();
        params.put("a", "a");

        QuidoRestClient.post("/login/generateCode", params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // If the response is JSONObject instead of expected JSONArray
                Log.d("LOGIN",response.toString());
                String code = "";
                try {
                    code = response.getString("code");
                }
                catch (JSONException e){

                }
                Context context = getApplicationContext();
                CharSequence text = "Hello toast!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray data) {
                // If the response is JSONArray instead of expected JSONObject
            }
        });
    }
}
</code>```

This is the error

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
</code>```

I've also tried

```<code>Toast toast = Toast.makeText(Login.this, text, duration);
</code>```

I've solved the issue by calling my method directly instead of Login login = new Login();

答:
Activities are Contexts (or at least they inherit from Context). So instead of getApplicationContext(), simply use this or YourActivity.this in the first argument of Toast.makeText.

Another thing: don't do Login login = new Login();. Activities are instantiated by the Android runtime, not by us ! Instead, simply call getAccessCode() directly.

(Also, note that AppCompatActivity does not have any getApplicationContext method)

If the error persists, it might come from the fact that the onSuccess callback does not run in the UI thread. If this is the case, possible fixes are:

Don't use Toast, but Log to get debug messages:

```<code>Log.d("your tag", "your message");
</code>```

Enclose your toast creation inside a UI thread runnable:

```<code>runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(MyActivity.this, text, duration).show();
    }
});
</code>```

Title: Showing toast causes app to crash

Body:
My class extends AppCompatActivity

This is my class

public class Login extends AppCompatActivity {

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

        final Button loginBtn = (Button) findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                Login login = new Login();
                try {
                    login.getAccessCode();
                }
                catch (IOException e){
                    Log.e("LOGIN", "I got an error", e);
                }

            }
        });
    }

    public void getAccessCode() throws IOException {
        RequestParams params = new RequestParams();
        params.put("a", "a");

        QuidoRestClient.post("/login/generateCode", params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // If the response is JSONObject instead of expected JSONArray
                Log.d("LOGIN",response.toString());
                String code = "";
                try {
                    code = response.getString("code");
                }
                catch (JSONException e){

                }
                Context context = getApplicationContext();
                CharSequence text = "Hello toast!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray data) {
                // If the response is JSONArray instead of expected JSONObject
            }
        });
    }
}

This is the error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

I've also tried

Toast toast = Toast.makeText(Login.this, text, duration);

I've solved the issue by calling my method directly instead of Login login = new Login();

Body:
Activities are Contexts (or at least they inherit from Context). So instead of getApplicationContext(), simply use this or YourActivity.this in the first argument of Toast.makeText.

Another thing: don't do Login login = new Login();. Activities are instantiated by the Android runtime, not by us ! Instead, simply call getAccessCode() directly.

(Also, note that AppCompatActivity does not have any getApplicationContext method)

If the error persists, it might come from the fact that the onSuccess callback does not run in the UI thread. If this is the case, possible fixes are:

Don't use Toast, but Log to get debug messages:

Log.d("your tag", "your message");

Enclose your toast creation inside a UI thread runnable:

runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(MyActivity.this, text, duration).show();
    }
});


问:
How to show table in columns from to to bottom?
I have array:

```<code>$array = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];
</code>```

How can I show this data from array in table from top to bottom?

This should looks this:

```<code>category1  | category 2 | category3
product33  | product1   | product65
product41  | product45  | product23
           |            | product423
</code>```

I tried:

```<code><table>
  <tr>
     <?php foreach ($array as $category): ?>
         <td><?php echo $category ?></td>
     <?php endforeach ?>
  </tr>
//????
</table>
</code>```

答:
Take a look at this simple example:

```<code><?php
$data = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];

$maxSize = 0;
foreach ($data as $category) {
    $maxSize = max($maxSize, count($category));
}

for ($i=-1; $i<$maxSize; $i++) {
    foreach ($data as $key=>$category) {
        if (-1 === $i) {
            echo $key . "\t";
        } else {
            echo isset($category[$i]) ? $category[$i] . "\t" : "\t\t";
        }
    }
    echo "\n";
}
</code>```

The output of that code is:

```<code>category1       category2       category3
product33       product1        product65
product41       product45       product23
                                product423
</code>```

Note: this is meant to be used on CLI for demonstration purpose. The additional html markup would only bloat the code demonstration.

Body:
I have array:

$array = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];

How can I show this data from array in table from top to bottom?

This should looks this:

category1  | category 2 | category3
product33  | product1   | product65
product41  | product45  | product23
           |            | product423

I tried:

     <?php foreach ($array as $category): ?>
         <?php echo $category ?>
     <?php endforeach ?>

//????

Body:
Take a look at this simple example:

<?php
$data = [
    'category1' => [
        'product33',
        'product41'
    ],
    'category2' => [
        'product1',
        'product45'
    ],
    'category3' => [
        'product65',
        'product23',
        'product423'
    ],
];

$maxSize = 0;
foreach ($data as $category) {
    $maxSize = max($maxSize, count($category));
}

for ($i=-1; $i<$maxSize; $i++) {
    foreach ($data as $key=>$category) {
        if (-1 === $i) {
            echo $key . "\t";
        } else {
            echo isset($category[$i]) ? $category[$i] . "\t" : "\t\t";
        }
    }
    echo "\n";
}

The output of that code is:

category1       category2       category3
product33       product1        product65
product41       product45       product23
                                product423

Note: this is meant to be used on CLI for demonstration purpose. The additional html markup would only bloat the code demonstration.


答:
Create a .gitignore file in the directory where directory .git is. You can list files in it separated by a newline. You also can use wildcards:

```<code>*.o
.*.swp
</code>```

Title: How to ignore certain files in Git

Body:
I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated.

I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked.

How can I make Git ignore Hello.class?

Body:
Create a .gitignore file in the directory where directory .git is. You can list files in it separated by a newline. You also can use wildcards:

*.o
.*.swp


问:
Exponential of large negative numbers
How does one compute a number such as np.exp(-28000) on Python? The answer is around 5E-12161. I've been told that due to the double-precision floating point format, I would only be able to calculate a number > 1e-2048</p>

答:
You could define a function to calculate the "bigexponent" and apply it to the array (along an axis). But, note that the input array has to be of type int.

```<code># solution courtesy: http://stackoverflow.com/a/43084475/2956066
In [97]: def bigexp(x):
    ...:     return Decimal(math.exp(1))**x

In [98]: np.apply_along_axis(bigexp, 1, arr)
</code>```

Efficiency (in descending order)

```<code># twice faster than applying along axis 0
In [115]: %timeit np.apply_along_axis(bigexp, 1, a)
1000 loops, best of 3: 272 µs per loop

In [116]: %timeit np.apply_along_axis(bigexp, 0, a)
1000 loops, best of 3: 465 µs per loop
</code>```

Title: Exponential of large negative numbers

Body:
You could define a function to calculate the "bigexponent" and apply it to the array (along an axis). But, note that the input array has to be of type int.

# solution courtesy: http://stackoverflow.com/a/43084475/2956066
In [97]: def bigexp(x):
    ...:     return Decimal(math.exp(1))**x

In [98]: np.apply_along_axis(bigexp, 1, arr)

Efficiency (in descending order)

# twice faster than applying along axis 0
In [115]: %timeit np.apply_along_axis(bigexp, 1, a)
1000 loops, best of 3: 272 µs per loop

In [116]: %timeit np.apply_along_axis(bigexp, 0, a)
1000 loops, best of 3: 465 µs per loop


问:
MySQL Operand should contain 3 column(s)
```<code>let ids = [100,200,300]
let scond_ids = [100,200,300]
let name = ["a","b","c"]

connection.query("SELECT * FROM table_name WHERE (id,second_id,name) in ((?),(?),(?))", [ids,second_ids,name], (err,result,field) => {
    if(err)console.log(err)
});
</code>```

Operand should contain 3 column(s)

I get this error when I do this with node.js
Please tell me how to fix!!

答:
I have never seen such syntax. I would change to statement:

```<code>SELECT *
FROM table_name
WHERE id in ? and second_id in ? and name in ?
</code>```

Also if you work with prepared statements you should not add the brackets for in functions.

Body:
let ids = [100,200,300]
let scond_ids = [100,200,300]
let name = ["a","b","c"]

connection.query("SELECT * FROM table_name WHERE (id,second_id,name) in ((?),(?),(?))", [ids,second_ids,name], (err,result,field) => {
    if(err)console.log(err)
});

Operand should contain 3 column(s)

I get this error when I do this with node.js
Please tell me how to fix!!

Body:
I have never seen such syntax. I would change to statement:

SELECT *
FROM table_name
WHERE id in ? and second_id in ? and name in ?

Also if you work with prepared statements you should not add the brackets for in functions.


问:
Get a date range covering 2 business weeks starting with current monday
I am having trouble adjusting a week range in PHP.

I have it working to show the current work week starting on monday.

So for this week it shows 11/29/2010 - 12/03/2010.

I need to modify this to start from the current work week's monday and show and end date of two fridays from the monday.

So for example currently it would show a start date of 11/29/2010 and and end date of 12/10/2010.

Here is my code

```<code><?
$timestamp = time();
echo date("m/d/Y", strtotime("this monday", $timestamp));
echo " - ";
echo date("m/d/Y", strtotime("Next Friday", $timestamp));
?>
</code>```

How do I add +7 to "Next Friday"

thx

答: Instead of strtotime("Next Friday", $timestamp) do strtotime("Next Friday", $timestamp) + 60*60*24*7 (add the number of seconds in a week).

Body:
I am having trouble adjusting a week range in PHP.

I have it working to show the current work week starting on monday.

So for this week it shows 11/29/2010 - 12/03/2010.

I need to modify this to start from the current work week's monday and show and end date of two fridays from the monday.

So for example currently it would show a start date of 11/29/2010 and and end date of 12/10/2010.

Here is my code

<?
$timestamp = time();
echo date("m/d/Y", strtotime("this monday", $timestamp));
echo " - ";
echo date("m/d/Y", strtotime("Next Friday", $timestamp));
?>

How do I add +7 to "Next Friday"

thx


问:
angularjs How to escape “${variable}” in html?
I want to show a string like ${date} to the div element:

```<code><div>please use the ${date} as the substitute tag to the name</div>
</code>```

the content will be display like:

```<code>please use the ${date} as the substitute tag to the name.
</code>```

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

答:
Make a method in your controller to hand the string back to the template:

```<code>specialText() {
  return '${date}';
}
</code>```

Then in your template:

```<code><div>please use the {{vm.specialText()}} as the substitute tag to the name</div>
</code>```

Body:
I want to show a string like ${date} to the div element:

please use the ${date} as the substitute tag to the name

the content will be display like:

please use the ${date} as the substitute tag to the name.

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

Body:
Make a method in your controller to hand the string back to the template:

specialText() {
  return '${date}';
}

Then in your template:

<div>please use the {{vm.specialText()}} as the substitute tag to the name</div>


问:
Create a new WiFi connection with proxy
I'm using the WifiManager with WifiConfiguration to create a WiFi connection on an Android device. This all works successfully and I can happily create a WiFi connection in the OS.

I would now like to allow the user to provide proxy details, host, port, username and password. I cannot see any mechanism in the WifiConfiguration or WifiManager to set the proxy details.

Does anyone know how to set proxy details when creating a WiFi connection.

UPDATE: This issue is specific to Xamarin, there are other topics in stackoverflow that detail solutions in native Android, but here I am looking for a Xamarin solution.

答:
Well, rightly or wrongly this is how I am doing it (and it seems to work so far). To create a proxy setting, after I have created the Wifi connection I do:

```<code>            Lang.JavaSystem.SetProperty("http.proxySet", "true");
            Java.Lang.JavaSystem.SetProperty("http.proxyHost", _proxyName);
            Java.Lang.JavaSystem.SetProperty("http.proxyPort", _proxyPort);
            Java.Lang.JavaSystem.SetProperty("http.proxyUser", _proxyUsername);
            Java.Lang.JavaSystem.SetProperty("http.proxyPassword", _proxyPassword);
</code>```

And when I want to clear the proxy settings I do:

```<code>            Java.Lang.JavaSystem.ClearProperty("http.proxySet");
            Java.Lang.JavaSystem.ClearProperty("http.proxyHost");
            Java.Lang.JavaSystem.ClearProperty("http.proxyPort");
            Java.Lang.JavaSystem.ClearProperty("http.proxyUser");
            Java.Lang.JavaSystem.ClearProperty("http.proxyPassword");
</code>```

Title: Create a new WiFi connection with proxy

Body:
Well, rightly or wrongly this is how I am doing it (and it seems to work so far). To create a proxy setting, after I have created the Wifi connection I do:

            Lang.JavaSystem.SetProperty("http.proxySet", "true");
            Java.Lang.JavaSystem.SetProperty("http.proxyHost", _proxyName);
            Java.Lang.JavaSystem.SetProperty("http.proxyPort", _proxyPort);
            Java.Lang.JavaSystem.SetProperty("http.proxyUser", _proxyUsername);
            Java.Lang.JavaSystem.SetProperty("http.proxyPassword", _proxyPassword);

And when I want to clear the proxy settings I do:

            Java.Lang.JavaSystem.ClearProperty("http.proxySet");
            Java.Lang.JavaSystem.ClearProperty("http.proxyHost");
            Java.Lang.JavaSystem.ClearProperty("http.proxyPort");
            Java.Lang.JavaSystem.ClearProperty("http.proxyUser");
            Java.Lang.JavaSystem.ClearProperty("http.proxyPassword");


答:
You can try testing each element to see if the previous has a list and take the last element or if the element is part of a parent list and take the parent list value:

$('li').click(function(e) {
  e.stopPropagation()
  var prev = $(e.target).prev();
  var parent = $(e.target).parent().closest('li');

  if (prev.find('ul li').length) {
    console.log(prev.find('ul li:last').text());
  } else
  if (parent.length && !prev.length) {
    console.log(parent.clone().find('ul').remove().end().text())
  } else {
    console.log(prev.text());
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
      <li>GroupX
    <ul>
      <li>ParameterX</li>
    </ul>
  </li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul></code>```

Title: How to get previous LI in multi-level UL/LI elements

Body:
You can try testing each element to see if the previous has a list and take the last element or if the element is part of a parent list and take the parent list value:

$('li').click(function(e) {
  e.stopPropagation()
  var prev = $(e.target).prev();
  var parent = $(e.target).parent().closest('li');

  if (prev.find('ul li').length) {
    console.log(prev.find('ul li:last').text());
  } else
  if (parent.length && !prev.length) {
    console.log(parent.clone().find('ul').remove().end().text())
  } else {
    console.log(prev.text());
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
      <li>GroupX
    <ul>
      <li>ParameterX</li>
    </ul>
  </li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul>


问:
Calculate a field value using other 2 fields values using onChange
The scene:

Think about 3 fields: quantity, singlePrice, totalPrice.
I need all them to be fields in my form but totalPrice has to be re-calculated every time i change quantity or singlePrice with a simple operation that you can imagine..

What I did:

created a function triggered by the onChange event of the quantity field and another one for the singlePrice field.

the above function calls a redux action with a payload like this:

{ name: name_of_the_updated_field, value: new_field_value }

that action is picked up by a formReducer plugin that makes the calculations and return the updated value object.

The Problem:
My redux store is not updated nor my form is.

My form reducer (the property I have to update is inside another property).

```<code>import { reducer as formReducer } from 'redux-form';

export default formReducer.plugin({
  formName: (state, action) => {
    switch (action.type) {
      case 'CALC_TOTAL_PRICE':
        return {
          ...state,
          values: {
            ...state.values,
            competences: state.values.competences.map((c, i) => {
              if (i === action.payload.index) {
                const { name, value } = action.payload;
                const next = Object.assign({}, c);
                next[name] = value;
                next.totalPrice = next.quantity * next.singlePrice
                return next;
              }
              return c;
            }),
          },
        };
      default:
        return state;
    }
  },
});
</code>```

Am I missing something? How to fix this?
Is a simpler way to have this result?

Any help is very appreciated!

答:
You might think to use formValueSelector to get the present input value and calculate total something like-

```<code>import React, { PropTypes } from 'react';
import { Field, reduxForm, formValueSelector, FieldArray, SubmissionError } from 'redux-form';
import { connect } from 'react-redux';

class NewSaleForm extends React.Component {

   componentWillReceiveProps(nextProps) {
      if (nextProps.items && nextProps.items.length > 0) {
         nextProps.items.forEach((item) => {
            if (item.price && item.unit) {
               if (item.unit_discount) {
                  item.total = (item.price - item.unit_discount) * item.unit;
               } else {
                  item.total = item.price * item.unit;
               }
            } else {
               item.total = '';
            }
         });
      }
   }

render() {
   ......
}

NewSaleForm = reduxForm({ // eslint-disable-line
   form: 'newSaleForm'
})(NewSaleForm);

const selector = formValueSelector('newSaleForm');

NewSaleForm = connect(state => { // eslint-disable-line
   const items = selector(state, 'items');
   return {
      items,
   };
})(NewSaleForm);

export default NewSaleForm;
</code>```

Body:
The scene:

Think about 3 fields: quantity, singlePrice, totalPrice.
I need all them to be fields in my form but totalPrice has to be re-calculated every time i change quantity or singlePrice with a simple operation that you can imagine..

What I did:

created a function triggered by the onChange event of the quantity field and another one for the singlePrice field.

the above function calls a redux action with a payload like this:

{ name: name_of_the_updated_field, value: new_field_value }

that action is picked up by a formReducer plugin that makes the calculations and return the updated value object.

The Problem:
My redux store is not updated nor my form is.

My form reducer (the property I have to update is inside another property).

import { reducer as formReducer } from 'redux-form';

export default formReducer.plugin({
  formName: (state, action) => {
    switch (action.type) {
      case 'CALC_TOTAL_PRICE':
        return {
          ...state,
          values: {
            ...state.values,
            competences: state.values.competences.map((c, i) => {
              if (i === action.payload.index) {
                const { name, value } = action.payload;
                const next = Object.assign({}, c);
                next[name] = value;
                next.totalPrice = next.quantity * next.singlePrice
                return next;
              }
              return c;
            }),
          },
        };
      default:
        return state;
    }
  },
});

Am I missing something? How to fix this?
Is a simpler way to have this result?

Any help is very appreciated!

Body:
You might think to use formValueSelector to get the present input value and calculate total something like-

import React, { PropTypes } from 'react';
import { Field, reduxForm, formValueSelector, FieldArray, SubmissionError } from 'redux-form';
import { connect } from 'react-redux';

class NewSaleForm extends React.Component {

   componentWillReceiveProps(nextProps) {
      if (nextProps.items && nextProps.items.length > 0) {
         nextProps.items.forEach((item) => {
            if (item.price && item.unit) {
               if (item.unit_discount) {
                  item.total = (item.price - item.unit_discount) * item.unit;
               } else {
                  item.total = item.price * item.unit;
               }
            } else {
               item.total = '';
            }
         });
      }
   }

render() {
   ......
}

NewSaleForm = reduxForm({ // eslint-disable-line
   form: 'newSaleForm'
})(NewSaleForm);

const selector = formValueSelector('newSaleForm');

NewSaleForm = connect(state => { // eslint-disable-line
   const items = selector(state, 'items');
   return {
      items,
   };
})(NewSaleForm);

export default NewSaleForm;


问:
refitting glm model in R based on previous model output
I have this dataset that I am doing logistic regression against in R. I have several questions about the output which may be a result from my lack of understanding of statistics and R and then a question about reducing the model based on p-value of current output.

The command I was given is:

```<code>model = glm(col1 ~ 1+(col2+col3+col4+col5+col6+col7)^2, family=binomial, data=ds)
summary(model)
</code>```

The columns contain the below data

```<code>col1 has values of 0 and 1
col2 is an integer
col3 is an integer
col4 is an integer
col5 has values of horrible, bad, good, excellent
col6 has values of a, b, c
col7 has values of true and false
</code>```

A segment of the coefficient and p-value output

```<code>col1            0.2824
col2            0.3457
col3            0.7845
col4            0.1451
col5horrible        0.0541*
col5bad         0.5641
col5excellent       0.2354
col6a           0.0025**
col6b           0.6245
col7TRUE        0.4145
col1:col2       0.0124*
col1:col3       0.8401
col1:col4       0.3154
col1:col5horrible   0.0054**
col1:col5bad        0.2149
col1:col5excellent  0.0035**
col1:col6a      0.2487
col1:col6b      0.0354*
col1:col7TRUE       0.5647
</code>```

The first thing I noticed was that for col5, col6, and col7 the output wasn't just the column name like it was for col1, col2, col3, and col4, but was ColnameValue. The second thing I noticed was that for the columns where a value was being appended to the column name, not all possible values were being appended to the column name, but in fact for col5, col6, and col7 were each missing one value.

Questions for understanding

what is ~1 in the glm function? I haven't seen 1 used before so not sure how to read that.

why are column values appended to the column names in the summary output?

why are all the possible values for a column not appended to the column name where the column name has some of the values appended?

Code question

I want to reduce the model to see if it can be better fitted. The suggestion was to remove predictors from the current model that were over a certain p-value. Here is what I have so far, but I am not sure what to do next once I have the column names and how to put the columns with ColnameValue into a model.

```<code>p=coef(summary(model))[,4]
colnames=names(p[p<0.1])
colnames
</code>```

colnames output

```<code>"col5horrible"
"col6a"
"col1:col5horrible"
"col1:col5excellent"
"col1:col6b"
</code>```

What would be my next step or is there a better way to do this? How do I handle the fact that the value is append to the column name?

EDIT

Based on the answer posted by schalange below I looked up dummy variables in R. On this post there were several methods for creating dummy variables. For non-numeric columns: col5, col6, and col7 which all have a predefined set of values I ran the function createDummyFeatures then ran glm on the columns that came out from the original model with p-value < 0.1. Is this the correct approach to reducing the original model based on the p-values for the coefficients?

```<code>install.packages("mlr")
library(mlr)

ds<-createDummyFeatures(ds, cols = "col5")
ds<-createDummyFeatures(ds, cols = "col6")
ds<-createDummyFeatures(ds, cols = "col7")

model2 = glm(col1 ~ 1+(col5.horrible + col6.a +col5.excellent + col6.b))
summary(model2)
</code>```

答:
First of all, before estimating a model, you should be more sure about what the variables really mean. R tries to estimate coefficcients for your variables. This is hard to do when the "value" of the column is "horrible". So what R does (and which is a sensible thing to do), it treats those columns, 5,6 and 7, as factors/ as dummy variables. (You might want to google that, you'll find plenty of information.)
The Basic idea is that, for example True and False are different groups of data.  R estimates something corresponding to an intercept for every group you mentioned. However, this can only be done for k-1 categories of each column, this is way you only have a value for TRUE, but not for FALSE(google dummy trap). I can't be entierely sure because I do not have any detail about the nature of the groups, but in all but rare cases, you cannot keep HORRIBLE without also keeping the other two, EXCELLENT and BAD. Think of them as groups or names, not as values. </p>

<p>One last thing: If you want to have a model that is better fitted (meaning that it can explain more of the variance, that the R^2 is higher), reducing variables is not the way to go, it makes your model less precise. However, it can still be an improvement, because the things that are below a certain threshold are important determinants, and you can be relatively certain they have a true effect. The internet offers plenty of things to help you intepret p-values. </p>

Body:
I have this dataset that I am doing logistic regression against in R. I have several questions about the output which may be a result from my lack of understanding of statistics and R and then a question about reducing the model based on p-value of current output.

The command I was given is:

model = glm(col1 ~ 1+(col2+col3+col4+col5+col6+col7)^2, family=binomial, data=ds)
summary(model)

The columns contain the below data

col1 has values of 0 and 1
col2 is an integer
col3 is an integer
col4 is an integer
col5 has values of horrible, bad, good, excellent
col6 has values of a, b, c
col7 has values of true and false

A segment of the coefficient and p-value output

col1            0.2824
col2            0.3457
col3            0.7845
col4            0.1451
col5horrible        0.0541*
col5bad         0.5641
col5excellent       0.2354
col6a           0.0025**
col6b           0.6245
col7TRUE        0.4145
col1:col2       0.0124*
col1:col3       0.8401
col1:col4       0.3154
col1:col5horrible   0.0054**
col1:col5bad        0.2149
col1:col5excellent  0.0035**
col1:col6a      0.2487
col1:col6b      0.0354*
col1:col7TRUE       0.5647

The first thing I noticed was that for col5, col6, and col7 the output wasn't just the column name like it was for col1, col2, col3, and col4, but was ColnameValue. The second thing I noticed was that for the columns where a value was being appended to the column name, not all possible values were being appended to the column name, but in fact for col5, col6, and col7 were each missing one value.

Questions for understanding

what is ~1 in the glm function? I haven't seen 1 used before so not sure how to read that.

why are column values appended to the column names in the summary output?

why are all the possible values for a column not appended to the column name where the column name has some of the values appended?

Code question

I want to reduce the model to see if it can be better fitted. The suggestion was to remove predictors from the current model that were over a certain p-value. Here is what I have so far, but I am not sure what to do next once I have the column names and how to put the columns with ColnameValue into a model.

p=coef(summary(model))[,4]
colnames=names(p[p<0.1])
colnames

colnames output

"col5horrible"
"col6a"
"col1:col5horrible"
"col1:col5excellent"
"col1:col6b"

What would be my next step or is there a better way to do this? How do I handle the fact that the value is append to the column name?

EDIT

Based on the answer posted by schalange below I looked up dummy variables in R. On this post there were several methods for creating dummy variables. For non-numeric columns: col5, col6, and col7 which all have a predefined set of values I ran the function createDummyFeatures then ran glm on the columns that came out from the original model with p-value < 0.1. Is this the correct approach to reducing the original model based on the p-values for the coefficients?

install.packages("mlr")
library(mlr)

ds<-createDummyFeatures(ds, cols = "col5")
ds<-createDummyFeatures(ds, cols = "col6")
ds<-createDummyFeatures(ds, cols = "col7")

model2 = glm(col1 ~ 1+(col5.horrible + col6.a +col5.excellent + col6.b))
summary(model2)

Body:
First of all, before estimating a model, you should be more sure about what the variables really mean. R tries to estimate coefficcients for your variables. This is hard to do when the "value" of the column is "horrible". So what R does (and which is a sensible thing to do), it treats those columns, 5,6 and 7, as factors/ as dummy variables. (You might want to google that, you'll find plenty of information.)
The Basic idea is that, for example True and False are different groups of data.  R estimates something corresponding to an intercept for every group you mentioned. However, this can only be done for k-1 categories of each column, this is way you only have a value for TRUE, but not for FALSE(google dummy trap). I can't be entierely sure because I do not have any detail about the nature of the groups, but in all but rare cases, you cannot keep HORRIBLE without also keeping the other two, EXCELLENT and BAD. Think of them as groups or names, not as values.

One last thing: If you want to have a model that is better fitted (meaning that it can explain more of the variance, that the R^2 is higher), reducing variables is not the way to go, it makes your model less precise. However, it can still be an improvement, because the things that are below a certain threshold are important determinants, and you can be relatively certain they have a true effect. The internet offers plenty of things to help you intepret p-values.


问:
Jquery toolstrip deactivate when menu open
I am using jquery toolstrip plugin.I need to disable it when my sidebar menu is opened. Following codes are my menu with li tags.

```<code><div class="sidebar-wrapper" id="sidebar-wrapper">
<ul>
  <li class="navigation-header">
    <a href="#" class="btn btnMenu">
        Button
    </a>
  </li>
  <li>
    <a href="#" class="tooltipster" title="Redakte paneli"></a>
  </li>
  <li>
    <a href="#" class="tooltipster" title="Axtaris"></a>
  </li>
 </ul>
</div>
</code>```

My javascript codes:

```<code>$('.btnMenu').on('click', function (e) {
    e.preventDefault();
    if ($("#sidebar-wrapper").hasClass("closeMenu")) {
        $("#sidebar-wrapper").animate({ width: "240px" });
        $("#sidebar-wrapper").removeClass("closeMenu").addClass("openMenu");
        $(".content-wrapper").animate({ left: "280px" });

   }
}
</code>```

答:
I have solved the problem with using following code of jquery toolstriper : </p>

```<code>$(".tooltipster").tooltipster('disable');
</code>```

Body:
I am using jquery toolstrip plugin.I need to disable it when my sidebar menu is opened. Following codes are my menu with li tags.

        Button

My javascript codes:

$('.btnMenu').on('click', function (e) {
    e.preventDefault();
    if ($("#sidebar-wrapper").hasClass("closeMenu")) {
        $("#sidebar-wrapper").animate({ width: "240px" });
        $("#sidebar-wrapper").removeClass("closeMenu").addClass("openMenu");
        $(".content-wrapper").animate({ left: "280px" });

   }
}

Body:
I have solved the problem with using following code of jquery toolstriper :

$(".tooltipster").tooltipster('disable');


问:
source issue with my image element and React
Alright hey guys.  Trying to get this clock functioning with the pictures.  I have more than just the one but if I can get the one figured out I can handle the others.  After much searching I found out you can't use string interpolation within an attribute but I kept it there to show I tried.  The second one I think "should work" and it shows the variable i'm trying or pic0, pic1 and so on but it's a string not the actual module i'm importing at the top (in the actual app I have them all imported but cut them down for brevity on the question.  Any assistance??  I'm bashing my head what is causing this issue

```<code>import React, { Component } from 'react';
import './App.css';
import './bootstrap-3.3.7-dist/css/bootstrap.min.css';
import pic0 from './0.png';

export default class Clock extends Component {
  constructor(props) {
    super(props);
    this.incrementTime = this.incrementTime.bind(this);
    this.dayInWords = this.dayInWords.bind(this);
    this.state = {
      clock: new Date(),
      day: (new Date()).getDay(),
      hours0: 0,
      minutes0: 0,
      seconds0: 0,
      hours1: 0,
      minutes1: 0,
      seconds1: 0
    }
  }

  componentWillMount() {
    let intervalTimer = setInterval(this.incrementTime, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.state.intervalTimer);
  }

  incrementTime() {
    this.setState(currentState => {
      return {
        clock: new Date(),
        seconds1: ((new Date()).getSeconds())%10
      };
    });
  }
  render() {
    return(
        <div className='panel-body imgContainer'>
          <img src={pic0} alt='the digit 0' />
          <p>Know this one doesnt work but kept here to show I tried it</p>
          <img src={`pic${this.state.seconds1}`} alt='seconds1' />

          <p>I think this should work and the src is what I want as the variable that im importing at the top but its just a string not the variable.</p>
          <img src={'pic' + this.state.seconds1} alt='seconds1' />

          <p>This is the end goal im trying to accomplish but im trying to see if it can be done using this.state.seconds so its kind of "dynamic" and the source changes every second thus changing the image</p>
          <img src={pic0} alt='seconds1' />
        </div>
        );
      }
    }
</code>```

this is what i'm seeing it's the image not showing the src is the "variable" im importing at the top but it's not actually calling that variable/module sorry if my terminology is wrong i'm clearly pretty new at this.

Thanks for all the assistance!!!!

答:
Although this was clarified in the comments, for future visitors of this post - you need to reference the imported image directly:

```<code>import pic from './myImage';

// works
<img src={ pic } />
</code>```

It can be placed in the state, or some other variable, but can't be accessed via a string with the same name:

```<code>// Doesn't work
<img pic={ 'pic' } />
</code>```

Body:
Alright hey guys.  Trying to get this clock functioning with the pictures.  I have more than just the one but if I can get the one figured out I can handle the others.  After much searching I found out you can't use string interpolation within an attribute but I kept it there to show I tried.  The second one I think "should work" and it shows the variable i'm trying or pic0, pic1 and so on but it's a string not the actual module i'm importing at the top (in the actual app I have them all imported but cut them down for brevity on the question.  Any assistance??  I'm bashing my head what is causing this issue

import React, { Component } from 'react';
import './App.css';
import './bootstrap-3.3.7-dist/css/bootstrap.min.css';
import pic0 from './0.png';

export default class Clock extends Component {
  constructor(props) {
    super(props);
    this.incrementTime = this.incrementTime.bind(this);
    this.dayInWords = this.dayInWords.bind(this);
    this.state = {
      clock: new Date(),
      day: (new Date()).getDay(),
      hours0: 0,
      minutes0: 0,
      seconds0: 0,
      hours1: 0,
      minutes1: 0,
      seconds1: 0
    }
  }

  componentWillMount() {
    let intervalTimer = setInterval(this.incrementTime, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.state.intervalTimer);
  }

  incrementTime() {
    this.setState(currentState => {
      return {
        clock: new Date(),
        seconds1: ((new Date()).getSeconds())%10
      };
    });
  }
  render() {
    return(

Know this one doesnt work but kept here to show I tried it

          <img src={`pic${this.state.seconds1}`} alt='seconds1' />

I think this should work and the src is what I want as the variable that im importing at the top but its just a string not the variable.

This is the end goal im trying to accomplish but im trying to see if it can be done using this.state.seconds so its kind of "dynamic" and the source changes every second thus changing the image

        );
      }
    }

this is what i'm seeing it's the image not showing the src is the "variable" im importing at the top but it's not actually calling that variable/module sorry if my terminology is wrong i'm clearly pretty new at this.

Thanks for all the assistance!!!!

Body:
Although this was clarified in the comments, for future visitors of this post - you need to reference the imported image directly:

import pic from './myImage';

// works
<img src={ pic } />

It can be placed in the state, or some other variable, but can't be accessed via a string with the same name:

// Doesn't work
<img pic={ 'pic' } />


问:
Why multiple definition error happens in CUDA .cu files
I'm learning to use CUDA. I wrote two .cu files, one containing the main function and the other serves as a library providing all the other functions. But I met with multiple definition errors when compiling the two .cu files. I show a toy example as follows:

main.cu file:

```<code>#ifndef MAIN
#define MAIN
#include "book.h"
#include <iostream>
#include "lib.h"

using namespace std;

int main(int argc, char const *argv[])
{
    HelloWorld();
    return 0;
}
#endif
</code>```

lib.cu file:

```<code>#ifndef LIB
#define LIB

#include "book.h"
#include <iostream>
#include "lib.h"

using namespace std;

void HelloWorld(){
    cout <<"HelloWorld" << endl;
    return;
}
#endif
</code>```

lib.h file:

```<code>#ifndef LIB_H
#define LIB_H

#include <iostream>

using namespace std;

void HelloWorld();
#endif
</code>```

book.h file:

```<code>#ifndef __BOOK_H__
#define __BOOK_H__
#include <stdio.h>

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

template< typename T >
void swap( T& a, T& b ) {
    T t = a;
    a = b;
    b = t;
}

void* big_random_block( int size ) {
    unsigned char *data = (unsigned char*)malloc( size );
    HANDLE_NULL( data );
    for (int i=0; i<size; i++)
        data[i] = rand();

    return data;
}

int* big_random_block_int( int size ) {
    int *data = (int*)malloc( size * sizeof(int) );
    HANDLE_NULL( data );
    for (int i=0; i<size; i++)
        data[i] = rand();

    return data;
}

// a place for common kernels - starts here

__device__ unsigned char value( float n1, float n2, int hue ) {
    if (hue > 360)      hue -= 360;
    else if (hue < 0)   hue += 360;

    if (hue < 60)
        return (unsigned char)(255 * (n1 + (n2-n1)*hue/60));
    if (hue < 180)
        return (unsigned char)(255 * n2);
    if (hue < 240)
        return (unsigned char)(255 * (n1 + (n2-n1)*(240-hue)/60));
    return (unsigned char)(255 * n1);
}

__global__ void float_to_color( unsigned char *optr,
                              const float *outSrc ) {
    // map from threadIdx/BlockIdx to pixel position
    int x = threadIdx.x + blockIdx.x * blockDim.x;
    int y = threadIdx.y + blockIdx.y * blockDim.y;
    int offset = x + y * blockDim.x * gridDim.x;

    float l = outSrc[offset];
    float s = 1;
    int h = (180 + (int)(360.0f * outSrc[offset])) % 360;
    float m1, m2;

    if (l <= 0.5f)
        m2 = l * (1 + s);
    else
        m2 = l + s - l * s;
    m1 = 2 * l - m2;

    optr[offset*4 + 0] = value( m1, m2, h+120 );
    optr[offset*4 + 1] = value( m1, m2, h );
    optr[offset*4 + 2] = value( m1, m2, h -120 );
    optr[offset*4 + 3] = 255;
}

__global__ void float_to_color( uchar4 *optr,
                              const float *outSrc ) {
    // map from threadIdx/BlockIdx to pixel position
    int x = threadIdx.x + blockIdx.x * blockDim.x;
    int y = threadIdx.y + blockIdx.y * blockDim.y;
    int offset = x + y * blockDim.x * gridDim.x;

    float l = outSrc[offset];
    float s = 1;
    int h = (180 + (int)(360.0f * outSrc[offset])) % 360;
    float m1, m2;

    if (l <= 0.5f)
        m2 = l * (1 + s);
    else
        m2 = l + s - l * s;
    m1 = 2 * l - m2;

    optr[offset].x = value( m1, m2, h+120 );
    optr[offset].y = value( m1, m2, h );
    optr[offset].z = value( m1, m2, h -120 );
    optr[offset].w = 255;
}

#if _WIN32
    //Windows threads.
    #include <windows.h>

    typedef HANDLE CUTThread;
    typedef unsigned (WINAPI *CUT_THREADROUTINE)(void *);

    #define CUT_THREADPROC unsigned WINAPI
    #define  CUT_THREADEND return 0

#else
    //POSIX threads.
    #include <pthread.h>

    typedef pthread_t CUTThread;
    typedef void *(*CUT_THREADROUTINE)(void *);

    #define CUT_THREADPROC void
    #define  CUT_THREADEND
#endif

//Create thread.
CUTThread start_thread( CUT_THREADROUTINE, void *data );

//Wait for thread to finish.
void end_thread( CUTThread thread );

//Destroy thread.
void destroy_thread( CUTThread thread );

//Wait for multiple threads.
void wait_for_threads( const CUTThread *threads, int num );

#if _WIN32
    //Create thread
    CUTThread start_thread(CUT_THREADROUTINE func, void *data){
        return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, data, 0, NULL);
    }

    //Wait for thread to finish
    void end_thread(CUTThread thread){
        WaitForSingleObject(thread, INFINITE);
        CloseHandle(thread);
    }

    //Destroy thread
    void destroy_thread( CUTThread thread ){
        TerminateThread(thread, 0);
        CloseHandle(thread);
    }

    //Wait for multiple threads
    void wait_for_threads(const CUTThread * threads, int num){
        WaitForMultipleObjects(num, threads, true, INFINITE);

        for(int i = 0; i < num; i++)
            CloseHandle(threads[i]);
    }

#else
    //Create thread
    CUTThread start_thread(CUT_THREADROUTINE func, void * data){
        pthread_t thread;
        pthread_create(&thread, NULL, func, data);
        return thread;
    }

    //Wait for thread to finish
    void end_thread(CUTThread thread){
        pthread_join(thread, NULL);
    }

    //Destroy thread
    void destroy_thread( CUTThread thread ){
        pthread_cancel(thread);
    }

    //Wait for multiple threads
    void wait_for_threads(const CUTThread * threads, int num){
        for(int i = 0; i < num; i++)
            end_thread( threads[i] );
    }

#endif
#endif  // __BOOK_H__
</code>```

I compile the files using the command:

```<code>nvcc *.cu -O3 -o a.out -lm -ccbin=/usr/bin/g++
</code>```

Then I got error messages like multiple definition of float_to_color(uchar4*, float const*)'.

Otherwise, if I comment one include of the book.h, the compilation will succeed and the program runs correctly.
I found that one possible reason is the version of gcc, so I tried with gcc-4.4 and gcc-4.8, but the error happens in both cases. I also tried with g++, but it does not solve this problem.
What's wrong with my code?
Thank you all for helping me!

答:
You have multiple definitions because the function is in the header file. It means every single translation unit that includes the file will have a copy of the function.

Either move it to an implementation file and link, or mark the function inline.

Further things to improve upon:

Do not place a using namespace directive in a header file, ever. It's a major namespace pollution.

Prefer std::swap to a home-brewed naive swap template.

Body:
I'm learning to use CUDA. I wrote two .cu files, one containing the main function and the other serves as a library providing all the other functions. But I met with multiple definition errors when compiling the two .cu files. I show a toy example as follows:

main.cu file:

#ifndef MAIN
#define MAIN
#include "book.h"
#include <iostream>
#include "lib.h"

using namespace std;

int main(int argc, char const *argv[])
{
    HelloWorld();
    return 0;
}
#endif

lib.cu file:

#ifndef LIB
#define LIB

#include "book.h"
#include <iostream>
#include "lib.h"

using namespace std;

void HelloWorld(){
    cout <<"HelloWorld" << endl;
    return;
}
#endif

lib.h file:

#ifndef LIB_H
#define LIB_H

#include <iostream>

using namespace std;

void HelloWorld();
#endif

book.h file:

#ifndef __BOOK_H__
#define __BOOK_H__
#include <stdio.h>

static void HandleError( cudaError_t err,
                         const char *file,
                         int line ) {
    if (err != cudaSuccess) {
        printf( "%s in %s at line %d\n", cudaGetErrorString( err ),
                file, line );
        exit( EXIT_FAILURE );
    }
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if (a == NULL) { \
                            printf( "Host memory failed in %s at line %d\n", \
                                    __FILE__, __LINE__ ); \
                            exit( EXIT_FAILURE );}}

template< typename T >
void swap( T& a, T& b ) {
    T t = a;
    a = b;
    b = t;
}

void* big_random_block( int size ) {
    unsigned char *data = (unsigned char*)malloc( size );
    HANDLE_NULL( data );
    for (int i=0; i<size; i++)
        data[i] = rand();

    return data;
}

int* big_random_block_int( int size ) {
    int *data = (int*)malloc( size * sizeof(int) );
    HANDLE_NULL( data );
    for (int i=0; i<size; i++)
        data[i] = rand();

    return data;
}

// a place for common kernels - starts here

__device__ unsigned char value( float n1, float n2, int hue ) {
    if (hue > 360)      hue -= 360;
    else if (hue < 0)   hue += 360;

    if (hue < 60)
        return (unsigned char)(255 * (n1 + (n2-n1)*hue/60));
    if (hue < 180)
        return (unsigned char)(255 * n2);
    if (hue < 240)
        return (unsigned char)(255 * (n1 + (n2-n1)*(240-hue)/60));
    return (unsigned char)(255 * n1);
}

__global__ void float_to_color( unsigned char *optr,
                              const float *outSrc ) {
    // map from threadIdx/BlockIdx to pixel position
    int x = threadIdx.x + blockIdx.x * blockDim.x;
    int y = threadIdx.y + blockIdx.y * blockDim.y;
    int offset = x + y * blockDim.x * gridDim.x;

    float l = outSrc[offset];
    float s = 1;
    int h = (180 + (int)(360.0f * outSrc[offset])) % 360;
    float m1, m2;

    if (l <= 0.5f)
        m2 = l * (1 + s);
    else
        m2 = l + s - l * s;
    m1 = 2 * l - m2;

    optr[offset*4 + 0] = value( m1, m2, h+120 );
    optr[offset*4 + 1] = value( m1, m2, h );
    optr[offset*4 + 2] = value( m1, m2, h -120 );
    optr[offset*4 + 3] = 255;
}

__global__ void float_to_color( uchar4 *optr,
                              const float *outSrc ) {
    // map from threadIdx/BlockIdx to pixel position
    int x = threadIdx.x + blockIdx.x * blockDim.x;
    int y = threadIdx.y + blockIdx.y * blockDim.y;
    int offset = x + y * blockDim.x * gridDim.x;

    float l = outSrc[offset];
    float s = 1;
    int h = (180 + (int)(360.0f * outSrc[offset])) % 360;
    float m1, m2;

    if (l <= 0.5f)
        m2 = l * (1 + s);
    else
        m2 = l + s - l * s;
    m1 = 2 * l - m2;

    optr[offset].x = value( m1, m2, h+120 );
    optr[offset].y = value( m1, m2, h );
    optr[offset].z = value( m1, m2, h -120 );
    optr[offset].w = 255;
}

#if _WIN32
    //Windows threads.
    #include <windows.h>

    typedef HANDLE CUTThread;
    typedef unsigned (WINAPI *CUT_THREADROUTINE)(void *);

    #define CUT_THREADPROC unsigned WINAPI
    #define  CUT_THREADEND return 0

#else
    //POSIX threads.
    #include <pthread.h>

    typedef pthread_t CUTThread;
    typedef void *(*CUT_THREADROUTINE)(void *);

    #define CUT_THREADPROC void
    #define  CUT_THREADEND
#endif

//Create thread.
CUTThread start_thread( CUT_THREADROUTINE, void *data );

//Wait for thread to finish.
void end_thread( CUTThread thread );

//Destroy thread.
void destroy_thread( CUTThread thread );

//Wait for multiple threads.
void wait_for_threads( const CUTThread *threads, int num );

#if _WIN32
    //Create thread
    CUTThread start_thread(CUT_THREADROUTINE func, void *data){
        return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, data, 0, NULL);
    }

    //Wait for thread to finish
    void end_thread(CUTThread thread){
        WaitForSingleObject(thread, INFINITE);
        CloseHandle(thread);
    }

    //Destroy thread
    void destroy_thread( CUTThread thread ){
        TerminateThread(thread, 0);
        CloseHandle(thread);
    }

    //Wait for multiple threads
    void wait_for_threads(const CUTThread * threads, int num){
        WaitForMultipleObjects(num, threads, true, INFINITE);

        for(int i = 0; i < num; i++)
            CloseHandle(threads[i]);
    }

#else
    //Create thread
    CUTThread start_thread(CUT_THREADROUTINE func, void * data){
        pthread_t thread;
        pthread_create(&thread, NULL, func, data);
        return thread;
    }

    //Wait for thread to finish
    void end_thread(CUTThread thread){
        pthread_join(thread, NULL);
    }

    //Destroy thread
    void destroy_thread( CUTThread thread ){
        pthread_cancel(thread);
    }

    //Wait for multiple threads
    void wait_for_threads(const CUTThread * threads, int num){
        for(int i = 0; i < num; i++)
            end_thread( threads[i] );
    }

#endif
#endif  // __BOOK_H__

I compile the files using the command:

nvcc *.cu -O3 -o a.out -lm -ccbin=/usr/bin/g++

Then I got error messages like multiple definition of float_to_color(uchar4*, float const*)'.

Otherwise, if I comment one include of the book.h, the compilation will succeed and the program runs correctly.
I found that one possible reason is the version of gcc, so I tried with gcc-4.4 and gcc-4.8, but the error happens in both cases. I also tried with g++, but it does not solve this problem.
What's wrong with my code?
Thank you all for helping me!


问:
Jasper strech subreport
I have Detail band in master report with two subreports

When I form report I see that left subreport more higher then right

Subreport has such structure

How to make, that if in the report there are less lines than in other, it was stretched? Actually, the ColumnFooter band was on the same level.

Subreports attributes:

```<code>Position Type: Float
Strech Type: Relatives to tallest object
Overflow Type: Strech
</code>```

答: I decided. Listed all list in one detail band to one size</p>

Title: Jasper strech subreport

Body:
I have Detail band in master report with two subreports

When I form report I see that left subreport more higher then right

Subreport has such structure

How to make, that if in the report there are less lines than in other, it was stretched? Actually, the ColumnFooter band was on the same level.

Subreports attributes:

Position Type: Float
Strech Type: Relatives to tallest object
Overflow Type: Strech