问:
Problems implementing an editable TableView<ObservableList<String>
So I've been trying to implement a TableView where you can edit a column just by clicking on it, and then save the edit by pressing the enter key. I've taken at lot of the code from the answer in this thread. This is the result:

```<code>import com.sun.javafx.collections.ObservableListWrapper;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;

public class TestEditableTable extends Application {

    public void start(Stage stage) {

        TableView<ObservableList<String>> tableView = new TableView<ObservableList<String>>();
        tableView.setEditable(true);

        // Some dummy data.
        ObservableList<ObservableList<String>> dummyData = FXCollections.observableArrayList();
        ObservableList<String> firstRow = FXCollections.observableArrayList("Jack", "Smith");
        dummyData.add(firstRow);
        ObservableList<String> secondRow = FXCollections.observableArrayList("Peter", "Smith");
        dummyData.add(secondRow);

        TableColumn<ObservableList<String>, String> firstCol = new TableColumn<ObservableList<String>, String>(
                "First name");
        firstCol.setCellValueFactory(
                (TableColumn.CellDataFeatures<ObservableList<String>, String> param) -> new SimpleStringProperty(
                        param.getValue().get(0)));

        TableColumn<ObservableList<String>, String> secondCol = new TableColumn<ObservableList<String>, String>(
                "Last name");
        secondCol.setCellValueFactory(
                (TableColumn.CellDataFeatures<ObservableList<String>, String> param) -> new SimpleStringProperty(
                        param.getValue().get(1)));

        secondCol.setCellFactory(cell -> new EditableCell());

        tableView.getColumns().addAll(firstCol, secondCol);

        tableView.getItems().addAll(dummyData);

        Scene scene = new Scene(tableView);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

    class EditableCell extends TableCell<ObservableList<String>, String> {

        private TextField textfield = new TextField();

        // When the user presses the enter button the edit is saved.
        public EditableCell() {
            setOnKeyPressed(e -> {
                if (e.getCode().equals(KeyCode.ENTER)) {
                    commitEdit(textfield.getText());
                }
            });
        }

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (isEmpty()) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    textfield.setText(item);
                    setGraphic(textfield);
                    setText(null);
                } else {
                    setText(item);
                    setGraphic(null);
                }
            }
        }

        @Override
        public void startEdit() {
            super.startEdit();
            textfield.setText(getItem());
            setGraphic(textfield);
            setText(null);
        }

        @Override
        public void cancelEdit() {
            super.cancelEdit();
            setGraphic(null);
            setText(getItem());
        }

        @Override
        public void commitEdit(String value) {
            super.commitEdit(value);

            // This works. But gives me a "Discouraged access: The type 'ObservableListWrapper<String>' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')".
            ObservableListWrapper<String> ob = ((ObservableListWrapper<String>) this.getTableRow().getItem());
            ob.set(1, value);

            // I had to put this in a Platform.runLater(), otherwise the textfield remained open.
            Platform.runLater(() -> {
                setText(value);
                setGraphic(null);
            });
        }
    }
}
</code>```

And this program works OK. The cell is edited when you press the enter button. But there are two main issues with this:

Once I've pressed enter and a cell has been edited. I can't edit it again by clicking on it. I need to press another row to be able to edit it again. Setting to focus on the parent of the row didn't do the trick.

The code inside commitEdit() works. But it is ugly and using a ObservableListWrapper gives me the warning "Discouraged access: The type 'ObservableListWrapper' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')". Also the cell index is hard coded, which wont work if I use this in many different columns.

None of the issues mentioned above is acceptable.

The final implementation must support restriction of the input in the textfield. As far as I understand it this means that I need to have access to the TextField object displayed in the cell, as in my current implementation.

答:
An Other way is to replace JRE Library by JDK Library in your Buildpath
Project->Build Path-> Configure build path
 -1 Remove JRE Library

-2 Add library
    -2.1 -> Select Java Library associated with your JDK environnement

All errors will disappear

Body:
So I've been trying to implement a TableView where you can edit a column just by clicking on it, and then save the edit by pressing the enter key. I've taken at lot of the code from the answer in this thread. This is the result:

import com.sun.javafx.collections.ObservableListWrapper;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;

public class TestEditableTable extends Application {

    public void start(Stage stage) {

        TableView<ObservableList<String>> tableView = new TableView<ObservableList<String>>();
        tableView.setEditable(true);

        // Some dummy data.
        ObservableList<ObservableList<String>> dummyData = FXCollections.observableArrayList();
        ObservableList<String> firstRow = FXCollections.observableArrayList("Jack", "Smith");
        dummyData.add(firstRow);
        ObservableList<String> secondRow = FXCollections.observableArrayList("Peter", "Smith");
        dummyData.add(secondRow);

        TableColumn<ObservableList<String>, String> firstCol = new TableColumn<ObservableList<String>, String>(
                "First name");
        firstCol.setCellValueFactory(
                (TableColumn.CellDataFeatures<ObservableList<String>, String> param) -> new SimpleStringProperty(
                        param.getValue().get(0)));

        TableColumn<ObservableList<String>, String> secondCol = new TableColumn<ObservableList<String>, String>(
                "Last name");
        secondCol.setCellValueFactory(
                (TableColumn.CellDataFeatures<ObservableList<String>, String> param) -> new SimpleStringProperty(
                        param.getValue().get(1)));

        secondCol.setCellFactory(cell -> new EditableCell());

        tableView.getColumns().addAll(firstCol, secondCol);

        tableView.getItems().addAll(dummyData);

        Scene scene = new Scene(tableView);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

    class EditableCell extends TableCell<ObservableList<String>, String> {

        private TextField textfield = new TextField();

        // When the user presses the enter button the edit is saved.
        public EditableCell() {
            setOnKeyPressed(e -> {
                if (e.getCode().equals(KeyCode.ENTER)) {
                    commitEdit(textfield.getText());
                }
            });
        }

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (isEmpty()) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    textfield.setText(item);
                    setGraphic(textfield);
                    setText(null);
                } else {
                    setText(item);
                    setGraphic(null);
                }
            }
        }

        @Override
        public void startEdit() {
            super.startEdit();
            textfield.setText(getItem());
            setGraphic(textfield);
            setText(null);
        }

        @Override
        public void cancelEdit() {
            super.cancelEdit();
            setGraphic(null);
            setText(getItem());
        }

        @Override
        public void commitEdit(String value) {
            super.commitEdit(value);

            // This works. But gives me a "Discouraged access: The type 'ObservableListWrapper<String>' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')".
            ObservableListWrapper<String> ob = ((ObservableListWrapper<String>) this.getTableRow().getItem());
            ob.set(1, value);

            // I had to put this in a Platform.runLater(), otherwise the textfield remained open.
            Platform.runLater(() -> {
                setText(value);
                setGraphic(null);
            });
        }
    }
}

And this program works OK. The cell is edited when you press the enter button. But there are two main issues with this:

Once I've pressed enter and a cell has been edited. I can't edit it again by clicking on it. I need to press another row to be able to edit it again. Setting to focus on the parent of the row didn't do the trick.

The code inside commitEdit() works. But it is ugly and using a ObservableListWrapper gives me the warning "Discouraged access: The type 'ObservableListWrapper' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')". Also the cell index is hard coded, which wont work if I use this in many different columns.

None of the issues mentioned above is acceptable.

The final implementation must support restriction of the input in the textfield. As far as I understand it this means that I need to have access to the TextField object displayed in the cell, as in my current implementation.


来源: stackexchange

问:
How can I use Javascript to make a file that automatically opens as an Excel spreadsheet?
I have a string in a Javascript file that I'd like to make an Excel spreadsheet out of. I use the following code:

```<code>var url = 'data:application/vnd.ms-excel,' + encodeURIComponent(excel);
location.href = url;
</code>```

where "excel" here is the string in question.

This works perfectly well; I can download the file and then open it as an Excel spreadsheet, and it's formatted correctly and everything. But when I open the file, I have to choose which program I want to open it with. Is there a way to make it so that I can open the file with Excel automatically, without having to choose from a list of programs?

答:
Alright, David's advice works. This link:

http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/

will take an HTML table and export it to an Excel spreadsheet. I was using a raw string instead of an HTML table, but the relevant part works the same for both:

```<code>var a = document.createElement("A");
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + "," + excel;
a.download = "student_data.xlsx";
a.click();
</code>```

This will automatically download the string as a .xlsx file.

I did run into other issues with the .xlsx format - Excel thought the file was corrupt and wouldn't open it - but using .csv instead of .xlsx fixes that.

ContentLicense: CC BY-SA 3.0

Body:
I have a string in a Javascript file that I'd like to make an Excel spreadsheet out of. I use the following code:

var url = 'data:application/vnd.ms-excel,' + encodeURIComponent(excel);
location.href = url;

where "excel" here is the string in question.

This works perfectly well; I can download the file and then open it as an Excel spreadsheet, and it's formatted correctly and everything. But when I open the file, I have to choose which program I want to open it with. Is there a way to make it so that I can open the file with Excel automatically, without having to choose from a list of programs?

Body:
Alright, David's advice works. This link:

http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/

will take an HTML table and export it to an Excel spreadsheet. I was using a raw string instead of an HTML table, but the relevant part works the same for both:

var a = document.createElement("A");
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + "," + excel;
a.download = "student_data.xlsx";
a.click();

This will automatically download the string as a .xlsx file.

I did run into other issues with the .xlsx format - Excel thought the file was corrupt and wouldn't open it - but using .csv instead of .xlsx fixes that.


问:
Set string while series is a boolean value?
I would like to set a string in Column C while values in Column B are >= 2 (yes if>= is True, no if >= is False). The output should be as follows:

```<code>    A B   C
1   A 2 'yes'
2   B 3 'yes'
3   C 4 'yes'
4   D 5 'yes'
5   A 6 'yes'
6   B 7 'yes'
7   C 0 'no'
8   D 1 'no'
9   A 2 'yes'
10  B 3 'yes'
11  C 4 'yes'
12  D 0 'no'
</code>```

So far I have tried to implement nested loops, which are far too slow:

```<code>i= 0
for row in range(0, len(df)-1):
    if df['B'][i] >= 2:
        if df['B'][i] >= 2:
            df['C'][i] = 'yes'
        elif df['B'][i] >= 2:
            df['C'][i] = 'yes'
</code>```

答:
Something like this</p>

```<code>df['C'] = 'no'
df['C'][df['B'] >= 2] = 'yes'
</code>```

Body:
I would like to set a string in Column C while values in Column B are >= 2 (yes if>= is True, no if >= is False). The output should be as follows:

    A B   C
1   A 2 'yes'
2   B 3 'yes'
3   C 4 'yes'
4   D 5 'yes'
5   A 6 'yes'
6   B 7 'yes'
7   C 0 'no'
8   D 1 'no'
9   A 2 'yes'
10  B 3 'yes'
11  C 4 'yes'
12  D 0 'no'

