问:
How is the 'equal' template function implemented? (predicate version)
I am working through the book "Accelerated C++" and one of the exercises require us to emulate the 'equal' function in the  header and so far I have implemented the simple version which takes three parameters as follows:

```<code>template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){

    while(begin != end){
        if(!(*begin == *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}
</code>```

and the second version which can accept a fourth parameter...

```<code>template <class iterType1, class iterType2, class boolPred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}
</code>```

My question is, is this the ideal way to do it? or are these two functions mergable?

答:
The first version can call the second version, passing an equal_to object as the last parameter.  Or you can just set that as a default parameter. I take that back.  I can't actually figure out a way to have a default argument for a function template.  I can't even figure out how to re-use the code in the overload solution without using a c++0x feature(decltype).

```<code>template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){
    return cequal(begin, end, e, std::equal_to<decltype(*begin)>());
}
</code>```

Body:
I am working through the book "Accelerated C++" and one of the exercises require us to emulate the 'equal' function in the  header and so far I have implemented the simple version which takes three parameters as follows:

template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){

    while(begin != end){
        if(!(*begin == *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}

and the second version which can accept a fourth parameter...

template <class iterType1, class iterType2, class boolPred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}

My question is, is this the ideal way to do it? or are these two functions mergable?

Body:
The first version can call the second version, passing an equal_to object as the last parameter.  Or you can just set that as a default parameter. I take that back.  I can't actually figure out a way to have a default argument for a function template.  I can't even figure out how to re-use the code in the overload solution without using a c++0x feature(decltype).

template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){
    return cequal(begin, end, e, std::equal_to<decltype(*begin)>());
}


来源: stackexchange

问:
How can I move partial changes from an old commit to the working directory?
Given a history of Git commits and a clean working directory, I want to remove some of the changes of a previous commit and apply those changes to my current working directory instead. To clarify, after taking the action the old commit should be modified to only contain the changes that are left, and the following commits will be rewritten. How can I do this the easiest?</p>

答:
From a clean working tree I'd probably do:

```<code>git cherry-pick -n old_commit # bring in all the changes
</code>```

At this point, you have all the changes in your working tree but none of them are staged for commit.

```<code>git add -i
</code>```

Select the changes you want to keep using the normal git add -i interface

At this point you have all the changes you want to keep staged.  If you want to commit those changes then:

```<code>git commit #commit staged changes
git reset --hard # remove changes that you didn't accept from your working tree
</code>```

This may leave you with some files that were added in the old commit and that you chose not to add.

Alternatively, if you just want the changes in your working tree, but not staged or committed yet:

```<code>git commit # we will get rid of this commit shortly
git reset --hard # get rid of changes we didn't accept
git reset HEAD~1
</code>```

The git reset HEAD~1 will change the index state, discarding the commit we  just made, and leaving us with a working tree that has the changes you decided to keep, but with nothing staged and no new commits.

This leaves the old commit in tact.  So, this answer is useful in the case where you're moving changes across branches or similar.  That is, the changes need to not be present in HEAD.  That happens either if HEAD never contained these changes or if you have reverted them.
It's impossible to change the old commit; Git commits cannot be changed.  It is possible to produce an alternate history where the commit corresponding to the old commit didn't have some of the changes it has in the current history.  That's a different question and so I did not answer it here.

ContentLicense: CC BY-SA 3.0

Body:
From a clean working tree I'd probably do:

git cherry-pick -n old_commit # bring in all the changes

At this point, you have all the changes in your working tree but none of them are staged for commit.

git add -i

Select the changes you want to keep using the normal git add -i interface

At this point you have all the changes you want to keep staged.  If you want to commit those changes then:

git commit #commit staged changes
git reset --hard # remove changes that you didn't accept from your working tree

This may leave you with some files that were added in the old commit and that you chose not to add.

Alternatively, if you just want the changes in your working tree, but not staged or committed yet:

git commit # we will get rid of this commit shortly
git reset --hard # get rid of changes we didn't accept
git reset HEAD~1

The git reset HEAD~1 will change the index state, discarding the commit we  just made, and leaving us with a working tree that has the changes you decided to keep, but with nothing staged and no new commits.

This leaves the old commit in tact.  So, this answer is useful in the case where you're moving changes across branches or similar.  That is, the changes need to not be present in HEAD.  That happens either if HEAD never contained these changes or if you have reverted them.
It's impossible to change the old commit; Git commits cannot be changed.  It is possible to produce an alternate history where the commit corresponding to the old commit didn't have some of the changes it has in the current history.  That's a different question and so I did not answer it here.


问:
how to unload dynamic lib in lua
I'm using luajit2.0.4 as lua interpreter. here is the situation:

after I load a dynamic lib like cjson.so with

```<code>cjson = require('cjson')
a=cjson.new() -- blahblah... do things i want
</code>```

then I need to overwrite the lib file, ( a situation of hot upgrade, and here cjson.so_1 and cjson.so might be the same)

```<code>[root@localhost lib]# cp cjson.so_1 cjson.so
cp: overwrite `cjson.so'? y
</code>```

it will force kernel to truncate the physical memory of cjson.so's pmap, and causing a page missing
then when I call

```<code>a=cjson.new()
</code>```

again, the kernel will recopy the cjson.so lib into memory, this time not parsing the global symbols. so when I call new() which need to call external functions like malloc(), a segment fault will occur.

I've already found a way to reload by writing a unload funtion in C,

and my question is can I do this by lua code itself?

答:
Sadly, this is not possible.

You'd have to approach the situation using C/C++, but not using Lua, due to the way in which Lua works, and I wish there would've been a different answer but Lua has got it's limits.

Title: how to unload dynamic lib in lua

Body:
I'm using luajit2.0.4 as lua interpreter. here is the situation:

after I load a dynamic lib like cjson.so with

cjson = require('cjson')
a=cjson.new() -- blahblah... do things i want

then I need to overwrite the lib file, ( a situation of hot upgrade, and here cjson.so_1 and cjson.so might be the same)

[root@localhost lib]# cp cjson.so_1 cjson.so
cp: overwrite `cjson.so'? y

it will force kernel to truncate the physical memory of cjson.so's pmap, and causing a page missing
then when I call

a=cjson.new()

again, the kernel will recopy the cjson.so lib into memory, this time not parsing the global symbols. so when I call new() which need to call external functions like malloc(), a segment fault will occur.

I've already found a way to reload by writing a unload funtion in C,

and my question is can I do this by lua code itself?


问:
Table is not refreshed on setOnCloseRequest
When the worker is updated in the stageAdd window and the button ok is pressed, refreshButtonClicked() method is not executed on stage.setOnCloseRequest((e)-> refreshButtonClicked());. workersTable should be automatically refreshed when update is finished and button ok is clicked.

I am using stageAdd when edit button is pressed in editButtonClicked() method.

```<code> public class ElectricalDepartmentController {

    @FXML private Label name;
    @FXML private Label surname;
    @FXML private Label age;
    @FXML private Label city;
    @FXML private Label address;
    @FXML private Label telephoneNum;
    @FXML private Label email;
    @FXML private Label idNumber;
    @FXML private Label startDate;
    @FXML private Label contractType;
    @FXML private Label endDate;
    @FXML private Label payFrequency;
    @FXML private Label accountNumber;
    @FXML private Label taxCoefficient;
    @FXML private Label netSalary;
    @FXML private Button refreshButton;
    @FXML private Button deleteButton;
    @FXML private Button editButton;
    @FXML private TableView<Worker> workersTable;
    @FXML private TableColumn<Worker, String> workersTableColumn;

    private WorkerDao workerDao = WorkerDaoFactory.getWorkerDao();
    private final ObservableList<Worker> workersList = FXCollections.observableArrayList();

    //initialize method
    public void initialize() throws IOException {
        workersTableColumn.setCellValueFactory(new PropertyValueFactory<>("nameSurname"));
        rowSelected();
    }

    //Refresh the table when the button is clicked
    @FXML
    public void refreshButtonClicked() {
        workersList.removeAll(workersList);
        populateTable();
    }

    //Delete worker
    @FXML
    private void deleteButtonClicked() {
        Worker selectedWorker = workersTable.getSelectionModel().getSelectedItem();
        workersTable.getItems().remove(selectedWorker);
        workerDao.deleteSelectedWorker(selectedWorker, "Electrical");
    }

    //Populate the table
    @FXML
    public void populateTable() {
        for(Worker worker : workerDao.getWorkersNameSurname("Electrical")) workersList.addAll(worker);
        workersTable.setItems(workersList);
    }

    //Show worker's information when row is selected
    @FXML
    private void rowSelected() {

        workersTable.getSelectionModel().selectedItemProperty().
                addListener((observable, oldValue, newValue) -> {

                    if (newValue != null) {
                        name.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getName());
                        surname.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getSurname());
                        age.setText(String.valueOf(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getAge()));
                        city.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getCity());
                        address.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getAddress());
                        telephoneNum.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getTelephoneNum());
                        email.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getEmail());
                        idNumber.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getIdNumber().toString());
                        startDate.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getStartDate().toString());
                        contractType.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getContractType());

                        if(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getEndDate()== null)endDate.setText("");
                        else endDate.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getEndDate().toString());

                        payFrequency.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getPayFreq());
                        accountNumber.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getAccountNum().toString());
                        taxCoefficient.setText(String.valueOf(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getTaxCoeficient()));
                        netSalary.setText(String.valueOf(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getNetSalary()));
                    }
                });
    }
    @FXML
    public void editButtonClicked() throws IOException {
        Worker workerSelectedForEdit = workersTable.getSelectionModel().getSelectedItem();

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/views/StageAdd.fxml"));
        Parent parent = loader.load();

        StageAddController controller = loader.getController();
        controller.showEditWorkerOldInformation(workerSelectedForEdit);

        Stage stage = new Stage();
        stage.setTitle("Edit Worker");
        stage.setScene(new Scene(parent));
        parent.getStylesheets().add("/css/redBorder.css");

        stage.show();

        stage.setOnCloseRequest((e)-> refreshButtonClicked());

    }
}
</code>```

Methods for closing stageAdd and saving/updating worker in stageAdd Controller class:

```<code> //Close Stage
    @FXML private void closeButtonClicked(){
        Stage stage = (Stage) rootPane.getScene().getWindow();
        stage.close();
    }
//Submit entered information - OK button pressed
    @FXML private void okButtonClicked() throws IOException{
        WorkerDao workerDao = WorkerDaoFactory.getWorkerDao();
        List<Control> requiredFieleds = new ArrayList<>();
        int count=0;

        // Getting required fields
        for(Control c : allControls){
            if(!c.equals(email) && !c.equals(endDate)){
                requiredFieleds.add(c);
            }
        }

        //Check if all required fields are valid
        for (Control c : requiredFieleds) {
            if (c instanceof TextField) {
                if (!stageAddService.validateField((TextField)c, field-> field.getText().trim().isEmpty()))
                    count++;
                else c.pseudoClassStateChanged(errorClass, true);
            }
            else if (c instanceof DatePicker){
                if (!stageAddService.validateField((DatePicker)c, field-> field.getValue()==null))
                    count++;
                else c.pseudoClassStateChanged(errorClass1, true);
            }
            else {
                if (!stageAddService.validateField((ChoiceBox)c, field-> field.getValue()==null))
                    count++;
                else c.pseudoClassStateChanged(errorClass2, true);
            }
        }

        //If required fields are valid, save data
        if (count == requiredFieleds.size()) {
            Worker worker = new Worker();

            worker.setName(name.getText().trim());
            worker.setSurname(surname.getText().trim());
            worker.setAge(age.getValue());

            ContactInformation contactInformation = new ContactInformation();
            contactInformation.setAddress(address.getText().trim());
            contactInformation.setCity(city.getText().trim());
            contactInformation.setTelephoneNum(telephoneNumber.getText().trim());
            contactInformation.setEmail(email.getText().trim());
            worker.setContactInformation(contactInformation);

            EmploymentInformation employmentInformation = new EmploymentInformation();
            employmentInformation.setDepartment(departmentBox.getValue());
            employmentInformation.setIdNumber(Long.parseLong(idNumber.getText().trim()));
            employmentInformation.setStartDate(startDate.getValue());
            employmentInformation.setContractType(contractType.getValue());
            employmentInformation.setEndDate(endDate.getValue());
            employmentInformation.setPayFreq(payFrequency.getValue());
            employmentInformation.setAccountNum(Long.parseLong(accountNumber.getText().trim()));
            employmentInformation.setTaxCoeficient(Double.parseDouble(taxCoeficient.getText().trim()));
            employmentInformation.setNetSalary(Double.parseDouble(netSalary.getText().trim()));
            worker.setEmploymentInformation(employmentInformation);

            if(isInEditMode){
                worker.setId(id);
                workerDao.updateWorker(worker);
            }
            else {workerDao.saveWorker(worker);}

            closeButtonClicked();

        }
        else {error1.setText("Fill in all red fields");
            error2.setText("Fill in all red fields");
        }

    }
</code>```

Method in other class to load the stageAdd

```<code>public static void showStageAdd() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("/views/StageAdd.fxml"));
        BorderPane addWorkerPane = loader.load();
        stageAdd = new Stage();
        stageAdd.setTitle("Add New Worker");
        stageAdd.resizableProperty().setValue(Boolean.FALSE);
        Scene scene = new Scene(addWorkerPane);
        scene.getStylesheets().add("/css/redBorder.css");
        stageAdd.setScene(scene);
        stageAdd.initModality(Modality.WINDOW_MODAL);
        stageAdd.initOwner(stage1);
        stageAdd.showAndWait();
    }
</code>```

答:
We ran into a similar issue -> the following code:

```<code>stage.setOnCloseRequest((e)-> refreshButtonClicked());
</code>```

This will be called when the window is closed via the "X" on the window.  However this code

```<code>Stage stage = (Stage) rootPane.getScene().getWindow();
stage.close();
</code>```

Actually will not call the close request.  You can accomplish this by sending a close event to the window rather than stage.close() or you can do this:

```<code>stage.setOnHidden((e)-> refreshButtonClicked());
</code>```

Body:
When the worker is updated in the stageAdd window and the button ok is pressed, refreshButtonClicked() method is not executed on stage.setOnCloseRequest((e)-> refreshButtonClicked());. workersTable should be automatically refreshed when update is finished and button ok is clicked.

I am using stageAdd when edit button is pressed in editButtonClicked() method.

 public class ElectricalDepartmentController {

    @FXML private Label name;
    @FXML private Label surname;
    @FXML private Label age;
    @FXML private Label city;
    @FXML private Label address;
    @FXML private Label telephoneNum;
    @FXML private Label email;
    @FXML private Label idNumber;
    @FXML private Label startDate;
    @FXML private Label contractType;
    @FXML private Label endDate;
    @FXML private Label payFrequency;
    @FXML private Label accountNumber;
    @FXML private Label taxCoefficient;
    @FXML private Label netSalary;
    @FXML private Button refreshButton;
    @FXML private Button deleteButton;
    @FXML private Button editButton;
    @FXML private TableView<Worker> workersTable;
    @FXML private TableColumn<Worker, String> workersTableColumn;

    private WorkerDao workerDao = WorkerDaoFactory.getWorkerDao();
    private final ObservableList<Worker> workersList = FXCollections.observableArrayList();

    //initialize method
    public void initialize() throws IOException {
        workersTableColumn.setCellValueFactory(new PropertyValueFactory<>("nameSurname"));
        rowSelected();
    }

    //Refresh the table when the button is clicked
    @FXML
    public void refreshButtonClicked() {
        workersList.removeAll(workersList);
        populateTable();
    }

    //Delete worker
    @FXML
    private void deleteButtonClicked() {
        Worker selectedWorker = workersTable.getSelectionModel().getSelectedItem();
        workersTable.getItems().remove(selectedWorker);
        workerDao.deleteSelectedWorker(selectedWorker, "Electrical");
    }

    //Populate the table
    @FXML
    public void populateTable() {
        for(Worker worker : workerDao.getWorkersNameSurname("Electrical")) workersList.addAll(worker);
        workersTable.setItems(workersList);
    }

    //Show worker's information when row is selected
    @FXML
    private void rowSelected() {

        workersTable.getSelectionModel().selectedItemProperty().
                addListener((observable, oldValue, newValue) -> {

                    if (newValue != null) {
                        name.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getName());
                        surname.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getSurname());
                        age.setText(String.valueOf(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getAge()));
                        city.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getCity());
                        address.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getAddress());
                        telephoneNum.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getTelephoneNum());
                        email.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getContactInformation().getEmail());
                        idNumber.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getIdNumber().toString());
                        startDate.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getStartDate().toString());
                        contractType.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getContractType());

                        if(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getEndDate()== null)endDate.setText("");
                        else endDate.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getEndDate().toString());

                        payFrequency.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getPayFreq());
                        accountNumber.setText(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getAccountNum().toString());
                        taxCoefficient.setText(String.valueOf(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getTaxCoeficient()));
                        netSalary.setText(String.valueOf(workerDao.getWorkersInfoByNameSurname(newValue.getNameSurname()).getEmploymentInformation().getNetSalary()));
                    }
                });
    }
    @FXML
    public void editButtonClicked() throws IOException {
        Worker workerSelectedForEdit = workersTable.getSelectionModel().getSelectedItem();

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/views/StageAdd.fxml"));
        Parent parent = loader.load();

        StageAddController controller = loader.getController();
        controller.showEditWorkerOldInformation(workerSelectedForEdit);

        Stage stage = new Stage();
        stage.setTitle("Edit Worker");
        stage.setScene(new Scene(parent));
        parent.getStylesheets().add("/css/redBorder.css");

        stage.show();

        stage.setOnCloseRequest((e)-> refreshButtonClicked());

    }
}