So far I have tried to implement nested loops, which are far too slow:

i= 0
for row in range(0, len(df)-1):
    if df['B'][i] >= 2:
        if df['B'][i] >= 2:
            df['C'][i] = 'yes'
        elif df['B'][i] >= 2:
            df['C'][i] = 'yes'

Body:
Something like this

df['C'] = 'no'
df['C'][df['B'] >= 2] = 'yes'


问:
FreeMarker - Remove comma from milliseconds
Using FreeMarker, I want to display a date into milliseconds:

```<code>${mydate?long}
</code>```

but I get as output a comma separated millisecond:

```<code>524,354,400,000
</code>```

is there any built-in function in Freemarker to remove comma ?

Thanks

答:
As an alternative you could write on your Freemarker template this directive:

```<code><#setting number_format="computer">
</code>```

This will remove all commas from numbers.

This works fine for Freemarker 2.3.23

More info about these directives can be found here:

http://freemarker.org/docs/ref_directive_setting.html

Body:
Using FreeMarker, I want to display a date into milliseconds:

${mydate?long}

but I get as output a comma separated millisecond:

524,354,400,000

is there any built-in function in Freemarker to remove comma ?

Thanks

Body:
As an alternative you could write on your Freemarker template this directive:

<#setting number_format="computer">

This will remove all commas from numbers.

This works fine for Freemarker 2.3.23

More info about these directives can be found here:

http://freemarker.org/docs/ref_directive_setting.html


问:
Ionic2 and SOAP api
I need to make an integration using "Ionic2" and a SOAP webService! But do not have someone Lib that make this integration.

I try to make it with https://github.com/autopulous/angular2-soap and others, but it's depreciated in some packages, and I can not depreciate the packages because if I make it maybe break my application.

What do?

答: I just fix it making a API with python to be my 'conversationalist'. :s</p>

Title: Ionic2 and SOAP api


问:
In an Office add-in manifest, why must <Permissions> immediately follow <FormSettings/>?
This issue is best demonstrated by example. Consider the following:

In the first example, my <Permissions/> element is placed immediately after the <FormSettings/> block:

```<code><?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0" xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0" xsi:type="MailApp">
  <Id>464672b2-35a8-44a1-8c06-3ad07ed893a7</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>Example</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="Example A"/>
  <Description DefaultValue="This is an example add-in."/>
  <IconUrl DefaultValue="https://placehold.it/64x64"/>
  <HighResolutionIconUrl DefaultValue="https://placehold.it/64x64"/>
  <SupportUrl DefaultValue="https://example.com/"/>
  <Hosts>
    <Host Name="Mailbox"/>
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="MailBox" MinVersion="1.1"/>
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemEdit">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://example.com"/>
      </DesktopSettings>
    </Form>
  </FormSettings>
  <Permissions>ReadWriteMailbox</Permissions>
  <Rule xsi:type="RuleCollection" Mode="And">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Edit"/>
  </Rule>
</OfficeApp>
</code>```

I am able to successfully add this manifest to my Exchange Admin Center's organization add-ins list.

However, if I move the <Permissions/> element anywhere else in the manifest, the manifest fails validation when attempting to add it:

```<code><?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0" xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0" xsi:type="MailApp">
  <Id>464672b2-35a8-44a1-8c06-3ad07ed893a7</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>Example</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="Example A"/>
  <Description DefaultValue="This is an example add-in."/>
  <IconUrl DefaultValue="https://placehold.it/64x64"/>
  <HighResolutionIconUrl DefaultValue="https://placehold.it/64x64"/>
  <SupportUrl DefaultValue="https://example.com/"/>
  <Hosts>
    <Host Name="Mailbox"/>
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="MailBox" MinVersion="1.1"/>
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemEdit">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://example.com"/>
      </DesktopSettings>
    </Form>
  </FormSettings>
  <Rule xsi:type="RuleCollection" Mode="And">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Edit"/>
  </Rule>
  <Permissions>ReadWriteMailbox</Permissions>
</OfficeApp>
</code>```

Attempting to add this manifest to my Exchange Admin Center's organization add-ins list produces the following error:

This app can't be installed. The manifest file doesn't conform to the schema definition. The element 'OfficeApp' in namespace 'http://schemas.microsoft.com/office/appforoffice/1.1' has invalid child element 'Permissions' in namespace 'http://schemas.microsoft.com/office/appforoffice/1.1'. List of possible elements expected: 'DisableEntityHighlighting' in namespace 'http://schemas.microsoft.com/office/appforoffice/1.1' as well as 'VersionOverrides' in namespace 'http://schemas.microsoft.com/office/mailappversionoverrides' as well as any element in namespace 'http://www.w3.org/2000/09/xmldsig#'...

It is only through trial and error were we able to find the root cause of this validation failure.

My question: Why does ordering matter? Why can the <Permissions/> element not appear anywhere within the same nesting level in the manifest?

Context

This validation failure occurs in hosted Exchange (Office 365), and also when attempting to submit an add-in to the Office Store, at the step where a manifest is requested.

答:
Order of the tags defined by schema file. Unfortunately this is not well documented and we are working to improve this documentation. Order matters when defining a manifest for Outlook web add-ins because of the way we validate the schema for installation. We realize this can be a hassle especially since it's not well documented but the main reason we require a specific order is because it allows us to validate the manifest content quickly and increase performance of the service.

Thank you for providing this feedback on our documentation.

Body:
This issue is best demonstrated by example. Consider the following:

In the first example, my <Permissions/> element is placed immediately after the <FormSettings/> block:

<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0" xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0" xsi:type="MailApp">
  <Id>464672b2-35a8-44a1-8c06-3ad07ed893a7</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>Example</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="Example A"/>
  <Description DefaultValue="This is an example add-in."/>
  <IconUrl DefaultValue="https://placehold.it/64x64"/>
  <HighResolutionIconUrl DefaultValue="https://placehold.it/64x64"/>
  <SupportUrl DefaultValue="https://example.com/"/>
  <Hosts>
    <Host Name="Mailbox"/>
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="MailBox" MinVersion="1.1"/>
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemEdit">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://example.com"/>
      </DesktopSettings>
    </Form>
  </FormSettings>
  <Permissions>ReadWriteMailbox</Permissions>
  <Rule xsi:type="RuleCollection" Mode="And">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Edit"/>
  </Rule>
</OfficeApp>

I am able to successfully add this manifest to my Exchange Admin Center's organization add-ins list.

However, if I move the <Permissions/> element anywhere else in the manifest, the manifest fails validation when attempting to add it:

<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0" xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0" xsi:type="MailApp">
  <Id>464672b2-35a8-44a1-8c06-3ad07ed893a7</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>Example</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="Example A"/>
  <Description DefaultValue="This is an example add-in."/>
  <IconUrl DefaultValue="https://placehold.it/64x64"/>
  <HighResolutionIconUrl DefaultValue="https://placehold.it/64x64"/>
  <SupportUrl DefaultValue="https://example.com/"/>
  <Hosts>
    <Host Name="Mailbox"/>
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="MailBox" MinVersion="1.1"/>
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemEdit">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://example.com"/>
      </DesktopSettings>
    </Form>
  </FormSettings>
  <Rule xsi:type="RuleCollection" Mode="And">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Edit"/>
  </Rule>
  <Permissions>ReadWriteMailbox</Permissions>
</OfficeApp>

Attempting to add this manifest to my Exchange Admin Center's organization add-ins list produces the following error:

This app can't be installed. The manifest file doesn't conform to the schema definition. The element 'OfficeApp' in namespace 'http://schemas.microsoft.com/office/appforoffice/1.1' has invalid child element 'Permissions' in namespace 'http://schemas.microsoft.com/office/appforoffice/1.1'. List of possible elements expected: 'DisableEntityHighlighting' in namespace 'http://schemas.microsoft.com/office/appforoffice/1.1' as well as 'VersionOverrides' in namespace 'http://schemas.microsoft.com/office/mailappversionoverrides' as well as any element in namespace 'http://www.w3.org/2000/09/xmldsig#'...

It is only through trial and error were we able to find the root cause of this validation failure.

My question: Why does ordering matter? Why can the <Permissions/> element not appear anywhere within the same nesting level in the manifest?

Context

This validation failure occurs in hosted Exchange (Office 365), and also when attempting to submit an add-in to the Office Store, at the step where a manifest is requested.

ContentLicense: CC BY-SA 4.0


问:
Visual Studio 2017 and 2019 C++/CLI Missing
I can't understand why I can't find C++/CLI project type in to Visual Studio 2017. I just updated my Visual Studio, and now I can't create any more Windows Forms applications.

答:
Valid for visual studio 2017,2019,2022

The answer is solved in this visual studio community forum.

I copied the solution here for convenience:

Please make sure you have selected the component "C++/CLI support" in your installation;

Please launch the "Visual Studio Installer"

Modify your installed VS;

You can find the component "C++/CLI support" under thw workload "Desktop development with C++"


问:
C# Design Pattern for save state of a file/project/work unit
Morning Everyone.

We have an application that is project based, so the user opens, create a project then there are many things that they do within that project that may or maynot need their state saving.

I have been looking around trying to find if there was an accepted pattern for this. I think the best way to describe it is to think of Visual Studio, what I am looking for is a pattern designed to recognise when one of the classes changes (putting the little star on the tab) and provides a way for the save routine to know what it needs to save / if anything needs to be saved.

Thanks in advance.

答: Looks best fit for Memento pattern.</p>

ContentLicense: CC BY-SA 2.5

Body: Looks best fit for Memento pattern.


问:
HTML doctype, how browser performs on reading doctype
actually i was thinking how browser performs or knows when it reads an specific doctype and after reading doctype, is there a pattern present or build in the browser or it searches on internet to know how to display ?</p>

答:
It's all in the doctype header of an html page

HTML5 looks like this

```<code><!DOCTYPE html>
</code>```

HTML4

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"{{dead link|date=May 2017 |bot=Pigsonthewing |fix-attempted=yes }}>
</code>```

there is a wiki on the different doctypes:
https://en.wikipedia.org/wiki/Document_type_declaration

It's up to the browser vendor what doctypes to support. Generally they want to support as many different types to have as broad user base as possible. Which is also where all the trouble come in, since they will have to support 40 years or so of doctypes, there are still some ancient websites out there.

Body:
It's all in the doctype header of an html page

HTML5 looks like this

<!DOCTYPE html>

HTML4

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"{{dead link|date=May 2017 |bot=Pigsonthewing |fix-attempted=yes }}>

there is a wiki on the different doctypes:
https://en.wikipedia.org/wiki/Document_type_declaration

It's up to the browser vendor what doctypes to support. Generally they want to support as many different types to have as broad user base as possible. Which is also where all the trouble come in, since they will have to support 40 years or so of doctypes, there are still some ancient websites out there.


问:
Python Text Classification Error - expected string or bytes-like object
I'm trying to do text classification for a large corpus (732,066 tweets) in python

```<code># Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
#dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3)

# Importing the dataset
cols = ["text","geocoordinates0","geocoordinates1","grid"]
dataset = pd.read_csv('tweets.tsv', delimiter = '\t', usecols=cols, quoting = 3, error_bad_lines=False, low_memory=False)

# Removing Non-ASCII characters
def remove_non_ascii_1(dataset):
    return ''.join([i if ord(i) < 128 else ' ' for i in dataset])

# Cleaning the texts
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 732066):
    review = re.sub('[^a-zA-Z]', ' ', dataset['text'][i])
    review = review.lower()
    review = review.split()
    ps = PorterStemmer()
    review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
    review = ' '.join(review)
    corpus.append(review)

# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 1].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
accuracies.mean()
accuracies.std()
</code>```

This is the error I get and where i'm stuck and unable to proceed with the rest of the machine learning text classification

```<code>Traceback (most recent call last):

  File "<ipython-input-2-3fac33122b74>", line 2, in <module>
    review = re.sub('[^a-zA-Z]', ' ', dataset['text'][i])

  File "C:\Anaconda3\envs\py35\lib\re.py", line 182, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object
</code>```

Thanks ahead for the help

答:
Try

```<code>str(dataset.loc[df.index[i], 'text'])
</code>```

That'll convert it to a str object, from whatever type it was before.

Body:
I'm trying to do text classification for a large corpus (732,066 tweets) in python

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
#dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3)

# Importing the dataset
cols = ["text","geocoordinates0","geocoordinates1","grid"]
dataset = pd.read_csv('tweets.tsv', delimiter = '\t', usecols=cols, quoting = 3, error_bad_lines=False, low_memory=False)

# Removing Non-ASCII characters
def remove_non_ascii_1(dataset):
    return ''.join([i if ord(i) < 128 else ' ' for i in dataset])

# Cleaning the texts
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 732066):
    review = re.sub('[^a-zA-Z]', ' ', dataset['text'][i])
    review = review.lower()
    review = review.split()
    ps = PorterStemmer()
    review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
    review = ' '.join(review)
    corpus.append(review)

# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 1].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
accuracies.mean()
accuracies.std()

This is the error I get and where i'm stuck and unable to proceed with the rest of the machine learning text classification

Traceback (most recent call last):

  File "<ipython-input-2-3fac33122b74>", line 2, in <module>
    review = re.sub('[^a-zA-Z]', ' ', dataset['text'][i])

  File "C:\Anaconda3\envs\py35\lib\re.py", line 182, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

Thanks ahead for the help

Body:
Try

str(dataset.loc[df.index[i], 'text'])

That'll convert it to a str object, from whatever type it was before.


答:
This can by done by using "apply" on column B along with a lambda function and a ternary "if":

```<code>import pandas as pd
df = pd.DataFrame.from_dict({'A': ['A', 'B', 'C'], 'B': [1, 2, 3]})
df['C'] = df['B'].apply(lambda r: "yes" if r >= 2 else "no")
</code>```

"apply" applied to a column of a DataFrame will let you apply a function to each value in the dataframe. So we test if each value is >= 2, and if so, return "yes", otherwise "no".

Title: Set string while series is a boolean value?

Body:
This can by done by using "apply" on column B along with a lambda function and a ternary "if":

import pandas as pd
df = pd.DataFrame.from_dict({'A': ['A', 'B', 'C'], 'B': [1, 2, 3]})
df['C'] = df['B'].apply(lambda r: "yes" if r >= 2 else "no")

"apply" applied to a column of a DataFrame will let you apply a function to each value in the dataframe. So we test if each value is >= 2, and if so, return "yes", otherwise "no".


问:
Duplicate keys in map
I have a list of papers and each paper has a set of keyword assigned to it. I want to get a Map, which will store the keyword and total sum of its frequencies in all papers. I have implemented as following:

```<code>public Map<Keyword, Integer> getKeywordFrequencies(List<Integer> userPapers,
            Map<Integer, List<PaperKeywordMapping>> paperKeywords) {
        Map<Keyword, Integer> frequencies = new HashMap<>();
        for (Integer ind : userPapers) {
            for (PaperKeywordMapping pKeyword : paperKeywords.get(ind)) {
                frequencies.compute(pKeyword.getKeyword(), (k, v) -> {
                    return v == null ? pKeyword.getTermFrequency() : v + pKeyword.getTermFrequency();
                });
            }
        }
        frequencies.forEach((k,v)->System.out.println("keyword : " + k.getKeywordName() + " freq : " + v));
        return frequencies;
    }
</code>```

The issue is that, I am getting not unique keys in the map. Here is output:

```<code>keyword : Nonfiction freq : 60
keyword : Reference freq : 38
keyword : Sports freq : 263
keyword : Arts freq : 90
keyword : Astronomy freq : 50
keyword : Medicine freq : 16
keyword : Applied freq : 31
keyword : History freq : 106
keyword : Discrete freq : 47
keyword : microeconomics freq : 68
keyword : macroeconomics freq : 41
keyword : Nonfiction freq : 99
keyword : Reference freq : 101
keyword : Sports freq : 262
keyword : Arts freq : 126
keyword : Astronomy freq : 58
keyword : Medicine freq : 31
</code>```

Tried to add check, if the key exists or no, but still the same.

Any help is appreciated.

答:
What is unique key for HashMap?
It's identified by hashCode and equals methods.
To have this property working correctly you need to define these methods in your Keyword class.</p>

Title: Duplicate keys in map

Body:
I have a list of papers and each paper has a set of keyword assigned to it. I want to get a Map, which will store the keyword and total sum of its frequencies in all papers. I have implemented as following:

public Map<Keyword, Integer> getKeywordFrequencies(List<Integer> userPapers,
            Map<Integer, List<PaperKeywordMapping>> paperKeywords) {
        Map<Keyword, Integer> frequencies = new HashMap<>();
        for (Integer ind : userPapers) {
            for (PaperKeywordMapping pKeyword : paperKeywords.get(ind)) {
                frequencies.compute(pKeyword.getKeyword(), (k, v) -> {
                    return v == null ? pKeyword.getTermFrequency() : v + pKeyword.getTermFrequency();
                });
            }
        }
        frequencies.forEach((k,v)->System.out.println("keyword : " + k.getKeywordName() + " freq : " + v));
        return frequencies;
    }

The issue is that, I am getting not unique keys in the map. Here is output:

keyword : Nonfiction freq : 60
keyword : Reference freq : 38
keyword : Sports freq : 263
keyword : Arts freq : 90
keyword : Astronomy freq : 50
keyword : Medicine freq : 16
keyword : Applied freq : 31
keyword : History freq : 106
keyword : Discrete freq : 47
keyword : microeconomics freq : 68
keyword : macroeconomics freq : 41
keyword : Nonfiction freq : 99
keyword : Reference freq : 101
keyword : Sports freq : 262
keyword : Arts freq : 126
keyword : Astronomy freq : 58
keyword : Medicine freq : 31

Tried to add check, if the key exists or no, but still the same.

Any help is appreciated.


问:
If and when my user put data in Column A, Column B should auto populate who the editor is in Google Spreadsheet?
I am on google domain (G Suite). I would like to have this simple task of getting the editor/user name of a cell in column B of a spreadsheet as soon as s/he edit the cell in column A of the same row.

I have found and used a few sets of Google script, such as one below, but they didn't work unfortunately.

```<code>function checkEdits() {
var SS = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = SS.getSheetByName('Sheet1');
var specialCell = sheet1.getRange("A:A");

if (SS.getActiveCell().getA1Notation() == specialCell.getA1Notation()) {
var htmlEmail = "Cell " + specialCell.getA1Notation() +
  " edited by " + Session.getActiveUser().getEmail();
GmailApp.sendEmail("YOUR EMAIL HERE", "Spreadsheet Update " + new Date(), "", {htmlBody:htmlEmail} );
 }
}
</code>```

Thank you very much!

答:
You can use an onEdit() trigger to fire when a cell is modified, however it won't get a users email address unless they first authorise the script to allow it to get their email address. See the documentation re. simple triggers

You would need to use a manual trigger i.e. a button to call the  onEdit() function to get the user to authorise the script(they only need to authorise the script once), then every time that user edits the sheet thereafter it will collect their email address.

Try the code below to see it in action, if you paste the code, save it and edit the sheet you will see 2 blank entries in the log. Then click the debug on the onEdit() function and authorise the script, it will fail as no information gets passed to ein debug. Edit the sheet again and check the log, now you will see that it can get your email address.

If you are an admin you can use the Admin directory to get the users name etc. using the email address.

```<code>function onEdit(e){
  Logger.log(e.user);
  Logger.log(Session.getActiveUser().getEmail());
}
</code>```

EDIT Based on comments

Go to 'Resources' -> 'Advanced Google services' and enable the 'Admin Directory API' and also enable it in the API console.

Paste the code:

```<code>function onEdit(e) {
    var sheet = e.source.getActiveSheet().getName();
    if (sheet == "Sheet1") {
        var sheet1 = e.source.getSheetByName('Sheet1');
        var range = e.range;
        var getCol = range.getColumn();
        var getRow = range.getRow();

        if (getCol == 1) {
            var user = e.user.getEmail();
                var name = AdminDirectory.Users.get(user).name.fullName; // familyName, fullName or givenName
                sheet1.getRange(getRow, 2).setValue(name);
            var htmlEmail = "Cell " + range.getA1Notation() +
                " edited by " + name;
            GmailApp.sendEmail("----------", "Spreadsheet Update " + new Date(), "", {
                htmlBody : htmlEmail
            });
        }
    }
}
</code>```

And create an onEdit trigger as shown('Edit' -> 'Current project's triggers')

Body:
I am on google domain (G Suite). I would like to have this simple task of getting the editor/user name of a cell in column B of a spreadsheet as soon as s/he edit the cell in column A of the same row.

I have found and used a few sets of Google script, such as one below, but they didn't work unfortunately.

function checkEdits() {
var SS = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = SS.getSheetByName('Sheet1');
var specialCell = sheet1.getRange("A:A");

if (SS.getActiveCell().getA1Notation() == specialCell.getA1Notation()) {
var htmlEmail = "Cell " + specialCell.getA1Notation() +
  " edited by " + Session.getActiveUser().getEmail();
GmailApp.sendEmail("YOUR EMAIL HERE", "Spreadsheet Update " + new Date(), "", {htmlBody:htmlEmail} );
 }
}

Thank you very much!

Body:
You can use an onEdit() trigger to fire when a cell is modified, however it won't get a users email address unless they first authorise the script to allow it to get their email address. See the documentation re. simple triggers

You would need to use a manual trigger i.e. a button to call the  onEdit() function to get the user to authorise the script(they only need to authorise the script once), then every time that user edits the sheet thereafter it will collect their email address.

Try the code below to see it in action, if you paste the code, save it and edit the sheet you will see 2 blank entries in the log. Then click the debug on the onEdit() function and authorise the script, it will fail as no information gets passed to ein debug. Edit the sheet again and check the log, now you will see that it can get your email address.

If you are an admin you can use the Admin directory to get the users name etc. using the email address.

function onEdit(e){
  Logger.log(e.user);
  Logger.log(Session.getActiveUser().getEmail());
}

EDIT Based on comments

Go to 'Resources' -> 'Advanced Google services' and enable the 'Admin Directory API' and also enable it in the API console.

Paste the code:

function onEdit(e) {
    var sheet = e.source.getActiveSheet().getName();
    if (sheet == "Sheet1") {
        var sheet1 = e.source.getSheetByName('Sheet1');
        var range = e.range;
        var getCol = range.getColumn();
        var getRow = range.getRow();

        if (getCol == 1) {
            var user = e.user.getEmail();
                var name = AdminDirectory.Users.get(user).name.fullName; // familyName, fullName or givenName
                sheet1.getRange(getRow, 2).setValue(name);
            var htmlEmail = "Cell " + range.getA1Notation() +
                " edited by " + name;
            GmailApp.sendEmail("----------", "Spreadsheet Update " + new Date(), "", {
                htmlBody : htmlEmail
            });
        }
    }
}

And create an onEdit trigger as shown('Edit' -> 'Current project's triggers')


问:
Jquery event is not firing on elements generated via loops
I have the following code which I render through a partial that display a strength title and a strength summary

```<code><div id="strengths" class="row">
  <% FR_STRENGTHS.each do |strength| %>
    <div class="col-xs-12 col-sm-6 col-md-4">
      <div >
        <h3 class="jobtitle text-center">  <%= strength[1]["title"] %></h3>
        <div class="text-justify strength_summary">
          <p> <%= strength[1]["summary"] %></p>
        </div>
      </div>
    </div>
  <% end %>