Methods for closing stageAdd and saving/updating worker in stageAdd Controller class:

 //Close Stage
    @FXML private void closeButtonClicked(){
        Stage stage = (Stage) rootPane.getScene().getWindow();
        stage.close();
    }
//Submit entered information - OK button pressed
    @FXML private void okButtonClicked() throws IOException{
        WorkerDao workerDao = WorkerDaoFactory.getWorkerDao();
        List<Control> requiredFieleds = new ArrayList<>();
        int count=0;

        // Getting required fields
        for(Control c : allControls){
            if(!c.equals(email) && !c.equals(endDate)){
                requiredFieleds.add(c);
            }
        }

        //Check if all required fields are valid
        for (Control c : requiredFieleds) {
            if (c instanceof TextField) {
                if (!stageAddService.validateField((TextField)c, field-> field.getText().trim().isEmpty()))
                    count++;
                else c.pseudoClassStateChanged(errorClass, true);
            }
            else if (c instanceof DatePicker){
                if (!stageAddService.validateField((DatePicker)c, field-> field.getValue()==null))
                    count++;
                else c.pseudoClassStateChanged(errorClass1, true);
            }
            else {
                if (!stageAddService.validateField((ChoiceBox)c, field-> field.getValue()==null))
                    count++;
                else c.pseudoClassStateChanged(errorClass2, true);
            }
        }

        //If required fields are valid, save data
        if (count == requiredFieleds.size()) {
            Worker worker = new Worker();

            worker.setName(name.getText().trim());
            worker.setSurname(surname.getText().trim());
            worker.setAge(age.getValue());

            ContactInformation contactInformation = new ContactInformation();
            contactInformation.setAddress(address.getText().trim());
            contactInformation.setCity(city.getText().trim());
            contactInformation.setTelephoneNum(telephoneNumber.getText().trim());
            contactInformation.setEmail(email.getText().trim());
            worker.setContactInformation(contactInformation);

            EmploymentInformation employmentInformation = new EmploymentInformation();
            employmentInformation.setDepartment(departmentBox.getValue());
            employmentInformation.setIdNumber(Long.parseLong(idNumber.getText().trim()));
            employmentInformation.setStartDate(startDate.getValue());
            employmentInformation.setContractType(contractType.getValue());
            employmentInformation.setEndDate(endDate.getValue());
            employmentInformation.setPayFreq(payFrequency.getValue());
            employmentInformation.setAccountNum(Long.parseLong(accountNumber.getText().trim()));
            employmentInformation.setTaxCoeficient(Double.parseDouble(taxCoeficient.getText().trim()));
            employmentInformation.setNetSalary(Double.parseDouble(netSalary.getText().trim()));
            worker.setEmploymentInformation(employmentInformation);

            if(isInEditMode){
                worker.setId(id);
                workerDao.updateWorker(worker);
            }
            else {workerDao.saveWorker(worker);}

            closeButtonClicked();

        }
        else {error1.setText("Fill in all red fields");
            error2.setText("Fill in all red fields");
        }

    }