</div>
</code>```

Details of the strengths are in yml files for translation purposes (I have the same code as above for English language pending params).
I want to hide the strength summary and show it when the user hover the strength title using Jquery, but I can't have it working.

following jQuery propagation documentation I have used this js code:

```<code>$(document).ready(function() {
  $('#strengths').on("mouseenter", "h3",
    function() {
      $('.strength_summary').slideDown();
    },
    function() {
      $('.strength_summary').slideUp();
    }
  );
});
</code>```

In any case I don't think using a class as a selector for the "strength_summary" would work as I assume all sections would slide down when hovering on any h3? But it's impossible to use ids so...
Thanks for your help!

答:
You need to use a traversal function so you only slide slide the DIV after the current element. Also, you can't give two functions to .on(); if you want another function to run when you stop hovering, bind a mouseleave event.

```<code>$("#strengths").on({
  "mouseenter": function() {
    $(this).next(".strength_summary").slideDown();
  },
  "mouseleave": function() {
    $(this).next(".strength_summary").slideUp();
  }
}, "h3");
</code>```

Body:
I have the following code which I render through a partial that display a strength title and a strength summary

  <% FR_STRENGTHS.each do |strength| %>

  <%= strength[1]["title"] %>

 <%= strength[1]["summary"] %>

  <% end %>

Details of the strengths are in yml files for translation purposes (I have the same code as above for English language pending params).
I want to hide the strength summary and show it when the user hover the strength title using Jquery, but I can't have it working.

following jQuery propagation documentation I have used this js code:

$(document).ready(function() {
  $('#strengths').on("mouseenter", "h3",
    function() {
      $('.strength_summary').slideDown();
    },
    function() {
      $('.strength_summary').slideUp();
    }
  );
});

In any case I don't think using a class as a selector for the "strength_summary" would work as I assume all sections would slide down when hovering on any h3? But it's impossible to use ids so...
Thanks for your help!

Body:
You need to use a traversal function so you only slide slide the DIV after the current element. Also, you can't give two functions to .on(); if you want another function to run when you stop hovering, bind a mouseleave event.

$("#strengths").on({
  "mouseenter": function() {
    $(this).next(".strength_summary").slideDown();
  },
  "mouseleave": function() {
    $(this).next(".strength_summary").slideUp();
  }
}, "h3");


问:
Connecting two specific points in a map
Using this we have a map with data points:

Load data:

```<code>countries <- structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))
</code>```

Code for map plot using this:

```<code>library(maps)
 library(ggplot2)
 base_world <- map_data("world")
p <- ggplot() +
   geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
   geom_point(data=countries, aes(x=Longitude, y=Latitude, colour="blue"), size=5, alpha=I(0.7))
</code>```

I try to connect to points. Example I want to connect:
Spain - China
USA - Spain

What I have until now is this:

```<code>p + geom_line(data=countries, aes(x=Longitude, y=Latitude), color="black", size=1)
</code>```

and this connects all points in the map. Is it possible to connect only specific values and show in the data point in the map the number of value column?

Also this is what I tried for number labels in every point (Value)

```<code>p + geom_text(aes(label=countries$Value),hjust=0, vjust=0, aes(x=Longitude, y=Latitude))
Error: ggplot2 doesn't know how to deal with data of class uneval
</code>```

Example of the list with more than two points (every row is a different connection):

```<code>("USA", "Spain","China")
("Australia", "Poland")
</code>```

答:
You can get a subset based on the points you want to be connected;

```<code>link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

base_world <- map_data("world")
p <- ggplot() +
      geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
      geom_line(data=link1, aes(x=Longitude, y=Latitude), color="red", size=1) +
      geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
      geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
      theme(text = element_text(size=20), legend.position="none")  #remove the legend
</code>```

and your plot would look like:

> p

You may need to play around a little bit for formatting issues.

Title: Connecting two specific points in a map

Body:
Using this we have a map with data points:

Load data:

countries <- structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))

Code for map plot using this:

library(maps)
 library(ggplot2)
 base_world <- map_data("world")
p <- ggplot() +
   geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
   geom_point(data=countries, aes(x=Longitude, y=Latitude, colour="blue"), size=5, alpha=I(0.7))

I try to connect to points. Example I want to connect:
Spain - China
USA - Spain

What I have until now is this:

p + geom_line(data=countries, aes(x=Longitude, y=Latitude), color="black", size=1)

and this connects all points in the map. Is it possible to connect only specific values and show in the data point in the map the number of value column?

Also this is what I tried for number labels in every point (Value)

p + geom_text(aes(label=countries$Value),hjust=0, vjust=0, aes(x=Longitude, y=Latitude))
Error: ggplot2 doesn't know how to deal with data of class uneval

Example of the list with more than two points (every row is a different connection):

("USA", "Spain","China")
("Australia", "Poland")

Body:
You can get a subset based on the points you want to be connected;

link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

base_world <- map_data("world")
p <- ggplot() +
      geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
      geom_line(data=link1, aes(x=Longitude, y=Latitude), color="red", size=1) +
      geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
      geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
      theme(text = element_text(size=20), legend.position="none")  #remove the legend

and your plot would look like:

> p

You may need to play around a little bit for formatting issues.


问:
Ionic trigger modal open function with ion-searchbar focus - click not working
I have an ion-searchbar that, when clicked, opens a modal. However, currently the click process is actually taking two clicks, one to focus, one to open the modal. I have tried to add the click to the ion-toolbar it is contained in, and have tried to disable the ion-searchbar with [disabled]="true", but the disabled functionality isn't available to the ion-searchbar. How can I trigger the new modal to open without having to double click, and in such a way that the focus doesn't happen on the original searchbar?

HTML

```<code><ion-header>
  <ion-toolbar >
    <ion-searchbar (click)="openSearchModal()"></ion-searchbar>
  </ion-toolbar>
</ion-header>
</code>```

JS

```<code>  openSearchModal() {
    let myModal = this.modalCtrl.create(SearchmodalPage);
    myModal.present();
  }
</code>```

答:
Like you are saying, ion-searchbar doesn't have a disabled functionnality.

But you can create your own searchbar, that will use ionic classes to avoid recoding it and you will be able to disable it.

See my code here :

```<code><ion-header>
   <ion-toolbar>
    <div class="searchbar searchbar-ios searchbar-left-aligned searchbar-active" (click)="openSearchModal()">
      <div class="searchbar-input-container">
        <div class="searchbar-search-icon"></div>
        <input class="searchbar-input" placeholder="Search" type="search" autocomplete="off" autocorrect="off" spellcheck="false" disabled="true">
      </div>
    </div>
  </ion-toolbar>
</ion-header>
</code>```

Body:
I have an ion-searchbar that, when clicked, opens a modal. However, currently the click process is actually taking two clicks, one to focus, one to open the modal. I have tried to add the click to the ion-toolbar it is contained in, and have tried to disable the ion-searchbar with [disabled]="true", but the disabled functionality isn't available to the ion-searchbar. How can I trigger the new modal to open without having to double click, and in such a way that the focus doesn't happen on the original searchbar?

HTML

<ion-header>
  <ion-toolbar >
    <ion-searchbar (click)="openSearchModal()"></ion-searchbar>
  </ion-toolbar>
</ion-header>

JS

  openSearchModal() {
    let myModal = this.modalCtrl.create(SearchmodalPage);
    myModal.present();
  }

Body:
Like you are saying, ion-searchbar doesn't have a disabled functionnality.

But you can create your own searchbar, that will use ionic classes to avoid recoding it and you will be able to disable it.

See my code here :

<ion-header>
   <ion-toolbar>
    <div class="searchbar searchbar-ios searchbar-left-aligned searchbar-active" (click)="openSearchModal()">
      <div class="searchbar-input-container">
        <div class="searchbar-search-icon"></div>
        <input class="searchbar-input" placeholder="Search" type="search" autocomplete="off" autocorrect="off" spellcheck="false" disabled="true">
      </div>
    </div>
  </ion-toolbar>
</ion-header>


问:
In ReactJS, why does `setState` behave differently when called synchronously?
I am trying to understand the underlying cause for some somewhat "magical" behavior I am seeing that I cannot fully explain, and which is not apparent from reading the ReactJS source code.

When calling the setState method synchronously in response to an onChange event on an input, everything works as expected. The "new" value of the input is already present, and so the DOM is not actually updated. This is highly desirable because it means the cursor will not jump to the end of the input box.

However, when running a component with exactly the same structure but that calls setState asynchronously, the "new" value of the input does not appear to be present, causing ReactJS to actually touch the DOM, which causes the cursor to jump to the end of the input.

Apparently, something is intervening to "reset" the input back to its prior value in the asynchronous case, which it is not doing in the synchronous case. What is this mechanic?

Synchronous Example

var synchronouslyUpdatingComponent =
    React.createFactory(React.createClass({
      getInitialState: function () {
        return {value: "Hello"};
      },

      changeHandler: function (e) {
        this.setState({value: e.target.value});
      },

      render: function () {
        var valueToSet = this.state.value;

        console.log("Rendering...");
        console.log("Setting value:" + valueToSet);
        if(this.isMounted()) {
            console.log("Current value:" + this.getDOMNode().value);
        }

        return React.DOM.input({value: valueToSet,
                                onChange: this.changeHandler});
    }
}));
```

<p>Note that the code will log in the <code>render</code> method, printing out the current <code>value</code> of the actual DOM node.</p>

<p>When typing an "X" between the two Ls of "Hello", we see the following console output, and the cursor stays where expected:</p>

<pre class="lang-none prettyprint-override"><code>Rendering...
Setting value:HelXlo
Current value:HelXlo
</code>```

Asynchronous Example

var asynchronouslyUpdatingComponent =
  React.createFactory(React.createClass({
    getInitialState: function () {
      return {value: "Hello"};
    },

    changeHandler: function (e) {
      var component = this;
      var value = e.target.value;
      window.setTimeout(function() {
        component.setState({value: value});
      });
    },

    render: function () {
      var valueToSet = this.state.value;

      console.log("Rendering...");
      console.log("Setting value:" + valueToSet);
      if(this.isMounted()) {
          console.log("Current value:" + this.getDOMNode().value);
      }

      return React.DOM.input({value: valueToSet,
                              onChange: this.changeHandler});
    }
}));
```

<p>This is precisely the same as the above, except that the call to <code>setState</code> is in a <code>setTimeout</code> callback.</p>

<p>In this case, typing an X between the two Ls yields the following console output, and the cursor jumps to the end of the input:</p>

<pre class="lang-none prettyprint-override"><code>Rendering...
Setting value:HelXlo
Current value:Hello
</code>```

Why is this?

I understand React's concept of a Controlled Component, and so it makes sense that user changes to the value are ignored. But it looks like the value is in fact changed, and then explicitly reset.

Apparently, calling setState synchronously ensures that it takes effect before the reset, while calling setState at any other time happens after the reset, forcing a re-render.

Is this in fact what's happening?

JS Bin Example

http://jsbin.com/sogunutoyi/1/

答:
We have a similar issue and in our case we have to use asyncronous state updates.

So we use defaultValue, and add a key param to the input associated with the model that the input is reflecting.  This insures that for any model the input will remain syncronized to the model, but if the actual model changes will force a new input to be generated.

Body:
I am trying to understand the underlying cause for some somewhat "magical" behavior I am seeing that I cannot fully explain, and which is not apparent from reading the ReactJS source code.

When calling the setState method synchronously in response to an onChange event on an input, everything works as expected. The "new" value of the input is already present, and so the DOM is not actually updated. This is highly desirable because it means the cursor will not jump to the end of the input box.

However, when running a component with exactly the same structure but that calls setState asynchronously, the "new" value of the input does not appear to be present, causing ReactJS to actually touch the DOM, which causes the cursor to jump to the end of the input.

Apparently, something is intervening to "reset" the input back to its prior value in the asynchronous case, which it is not doing in the synchronous case. What is this mechanic?

Synchronous Example

var synchronouslyUpdatingComponent =
    React.createFactory(React.createClass({
      getInitialState: function () {
        return {value: "Hello"};
      },

      changeHandler: function (e) {
        this.setState({value: e.target.value});
      },

      render: function () {
        var valueToSet = this.state.value;

        console.log("Rendering...");
        console.log("Setting value:" + valueToSet);
        if(this.isMounted()) {
            console.log("Current value:" + this.getDOMNode().value);
        }

        return React.DOM.input({value: valueToSet,
                                onChange: this.changeHandler});
    }
}));

Note that the code will log in the render method, printing out the current value of the actual DOM node.

When typing an "X" between the two Ls of "Hello", we see the following console output, and the cursor stays where expected:

Rendering...
Setting value:HelXlo
Current value:HelXlo

Asynchronous Example

var asynchronouslyUpdatingComponent =
  React.createFactory(React.createClass({
    getInitialState: function () {
      return {value: "Hello"};
    },

    changeHandler: function (e) {
      var component = this;
      var value = e.target.value;
      window.setTimeout(function() {
        component.setState({value: value});
      });
    },

    render: function () {
      var valueToSet = this.state.value;

      console.log("Rendering...");
      console.log("Setting value:" + valueToSet);
      if(this.isMounted()) {
          console.log("Current value:" + this.getDOMNode().value);
      }

      return React.DOM.input({value: valueToSet,
                              onChange: this.changeHandler});
    }
}));

This is precisely the same as the above, except that the call to setState is in a setTimeout callback.

In this case, typing an X between the two Ls yields the following console output, and the cursor jumps to the end of the input:

Rendering...
Setting value:HelXlo
Current value:Hello

Why is this?

I understand React's concept of a Controlled Component, and so it makes sense that user changes to the value are ignored. But it looks like the value is in fact changed, and then explicitly reset.

Apparently, calling setState synchronously ensures that it takes effect before the reset, while calling setState at any other time happens after the reset, forcing a re-render.

Is this in fact what's happening?

JS Bin Example

http://jsbin.com/sogunutoyi/1/


问:
Changing specific observation color (value text) with sgplot - forest plot
I am currently writing an sgplot code for forest plot (SAS University edition). I have managed to get the correct graph as I want, however I can not change the color of a specific observation. This is my code

```<code>data my_data;
    input study $ year rr lcl ucl;
    datalines;
    mickey 2015 1.5 0.7 2.3
    minny 2010 1.2 1.0 1.4
    donald 2013 0.8 0.2 1.4
    daisy 2014 1.3 1.0 1.6
    goofy 2017 1.9 0.9 2.9
    pluto 2010 1.4 0.7 2.1
    ;
run;

proc sgplot data=my_data
            noautolegend nocycleattrs;

    scatter y=study x=rr/ markerattrs=(symbol=squarefilled size=12 color=black);
    highlow high=ucl low=lcl y=study / type=line lineattrs=(color=black);

    yaxistable study year / labelattrs=(family=arial size=12pt weight=bold) position=left location=inside valueattrs=(family=arial size=10pt);
    yaxistable rr lcl ucl / labelattrs=(family=arial size=12pt weight=bold) position=right location=inside valueattrs=(family=arial size=10pt);

    xaxis offsetmin=0.1 offsetmax=1 min=0.5 max=3.0 display=(nolabel);
    yaxis offsetmin=0.1 offsetmax=0.1 display=none reverse;

    refline 1 / axis=x;

    styleattrs axisextent=data;
 run;
</code>```

What I am trying to achieve is changing observation number 3 (donald, 2013, 0.8 0.2 1.4) into a red color (the text when plotting, not only the marker attributes).

I have tried to check for different sgplot attributes, but I am not able to change this specific color of observation number 3 (as red, and other observations remain black) when plotting. I have also looked at template, but this does not help. How can I achieve this?

答:
Assuming there is some programming logic behind the decision, one approach is to create a dummy group variable.  Here I assume the logic is rr < 1.0.

I remove add colorgroup and attrid to the yaxistable in question.  You can change what colors are assigned to the groups (to restore black for the majority) fairly easily, either by using an attribute map as I do below (most correct) or a few other options including editing the default graph colors.

```<code>data my_data;
    length groupvar $20;
    input study $ year rr lcl ucl;
    if rr < 1.0 then groupvar='redgroup';
    else groupvar='blackgroup';
    datalines;
    mickey 2015 1.5 0.7 2.3
    minny 2010 1.2 1.0 1.4
    donald 2013 0.8 0.2 1.4
    daisy 2014 1.3 1.0 1.6
    goofy 2017 1.9 0.9 2.9
    pluto 2010 1.4 0.7 2.1
    ;
run;

data attrmap;
length value $20;
input value $ textcolor $;
retain id 'colorgroup';
datalines;
redgroup red
blackgroup black
;;;;
run;

proc sgplot data=my_data
            noautolegend nocycleattrs dattrmap=attrmap;

    scatter y=study x=rr/ markerattrs=(symbol=squarefilled size=12 color=black) group=groupvar attrid=colorgroup;
    highlow high=ucl low=lcl y=study / type=line lineattrs=(color=black);

    yaxistable study year / labelattrs=(family=arial size=12pt weight=bold) position=left location=inside valueattrs=(family=arial size=10pt)
                            attrid=colorgroup colorgroup=groupvar;
    yaxistable rr lcl ucl / labelattrs=(family=arial size=12pt weight=bold) position=right location=inside valueattrs=(family=arial size=10pt) ;

    xaxis offsetmin=0.1 offsetmax=1 min=0.5 max=3.0 display=(nolabel);
    yaxis offsetmin=0.1 offsetmax=0.1 display=none reverse;

    refline 1 / axis=x;

    styleattrs axisextent=data;
 run;