Method in other class to load the stageAdd

public static void showStageAdd() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(Main.class.getResource("/views/StageAdd.fxml"));
        BorderPane addWorkerPane = loader.load();
        stageAdd = new Stage();
        stageAdd.setTitle("Add New Worker");
        stageAdd.resizableProperty().setValue(Boolean.FALSE);
        Scene scene = new Scene(addWorkerPane);
        scene.getStylesheets().add("/css/redBorder.css");
        stageAdd.setScene(scene);
        stageAdd.initModality(Modality.WINDOW_MODAL);
        stageAdd.initOwner(stage1);
        stageAdd.showAndWait();
    }

Body:
We ran into a similar issue -> the following code:

stage.setOnCloseRequest((e)-> refreshButtonClicked());

This will be called when the window is closed via the "X" on the window.  However this code

Stage stage = (Stage) rootPane.getScene().getWindow();
stage.close();

Actually will not call the close request.  You can accomplish this by sending a close event to the window rather than stage.close() or you can do this:

stage.setOnHidden((e)-> refreshButtonClicked());


问:
Delete fields that have a specific substring on logstash
I want to delete the fields which the value has a specific substring.

I have this code:

```<code>ruby {
            code => "
                event.each do |key, value|
                    if value =~ /substring/
                        event.delete(key)
                  end
                end
            "
          }
</code>```

I am getting a ruby exception on tags and I don't know why.
Thanks!

答:
One can not modify a hash while iterating it.

```<code>event.reject! { |_, value| value =~ /substring/ }
</code>```

The above should do.

Body:
I want to delete the fields which the value has a specific substring.

I have this code:

ruby {
            code => "
                event.each do |key, value|
                    if value =~ /substring/
                        event.delete(key)
                  end
                end
            "
          }

I am getting a ruby exception on tags and I don't know why.
Thanks!

Body:
One can not modify a hash while iterating it.

event.reject! { |_, value| value =~ /substring/ }

The above should do.


答:
If you want to merge them, you could provide a default predicate for the last parameter that only calls operator== on the inputs.

edit: an example would be:

```<code>template<typename T1, typename T2>
struct eqpred
{
  bool operator(T1 &a, T2 &b) { return a==b; }
}

template <class iterType1, class iterType2, class boolPred=eqpred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How is the 'equal' template function implemented? (predicate version)

Body:
If you want to merge them, you could provide a default predicate for the last parameter that only calls operator== on the inputs.

edit: an example would be:

template<typename T1, typename T2>
struct eqpred
{
  bool operator(T1 &a, T2 &b) { return a==b; }
}

template <class iterType1, class iterType2, class boolPred=eqpred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}


问:
Excel VBA keeps turning cells black
I have written code so if the cell value is more than 0.10 it turns yellow. If not, it should stay white. Instead of staying white, the cell turns black. I can't figure out why it is doing this.

```<code>Sub moreThan10Percent()
For nRow = 2 To 1937
    For nColumn = 6 To 6
        If Cells(nRow, nColumn) >= 0.1 Then
            Cells(nRow, nColumn).Interior.ColorIndex = 6
            Else
            Cells(nRow, nColumn).Interior.Color = 1
        End If
    Next nColumn
Next nRow
</code>```

End Sub

答:
Try this. I put the bulk of your checker into a separate sub with parameters. The first sub is the one with the name you chose, and the others are examples of different ways to refer to the cells you want to check. Following that is the main sub that loops through the cells and does the checking, but without nested for-next loops. The last sub is an extension of the conversation, and it creates a reference worksheet with a table of all the Excel indexed colors.

The three parameters are: 1) Range of cells to check, 2) Threshold of the check, and 3) Color to change the cell to.

The reason for the breakout into a sub with parameters is that I was also trying to make this work from the Worksheet_Change and Workbook_SheetChange events. This can be a wonderful extension of the regular Conditional Formatting on the Excel UI, but without constraint of that wonky set of controls. You can make Excel do anything you within its power when someone types a certain value in a certain cell or range of cells.

But my way of implementing those events this way requires the use of the Intersect() function, and I'm getting some weird errors that I don't recall getting before. I'll work them out and report back with the completed code.

```<code>Sub moreThan10Percent()
    checkValues Range(Cells(2, 6), Cells(1937, 6)), 0.1, 3
End Sub

Sub moreWays1()
    checkValues Range("F2:F1937"), 0.1, 6
End Sub

Sub moreWays2()
    checkValues Intersect(Range("F:F"), Range("2:1937")), 0.1, 6
End Sub

Sub moreWays3()
    checkValues Intersect(Columns(6).EntireColumn, Range(Rows(2).EntireRow, Rows(1937).EntireRow)), 0.1, 6
End Sub

Sub moreWays4()
    checkValues Intersect(Columns(6).EntireColumn, Range(Rows(2), Rows(1937).EntireRow)), 0.1, 6
End Sub

Sub checkValues(targetRange As Range, targetThreshold As Single, targetColor As Long)
    Dim targetCell As Range
    For Each targetCell In targetRange
        With targetCell
            If .value >= targetThreshold Then
                .Interior.ColorIndex = targetColor
            Else
                .Interior.ColorIndex = xlColorIndexNone
            End If
        End With
    Next
End Sub

Sub generateTableOfExcelColorIndexes()
    Dim cell As Range
    Dim i As Integer
    Worksheets.Add(after:=Worksheets(Worksheets.Count)).Name = "COLORS"
    i = 0
    For Each cell In Range("A1:H7")
        i = i + 1
        With cell
            .HorizontalAlignment = xlCenter
            .value = i
            With cell.Interior
                .Pattern = xlSolid
                .ColorIndex = i
            End With
        End With
    Next
End Sub
</code>```

Title: Excel VBA keeps turning cells black

Body:
I have written code so if the cell value is more than 0.10 it turns yellow. If not, it should stay white. Instead of staying white, the cell turns black. I can't figure out why it is doing this.

Sub moreThan10Percent()
For nRow = 2 To 1937
    For nColumn = 6 To 6
        If Cells(nRow, nColumn) >= 0.1 Then
            Cells(nRow, nColumn).Interior.ColorIndex = 6
            Else
            Cells(nRow, nColumn).Interior.Color = 1
        End If
    Next nColumn
Next nRow

End Sub

Body:
Try this. I put the bulk of your checker into a separate sub with parameters. The first sub is the one with the name you chose, and the others are examples of different ways to refer to the cells you want to check. Following that is the main sub that loops through the cells and does the checking, but without nested for-next loops. The last sub is an extension of the conversation, and it creates a reference worksheet with a table of all the Excel indexed colors.

The three parameters are: 1) Range of cells to check, 2) Threshold of the check, and 3) Color to change the cell to.

The reason for the breakout into a sub with parameters is that I was also trying to make this work from the Worksheet_Change and Workbook_SheetChange events. This can be a wonderful extension of the regular Conditional Formatting on the Excel UI, but without constraint of that wonky set of controls. You can make Excel do anything you within its power when someone types a certain value in a certain cell or range of cells.

But my way of implementing those events this way requires the use of the Intersect() function, and I'm getting some weird errors that I don't recall getting before. I'll work them out and report back with the completed code.

Sub moreThan10Percent()
    checkValues Range(Cells(2, 6), Cells(1937, 6)), 0.1, 3
End Sub

Sub moreWays1()
    checkValues Range("F2:F1937"), 0.1, 6
End Sub

Sub moreWays2()
    checkValues Intersect(Range("F:F"), Range("2:1937")), 0.1, 6
End Sub

Sub moreWays3()
    checkValues Intersect(Columns(6).EntireColumn, Range(Rows(2).EntireRow, Rows(1937).EntireRow)), 0.1, 6
End Sub

Sub moreWays4()
    checkValues Intersect(Columns(6).EntireColumn, Range(Rows(2), Rows(1937).EntireRow)), 0.1, 6
End Sub

Sub checkValues(targetRange As Range, targetThreshold As Single, targetColor As Long)
    Dim targetCell As Range
    For Each targetCell In targetRange
        With targetCell
            If .value >= targetThreshold Then
                .Interior.ColorIndex = targetColor
            Else
                .Interior.ColorIndex = xlColorIndexNone
            End If
        End With
    Next
End Sub

Sub generateTableOfExcelColorIndexes()
    Dim cell As Range
    Dim i As Integer
    Worksheets.Add(after:=Worksheets(Worksheets.Count)).Name = "COLORS"
    i = 0
    For Each cell In Range("A1:H7")
        i = i + 1
        With cell
            .HorizontalAlignment = xlCenter
            .value = i
            With cell.Interior
                .Pattern = xlSolid
                .ColorIndex = i
            End With
        End With
    Next
End Sub


问:
Angular Material - Prevent mat-stepper from navigating between steps
I have a mat-horizontal-stepper where I set linear property as true. When all the steps are valid as of now I can navigate to previous steps by clicking the header or label. I don't want that property.

I need to navigate only through buttons.

I tried disabling pointer function with:

```<code>    .mat-horizontal-stepper-header{
       pointer-events: none;
     }