</code>```

Body:
I am currently writing an sgplot code for forest plot (SAS University edition). I have managed to get the correct graph as I want, however I can not change the color of a specific observation. This is my code

data my_data;
    input study $ year rr lcl ucl;
    datalines;
    mickey 2015 1.5 0.7 2.3
    minny 2010 1.2 1.0 1.4
    donald 2013 0.8 0.2 1.4
    daisy 2014 1.3 1.0 1.6
    goofy 2017 1.9 0.9 2.9
    pluto 2010 1.4 0.7 2.1
    ;
run;

proc sgplot data=my_data
            noautolegend nocycleattrs;

    scatter y=study x=rr/ markerattrs=(symbol=squarefilled size=12 color=black);
    highlow high=ucl low=lcl y=study / type=line lineattrs=(color=black);

    yaxistable study year / labelattrs=(family=arial size=12pt weight=bold) position=left location=inside valueattrs=(family=arial size=10pt);
    yaxistable rr lcl ucl / labelattrs=(family=arial size=12pt weight=bold) position=right location=inside valueattrs=(family=arial size=10pt);

    xaxis offsetmin=0.1 offsetmax=1 min=0.5 max=3.0 display=(nolabel);
    yaxis offsetmin=0.1 offsetmax=0.1 display=none reverse;

    refline 1 / axis=x;

    styleattrs axisextent=data;
 run;

What I am trying to achieve is changing observation number 3 (donald, 2013, 0.8 0.2 1.4) into a red color (the text when plotting, not only the marker attributes).

I have tried to check for different sgplot attributes, but I am not able to change this specific color of observation number 3 (as red, and other observations remain black) when plotting. I have also looked at template, but this does not help. How can I achieve this?

Body:
Assuming there is some programming logic behind the decision, one approach is to create a dummy group variable.  Here I assume the logic is rr < 1.0.

I remove add colorgroup and attrid to the yaxistable in question.  You can change what colors are assigned to the groups (to restore black for the majority) fairly easily, either by using an attribute map as I do below (most correct) or a few other options including editing the default graph colors.

data my_data;
    length groupvar $20;
    input study $ year rr lcl ucl;
    if rr < 1.0 then groupvar='redgroup';
    else groupvar='blackgroup';
    datalines;
    mickey 2015 1.5 0.7 2.3
    minny 2010 1.2 1.0 1.4
    donald 2013 0.8 0.2 1.4
    daisy 2014 1.3 1.0 1.6
    goofy 2017 1.9 0.9 2.9
    pluto 2010 1.4 0.7 2.1
    ;
run;

data attrmap;
length value $20;
input value $ textcolor $;
retain id 'colorgroup';
datalines;
redgroup red
blackgroup black
;;;;
run;

proc sgplot data=my_data
            noautolegend nocycleattrs dattrmap=attrmap;

    scatter y=study x=rr/ markerattrs=(symbol=squarefilled size=12 color=black) group=groupvar attrid=colorgroup;
    highlow high=ucl low=lcl y=study / type=line lineattrs=(color=black);

    yaxistable study year / labelattrs=(family=arial size=12pt weight=bold) position=left location=inside valueattrs=(family=arial size=10pt)
                            attrid=colorgroup colorgroup=groupvar;
    yaxistable rr lcl ucl / labelattrs=(family=arial size=12pt weight=bold) position=right location=inside valueattrs=(family=arial size=10pt) ;

    xaxis offsetmin=0.1 offsetmax=1 min=0.5 max=3.0 display=(nolabel);
    yaxis offsetmin=0.1 offsetmax=0.1 display=none reverse;

    refline 1 / axis=x;

    styleattrs axisextent=data;
 run;


问:
JDBC Spring Mockito
I want to test this method (getDetails) is part of my DaoImpl, but I do not know how to do it. I know that I have to test the database mocking it with the JDBC template:

```<code> public List<DataLoadDetail> getDetails(int fileId, String templateType, String status, int start, int end) {

    List<DataLoadDetail> list = new ArrayList<DataLoadDetail>();
    StringBuffer sql = new StringBuffer();

    sql.append("SELECT * FROM ( ")
        .append("SELECT ROW_NUMBER() OVER(ORDER BY TB_DETAIL.UPLOADITEM_SEQ_NR ASC) AS RowNum, ")
        .append("TB_DETAIL.UPLOAD_ID, TB_DETAIL.UPLOADITEM_SEQ_NR, TB_DETAIL.UPLOADITEM_ACTION_CD, ")
        .append("TB_DETAIL.UPLOADITEM_INSERT_DT, TB_DETAIL.UPLOADITEM_UPDATE_DT, TB_DETAIL.UPLOADITEM_STATUS_CD, ")
        .append("TB_DETAIL.UPLOADITEM_PAYLOAD, TB_DETAIL.UPLOADITEM_RESPONSE, TB_MESSAGE.DESCRIPTION ")
        .append("FROM DL_DETAIL TB_DETAIL LEFT JOIN DL_MESSAGE TB_MESSAGE ")
        .append("ON TB_DETAIL.UPLOAD_ID = TB_MESSAGE.UPLOAD_ID ")
        .append("AND TB_DETAIL.UPLOADITEM_SEQ_NR = TB_MESSAGE.UPLOADITEM_SEQ_NR ")
        .append("WHERE TB_DETAIL.UPLOAD_ID =:fileId ");

    if (StringUtils.equalsIgnoreCase(status, "s")) {
        sql.append(" AND TB_DETAIL.UPLOADITEM_STATUS_CD = 'S' ");
    } else if (StringUtils.equalsIgnoreCase(status, "f")) {
        sql.append(" AND TB_DETAIL.UPLOADITEM_STATUS_CD != 'S' ");
    }

    sql.append(" ) AS DT WHERE RowNum > :start ");

    if (end > 0) {
        sql.append(" AND RowNum <= :end ");
    }

    System.out.println("getDetails - File Id "+fileId+", Query --> " + sql.toString());

    Map<String, Object> props = new HashMap<String, Object>();
    props.put("fileId", fileId);
    props.put("start", start);
    props.put("end", end);

    list = npTemplate.query(sql.toString(), props, new DataLoadDetailRowMapper());
    return list;
}
</code>```

The applicationContext.xml file is:

```<code><bean id="dataLoadDetailDao" class="com.hp.it.mdm.dao.impl.DataLoadDetailDaoImpl">
    <property name="npTemplate">
        <ref bean="nameParamJdbcTemplate"/>
    </property>
    <property name="dlmdao">
        <ref bean="dlmdao"/>
    </property>
</bean>
</code>```

I have seen several posts in StackOverflow but I can not get the concept of the test.

Regards.

答:
Depending on what you want to test there might be different types of tests.

First you need to test the logic of the method.
Each branch of your code must be tested (you have several if conditions).
To achieve that you have to mock npTemplate.query() method passing different combinations of sql query string and parameters.
All your tests will look somehow like this

```<code>// given
String expectedSql =
Map<String, Object> expectedProps = ...
DataLoadDetailRowMapper expectedMapper = new DataLoadDetailRowMapper();
List<DataLoadDetail> expectedResult = ...
NpTemplate npTemplate = Mockito.mock(NpTemplate.class);
BDDMockito.given(npTemplate.query(expectedSql, props, expectedMapper))
        .willReturn(expectedResult);
DaoImpl dao = ... // Initialize it using the mocked npTemplate.

// when
List<DataLoadDetail> result = dao.getDetails(); // pass needed parameters

// then
assertThat(result, is(expectedResult));
</code>```

I didn't use static imports just to make clear which classes were used. But it is preferable to import everything statically in unit tests.

Second thing is the query itself, you have to test the sql code. To achieve that you might make data setup use inmemory db (for instance H2) and run the sql over it.

Title: JDBC Spring Mockito

Body:
I want to test this method (getDetails) is part of my DaoImpl, but I do not know how to do it. I know that I have to test the database mocking it with the JDBC template:

 public List<DataLoadDetail> getDetails(int fileId, String templateType, String status, int start, int end) {

    List<DataLoadDetail> list = new ArrayList<DataLoadDetail>();
    StringBuffer sql = new StringBuffer();

    sql.append("SELECT * FROM ( ")
        .append("SELECT ROW_NUMBER() OVER(ORDER BY TB_DETAIL.UPLOADITEM_SEQ_NR ASC) AS RowNum, ")
        .append("TB_DETAIL.UPLOAD_ID, TB_DETAIL.UPLOADITEM_SEQ_NR, TB_DETAIL.UPLOADITEM_ACTION_CD, ")
        .append("TB_DETAIL.UPLOADITEM_INSERT_DT, TB_DETAIL.UPLOADITEM_UPDATE_DT, TB_DETAIL.UPLOADITEM_STATUS_CD, ")
        .append("TB_DETAIL.UPLOADITEM_PAYLOAD, TB_DETAIL.UPLOADITEM_RESPONSE, TB_MESSAGE.DESCRIPTION ")
        .append("FROM DL_DETAIL TB_DETAIL LEFT JOIN DL_MESSAGE TB_MESSAGE ")
        .append("ON TB_DETAIL.UPLOAD_ID = TB_MESSAGE.UPLOAD_ID ")
        .append("AND TB_DETAIL.UPLOADITEM_SEQ_NR = TB_MESSAGE.UPLOADITEM_SEQ_NR ")
        .append("WHERE TB_DETAIL.UPLOAD_ID =:fileId ");

    if (StringUtils.equalsIgnoreCase(status, "s")) {
        sql.append(" AND TB_DETAIL.UPLOADITEM_STATUS_CD = 'S' ");
    } else if (StringUtils.equalsIgnoreCase(status, "f")) {
        sql.append(" AND TB_DETAIL.UPLOADITEM_STATUS_CD != 'S' ");
    }

    sql.append(" ) AS DT WHERE RowNum > :start ");

    if (end > 0) {
        sql.append(" AND RowNum <= :end ");
    }

    System.out.println("getDetails - File Id "+fileId+", Query --> " + sql.toString());

    Map<String, Object> props = new HashMap<String, Object>();
    props.put("fileId", fileId);
    props.put("start", start);
    props.put("end", end);

    list = npTemplate.query(sql.toString(), props, new DataLoadDetailRowMapper());
    return list;
}

The applicationContext.xml file is:

<bean id="dataLoadDetailDao" class="com.hp.it.mdm.dao.impl.DataLoadDetailDaoImpl">
    <property name="npTemplate">
        <ref bean="nameParamJdbcTemplate"/>
    </property>
    <property name="dlmdao">
        <ref bean="dlmdao"/>
    </property>
</bean>

I have seen several posts in StackOverflow but I can not get the concept of the test.

Regards.

Body:
Depending on what you want to test there might be different types of tests.

First you need to test the logic of the method.
Each branch of your code must be tested (you have several if conditions).
To achieve that you have to mock npTemplate.query() method passing different combinations of sql query string and parameters.
All your tests will look somehow like this

// given
String expectedSql =
Map<String, Object> expectedProps = ...
DataLoadDetailRowMapper expectedMapper = new DataLoadDetailRowMapper();
List<DataLoadDetail> expectedResult = ...
NpTemplate npTemplate = Mockito.mock(NpTemplate.class);
BDDMockito.given(npTemplate.query(expectedSql, props, expectedMapper))
        .willReturn(expectedResult);
DaoImpl dao = ... // Initialize it using the mocked npTemplate.

// when
List<DataLoadDetail> result = dao.getDetails(); // pass needed parameters

// then
assertThat(result, is(expectedResult));

I didn't use static imports just to make clear which classes were used. But it is preferable to import everything statically in unit tests.

Second thing is the query itself, you have to test the sql code. To achieve that you might make data setup use inmemory db (for instance H2) and run the sql over it.


答:
You can use np.where</p>

```<code>df['C'] = np.where(df.B>=2, 'yes', 'no')

    A   B   C
1   A   2   yes
2   B   3   yes
3   C   4   yes
4   D   5   yes
5   A   6   yes
6   B   7   yes
7   C   0   no
8   D   1   no
9   A   2   yes
10  B   3   yes
11  C   4   yes
12  D   0   no
</code>```

Body:
I would like to set a string in Column C while values in Column B are >= 2 (yes if>= is True, no if >= is False). The output should be as follows:

    A B   C
1   A 2 'yes'
2   B 3 'yes'
3   C 4 'yes'
4   D 5 'yes'
5   A 6 'yes'
6   B 7 'yes'
7   C 0 'no'
8   D 1 'no'
9   A 2 'yes'
10  B 3 'yes'
11  C 4 'yes'
12  D 0 'no'

So far I have tried to implement nested loops, which are far too slow:

i= 0
for row in range(0, len(df)-1):
    if df['B'][i] >= 2:
        if df['B'][i] >= 2:
            df['C'][i] = 'yes'
        elif df['B'][i] >= 2:
            df['C'][i] = 'yes'

Body:
You can use np.where

df['C'] = np.where(df.B>=2, 'yes', 'no')

    A   B   C
1   A   2   yes
2   B   3   yes
3   C   4   yes
4   D   5   yes
5   A   6   yes
6   B   7   yes
7   C   0   no
8   D   1   no
9   A   2   yes
10  B   3   yes
11  C   4   yes
12  D   0   no


问:
Limitations of the Levenberg-Marquardt algorithm
I am using Levenberg-Marquardt algorithm to minimize a non-linear function of 6 parameters. I have got about 50 data points for each minimization, but I do not get sufficiently accurate results. Does the fact, that my parameters differ from each other by a few orders of magnitudes can be so much significant? If yes, where should I look for the solution? If no, what kind of limitations of LMA you met in your work (it may help to find other problems with my applictaion)?
Many Thanks for your help.

Edit: The problem I am trying to solve is to determine the best transformation T:

```<code>typedef struct
{
    double x_translation, y_translation, z_translation;
    double x_rotation, y_rotation, z_rotation;
} transform_3D;
</code>```

to fit the set of 3D points to the bunch of 3D lines. In detail I have got a set of coordinates of 3D points and equations of corresponding 3D lines, which should go through those points (in ideal situation). The LMA is minimizing the summ of distances of the transfomed 3D points to corresponding 3D lines.
The transform function is as follows:

```<code>cv::Point3d Geometry::transformation_3D(cv::Point3d point, transform_3D transformation)
{
    cv::Point3d p_odd,p_even;

    //rotation x
    p_odd.x=point.x;
    p_odd.y=point.y*cos(transformation.x_rotation)-point.z*sin(transformation.x_rotation);
    p_odd.z=point.y*sin(transformation.x_rotation)+point.z*cos(transformation.x_rotation);

    //rotation y
    p_even.x=p_odd.z*sin(transformation.y_rotation)+p_odd.x*cos(transformation.y_rotation);
    p_even.y=p_odd.y;
    p_even.z=p_odd.z*cos(transformation.y_rotation)-p_odd.x*sin(transformation.y_rotation);

    //rotation z
    p_odd.x=p_even.x*cos(transformation.z_rotation)-p_even.y*sin(transformation.z_rotation);
    p_odd.y=p_even.x*sin(transformation.z_rotation)+p_even.y*cos(transformation.z_rotation);
    p_odd.z=p_even.z;

    //translation
    p_even.x=p_odd.x+transformation.x_translation;
    p_even.y=p_odd.y+transformation.y_translation;
    p_even.z=p_odd.z+transformation.z_translation;

    return p_even;
}
</code>```

Hope this explanation will help a bit...

Edit2:

Some exemplary data is pasted below. 3D lines are described by the center point and the directional vector. Center point for all lines are (0,0,0) and 'uz' coordinate for each vector is equal to 1.
Set of 'ux' coordinates of directional vectors:

```<code>-1.0986, -1.0986, -1.0986,
-1.0986, -1.0990, -1.0986,
-1.0986, -1.0986, -0.9995,
-0.9996, -0.9996, -0.9995,
-0.9995, -0.9995, -0.9996,
-0.9003, -0.9003, -0.9004,
-0.9003, -0.9003, -0.9003,
-0.9003, -0.9003, -0.8011,
-0.7020, -0.7019, -0.6028,
-0.5035, -0.5037, -0.4045,
-0.3052, -0.3053, -0.2062,
-0.1069, -0.1069, -0.1075,
-0.1070, -0.1070, -0.1069,
-0.1069, -0.1070, -0.0079,
-0.0079, -0.0079, -0.0078,
-0.0078, -0.0079, -0.0079,
 0.0914,  0.0914,  0.0913,
 0.0913,  0.0914,  0.0915,
 0.0914,  0.0914
</code>```

Set of 'uy' coordinates of directional vectors:

```<code>-0.2032,  -0.0047,    0.1936,
0.3919,    0.5901,    0.7885,
0.9869,    1.1852,    -0.1040,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1936,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    1.0860,
0.9869,    1.1852,    1.0861,
0.9865,    1.1853,    1.0860,
0.9870,    1.1852,    1.0861,
-0.2032,  -0.0047,    0.1937,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    -0.1039,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1935,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852
</code>```

and set of 3D points in (x. y. z. x. y. z. x. y. z. ...) form:

```<code> {{0, 0, 0}, {0, 16, 0},   {0, 32, 0},
 {0, 48, 0}, {0, 64, 0},   {0, 80, 0},
 {0, 96, 0}, {0, 112,0},   {8, 8, 0},
 {8, 24, 0}, {8, 40, 0},   {8, 56, 0},
 {8, 72, 0}, {8, 88, 0},   {8, 104, 0},
 {16, 0, 0}, {16, 16,0},   {16, 32, 0},
{16, 48, 0}, {16, 64, 0},  {16, 80, 0},
{16, 96, 0}, {16, 112, 0}, {24, 104, 0},
{32, 96, 0}, {32, 112, 0}, {40, 104, 0},
{48, 96, 0}, {48, 112, 0}, {56, 104, 0},
{64, 96, 0}, {64, 112, 0}, {72, 104, 0},
{80, 0, 0},  {80, 16, 0},  {80, 32, 0},
{80,48, 0},  {80, 64, 0},  {80, 80, 0},
{80, 96, 0}, {80, 112, 0}, {88,  8, 0},
{88, 24, 0}, {88, 40, 0},  {88, 56, 0},
{88, 72, 0}, {88, 88, 0},  {88, 104, 0},
{96, 0, 0},  {96, 16, 0},  {96, 32, 0},
{96, 48,0},  {96, 64, 0},  {96, 80, 0},
{96, 96, 0}, {96, 112, 0}}
</code>```

This is kind of an "easy" modelled data with very small rotations.

答:
Well, the proper way of using Levenberg-Marquardt is that you need a good initial estimate (a "seed") for your parameters. Recall that LM is a variant of Newton-Raphson; as with such iterative algorithms, the quality of your starting point will make or break your iteration; either converging to what you want, converging to something completely different (not that unlikely to happen, especially if you have a lot of parameters), or shooting off into the wild blue yonder (diverges).

In any event, it would be more helpful if you could mention the model function you're fitting, and possibly a scatter plot of your data; it might go a long way towards finding a workable solution for this.

Body:
I am using Levenberg-Marquardt algorithm to minimize a non-linear function of 6 parameters. I have got about 50 data points for each minimization, but I do not get sufficiently accurate results. Does the fact, that my parameters differ from each other by a few orders of magnitudes can be so much significant? If yes, where should I look for the solution? If no, what kind of limitations of LMA you met in your work (it may help to find other problems with my applictaion)?
Many Thanks for your help.

Edit: The problem I am trying to solve is to determine the best transformation T:

typedef struct
{
    double x_translation, y_translation, z_translation;
    double x_rotation, y_rotation, z_rotation;
} transform_3D;

to fit the set of 3D points to the bunch of 3D lines. In detail I have got a set of coordinates of 3D points and equations of corresponding 3D lines, which should go through those points (in ideal situation). The LMA is minimizing the summ of distances of the transfomed 3D points to corresponding 3D lines.
The transform function is as follows:

cv::Point3d Geometry::transformation_3D(cv::Point3d point, transform_3D transformation)
{
    cv::Point3d p_odd,p_even;

    //rotation x
    p_odd.x=point.x;
    p_odd.y=point.y*cos(transformation.x_rotation)-point.z*sin(transformation.x_rotation);
    p_odd.z=point.y*sin(transformation.x_rotation)+point.z*cos(transformation.x_rotation);

    //rotation y
    p_even.x=p_odd.z*sin(transformation.y_rotation)+p_odd.x*cos(transformation.y_rotation);
    p_even.y=p_odd.y;
    p_even.z=p_odd.z*cos(transformation.y_rotation)-p_odd.x*sin(transformation.y_rotation);

    //rotation z
    p_odd.x=p_even.x*cos(transformation.z_rotation)-p_even.y*sin(transformation.z_rotation);
    p_odd.y=p_even.x*sin(transformation.z_rotation)+p_even.y*cos(transformation.z_rotation);
    p_odd.z=p_even.z;

    //translation
    p_even.x=p_odd.x+transformation.x_translation;
    p_even.y=p_odd.y+transformation.y_translation;
    p_even.z=p_odd.z+transformation.z_translation;

    return p_even;
}

Hope this explanation will help a bit...

Edit2:

Some exemplary data is pasted below. 3D lines are described by the center point and the directional vector. Center point for all lines are (0,0,0) and 'uz' coordinate for each vector is equal to 1.
Set of 'ux' coordinates of directional vectors:

-1.0986, -1.0986, -1.0986,
-1.0986, -1.0990, -1.0986,
-1.0986, -1.0986, -0.9995,
-0.9996, -0.9996, -0.9995,
-0.9995, -0.9995, -0.9996,
-0.9003, -0.9003, -0.9004,
-0.9003, -0.9003, -0.9003,
-0.9003, -0.9003, -0.8011,
-0.7020, -0.7019, -0.6028,
-0.5035, -0.5037, -0.4045,
-0.3052, -0.3053, -0.2062,
-0.1069, -0.1069, -0.1075,
-0.1070, -0.1070, -0.1069,
-0.1069, -0.1070, -0.0079,
-0.0079, -0.0079, -0.0078,
-0.0078, -0.0079, -0.0079,
 0.0914,  0.0914,  0.0913,
 0.0913,  0.0914,  0.0915,
 0.0914,  0.0914

Set of 'uy' coordinates of directional vectors:

-0.2032,  -0.0047,    0.1936,
0.3919,    0.5901,    0.7885,
0.9869,    1.1852,    -0.1040,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1936,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    1.0860,
0.9869,    1.1852,    1.0861,
0.9865,    1.1853,    1.0860,
0.9870,    1.1852,    1.0861,
-0.2032,  -0.0047,    0.1937,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    -0.1039,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1935,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852

and set of 3D points in (x. y. z. x. y. z. x. y. z. ...) form:

 {{0, 0, 0}, {0, 16, 0},   {0, 32, 0},
 {0, 48, 0}, {0, 64, 0},   {0, 80, 0},
 {0, 96, 0}, {0, 112,0},   {8, 8, 0},
 {8, 24, 0}, {8, 40, 0},   {8, 56, 0},
 {8, 72, 0}, {8, 88, 0},   {8, 104, 0},
 {16, 0, 0}, {16, 16,0},   {16, 32, 0},
{16, 48, 0}, {16, 64, 0},  {16, 80, 0},
{16, 96, 0}, {16, 112, 0}, {24, 104, 0},
{32, 96, 0}, {32, 112, 0}, {40, 104, 0},
{48, 96, 0}, {48, 112, 0}, {56, 104, 0},
{64, 96, 0}, {64, 112, 0}, {72, 104, 0},
{80, 0, 0},  {80, 16, 0},  {80, 32, 0},
{80,48, 0},  {80, 64, 0},  {80, 80, 0},
{80, 96, 0}, {80, 112, 0}, {88,  8, 0},
{88, 24, 0}, {88, 40, 0},  {88, 56, 0},
{88, 72, 0}, {88, 88, 0},  {88, 104, 0},
{96, 0, 0},  {96, 16, 0},  {96, 32, 0},
{96, 48,0},  {96, 64, 0},  {96, 80, 0},
{96, 96, 0}, {96, 112, 0}}

This is kind of an "easy" modelled data with very small rotations.


问:
Selenium/Java/EdgeDriver: Modal window dialog box stops execution of test script
I'm currently writing a test script for our web application that tests uploading a profile picture image using Microsoft Edge and EdgeDriver.  When I initialize the click operation for the add photo button the script stops executing altogether.  I think it's a parent/child window or javascript issue but have been stumped on this issue for some time now.  I have it working in Chrome/Firefox/IE11. The code below should click the button to pop up the modal window, copy the path to the desired image, and then paste the path in the dialog box.

Here is the code snippet relevant to the issue:

```<code>    driverElement = driver.findElement(By.xpath("//span[text()='Add Photo']"));
    actions.moveToElement(driverElement).click().build().perform(); //click button for modal window

    //find the image and upload it
    pathToImage = new StringSelection("C:\\path\\to\\image");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pathToImage, null);
    bot = new Robot();

    Thread.sleep(500);
    bot.keyPress(KeyEvent.VK_CONTROL);
    bot.keyPress(KeyEvent.VK_V);

    bot.keyRelease(KeyEvent.VK_CONTROL);
    bot.keyRelease(KeyEvent.VK_V);
    Thread.sleep(500);

    bot.keyPress(KeyEvent.VK_ENTER);
    bot.keyRelease(KeyEvent.VK_ENTER);