</code>```

but it didn't worked.

I need either to stop navigating by clicking header or fire a function on clicking the stepper header.

答:
Set editable to false for mat-step

```<code><mat-step editable="false"> ... </mat-step>
</code>```

Body:
I have a mat-horizontal-stepper where I set linear property as true. When all the steps are valid as of now I can navigate to previous steps by clicking the header or label. I don't want that property.

I need to navigate only through buttons.

I tried disabling pointer function with:

    .mat-horizontal-stepper-header{
       pointer-events: none;
     }

but it didn't worked.

I need either to stop navigating by clicking header or fire a function on clicking the stepper header.

Body:
Set editable to false for mat-step

<mat-step editable="false"> ... </mat-step>


问:
adding same class to div using another divs class
i need your help. I´m totally new to javascript but i was able to make a website using some functions. Now my question is:

All in all i got 77 divs and 77 paths. I want every path to get the same class as the div that belongs to the path. Every div and every path has its own ID. My index markup looks like this:

```<code><div id="div_1" class="div_class_1"></div>
<div id="div_2" class="div_class_2"></div>
<div id="div_3" class="div_class_3"></div>
<div id="div_4" class="div_class_4"></div>
  ....
<div id="div-77"></div>

<div id="map">
  <path id="path_1" class="get class from #div_1"></path>
  <path id="path_2" class="get class from #div_2"></path>
  <path id="path_3" class="get class from #div_3"></path>
  <path id="path_4" class="get class from #div_4"></path>
    ...
  <path id="path_77" class="get class from #div_77"></path>
</div>
</code>```

So basically when the page is loaded i want the function to read the class of #div_1 to add it as class for #path_1.

答:
https://developer.mozilla.org/en-US/docs/Web/API/Element/className

look at this example.

you can get the class of an element using this method

```<code>elm = document.getElementById('item');
var cName = elm.className;
</code>```

and you can change the classname on the fly this way.

```<code>elm.className = 'inactive'; // class name inactive will be applied to the selected element
</code>```

create a for loop then you can get ,apply or remove classes on the fly.

Body:
i need your help. I´m totally new to javascript but i was able to make a website using some functions. Now my question is:

All in all i got 77 divs and 77 paths. I want every path to get the same class as the div that belongs to the path. Every div and every path has its own ID. My index markup looks like this:

  ....

  <path id="path_1" class="get class from #div_1"></path>
  <path id="path_2" class="get class from #div_2"></path>
  <path id="path_3" class="get class from #div_3"></path>
  <path id="path_4" class="get class from #div_4"></path>
    ...
  <path id="path_77" class="get class from #div_77"></path>

So basically when the page is loaded i want the function to read the class of #div_1 to add it as class for #path_1.

Body:
https://developer.mozilla.org/en-US/docs/Web/API/Element/className

look at this example.

you can get the class of an element using this method

elm = document.getElementById('item');
var cName = elm.className;

and you can change the classname on the fly this way.

elm.className = 'inactive'; // class name inactive will be applied to the selected element

create a for loop then you can get ,apply or remove classes on the fly.


问:
Check authenticity of SAML assertion message as SP
We are sharing our SP metadata on public URL which also contains our public key and SSO URL (binding as well). I completely understand that public keys are meant to be freely shared between parties. But I am just trying to understand what if an unauthorised user gets access to our public key (as this is available in publicly available metadata) and knows the URL for our company's SSO (that is also available in our publicly available metadata), would they be able to authenticate themselves? How I can ensure that SAML assertion is coming from authorised source only?</p>

答:
How someone having your public key would sign the assertion? They would definitely need the private key for this.

And this can't be just any private key - your SP is supposed to know the IdP's public key in advance (you don't need the whole public key, the Subject name and Thumbprint should be sufficient).

Then, when an assertion comes to the SP, it validates not only the signature itself but also, what certificate was used to sign the assertion. The SP does so by comparing the certificate information from the incoming signature to the previously stored information about the valid IdP's public key.


问:
Whitespace Matching Regex - Java
The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

```<code>Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");
</code>```

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

Am I having a grave misunderstanding of regexes or the term "whitespace"?

答:
Yeah, you need to grab the result of matcher.replaceAll():

```<code>String result = matcher.replaceAll(" ");
System.out.println(result);
</code>```

Title: Whitespace Matching Regex - Java

Body:
The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

Am I having a grave misunderstanding of regexes or the term "whitespace"?

Body:
Yeah, you need to grab the result of matcher.replaceAll():

String result = matcher.replaceAll(" ");
System.out.println(result);

ContentLicense: CC BY-SA 4.0


问:
Conditional static class method access from another class
I have static classes A,B and C like

```<code>public static class A
{
    public static bool SampleMethod()
    {
        ...
    }
}

public static class B
{
    public static bool SampleMethod()
    {
        ...
    }
}

public static class C
{
    public static bool DoStuff(Enum dataType)
    {
        Type targetClass = null;
        switch (dataType)
        {
            case DataType.1:
                targetClass = typeof(A);
                break;
            case DataType.2:
                targetClass = typeof(B);
                break;
        }

        return targetClass.SampleMethod();
    }
}
</code>```

Im trying to set variable targetClass with name of the class. The method im trying to access in class A and B is with same name. However im getting an error like

Type doesnot contain definition for 'SampleMethod'

答:
Like other comments said, the type returned from typeof operator is Type, not A or B, so you cannot invoke SampleMethod.

There are several ways to achieve this. Simplest is to use Func to store the method:

```<code>public static class C
{
    public static bool DoStuff(DataType dataType)
    {
        Func<bool> method = null;

        switch (dataType)
        {
            case DataType.A:
                method = A.SampleMethod;
                break;
            case DataType.B:
                method = B.SampleMethod;
                break;
        }

        return method();
    }
}
</code>```

The other way is to let A, B implement a common interface

Body:
I have static classes A,B and C like

public static class A
{
    public static bool SampleMethod()
    {
        ...
    }
}

public static class B
{
    public static bool SampleMethod()
    {
        ...
    }
}

public static class C
{
    public static bool DoStuff(Enum dataType)
    {
        Type targetClass = null;
        switch (dataType)
        {
            case DataType.1:
                targetClass = typeof(A);
                break;
            case DataType.2:
                targetClass = typeof(B);
                break;
        }

        return targetClass.SampleMethod();
    }
}

Im trying to set variable targetClass with name of the class. The method im trying to access in class A and B is with same name. However im getting an error like

Type doesnot contain definition for 'SampleMethod'

Body:
Like other comments said, the type returned from typeof operator is Type, not A or B, so you cannot invoke SampleMethod.

There are several ways to achieve this. Simplest is to use Func to store the method:

public static class C
{
    public static bool DoStuff(DataType dataType)
    {
        Func<bool> method = null;

        switch (dataType)
        {
            case DataType.A:
                method = A.SampleMethod;
                break;
            case DataType.B:
                method = B.SampleMethod;
                break;
        }

        return method();
    }
}

The other way is to let A, B implement a common interface


问:
Phonekeypad string to number
There is international keypad for phones and it's look like:

My program do the following:

Convert the string to number e.g ABC equal to 1

Display result.

And I'm doing it like below:

```<code>private static String getNumber(String s) {

    String result = "";
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == 'A' || s.charAt(i) == 'B' || s.charAt(i) == 'C')
            result += "2";
        else if (s.charAt(i) == 'D' || s.charAt(i) == 'E' || s.charAt(i) == 'F')
            result += "3";
        else if (s.charAt(i) == 'G' || s.charAt(i) == 'H' || s.charAt(i) == 'I')
            result += "4";
        else if (s.charAt(i) == 'J' || s.charAt(i) == 'K' || s.charAt(i) == 'L')
            result += "5";
        else if (s.charAt(i) == 'M' || s.charAt(i) == 'N' || s.charAt(i) == 'O')
            result += "6";
        else if (s.charAt(i) == 'P' || s.charAt(i) == 'Q' || s.charAt(i) == 'R' || s.charAt(i) == 'S')
            result += "7";
        else if (s.charAt(i) == 'T' || s.charAt(i) == 'U' || s.charAt(i) == 'V')
            result += "8";
        else if (s.charAt(i) == 'W' || s.charAt(i) == 'X' || s.charAt(i) == 'Y' || s.charAt(i) == 'Z')
            result += "9";
        else
            result += s.charAt(i);
    }

    return result;
}
</code>```

Sample input: 1-800-Flowers

Output : 1-800-3569377

Question:

Can i shorthand this code with for loop or something?

答:
There are a lot of ways to accomplish this result, you can use replace() to get the number you want:</p>

```<code>public static String getNumber(String s) {
    // Set all String to caps
    s = s.toUpperCase();

    // Replace the letters with the corresponding numbers
    s = s.replaceAll("(A|B|C)", "2");
    s = s.replaceAll("(D|E|F)", "3");
    s = s.replaceAll("(G|H|I)", "4");
    s = s.replaceAll("(J|K|L)", "5");
    s = s.replaceAll("(M|N|O)", "6");
    s = s.replaceAll("(P|Q|R|S)", "7");
    s = s.replaceAll("(T|U|V)", "8");
    s = s.replaceAll("(W|X|Y|Z)", "9");

    return s;

}
</code>```

Title: Phonekeypad string to number

Body:
There is international keypad for phones and it's look like:

My program do the following:

Convert the string to number e.g ABC equal to 1

Display result.

And I'm doing it like below:

private static String getNumber(String s) {

    String result = "";
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == 'A' || s.charAt(i) == 'B' || s.charAt(i) == 'C')
            result += "2";
        else if (s.charAt(i) == 'D' || s.charAt(i) == 'E' || s.charAt(i) == 'F')
            result += "3";
        else if (s.charAt(i) == 'G' || s.charAt(i) == 'H' || s.charAt(i) == 'I')
            result += "4";
        else if (s.charAt(i) == 'J' || s.charAt(i) == 'K' || s.charAt(i) == 'L')
            result += "5";
        else if (s.charAt(i) == 'M' || s.charAt(i) == 'N' || s.charAt(i) == 'O')
            result += "6";
        else if (s.charAt(i) == 'P' || s.charAt(i) == 'Q' || s.charAt(i) == 'R' || s.charAt(i) == 'S')
            result += "7";
        else if (s.charAt(i) == 'T' || s.charAt(i) == 'U' || s.charAt(i) == 'V')
            result += "8";
        else if (s.charAt(i) == 'W' || s.charAt(i) == 'X' || s.charAt(i) == 'Y' || s.charAt(i) == 'Z')
            result += "9";
        else
            result += s.charAt(i);
    }

    return result;
}

Sample input: 1-800-Flowers

Output : 1-800-3569377

Question:

Can i shorthand this code with for loop or something?

Body:
There are a lot of ways to accomplish this result, you can use replace() to get the number you want:

public static String getNumber(String s) {
    // Set all String to caps
    s = s.toUpperCase();

    // Replace the letters with the corresponding numbers
    s = s.replaceAll("(A|B|C)", "2");
    s = s.replaceAll("(D|E|F)", "3");
    s = s.replaceAll("(G|H|I)", "4");
    s = s.replaceAll("(J|K|L)", "5");
    s = s.replaceAll("(M|N|O)", "6");
    s = s.replaceAll("(P|Q|R|S)", "7");
    s = s.replaceAll("(T|U|V)", "8");
    s = s.replaceAll("(W|X|Y|Z)", "9");

    return s;

}


问:
converting an function statement to an arrow function doesn't work
I am struggling with understanding the following.

I have the following code:

```<code>const myFunction = function (error) {
  console.error(error)
  callSomething();
}
</code>```

As you see I am using a function called callSomething() and it works but as soon as I use arrow function then callSomething() :

```<code>const myFunction = error => console.error(error);callSomething();
</code>```

Then callSomething() is not called.

答:
From the docs

Omitting the curly braces implies using an expression as the MDN documentations says

Basic Syntax

```<code>(param1, param2, …, paramN) => { statements } (param1, param2, …,
paramN) => expression // equivalent to: (param1, param2, …, paramN) =>
{ return expression; }

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements } singleParam => { statements }
singleParam => expression

// The parameter list for a function with no parameters should be
written with a pair of parentheses. () => { statements }
</code>```

Expressions versus statements in Javascript

Explanations

So basically the following should work as callSomething() is an expression

```<code>const myFunction = error => callSomething(error)
</code>```

With statements not being expressions (such as multiple expressions for exemple) the curly braces are mandatory

Example 1

```<code>const myFunction = error => {
  // other statements such as
  console.error(error);
  callSomehting(error);
});
</code>```

Example 2

throw error is a statement but not an expression!

```<code>const myFunction = error => {
  throw error;
});
</code>```

Body:
I am struggling with understanding the following.

I have the following code:

const myFunction = function (error) {
  console.error(error)
  callSomething();
}

As you see I am using a function called callSomething() and it works but as soon as I use arrow function then callSomething() :

const myFunction = error => console.error(error);callSomething();

Then callSomething() is not called.

Body:
From the docs

Omitting the curly braces implies using an expression as the MDN documentations says

Basic Syntax

(param1, param2, …, paramN) => { statements } (param1, param2, …,
paramN) => expression // equivalent to: (param1, param2, …, paramN) =>
{ return expression; }

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements } singleParam => { statements }
singleParam => expression

// The parameter list for a function with no parameters should be
written with a pair of parentheses. () => { statements }

Expressions versus statements in Javascript

Explanations

So basically the following should work as callSomething() is an expression

const myFunction = error => callSomething(error)

With statements not being expressions (such as multiple expressions for exemple) the curly braces are mandatory

Example 1

const myFunction = error => {
  // other statements such as
  console.error(error);
  callSomehting(error);
});

Example 2

throw error is a statement but not an expression!

const myFunction = error => {
  throw error;
});


问:
How can get the Transaction ID or Status for payment on Website?
I'm using PHP and this's my fist post and I have some doubts... The target is: "integrate the paypal payment for a online store, so when the user complete the car's items, he will be able to pay using PAYPAL platform, the website should receive some confirmation to ensure the purchase".

In my code I put the button for payment using this tutorial Client-Side REST (https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/client-side-REST-integration/), I tried the button using the "test credentials" generated in SANDBOX/ACCOUNTS (buyer account test), but when the buy process finish I only receive de "alert()" message, but it's all :(....

I know !... I can change this alert() function for my own code, but the problem is: "where is the Confirmation ID o Transaction ID" for the payment ?

Whats I need to do to know where is the "Transaction ID" for the payment ?

Regards !

答:
Using the demo code, once you get the alert that the payment was successful you'll need to login to the sandbox account at https://www.sandbox.paypal.com. You'll see your payment processed with the transaction id. Typically you'll be able to gather the information from the API Response or using GET to retrieve the data.

Show payment details: https://developer.paypal.com/docs/api/payments/#payment_get


问:
Is it possible to get `mvn tomcat6:run` to work correctly with a filtered web.xml?
I have a project that needs to have ${} placeholder substitution applied to web.xml that I want to run for development mode with mvn tomcat6:run. Is it possible to set this up?

This is a legacy codebase where I'm trying to introduce both deployment environments to get rid of the previous process that was "copy web.xml variants around and edit a config file and keep this out of source control." I also want to avoid having to maintain a Tomcat installation and setting up an IDE to deploy to it, and just have the application execute using tomcat6-maven-plugin.

What I have so far is this project layout:

```<code>foo
│   pom.xml
│
└───src
    └───main
        ├───environments
        │   ├───BAR
        │   │       filter.properties
        │   │
        │   └───FOO
        │           filter.properties
        │
        ├───java
        │   └───se
        │       └───millimoo
        │               IndexServlet.java
        │
        └───webapp
            └───WEB-INF
                    web.xml
</code>```

pom.xml

```<code>...
<build>
    <filters>
        <filter>src/main/environments/${environment}/filter.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/environments/${environment}</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat6-maven-plugin</artifactId>
            <version>2.2</version>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>env-foo</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <environment>FOO</environment>
        </properties>
    </profile>
    <profile>
        <id>env-bar</id>
        <properties>
            <environment>BAR</environment>
        </properties>
    </profile>
</profiles>
...
</code>```

That is: I add the directory for an environment as a resource; tell Maven to load placeholder values from filter.properties in that directory; and tell the WAR plugin to filter the deployment descriptors. I also set up two profiles to switch between the environments.

FOO\filter.properties

```<code>filter.environment=foofoo
</code>```

BAR\filter.properties

```<code>filter.environment=barbar
</code>```

web.xml

```<code>...
<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>se.millimoo.IndexServlet</servlet-class>
    <init-param>
        <param-name>environment</param-name>
        <param-value>${filter.environment}</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
...
</code>```

IndexServlet.java

Prints the value of the environment init param.

What happens is that when I run this using mvn tomcat6:run, it uses the unfiltered web.xml, which is obviously not what I want. The filtered version is used when I use mvn tomcat6:run-war, but I'm not a fan of that: it's slower, and has other issues in my real code that generally slow down turnaround, which is the point of the exercise. (It uses the JAR files of dependent projects where the backend code is from the Maven repository to build the JAR, which can be either outdated or not available at all if I haven't installed them after a version number bump; rather than using the current code.)

Is there a way to get the best of both worlds here? Be able to run the app server through maven or in another easily embedded way, while also having filtering applied to web.xml? Preferrably without significantly changing the app itself, i.e. I don't want to load the configuration values without using servlet init params. (In the real code, the servlet is a third-party one.)

答:
I think you need to add this in your pom.xml so Maven knows he needs to filter this directory too :

```<code><build>
    <resources>
        <resource>
            <directory>src/main/webapp/WEB-INF</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
...
</build>
</code>```

EDIT

As discused in the commentaries, this approach might not be a good solution.

Another solution :

From  Apache Maven WAR Plugin documentation

Overriding the default destination directory

By default web resources are copied to the root of the WAR, as shown
  in the previous example. To override the default destination
  directory, specify the target path.

```<code>        ...
        <configuration>
          <webResources>
            <resource>
              ...
            </resource>
            <resource>
              <directory>configurations</directory>
              <!-- override the destination directory for this resource -->
              <targetPath>WEB-INF</targetPath>
              <!-- enable filtering -->
              <filtering>true</filtering>
              <excludes>
                <exclude>**/properties</exclude>
              </excludes>
            </resource>
          </webResources>
        </configuration>
        ...