</code>```

After the click operation all execution stops, even in debug mode when I try to step over manually to the next line of execution.

Any help would be greatly appreciated.

答: After some extensive investigation and a ton of trying workarounds it appears that this is a plain showstopper.  Microsoft has not developed the WebDriver enough to differentiate the root file explorer and the web file explorer.  More details can be found here: Edge Upload File control using Selenium </p>

Body:
I'm currently writing a test script for our web application that tests uploading a profile picture image using Microsoft Edge and EdgeDriver.  When I initialize the click operation for the add photo button the script stops executing altogether.  I think it's a parent/child window or javascript issue but have been stumped on this issue for some time now.  I have it working in Chrome/Firefox/IE11. The code below should click the button to pop up the modal window, copy the path to the desired image, and then paste the path in the dialog box.

Here is the code snippet relevant to the issue:

    driverElement = driver.findElement(By.xpath("//span[text()='Add Photo']"));
    actions.moveToElement(driverElement).click().build().perform(); //click button for modal window

    //find the image and upload it
    pathToImage = new StringSelection("C:\\path\\to\\image");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pathToImage, null);
    bot = new Robot();

    Thread.sleep(500);
    bot.keyPress(KeyEvent.VK_CONTROL);
    bot.keyPress(KeyEvent.VK_V);

    bot.keyRelease(KeyEvent.VK_CONTROL);
    bot.keyRelease(KeyEvent.VK_V);
    Thread.sleep(500);

    bot.keyPress(KeyEvent.VK_ENTER);
    bot.keyRelease(KeyEvent.VK_ENTER);

After the click operation all execution stops, even in debug mode when I try to step over manually to the next line of execution.

Any help would be greatly appreciated.


问:
When i try to compile i got expected * but argument is type **, and warnings passing argument incompatible pointer type
```<code>listT *Stos;
void DFS(int wierz) {
  int v;
  nodeT *p;
  addfront(&Stos, wierz);
  tabzaznaczen[wierz] = 1;
  while (Stos) {
    removefront(&Stos, &v);
    printf("%d\n", v);
    for (p = tabwierz[v].front; p; p = p->next) {
      if (tabzaznaczen[p->data] == 0) {
        addfront(&Stos, p->data);
        tabzaznaczen[p->data] = 1;
      }
    }
  }
</code>```

And when i change declaration to listT Stos; its revealing error: used struct tpye value when scalar is required. And then when i change to while(&Stos) i\while goes to infinity.

```<code>typedef struct nodeTAG{
int data;
struct nodeTAG *next;
}nodeT;

typedef struct listTAG{
nodeT *front;
nodeT *end;
}listT;

void listinit (listT *plist)
{
plist -> front = NULL;
plist -> end = NULL;
}

int isempty (listT *plist)
{
if (plist -> front == NULL)
return 1;
else   return 0;
}

void addfront (listT *plist, int x)
{
nodeT *temp;
temp = (nodeT*)malloc(sizeof(nodeT));
temp -> data =x;

if (plist -> front == NULL)
{
temp -> next = NULL;
plist -> front = temp;
plist -> end = temp;
}
else
{
temp -> next = plist -> front;
plist -> front = temp;
}
}

void addend (listT *plist, int x)
{
nodeT *temp;
temp = (nodeT*)malloc(sizeof(nodeT));
temp -> data = x;

if (plist -> front == NULL)
{
temp -> next = NULL;
plist -> front = temp;
plist -> end =temp;
}
else
{
temp -> next = NULL;
plist -> end -> next = temp;
plist -> end = temp;
}
}

void removefront (listT *plist, int *x)
{
if (isempty(plist) == 0)
{
nodeT *temp;
*x=plist->front->data;
temp = plist -> front;
plist -> front = temp -> next;
free(temp);

}
}
</code>```

This is the list.  By the way program is working as it should just those warnings are bothering me to show this to my teacher. If u could tell me how to fix those i would be pleased.

答:
It would be nice to see the function prototypes of the functions used, but it looks like you need a pointer to your list pointer so that when removefront deletes the first node and reassigns the pointer to the new head it is not lost when returning.

Here is a wonderful tutorial on linked lists: http://www.learn-c.org/en/Linked_lists

Body:
listT *Stos;
void DFS(int wierz) {
  int v;
  nodeT *p;
  addfront(&Stos, wierz);
  tabzaznaczen[wierz] = 1;
  while (Stos) {
    removefront(&Stos, &v);
    printf("%d\n", v);
    for (p = tabwierz[v].front; p; p = p->next) {
      if (tabzaznaczen[p->data] == 0) {
        addfront(&Stos, p->data);
        tabzaznaczen[p->data] = 1;
      }
    }
  }

And when i change declaration to listT Stos; its revealing error: used struct tpye value when scalar is required. And then when i change to while(&Stos) i\while goes to infinity.

typedef struct nodeTAG{
int data;
struct nodeTAG *next;
}nodeT;

typedef struct listTAG{
nodeT *front;
nodeT *end;
}listT;

void listinit (listT *plist)
{
plist -> front = NULL;
plist -> end = NULL;
}

int isempty (listT *plist)
{
if (plist -> front == NULL)
return 1;
else   return 0;
}

void addfront (listT *plist, int x)
{
nodeT *temp;
temp = (nodeT*)malloc(sizeof(nodeT));
temp -> data =x;

if (plist -> front == NULL)
{
temp -> next = NULL;
plist -> front = temp;
plist -> end = temp;
}
else
{
temp -> next = plist -> front;
plist -> front = temp;
}
}

void addend (listT *plist, int x)
{
nodeT *temp;
temp = (nodeT*)malloc(sizeof(nodeT));
temp -> data = x;

if (plist -> front == NULL)
{
temp -> next = NULL;
plist -> front = temp;
plist -> end =temp;
}
else
{
temp -> next = NULL;
plist -> end -> next = temp;
plist -> end = temp;
}
}

void removefront (listT *plist, int *x)
{
if (isempty(plist) == 0)
{
nodeT *temp;
*x=plist->front->data;
temp = plist -> front;
plist -> front = temp -> next;
free(temp);

}
}

This is the list.  By the way program is working as it should just those warnings are bothering me to show this to my teacher. If u could tell me how to fix those i would be pleased.


问:
Some strings in a array match another array
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}
</code>```

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

答:
I understand that you want to know which value is present in both arrays.

We can use Sets to find them, as known from Set Theory in mathematics.

What you are looking for is called Intersection — an element is found in both set of elements. Mathematical notation: A ∩ B.

```<code>let usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
let verifiedUsers = ["hello", "hello1", "hello2", "hello3", "hello1212"]
let verifiedUsersInData = Array(Set(usersInData).intersection(verifiedUsers))
print(verifiedUsersInData)
</code>```

output:

```<code>["hello3", "hello", "hello2", "hello1"]
</code>```

As you can se the result array has another order than the two input array. This is due to the fact that sets don't have an ordering concept.

if maintaining an order is important for you, you have several options:

sort the result array by comparing the order to one of the input arrays,

wrap the values in the input arrays in a type that has a weight value, order the result array by it, than unwrap,

use NSOrderedSet, which keeps the order but isn't working for swift types,

find a ordered set implementation online. I don't have any recommendation for any, but you should pick one that promises to have the same BigO characteristics we are used from sets.

Body:
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

Body:
I understand that you want to know which value is present in both arrays.

We can use Sets to find them, as known from Set Theory in mathematics.

What you are looking for is called Intersection — an element is found in both set of elements. Mathematical notation: A ∩ B.

let usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
let verifiedUsers = ["hello", "hello1", "hello2", "hello3", "hello1212"]
let verifiedUsersInData = Array(Set(usersInData).intersection(verifiedUsers))
print(verifiedUsersInData)

output:

["hello3", "hello", "hello2", "hello1"]

As you can se the result array has another order than the two input array. This is due to the fact that sets don't have an ordering concept.

if maintaining an order is important for you, you have several options:

sort the result array by comparing the order to one of the input arrays,

wrap the values in the input arrays in a type that has a weight value, order the result array by it, than unwrap,

use NSOrderedSet, which keeps the order but isn't working for swift types,

find a ordered set implementation online. I don't have any recommendation for any, but you should pick one that promises to have the same BigO characteristics we are used from sets.