</code>```

In this example, we override a directory but maybe it's possible to override a single file.

Body:
I have a project that needs to have ${} placeholder substitution applied to web.xml that I want to run for development mode with mvn tomcat6:run. Is it possible to set this up?

This is a legacy codebase where I'm trying to introduce both deployment environments to get rid of the previous process that was "copy web.xml variants around and edit a config file and keep this out of source control." I also want to avoid having to maintain a Tomcat installation and setting up an IDE to deploy to it, and just have the application execute using tomcat6-maven-plugin.

What I have so far is this project layout:

foo
│   pom.xml
│
└───src
    └───main
        ├───environments
        │   ├───BAR
        │   │       filter.properties
        │   │
        │   └───FOO
        │           filter.properties
        │
        ├───java
        │   └───se
        │       └───millimoo
        │               IndexServlet.java
        │
        └───webapp
            └───WEB-INF
                    web.xml

pom.xml

...
<build>
    <filters>
        <filter>src/main/environments/${environment}/filter.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/environments/${environment}</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat6-maven-plugin</artifactId>
            <version>2.2</version>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>env-foo</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <environment>FOO</environment>
        </properties>
    </profile>
    <profile>
        <id>env-bar</id>
        <properties>
            <environment>BAR</environment>
        </properties>
    </profile>
</profiles>
...

That is: I add the directory for an environment as a resource; tell Maven to load placeholder values from filter.properties in that directory; and tell the WAR plugin to filter the deployment descriptors. I also set up two profiles to switch between the environments.

FOO\filter.properties

filter.environment=foofoo

BAR\filter.properties

filter.environment=barbar

web.xml

...
<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>se.millimoo.IndexServlet</servlet-class>
    <init-param>
        <param-name>environment</param-name>
        <param-value>${filter.environment}</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
...

IndexServlet.java

Prints the value of the environment init param.

What happens is that when I run this using mvn tomcat6:run, it uses the unfiltered web.xml, which is obviously not what I want. The filtered version is used when I use mvn tomcat6:run-war, but I'm not a fan of that: it's slower, and has other issues in my real code that generally slow down turnaround, which is the point of the exercise. (It uses the JAR files of dependent projects where the backend code is from the Maven repository to build the JAR, which can be either outdated or not available at all if I haven't installed them after a version number bump; rather than using the current code.)

Is there a way to get the best of both worlds here? Be able to run the app server through maven or in another easily embedded way, while also having filtering applied to web.xml? Preferrably without significantly changing the app itself, i.e. I don't want to load the configuration values without using servlet init params. (In the real code, the servlet is a third-party one.)

Body:
I think you need to add this in your pom.xml so Maven knows he needs to filter this directory too :

<build>
    <resources>
        <resource>
            <directory>src/main/webapp/WEB-INF</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
...
</build>

EDIT

As discused in the commentaries, this approach might not be a good solution.

Another solution :

From  Apache Maven WAR Plugin documentation

Overriding the default destination directory

By default web resources are copied to the root of the WAR, as shown
  in the previous example. To override the default destination
  directory, specify the target path.

        ...
        <configuration>
          <webResources>
            <resource>
              ...
            </resource>
            <resource>
              <directory>configurations</directory>
              <!-- override the destination directory for this resource -->
              <targetPath>WEB-INF</targetPath>
              <!-- enable filtering -->
              <filtering>true</filtering>
              <excludes>
                <exclude>**/properties</exclude>
              </excludes>
            </resource>
          </webResources>
        </configuration>
        ...

In this example, we override a directory but maybe it's possible to override a single file.


问:
Pycharm: "No Python interpreter configured for the project" everytime
Every time I open PyCharm I get this message:

No Python interpreter configured for the project.

So I set the interpreter, everything works fine, then I close PyCharm and reopen it, and the message pops up again.

Reinstalling Python and Pycharm didn't fix the problem.

答: One way you could try is: Run --> Edit Configurations --> set your interpreter there. That "sticks" for me...</p>


问:
Simple Highcharts chart not working in Firefox
I am experiencing a strange issue with highcharts and Firefox. For some reason, this code works with Chrome, but not with Firefox:

```<code>var options = {
chart: {
    renderTo: 'visits',
    backgroundColor:null,
    type: 'line'
},
exporting: { enabled: false },
title: {
    text: 'Visits'
},

xAxis: {
    categories: [],
    tickInterval: 7,
    labels: {
        style: {
            fontSize:'8px'
        }}
},
yAxis: {
    labels: {
            enabled: false
    },
    title: {
        text: null
    }
},
tooltip: {
    pointFormat: '{point.y:.0f} Visits'
},
legend: {
    enabled: false
},
series: [{
    name: [],
    data: []
}]};
</code>```

$.get('downloads/myfile.csv', function(data) {
    // Split the lines

```<code>var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
    var items = line.split(',');
    if (lineNo !== 0) {
        options.series[0].data.push({
            name: items[0],
            y: parseFloat(items[1])
        });

        options.xAxis.categories.push(x);
    }
});
var chart = new Highcharts.Chart(options); });
</code>```

My CSV file has the following data:

```<code>2017-09-01,65
2017-09-02,36
2017-09-03,36
2017-09-04,91
2017-09-05,75
2017-09-06,120
</code>```

Since items[1] is number, why it cannot be displayed in Firefox? If I replace items[1] with a plain number, say "1", I get a flat line which means that for some reason the parseFloat fails. I get no errors or warnings in the console.

How can I deal with this?

答: I have found why it did not work in firefox. The encoding of the CSV file is UTF-8 with BOM! For some reason Firefox cannot parse it. I have saved the CSV as ANSI and it works as expected. I guess I could resolve this by reading the file with AJAX.</p>

Body:
I am experiencing a strange issue with highcharts and Firefox. For some reason, this code works with Chrome, but not with Firefox:

var options = {
chart: {
    renderTo: 'visits',
    backgroundColor:null,
    type: 'line'
},
exporting: { enabled: false },
title: {
    text: 'Visits'
},

xAxis: {
    categories: [],
    tickInterval: 7,
    labels: {
        style: {
            fontSize:'8px'
        }}
},
yAxis: {
    labels: {
            enabled: false
    },
    title: {
        text: null
    }
},
tooltip: {
    pointFormat: '{point.y:.0f} Visits'
},
legend: {
    enabled: false
},
series: [{
    name: [],
    data: []
}]};

$.get('downloads/myfile.csv', function(data) {
    // Split the lines

var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
    var items = line.split(',');
    if (lineNo !== 0) {
        options.series[0].data.push({
            name: items[0],
            y: parseFloat(items[1])
        });

        options.xAxis.categories.push(x);
    }
});
var chart = new Highcharts.Chart(options); });

My CSV file has the following data:

2017-09-01,65
2017-09-02,36
2017-09-03,36
2017-09-04,91
2017-09-05,75
2017-09-06,120

Since items[1] is number, why it cannot be displayed in Firefox? If I replace items[1] with a plain number, say "1", I get a flat line which means that for some reason the parseFloat fails. I get no errors or warnings in the console.

How can I deal with this?


问:
nodejs json endpoint from api json stream
I am connecting to an api and pulling a set of json data. the javascript outputs the json as the variable feedData and when i include that in a html  i get the json on a html page as expected. What i want to do is output it as a json endpoint. I tried to get fancy and when i  tried:

```<code>var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send(feedData);
});
app.listen(3000, function () {
 console.log('posting data');
});
</code>```

the problem is that i need to import an api.js file and when i attempt to load this i get an error related to the api.js file which is windows is not defined.  Like i said, the html

```<code> document.getElementById('mydiv').innerHTML += JSON.stringify(feedData, undefined,2);
</code>```

then

```<code><pre id="mydiv">```
```

works fine but i will also to recall every x seconds because this is a live json feed.

Currently, i just decided to connect via python, loading it into mongodb and creating a nodejs endpoint from there, which works fine,  but it seems there should be a way here.

答: Try using res.json, res.json(feedData); to send objects. If you want to send a string just, use res.send

Body:
I am connecting to an api and pulling a set of json data. the javascript outputs the json as the variable feedData and when i include that in a html  i get the json on a html page as expected. What i want to do is output it as a json endpoint. I tried to get fancy and when i  tried:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send(feedData);
});
app.listen(3000, function () {
 console.log('posting data');
});

the problem is that i need to import an api.js file and when i attempt to load this i get an error related to the api.js file which is windows is not defined.  Like i said, the html

 document.getElementById('mydiv').innerHTML += JSON.stringify(feedData, undefined,2);

then

works fine but i will also to recall every x seconds because this is a live json feed.

Currently, i just decided to connect via python, loading it into mongodb and creating a nodejs endpoint from there, which works fine,  but it seems there should be a way here.


问:
How is the 'equal' template function implemented? (predicate version)
I am working through the book "Accelerated C++" and one of the exercises require us to emulate the 'equal' function in the  header and so far I have implemented the simple version which takes three parameters as follows:

```<code>template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){

    while(begin != end){
        if(!(*begin == *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}
</code>```

and the second version which can accept a fourth parameter...

```<code>template <class iterType1, class iterType2, class boolPred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}
</code>```

My question is, is this the ideal way to do it? or are these two functions mergable?

答:
Those two functions aren't just mergeable, they're almost exactly the same, line for line.

I could expand and do it all for you, but that would be a bit of a spoiler.

Body:
I am working through the book "Accelerated C++" and one of the exercises require us to emulate the 'equal' function in the  header and so far I have implemented the simple version which takes three parameters as follows:

template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){

    while(begin != end){
        if(!(*begin == *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}

and the second version which can accept a fourth parameter...

template <class iterType1, class iterType2, class boolPred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){

    while(begin != end){
        if(!pred(*begin, *e))
            return false;
        ++begin;
        ++e;
    }
    return true;
}

My question is, is this the ideal way to do it? or are these two functions mergable?


问:
All-auth / Crispyform : Error messages not displayed
I'm working on the all-auth authentification process of my website and I encounter a problem: I can't see the error messages of the login / signup views, when I do something wrong (bad password, not typing same password in signup for ex.)  the page just reload.

Views.py

```<code>class CustomLogin(LoginView):
    """
    Custom login view from Allauth
    """
    def get_context_data(self, **kwargs):
        context = super(CustomLogin, self).get_context_data(**kwargs)
        context.update({'title': self.title, 'help_text': self.help_text})
        return context

    title = 'Connectez-vous'
    help_text = 'Veuillez rentrer votre login et votre mot de passe pour vous connecter.'

    form = CustomLoginForm
    template_name = "allauth-custom/allauth-card.html"
</code>```

Forms.py

```<code>class CustomLoginForm(LoginForm):
    def __init__(self, *args, **kwargs):
        super(CustomLoginForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'signup_form'
        self.helper.form_class = 'signup'
        self.helper.form_method = 'post'
        self.helper.form_action = reverse('thankyou')
        # and then the rest as usual:
        self.helper.form_show_errors = True
        self.helper.form_show_labels = False
        self.helper.add_input(Submit('Log in', 'log in'))
</code>```

Template

```<code>{% extends "base.html" %}
{% load socialaccount %}
{% load bootstrap3 %}
{% load crispy_forms_tags %}
{% load i18n %}

{% bootstrap_messages %}

{% block content %}
<section id='masthead'>
<div class="container ">
<div class="row justify-content-center">
    <div class="card col-6 ">
      <div class="card-body">
        <h4 class="card-title">{{title}}</h4>
         <p class="card-text">{{help_text}}</p>
         {% if form.errors %}
           <div class="alert alert-danger">
               {% for field in form %}
                 {% for error in field.errors %}
                         <strong>{{ error|escape }}</strong><br />
                 {% endfor %}
             {% endfor %}
           </div>
             {% for error in form.non_field_errors %}
                 <div class="alert alert-danger">
                     <strong>{{ error|escape }}</strong>
                 </div>
             {% endfor %}
         {% endif %}
         {% crispy form %}
      </div>
  </div>
</div>
</section>
{% endblock %}
</code>```

答:
You should pass self (the current instance of your form) when doing self.helper = FormHelper()

self.helper = FormHelper(self)

From the exemple on this page: http://django-crispy-forms.readthedocs.io/en/latest/form_helper.html

```<code>from crispy_forms.helper import FormHelper

class ExampleForm(forms.Form):
    def __init__(self, *args, **kwargs):
         super(ExampleForm, self).__init__(*args, **kwargs)
         self.helper = FormHelper(self) # You missed to pass the self argument here
</code>```

Also, you define your action url as self.helper.form_action = reverse('thankyou')

I don't think this is what you want. The form_action should be your login url.

Body:
I'm working on the all-auth authentification process of my website and I encounter a problem: I can't see the error messages of the login / signup views, when I do something wrong (bad password, not typing same password in signup for ex.)  the page just reload.

Views.py

class CustomLogin(LoginView):
    """
    Custom login view from Allauth
    """
    def get_context_data(self, **kwargs):
        context = super(CustomLogin, self).get_context_data(**kwargs)
        context.update({'title': self.title, 'help_text': self.help_text})
        return context

    title = 'Connectez-vous'
    help_text = 'Veuillez rentrer votre login et votre mot de passe pour vous connecter.'

    form = CustomLoginForm
    template_name = "allauth-custom/allauth-card.html"

Forms.py

class CustomLoginForm(LoginForm):
    def __init__(self, *args, **kwargs):
        super(CustomLoginForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'signup_form'
        self.helper.form_class = 'signup'
        self.helper.form_method = 'post'
        self.helper.form_action = reverse('thankyou')
        # and then the rest as usual:
        self.helper.form_show_errors = True
        self.helper.form_show_labels = False
        self.helper.add_input(Submit('Log in', 'log in'))

Template

{% extends "base.html" %}
{% load socialaccount %}
{% load bootstrap3 %}
{% load crispy_forms_tags %}
{% load i18n %}

{% bootstrap_messages %}

{% block content %}

{{title}}

{{help_text}}

         {% if form.errors %}

               {% for field in form %}
                 {% for error in field.errors %}
                         {{ error|escape }}

                 {% endfor %}
             {% endfor %}

             {% for error in form.non_field_errors %}

                     {{ error|escape }}

             {% endfor %}
         {% endif %}
         {% crispy form %}

{% endblock %}

Body:
You should pass self (the current instance of your form) when doing self.helper = FormHelper()

self.helper = FormHelper(self)

From the exemple on this page: http://django-crispy-forms.readthedocs.io/en/latest/form_helper.html

from crispy_forms.helper import FormHelper

class ExampleForm(forms.Form):
    def __init__(self, *args, **kwargs):
         super(ExampleForm, self).__init__(*args, **kwargs)
         self.helper = FormHelper(self) # You missed to pass the self argument here

Also, you define your action url as self.helper.form_action = reverse('thankyou')

I don't think this is what you want. The form_action should be your login url.


答:
As you can see in this line Type targetClass = null;, targetClass is of type Type. A Type instance is an object itself, and is therefor not of type A or B. This means when you set targetClass to the value typeof(A), you're not creating an instance of A (even if A wasn't static you wouldn't), and instead you're setting targetObject to a value of type Type. This value is an object with meta information about the static class A.

What you're trying to do can be acchieved in a couple of ways.

The easiest way I can imagine is using a dictionary that indexes on an enum and stores values of type Action<bool> like this:

```<code>public static class C
{
        private static Dictionary<TypeEnum, Func<bool> dic = new Dictionary<TypeEnum, Func<bool>() {
             { DataType.1, A.SampleMethod },
             { DataType.2, B.SampleMethod }
        }
        public static bool DoStuff(Enum dataType)
        {
           return dic[dataType].Invoke();
        }
}
</code>```

This approach is limited because it only allows for methods with return type bool. There are similar ways to this though that allow for a more generic approach.

Title: Conditional static class method access from another class

Body:
As you can see in this line Type targetClass = null;, targetClass is of type Type. A Type instance is an object itself, and is therefor not of type A or B. This means when you set targetClass to the value typeof(A), you're not creating an instance of A (even if A wasn't static you wouldn't), and instead you're setting targetObject to a value of type Type. This value is an object with meta information about the static class A.

What you're trying to do can be acchieved in a couple of ways.

The easiest way I can imagine is using a dictionary that indexes on an enum and stores values of type Action<bool> like this:

public static class C
{
        private static Dictionary<TypeEnum, Func<bool> dic = new Dictionary<TypeEnum, Func<bool>() {
             { DataType.1, A.SampleMethod },
             { DataType.2, B.SampleMethod }
        }
        public static bool DoStuff(Enum dataType)
        {
           return dic[dataType].Invoke();
        }
}

This approach is limited because it only allows for methods with return type bool. There are similar ways to this though that allow for a more generic approach.


问:
Make your NPM package support multiple versions of peer dependency
I have a package on NPM that is using React version 15 as peer dependency. However, I want it to stop from throwing warnings for users that upgraded their React version. How do I make package support both version 15 and 16?

```<code>"peerDependencies": {
    "react-dom": "^15.0.0"
  },
</code>```

which is the most convenient way to deal with these?

Is "*15.0.0" good enough?

Body:
I have a package on NPM that is using React version 15 as peer dependency. However, I want it to stop from throwing warnings for users that upgraded their React version. How do I make package support both version 15 and 16?

"peerDependencies": {
    "react-dom": "^15.0.0"
  },

which is the most convenient way to deal with these?

Is "*15.0.0" good enough?

Body:
What about:

"peerDependencies": {
  "react": "^15.0.0 || ^16.0.0",
  "react-dom": "^15.0.0 || ^16.0.0"
}


问:
'X-Frame-Options' to 'SAMEORIGIN' google maps MVC
I want to display the Google maps with the following code using iframe

```<code><script type="text/javascript" src="https://www.googleadservices.com/pagead/conversion.js">
<noscript>
    <div style="display: inline;">
      <img height="1" width="1" style="border-style: none;" alt="" src="https://www.googleadservices.com/pagead/conversion/''/?label='';guid=ON&script=0" />
    </div>
</noscript>
    <div class="mapContainer" style="width: 251px; height: 202px;">
       <iframe id="iGmap" width="251" height="202" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="@Html.Raw(Model.CurrentBranch.GoogleMapURLWithZoomSet)">
       </iframe>
    </div>
</code>```

Where

```<code>src='http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=''&ll='',''&spn='',''&output=embed&z=4'
</code>```

The above code I am using in cshtml page
But giving the error like Refused to display 'https://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=…&ll=,&spn=,&output=embed&z=6' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

答:
I had same issue and resolve it by adding this AntiForgeryConfig.SuppressXFrameOptionsHeader = true to protected void Application_Start() method in my Global.asax.

That should resolve it.


问:
In cell range, if any of the cell is empty than show that cell reference in the msg box
Iam very new to this vba exel, I have a table ranging (C5:J30).so in this range if any of the cell is empty, then I should get a msgbox “showing the cell reference of that empty cell” since I very new to the exel vba so I couldn’t write any code,as usual the stackoverflow  demands code attempt, so please anybody can help me in this regard</p>

答:
I'd recommend updating ActiveSheet to your sheet name

```<code>Sub findEmptyCells()
    Dim c

    For Each c In ActiveSheet.Range("C5:J30")
        If IsEmpty(c) Then MsgBox c.Address
    Next c
End Sub
</code>```

Body:
I'd recommend updating ActiveSheet to your sheet name

Sub findEmptyCells()
    Dim c

    For Each c In ActiveSheet.Range("C5:J30")
        If IsEmpty(c) Then MsgBox c.Address
    Next c
End Sub


问:
Group concat with where match against in mysql
I'm working on a simple search function with SQL and got stuck. I use GROUP_CONCAT to put all keywords in a single row. The keywords are taken from categories.

Not all columns are in this example. I've stripped it down

```<code>SELECT
  p.id as id,
  p.title as title,
  p.title as company,
  GROUP_CONCAT(DISTINCT cat.title SEPARATOR " ") as keywords,
  FROM products p
    JOIN product_categories pc ON p.id = pc.product_id
    JOIN categories cat ON pc.category_id = cat.id
    JOIN companies co ON p.company_id = co.id
 WHERE MATCH (p.title) AGAINST ("Test")
 OR MATCH (co.title) AGAINST ("Test")
 GROUP BY p.id
</code>```

keywords contains something like keyword1 keyword2 keyword3.

The SQL above is working. However, I can't use MATCH AGAINST with a virtual value keywords value.

I've read about what I think is an ugly workaround, to add this:

```<code>HAVING keywords LIKE "%keyword1%"
</code>```

LIKE is probably slow and because HAVING is after GROUP BY I can't use OR so HAVING in this case will override the WHERE.

Ideally, I would like to use a MATCH AGAINST on keywords as well. So, what are my options?

Some kind of virtual table?

Subquery?

Something else?

I probably need an example code to understand.

答:
This doesn't answer the question you asked, but I think adding this condition to the WHERE clause of the query:

```<code>    OR EXISTS ( SELECT 1
                  FROM categories k
                 WHERE k.id = pc.category_id
                   AND k.title IN ('Test1','Test2')
              )
</code>```

before the GROUP BY would eliminate the need to scan the return from GROUP_CONCAT, if the specification is to return rows where the category title matches one of the specified search words.

If there's not a requirement to actually return the derived keywords column in the resultset, I'd avoid the GROUP BY.

```<code>SELECT p.id AS id
     , p.title AS title
     , p.title AS company
  FROM products p
  JOIN companies co
    ON co.id = p.company_id
 WHERE MATCH (p.title) AGAINST ('Test')
    OR MATCH (co.title) AGAINST ('Test')
    OR EXISTS ( SELECT 1
                  FROM categories k
                  JOIN product_categories pc
                    ON pc.category_id = k.id
                 WHERE pc.product_id = p.id
                   AND k.title IN ('Test1','Test2')
              )
 ORDER BY p.id
</code>```

Body:
I'm working on a simple search function with SQL and got stuck. I use GROUP_CONCAT to put all keywords in a single row. The keywords are taken from categories.

Not all columns are in this example. I've stripped it down

SELECT
  p.id as id,
  p.title as title,
  p.title as company,
  GROUP_CONCAT(DISTINCT cat.title SEPARATOR " ") as keywords,
  FROM products p
    JOIN product_categories pc ON p.id = pc.product_id
    JOIN categories cat ON pc.category_id = cat.id
    JOIN companies co ON p.company_id = co.id
 WHERE MATCH (p.title) AGAINST ("Test")
 OR MATCH (co.title) AGAINST ("Test")
 GROUP BY p.id

keywords contains something like keyword1 keyword2 keyword3.

The SQL above is working. However, I can't use MATCH AGAINST with a virtual value keywords value.

I've read about what I think is an ugly workaround, to add this:

HAVING keywords LIKE "%keyword1%"

LIKE is probably slow and because HAVING is after GROUP BY I can't use OR so HAVING in this case will override the WHERE.

Ideally, I would like to use a MATCH AGAINST on keywords as well. So, what are my options?

Some kind of virtual table?

Subquery?

Something else?

I probably need an example code to understand.

Body:
This doesn't answer the question you asked, but I think adding this condition to the WHERE clause of the query:

    OR EXISTS ( SELECT 1
                  FROM categories k
                 WHERE k.id = pc.category_id
                   AND k.title IN ('Test1','Test2')
              )

before the GROUP BY would eliminate the need to scan the return from GROUP_CONCAT, if the specification is to return rows where the category title matches one of the specified search words.

If there's not a requirement to actually return the derived keywords column in the resultset, I'd avoid the GROUP BY.

SELECT p.id AS id
     , p.title AS title
     , p.title AS company
  FROM products p
  JOIN companies co
    ON co.id = p.company_id
 WHERE MATCH (p.title) AGAINST ('Test')
    OR MATCH (co.title) AGAINST ('Test')
    OR EXISTS ( SELECT 1
                  FROM categories k
                  JOIN product_categories pc
                    ON pc.category_id = k.id
                 WHERE pc.product_id = p.id
                   AND k.title IN ('Test1','Test2')
              )
 ORDER BY p.id


问:
Using REGEXP_EXTRACT extract 7 digit numbers
I have one requirement.I want to extract 7 digit numbers from one of the column and lookup with another table get another column for each 7 digit number and concatenate with "|".

Column Data: In this need to extract 7 digit numbers.
";2435034;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605"

Output(Extract 7 digit number):

```<code> 2435034,1483528,1010203
</code>```

Another table:

```<code>account name
2435034 D1
1483528 D2
1010203 D3
</code>```

Final output is(after joining with another table):

```<code>     account_nbr        account_name
2435034|1483528|1010203  D1|D2|D3
</code>```

I tried with the following command to extract 7 digit number. I was getting only first number, remaining number are not coming.

```<code>REGEXP_EXTRACT(REGEXP_REPLACE(";2435034;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605", r'[^\d]+', ','),r'[0-9]+')
</code>```

This might be simple but not able to figure it out. Tried with GROUP_CONCAT and SPLIT function also getting following error.

```<code>Exactly one capturing group must be specified
</code>```

Please let me know if you have any suggestions.

Thanks in advance.

答:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  STRING_AGG(nbr, '|' ORDER BY pos) account_nbr,
  STRING_AGG(name, '|' ORDER BY pos) account_name,
  data
FROM `project.dataset.yourTable` t,
UNNEST(REGEXP_EXTRACT_ALL(REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
JOIN `project.dataset.anotherTable` x
ON CAST(x.account AS STRING) = nbr
GROUP BY data
```

<p>You can test / play with it using dummy data from your question:  </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT ";2435034;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605" data
), `project.dataset.anotherTable` AS (
  SELECT 2435034 account, 'D1' name UNION ALL
  SELECT 1483528, 'D2' UNION ALL
  SELECT 1010203, 'D3'
)
SELECT
  STRING_AGG(nbr, '|' ORDER BY pos) account_nbr,
  STRING_AGG(name, '|' ORDER BY pos) account_name,
  data
FROM `project.dataset.yourTable` t,
UNNEST(REGEXP_EXTRACT_ALL(REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
JOIN `project.dataset.anotherTable` x
ON CAST(x.account AS STRING) = nbr
GROUP BY data
</code>```

Update for new question in comments: records are getting filtered if t.data is null. Is there a way i can get the records even t.data is null? In my table some of the records doesnt have value for t.data

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 1 id, ";2435031;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605" data UNION ALL
  SELECT 2, NULL
), `project.dataset.anotherTable` AS (
  SELECT 2435034 account, 'D1' name UNION ALL
  SELECT 1483528, 'D2' UNION ALL
  SELECT 1010203, 'D3'
)
SELECT
  id,
  (SELECT STRING_AGG(nbr, '|' ORDER BY pos)
    FROM UNNEST(REGEXP_EXTRACT_ALL(
      REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
    JOIN `project.dataset.anotherTable` x
      ON CAST(x.account AS STRING) = nbr
  ) a_nbr,
  (SELECT STRING_AGG(name, '|' ORDER BY pos)
    FROM UNNEST(REGEXP_EXTRACT_ALL(
      REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
    JOIN `project.dataset.anotherTable` x
      ON CAST(x.account AS STRING) = nbr
  ) a_name,
  data
FROM `project.dataset.yourTable` t
GROUP BY id, data
```

Body:
I have one requirement.I want to extract 7 digit numbers from one of the column and lookup with another table get another column for each 7 digit number and concatenate with "|".

Column Data: In this need to extract 7 digit numbers.
";2435034;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605"

Output(Extract 7 digit number):

 2435034,1483528,1010203

Another table:

account name
2435034 D1
1483528 D2
1010203 D3

Final output is(after joining with another table):

     account_nbr        account_name
2435034|1483528|1010203  D1|D2|D3

I tried with the following command to extract 7 digit number. I was getting only first number, remaining number are not coming.

REGEXP_EXTRACT(REGEXP_REPLACE(";2435034;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605", r'[^\d]+', ','),r'[0-9]+')

This might be simple but not able to figure it out. Tried with GROUP_CONCAT and SPLIT function also getting following error.

Exactly one capturing group must be specified

Please let me know if you have any suggestions.

Thanks in advance.

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  STRING_AGG(nbr, '|' ORDER BY pos) account_nbr,
  STRING_AGG(name, '|' ORDER BY pos) account_name,
  data
FROM `project.dataset.yourTable` t,
UNNEST(REGEXP_EXTRACT_ALL(REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
JOIN `project.dataset.anotherTable` x
ON CAST(x.account AS STRING) = nbr
GROUP BY data

You can test / play with it using dummy data from your question:

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT ";2435034;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605" data
), `project.dataset.anotherTable` AS (
  SELECT 2435034 account, 'D1' name UNION ALL
  SELECT 1483528, 'D2' UNION ALL
  SELECT 1010203, 'D3'
)
SELECT
  STRING_AGG(nbr, '|' ORDER BY pos) account_nbr,
  STRING_AGG(name, '|' ORDER BY pos) account_name,
  data
FROM `project.dataset.yourTable` t,
UNNEST(REGEXP_EXTRACT_ALL(REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
JOIN `project.dataset.anotherTable` x
ON CAST(x.account AS STRING) = nbr
GROUP BY data

Update for new question in comments: records are getting filtered if t.data is null. Is there a way i can get the records even t.data is null? In my table some of the records doesnt have value for t.data

#standardSQL
WITH `project.dataset.yourTable` AS (
  SELECT 1 id, ";2435031;1;5.98;;eVar36=bopis|ev2=2605,;1483528;1;17.97;;ev6=bopis|evar52=2605,;1010203;1;7.98;;ev6=bopis|ev2=2605" data UNION ALL
  SELECT 2, NULL
), `project.dataset.anotherTable` AS (
  SELECT 2435034 account, 'D1' name UNION ALL
  SELECT 1483528, 'D2' UNION ALL
  SELECT 1010203, 'D3'
)
SELECT
  id,
  (SELECT STRING_AGG(nbr, '|' ORDER BY pos)
    FROM UNNEST(REGEXP_EXTRACT_ALL(
      REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
    JOIN `project.dataset.anotherTable` x
      ON CAST(x.account AS STRING) = nbr
  ) a_nbr,
  (SELECT STRING_AGG(name, '|' ORDER BY pos)
    FROM UNNEST(REGEXP_EXTRACT_ALL(
      REGEXP_REPLACE(t.data, r'[^\d]+', ','),r'[0-9]{7}')) nbr WITH OFFSET pos
    JOIN `project.dataset.anotherTable` x
      ON CAST(x.account AS STRING) = nbr
  ) a_name,
  data
FROM `project.dataset.yourTable` t
GROUP BY id, data