问:
Javafx table loads the correct number of rows, but loads duplicate data. Am I missing something?
My code should load a customer tableview in javafx via loadCusotmerTable() from MYSQL database with JDBC through the CustomerDOA.findAll() method. The findAll() method returns an ObservableList that should display the customers.

The Table output is currently displaying the correct number of rows for each customer in the Observable list, but it only displays the data from the last entry in the ObservableList. Is there something missing in my code to load the ObservableList<Customer> Customers correctly?

loadCustomerTable

package Controller;

import Model.Customer;
import Model.DAO.CustomerDAO;
import Model.DAO.UserDAO;
import Model.DBConnection;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

public class CustomerViewController implements Initializable {

    @FXML private TextField TextFieldCustomerID;
    @FXML private TextField TextFieldCustomerName;

    @FXML private Button ButtonGoBack;
    @FXML private Button ButtonAddModify;
    @FXML private Button ButtonRemove;
    @FXML private Button ButtonCancel;

    @FXML private MenuButton MenuButtonAddress;

    @FXML private MenuButton MenuButtonActive;
    @FXML private MenuItem MenuActiveItemActive;
    @FXML private MenuItem MenuActiveItemInactive;

    @FXML private TableView<Customer> TableViewCustomer;
    @FXML private TableColumn<Customer, String> TableCustomerColumnCustomerID;
    @FXML private TableColumn<Customer, String> TableCustomerColumnCustomerName;
    @FXML private TableColumn<Customer, String> TableCustomerColumnAddress;
    @FXML private TableColumn<Customer, String> TableCustomerColumnActive;

    private int addressId = 1;
    private int Active = 1;
    private int userId = 1;

    private boolean isCustomerSelected = true;
    private ObservableList<Customer> Customers = FXCollections.observableArrayList();

    // .......

    public void loadCustomerTable(){

        CustomerDAO customerDAO = new CustomerDAO(DBConnection.getConnection());
        ObservableList<Customer> Customers = customerDAO.findAll();

        TableCustomerColumnCustomerID.setCellValueFactory(new PropertyValueFactory<>("customerId"));
        TableCustomerColumnCustomerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
        TableCustomerColumnAddress.setCellValueFactory(new PropertyValueFactory<>("addressId"));
        TableCustomerColumnActive.setCellValueFactory(new PropertyValueFactory<>("active"));

        TableViewCustomer.setItems(Customers);
    }
```
<h1>CustomerDAO.findAll()</h1>
<pre class="lang-java prettyprint-override"><code> public ObservableList<Customer> findAll() {
        ObservableList<Customer> Customers = FXCollections.observableArrayList();
        Customer customer = new Customer();

        try(PreparedStatement statement = this.connection.prepareStatement(GET_ALL)){

            ResultSet resultSet = statement.executeQuery();
            int i =0;
            while(resultSet.next()){

                customer.setCustomerId(resultSet.getInt("customerId"));
                customer.setCustomerName(resultSet.getString("customerName"));
                customer.setAddressId(resultSet.getInt("addressId"));
                customer.setActive(resultSet.getInt("active"));
                customer.setCreateDate(resultSet.getTimestamp("createDate"));
                customer.setLastUpdate(resultSet.getTimestamp("lastUpdate"));
                customer.setCreatedBy(resultSet.getString("createdBy"));
                customer.setLastUpdateBy(resultSet.getString("lastUpdateBy"));

                Customers.add(customer);
                System.out.println(Customers.get(i).getCustomerName());
                i++;
            }

        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return Customers;
    }
</code>```

Customer Class

import Utils.DataTransferObject;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import javafx.beans.property.IntegerProperty;

public class Customer implements DataTransferObject {
    private int customerId;
    private String customerName; //varchar 45
    private int addressId;
    private int active; // tiny int 1
    private LocalDateTime createDate;
    private LocalDateTime  lastUpdate;
    private String createdBy;
    private String lastUpdateBy;

    @Override
    public long getId() {
        return customerId;
    }

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public int getAddressId() {
        return addressId;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }

    public int getActive() {
        return active;
    }

    public void setActive(int active) {
        this.active = active;
    }

    public LocalDateTime getCreateDate() {
        return createDate;
    }

    public void setCreateDate(LocalDateTime createDate) {
        this.createDate = createDate;
    }

    public void setCreateDate(Timestamp createDate) {

        this.createDate = createDate.toLocalDateTime();

    }

    public LocalDateTime getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(LocalDateTime lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public void setLastUpdate(Timestamp lastUpdate) {
        this.lastUpdate = lastUpdate.toLocalDateTime();
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public String getLastUpdateBy() {
        return lastUpdateBy;
    }

    public void setLastUpdateBy(String lastUpdateBy) {
        this.lastUpdateBy = lastUpdateBy;
    }

}

```

答:
Your CustomerDAO.findAll() method repeatedly adds the same Customer instance to the table (changing the data in that single object every time). Consequently, the table contains multiple references to the same object.

The memory picture looks like:

Since there's only one Customer object, there's only one customerId, one customerName, etc, and each element of the list refers to the same value.

Instead, create a new Customer every time, and add it to the list. Then the memory picture looks like:

```<code>public ObservableList<Customer> findAll() {
    ObservableList<Customer> customers = FXCollections.observableArrayList();

    try(PreparedStatement statement = this.connection.prepareStatement(GET_ALL)){

        ResultSet resultSet = statement.executeQuery();
        int i =0;
        while(resultSet.next()){

            // This line moved inside the loop, to create a new
            // object on each iteration:
            Customer customer = new Customer();

            customer.setCustomerId(resultSet.getInt("customerId"));
            customer.setCustomerName(resultSet.getString("customerName"));
            customer.setAddressId(resultSet.getInt("addressId"));
            customer.setActive(resultSet.getInt("active"));
            customer.setCreateDate(resultSet.getTimestamp("createDate"));
            customer.setLastUpdate(resultSet.getTimestamp("lastUpdate"));
            customer.setCreatedBy(resultSet.getString("createdBy"));
            customer.setLastUpdateBy(resultSet.getString("lastUpdateBy"));

            customers.add(customer);
            System.out.println(customers.get(i).getCustomerName());
            i++;
        }

    }catch(SQLException e){
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return customers;
}
</code>```

Body:
My code should load a customer tableview in javafx via loadCusotmerTable() from MYSQL database with JDBC through the CustomerDOA.findAll() method. The findAll() method returns an ObservableList that should display the customers.

The Table output is currently displaying the correct number of rows for each customer in the Observable list, but it only displays the data from the last entry in the ObservableList. Is there something missing in my code to load the ObservableList<Customer> Customers correctly?

loadCustomerTable

package Controller;

import Model.Customer;
import Model.DAO.CustomerDAO;
import Model.DAO.UserDAO;
import Model.DBConnection;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

public class CustomerViewController implements Initializable {

    @FXML private TextField TextFieldCustomerID;
    @FXML private TextField TextFieldCustomerName;

    @FXML private Button ButtonGoBack;
    @FXML private Button ButtonAddModify;
    @FXML private Button ButtonRemove;
    @FXML private Button ButtonCancel;

    @FXML private MenuButton MenuButtonAddress;

    @FXML private MenuButton MenuButtonActive;
    @FXML private MenuItem MenuActiveItemActive;
    @FXML private MenuItem MenuActiveItemInactive;

    @FXML private TableView<Customer> TableViewCustomer;
    @FXML private TableColumn<Customer, String> TableCustomerColumnCustomerID;
    @FXML private TableColumn<Customer, String> TableCustomerColumnCustomerName;
    @FXML private TableColumn<Customer, String> TableCustomerColumnAddress;
    @FXML private TableColumn<Customer, String> TableCustomerColumnActive;

    private int addressId = 1;
    private int Active = 1;
    private int userId = 1;

    private boolean isCustomerSelected = true;
    private ObservableList<Customer> Customers = FXCollections.observableArrayList();

    // .......

    public void loadCustomerTable(){

        CustomerDAO customerDAO = new CustomerDAO(DBConnection.getConnection());
        ObservableList<Customer> Customers = customerDAO.findAll();

        TableCustomerColumnCustomerID.setCellValueFactory(new PropertyValueFactory<>("customerId"));
        TableCustomerColumnCustomerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
        TableCustomerColumnAddress.setCellValueFactory(new PropertyValueFactory<>("addressId"));
        TableCustomerColumnActive.setCellValueFactory(new PropertyValueFactory<>("active"));

        TableViewCustomer.setItems(Customers);
    }

CustomerDAO.findAll()

 public ObservableList<Customer> findAll() {
        ObservableList<Customer> Customers = FXCollections.observableArrayList();
        Customer customer = new Customer();

        try(PreparedStatement statement = this.connection.prepareStatement(GET_ALL)){

            ResultSet resultSet = statement.executeQuery();
            int i =0;
            while(resultSet.next()){

                customer.setCustomerId(resultSet.getInt("customerId"));
                customer.setCustomerName(resultSet.getString("customerName"));
                customer.setAddressId(resultSet.getInt("addressId"));
                customer.setActive(resultSet.getInt("active"));
                customer.setCreateDate(resultSet.getTimestamp("createDate"));
                customer.setLastUpdate(resultSet.getTimestamp("lastUpdate"));
                customer.setCreatedBy(resultSet.getString("createdBy"));
                customer.setLastUpdateBy(resultSet.getString("lastUpdateBy"));

                Customers.add(customer);
                System.out.println(Customers.get(i).getCustomerName());
                i++;
            }

        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return Customers;
    }

Customer Class

import Utils.DataTransferObject;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import javafx.beans.property.IntegerProperty;

public class Customer implements DataTransferObject {
    private int customerId;
    private String customerName; //varchar 45
    private int addressId;
    private int active; // tiny int 1
    private LocalDateTime createDate;
    private LocalDateTime  lastUpdate;
    private String createdBy;
    private String lastUpdateBy;

    @Override
    public long getId() {
        return customerId;
    }

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public int getAddressId() {
        return addressId;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }

    public int getActive() {
        return active;
    }

    public void setActive(int active) {
        this.active = active;
    }

    public LocalDateTime getCreateDate() {
        return createDate;
    }

    public void setCreateDate(LocalDateTime createDate) {
        this.createDate = createDate;
    }

    public void setCreateDate(Timestamp createDate) {

        this.createDate = createDate.toLocalDateTime();

    }

    public LocalDateTime getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(LocalDateTime lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public void setLastUpdate(Timestamp lastUpdate) {
        this.lastUpdate = lastUpdate.toLocalDateTime();
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public String getLastUpdateBy() {
        return lastUpdateBy;
    }

    public void setLastUpdateBy(String lastUpdateBy) {
        this.lastUpdateBy = lastUpdateBy;
    }

}

Body:
Your CustomerDAO.findAll() method repeatedly adds the same Customer instance to the table (changing the data in that single object every time). Consequently, the table contains multiple references to the same object.

The memory picture looks like:

Since there's only one Customer object, there's only one customerId, one customerName, etc, and each element of the list refers to the same value.

Instead, create a new Customer every time, and add it to the list. Then the memory picture looks like:

public ObservableList<Customer> findAll() {
    ObservableList<Customer> customers = FXCollections.observableArrayList();

    try(PreparedStatement statement = this.connection.prepareStatement(GET_ALL)){

        ResultSet resultSet = statement.executeQuery();
        int i =0;
        while(resultSet.next()){

            // This line moved inside the loop, to create a new
            // object on each iteration:
            Customer customer = new Customer();

            customer.setCustomerId(resultSet.getInt("customerId"));
            customer.setCustomerName(resultSet.getString("customerName"));
            customer.setAddressId(resultSet.getInt("addressId"));
            customer.setActive(resultSet.getInt("active"));
            customer.setCreateDate(resultSet.getTimestamp("createDate"));
            customer.setLastUpdate(resultSet.getTimestamp("lastUpdate"));
            customer.setCreatedBy(resultSet.getString("createdBy"));
            customer.setLastUpdateBy(resultSet.getString("lastUpdateBy"));

            customers.add(customer);
            System.out.println(customers.get(i).getCustomerName());
            i++;
        }

    }catch(SQLException e){
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return customers;
}


来源: stackexchange

问:
How do I check if an element is hidden in jQuery?
How do I toggle the visibility of an element using  .hide(), .show(), or .toggle()?

How do I test if an element is visible or hidden?

答:
Extended function for checking if element is visible, display none, or even the opacity level

It returns false if the element is not visible.

```<code>function checkVisible(e) {
    if (!(e instanceof Element)) throw Error('not an Element');
    const elementStyle = getComputedStyle(e);
    if (elementStyle.display === 'none' || elementStyle.visibility !== 'visible' || elementStyle.opacity < 0.1) return false;
    if (e.offsetWidth + e.offsetHeight + e.getBoundingClientRect().height +
        e.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: e.getBoundingClientRect().left + e.offsetWidth / 2,
        y: e.getBoundingClientRect().top + e.offsetHeight / 2
    };
    if (elemCenter.x < 0 || elemCenter.y < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === e) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}
</code>```

OwnerDisplayName: Toytown Mafia

ContentLicense: CC BY-SA 4.0

Body:
Extended function for checking if element is visible, display none, or even the opacity level

It returns false if the element is not visible.

function checkVisible(e) {
    if (!(e instanceof Element)) throw Error('not an Element');
    const elementStyle = getComputedStyle(e);
    if (elementStyle.display === 'none' || elementStyle.visibility !== 'visible' || elementStyle.opacity < 0.1) return false;
    if (e.offsetWidth + e.offsetHeight + e.getBoundingClientRect().height +
        e.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: e.getBoundingClientRect().left + e.offsetWidth / 2,
        y: e.getBoundingClientRect().top + e.offsetHeight / 2
    };
    if (elemCenter.x < 0 || elemCenter.y < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === e) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}


问:
css and javascript under functions.php not working from WordPress

// calling styles

function calling_resources(){

// Slider for css

```<code>wp_enqueue_style( 'css', get_template_directory_uri() . './assets/css/flex-slider.css', '', '1.0.0');
</code>```

// Fontawsome css for icons

```<code>wp_enqueue_style( 'css', get_template_directory_uri() . './assets/css/fontawesome.css', '', '1.0.0');
</code>```

// Bootstrap for styling layouts

```<code>wp_enqueue_style( 'css', get_template_directory_uri() . './vendor/bootstrap/css/bootstrap.css', '', '1.0.0');

wp_enqueue_style( 'css', get_template_directory_uri() . './vendor/bootstrap/css/bootstrap.min.css', '', '1.0.0');
</code>```

// Core style.css

```<code>wp_enqueue_style( 'style', get_stylesheet_uri());
</code>```

// Bootstrap core JavaScript

```<code>wp_enqueue_script( 'script', get_template_directory_uri() , '/vendor/jquery/jquery.min.js', array ( 'jquery'), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/vendor/bootstrap/js/bootstrap.bundle.min.js', array ( ), 1.0, true);
</code>```

// Additional Scripts

```<code>wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/custom.js', array ( ), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/owl.js', array ( ), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/slick.js', array ( ), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/accordions.js', array ( ), 1.0, true);
</code>```

}
add_action('wp_enqueue_scripts', 'calling_resources');

答: Are you sure your getting the right URI? The wordpress funtions state that the passed URI parameter is relative to the wordpress root directory.</p>

Body:
// calling styles

function calling_resources(){

// Slider for css

wp_enqueue_style( 'css', get_template_directory_uri() . './assets/css/flex-slider.css', '', '1.0.0');

// Fontawsome css for icons

wp_enqueue_style( 'css', get_template_directory_uri() . './assets/css/fontawesome.css', '', '1.0.0');

// Bootstrap for styling layouts

wp_enqueue_style( 'css', get_template_directory_uri() . './vendor/bootstrap/css/bootstrap.css', '', '1.0.0');

wp_enqueue_style( 'css', get_template_directory_uri() . './vendor/bootstrap/css/bootstrap.min.css', '', '1.0.0');

// Core style.css

wp_enqueue_style( 'style', get_stylesheet_uri());

// Bootstrap core JavaScript

wp_enqueue_script( 'script', get_template_directory_uri() , '/vendor/jquery/jquery.min.js', array ( 'jquery'), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/vendor/bootstrap/js/bootstrap.bundle.min.js', array ( ), 1.0, true);

// Additional Scripts

wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/custom.js', array ( ), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/owl.js', array ( ), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/slick.js', array ( ), 1.0, true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/assets/js/accordions.js', array ( ), 1.0, true);

}
add_action('wp_enqueue_scripts', 'calling_resources');


问:
Maximum Pair Product strange results
I have been trying to learn C++ from a C# background, and I am running in to a very weird mistake in my Maximum Pair Product method.

The method works as expected with small numbers. For products of large numbers it produces a strange rounding and outputs the incorrect output.

```<code>int64_t Testing::MaximumPairProductFast(const std::vector<int>& numbers)
{

    int64_t largestIntA = 0;

    int64_t largestIntB = 0;

    for (int  i = 0; i < numbers.size(); i++)
    {
        // find first largest number
        if (numbers[i] > largestIntA) largestIntA =  numbers[i];
    }

    for (int i = 0; i < numbers.size(); i++)
    {
        //find second largest number
        if (numbers[i] > largestIntB && numbers[i]!= largestIntA) largestIntB = numbers[i];
    }

    return  largestIntA * largestIntB;

}
</code>```

The main program

```<code>int main()
{

    Testing ch;

    std::vector<int> test{ 100000,90000 };

    int result= ch.MaximumPairProductFast(test);

    std::cout << result << "\n";

}
</code>```

The output of the computation will be 410065408 instead of 9000000000 which is the correct answer

The weird thing is when I try to print this:

```<code>std::cout << (int64_t) 100000 * 90000 << "\n";
</code>```

It does give the correct result 9000000000.

But if I don't cast it to int64_t :

```<code>std::cout <<  100000 * 90000 << "\n";
</code>```

The result is 410065408, which is exactly the output from my method even though I have ensured to return an int64_t type.

I have also tried this, but the outcome is the same:

```<code>int64_t Test::MaximumPairProductFast(const std::vector<int>& numbers)
{

    int64_t largestIntA = 0;

    int64_t largestIntB = 0;

    for (int  i = 0; i < numbers.size(); i++)
    {
        // find first largest number
        if ((int64_t) numbers[i] > largestIntA) largestIntA = (int64_t) numbers[i];
    }

    for (int i = 0; i < numbers.size(); i++)
    {
        //find second largest number
        if ((int64_t) numbers[i] > largestIntB && (int64_t) numbers[i]!= largestIntA) largestIntB = (int64_t) numbers[i];
    }

    return  largestIntA * largestIntB;

}
</code>```

Am I missing an obvious detail?

答:
On your system int is a 32-bit integer. int64_t is 64-bit integer. The problem in your code is you are multiplying two 32-bit ints so you're getting a 32-bit int result. Your answer is overflowing. When you explicitly cast it to int64_t, the operands are now 64-bit ints and you're getting a 64-bit int result which can hold the large value and not overflow.

I'll suggest you either:

use std::vector<int64_t> instead of std::vector<int>

If you're worried about space, do as you did, explicitely cast it to 64-bit int and then multiply

Title: Maximum Pair Product strange results

Body:
I have been trying to learn C++ from a C# background, and I am running in to a very weird mistake in my Maximum Pair Product method.

The method works as expected with small numbers. For products of large numbers it produces a strange rounding and outputs the incorrect output.

int64_t Testing::MaximumPairProductFast(const std::vector<int>& numbers)
{

    int64_t largestIntA = 0;

    int64_t largestIntB = 0;

    for (int  i = 0; i < numbers.size(); i++)
    {
        // find first largest number
        if (numbers[i] > largestIntA) largestIntA =  numbers[i];
    }

    for (int i = 0; i < numbers.size(); i++)
    {
        //find second largest number
        if (numbers[i] > largestIntB && numbers[i]!= largestIntA) largestIntB = numbers[i];
    }

    return  largestIntA * largestIntB;

}

The main program

int main()
{

    Testing ch;

    std::vector<int> test{ 100000,90000 };

    int result= ch.MaximumPairProductFast(test);

    std::cout << result << "\n";

}

The output of the computation will be 410065408 instead of 9000000000 which is the correct answer

The weird thing is when I try to print this:

std::cout << (int64_t) 100000 * 90000 << "\n";

It does give the correct result 9000000000.

But if I don't cast it to int64_t :

std::cout <<  100000 * 90000 << "\n";

The result is 410065408, which is exactly the output from my method even though I have ensured to return an int64_t type.

I have also tried this, but the outcome is the same:

int64_t Test::MaximumPairProductFast(const std::vector<int>& numbers)
{

    int64_t largestIntA = 0;

    int64_t largestIntB = 0;

    for (int  i = 0; i < numbers.size(); i++)
    {
        // find first largest number
        if ((int64_t) numbers[i] > largestIntA) largestIntA = (int64_t) numbers[i];
    }

    for (int i = 0; i < numbers.size(); i++)
    {
        //find second largest number
        if ((int64_t) numbers[i] > largestIntB && (int64_t) numbers[i]!= largestIntA) largestIntB = (int64_t) numbers[i];
    }

    return  largestIntA * largestIntB;

}

Am I missing an obvious detail?


问:
Removing first three elements of 2d array C++
So here's my problem.. I have a 2d array of 2 char strings.

```<code>9D 5C 6S 9D KS 4S 9D
         9S
</code>```

If 3 found I need to delete the first 3 based on the first char.
card
My problem is I segfault almost anything i do...
pool is the 2d vector

```<code>        selection = "9S";
        while(col != GameBoard::pool.size()  ){
            while(GameBoard::pool[col][0].at(0) == selection.at(0) || cardsRem!=0){
                if(GameBoard::pool[col].size() == 1){
                    GameBoard::pool.erase(GameBoard::pool.begin() + col);
                    cardsRem--;
                }
                else{
                    GameBoard::pool[col].pop_back();
                    cardsRem--;
                }
            }
            if(GameBoard::pool[col][0].at(0) != selection.at(0)){
                col++;
            }
        }
</code>```

I've tried a series of for loops etc, and no luck! Any thoughts would save my sanity!

So I've tried to pull out a code segment to replicate it.  But I can't...
If I run my whole program in a loop it will eventually throw a segfault. If I run that exact code in the same circumstance it doesn't... I'm trying to figure out what I'm missing. I'll get back in if I figure out exactly where my issue is..

So in the end the issue is not my code itself, i've got memory leaks or something somewhere that are adding up to eventually crash my program... That tends to be in the same method each time I guess.

答:
So for anyone else in the future who comes across this...
The problem is I was deleting an element in the array in a loop, with the conditional stop was it's size.  The size is set before hand, and while it was accounted for in the code it still left open the possibility for while(array.size() ) which would be locked in at 8 in the loop be treated as 6 in the code.

The solution was to save the location in the vector to delete and then delete them outside of the loop.  I imagine there is a better, more technical answer to this, but it works as intended now!

```<code>    for (double col = 0; col < size; ++col)
    {
        if(GameBoard::pool[col][0].at(0) == selection.at(0)){
                while(GameBoard::pool[col][0].at(0) == selection.at(0) && cardsRem !=0){
                    if( GameBoard::pool[col].size() > 1 ){
                        GameBoard::pool[col].pop_back();
                        cardsRem--;
                    }
                    if(GameBoard::pool[col].size() <2){
                        toDel.insert ( toDel.begin() , col );
                        //GameBoard::pool.erase(GameBoard::pool.begin() + col);
                        cardsRem--;
                        size--;
                    }
                }
        }
    }
    for(int i = 0; i< toDel.size(); i++){
        GameBoard::pool.erase(GameBoard::pool.begin() + toDel[i]);
    }
</code>```

Body:
So here's my problem.. I have a 2d array of 2 char strings.

9D 5C 6S 9D KS 4S 9D
         9S

If 3 found I need to delete the first 3 based on the first char.
card
My problem is I segfault almost anything i do...
pool is the 2d vector

        selection = "9S";
        while(col != GameBoard::pool.size()  ){
            while(GameBoard::pool[col][0].at(0) == selection.at(0) || cardsRem!=0){
                if(GameBoard::pool[col].size() == 1){
                    GameBoard::pool.erase(GameBoard::pool.begin() + col);
                    cardsRem--;
                }
                else{
                    GameBoard::pool[col].pop_back();
                    cardsRem--;
                }
            }
            if(GameBoard::pool[col][0].at(0) != selection.at(0)){
                col++;
            }
        }

I've tried a series of for loops etc, and no luck! Any thoughts would save my sanity!

So I've tried to pull out a code segment to replicate it.  But I can't...
If I run my whole program in a loop it will eventually throw a segfault. If I run that exact code in the same circumstance it doesn't... I'm trying to figure out what I'm missing. I'll get back in if I figure out exactly where my issue is..

So in the end the issue is not my code itself, i've got memory leaks or something somewhere that are adding up to eventually crash my program... That tends to be in the same method each time I guess.

Body:
So for anyone else in the future who comes across this...
The problem is I was deleting an element in the array in a loop, with the conditional stop was it's size.  The size is set before hand, and while it was accounted for in the code it still left open the possibility for while(array.size() ) which would be locked in at 8 in the loop be treated as 6 in the code.

The solution was to save the location in the vector to delete and then delete them outside of the loop.  I imagine there is a better, more technical answer to this, but it works as intended now!

    for (double col = 0; col < size; ++col)
    {
        if(GameBoard::pool[col][0].at(0) == selection.at(0)){
                while(GameBoard::pool[col][0].at(0) == selection.at(0) && cardsRem !=0){
                    if( GameBoard::pool[col].size() > 1 ){
                        GameBoard::pool[col].pop_back();
                        cardsRem--;
                    }
                    if(GameBoard::pool[col].size() <2){
                        toDel.insert ( toDel.begin() , col );
                        //GameBoard::pool.erase(GameBoard::pool.begin() + col);
                        cardsRem--;
                        size--;
                    }
                }
        }
    }
    for(int i = 0; i< toDel.size(); i++){
        GameBoard::pool.erase(GameBoard::pool.begin() + toDel[i]);
    }


问:
How to print file contents with filename before each line?
I have several files, say, a,b,c, I would like to something like

```<code> > cat a b c
</code>```

but with "a,"  in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:

```<code>#!/bin/env python

files = 'a b c'

all_lines = []
for f in files.split():
  lines = open(f, 'r').readlines()
  for line in lines:
    all_lines.append(f + ',' + line.strip())

fout = open('out.csv', 'w')
fout.write('\n'.join(all_lines))
fout.close()
</code>```

but I would prefer to do it in the command line, combining some simple commands with the pipe | operator.

Is there a easy way of accomplishing this?

Thanks.

答:
You can also use the awk(1) program :)

```<code>$ awk 'BEGIN { OFS=","; } {print FILENAME , $0;}' *
a,hello
b,
b,
b,world
c,from space
d,,flubber
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have several files, say, a,b,c, I would like to something like

 > cat a b c

but with "a,"  in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:

#!/bin/env python

files = 'a b c'

all_lines = []
for f in files.split():
  lines = open(f, 'r').readlines()
  for line in lines:
    all_lines.append(f + ',' + line.strip())

fout = open('out.csv', 'w')
fout.write('\n'.join(all_lines))
fout.close()

but I would prefer to do it in the command line, combining some simple commands with the pipe | operator.

Is there a easy way of accomplishing this?

Thanks.

Body:
You can also use the awk(1) program :)

$ awk 'BEGIN { OFS=","; } {print FILENAME , $0;}' *
a,hello
b,
b,
b,world
c,from space
d,,flubber


问:
Losing \n In String Through GET
When I pass a \n in a string to this code through a link, it is getting lost in the Home and Splash portion of the conditional but if I hard-code the $String value to include it, it works as it should

For example using $String=$GETvalue; when there is a \n in the $GETvalue, will show Some text\nMore text but if I use $String="Some text\nMore text"; it shows:

```<code>Some text
More text
</code>```

as it should. How can I maintain the \n through a GET?

```<code><?php
$FontPath = "/internals/truetype/";
$FontName = "vineritc.ttf";
$EnableShadow=TRUE;
$CenterAlign=TRUE;

$GETkey = key($_GET);
$GETvalue = current($_GET);

switch ($GETkey):
    case "AuthorID":
        $Year = date("Y");
        $AuthorName = DBLookup("SELECT `AuthorName` FROM authorbiographies WHERE `ID`=$GETvalue",$siteDB);
        $String = "Copyright © $Year\n$AuthorName";
        $FontSize = 10;
        $Angle = 0;
    break;
    case "CategoryID":
        $String = DBLookup("SELECT `CategoryName` FROM categories WHERE `ID`=$GETvalue",$siteDB);
        $FontSize = 15;
        $Angle = 0;
    break;
    case "Home":
        $String = $GETvalue;
        $FontSize = 28;
        $Angle = 0;
    break;
    case "Splash":
        $String = $GETvalue;
        $FontSize = 38;
        $Angle = 0;
    break;
endswitch;

$TextImage = textimage();

header("Pragma: no-cache");
header('Content-Type: image/png');

echo $TextImage;
?>
</code>```

This code is called with:

```<code><img src="/viewers/show.php?Splash=Some+text\nMore+text!">
</code>```

答:
Problem solved! I was sending the string as (shortened here without alt or title:

```<code><img src="/viewers/show.php?Splash=Some+text\nMore+text!">
</code>```

when it should have been sent as:

```<code><img src="/viewers/show.php?Splash=<?=urlencode("Some text\nMore text!");?>">
</code>```

No decoding is apparently needed on the receiving end. Odd, I snapped awake in the middle of the night with the answer after fighting it for so long! It was sending it urlencoded() originally, then someone here in another area told me it was unnecessary so I removed the urlencode() from it, then forgot I had done so.

Title: Losing \n In String Through GET

Body:
When I pass a \n in a string to this code through a link, it is getting lost in the Home and Splash portion of the conditional but if I hard-code the $String value to include it, it works as it should

For example using $String=$GETvalue; when there is a \n in the $GETvalue, will show Some text\nMore text but if I use $String="Some text\nMore text"; it shows:

Some text
More text

as it should. How can I maintain the \n through a GET?

<?php
$FontPath = "/internals/truetype/";
$FontName = "vineritc.ttf";
$EnableShadow=TRUE;
$CenterAlign=TRUE;

$GETkey = key($_GET);
$GETvalue = current($_GET);

switch ($GETkey):
    case "AuthorID":
        $Year = date("Y");
        $AuthorName = DBLookup("SELECT `AuthorName` FROM authorbiographies WHERE `ID`=$GETvalue",$siteDB);
        $String = "Copyright © $Year\n$AuthorName";
        $FontSize = 10;
        $Angle = 0;
    break;
    case "CategoryID":
        $String = DBLookup("SELECT `CategoryName` FROM categories WHERE `ID`=$GETvalue",$siteDB);
        $FontSize = 15;
        $Angle = 0;
    break;
    case "Home":
        $String = $GETvalue;
        $FontSize = 28;
        $Angle = 0;
    break;
    case "Splash":
        $String = $GETvalue;
        $FontSize = 38;
        $Angle = 0;
    break;
endswitch;

$TextImage = textimage();

header("Pragma: no-cache");
header('Content-Type: image/png');

echo $TextImage;
?>

This code is called with:

Body:
Problem solved! I was sending the string as (shortened here without alt or title:

<img src="/viewers/show.php?Splash=Some+text\nMore+text!">

when it should have been sent as:

<img src="/viewers/show.php?Splash=<?=urlencode("Some text\nMore text!");?>">

No decoding is apparently needed on the receiving end. Odd, I snapped awake in the middle of the night with the answer after fighting it for so long! It was sending it urlencoded() originally, then someone here in another area told me it was unnecessary so I removed the urlencode() from it, then forgot I had done so.


问:
Error TS2554 Angular Project Expected 4 arguments but got 3
ng serve

then there was an error, was working fine previously. But after updating @angular/cli there was a problem with the ng serve.

ERROR in src/app/pages/products/products.component.html:17:32 - error
  TS2554: Expected 4 arguments, but got 3.

17         *ngFor="let product of productList | find: 'name':
  searchName | category: 'categoryID': searchCat">
                                    ~~~~~~~~~~~~~

src/app/pages/products/products.component.ts:10:16
      10   templateUrl: './products.component.html',
                        ~~~~~~~~~
      Error occurs in the template of component ProductsComponent.

This is the product.component.html

```<code><h1 class=text-center>Products</h1>
<div class='container text-center'>
    <select [(ngModel)]="searchCat">
        <option value='0'>
            No Filter
        </option>
        <option *ngFor="let x of categoryList" value="{{x.categoryID}}">
            {{x.name}}
        </option>
    </select>

    Search: <input type="text" [(ngModel)]="searchName">
</div>
<hr>
<div class="card-deck">
    <div class="col-sm-6 col-lg-4 mb-3"
        *ngFor="let product of productList | find: 'name': searchName | category: 'categoryID': searchCat">
        <img class="card-img-top" height=500px src={{product.imageURL}} alt="Card image cap">
        <div class="card-body"> {{product.name}} <br> {{product.brand}}</div>
        <div class="card-action"><button (click)="onViewDetail(product.productID)" class="btn btn-success">View
                Detail</button></div>
    </div>
</div>
</code>```

This is the product.component.ts

```<code>
import { Component, OnInit, Input } from '@angular/core';
import { CategoryService } from "../../services/category.service";
import { ProductService } from "../../services/product.service";
import { Product } from "../../models/product.model"
import { Router } from '@angular/router';
import { Category } from '../../models/category.model'

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
  providers: [CategoryService, ProductService]
})
export class ProductsComponent implements OnInit {

  searchName: string = "";

  productList: Product[] = [];

  categoryList: Category[] = [];

  searchCat: number = 0;

  constructor(public categoryService: CategoryService, public productService: ProductService, public router: Router) { }

  ngOnInit() {

    this.productList = this.productService.getProducts();
    this.categoryList = this.categoryService.getCategories();
    console.log(this.productList)
    console.log(this.categoryList)
  }
  onViewDetail(productID: number) {
    this.router.navigate(['/product-detail', productID])
  }

}

</code>```

find pipe

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'find'
})
export class FindPipe implements PipeTransform {
  //filter the result by sth
  transform(value: any, propertyName: string, searchStr: string, propertyContact: string): any {

    if (value.length === 0 || searchStr.trim().length === 0) {
      return value;
    }

    //matching
    let resultArr = [];

    searchStr = searchStr.toLowerCase()

    for (let elem of value) {
      const str = elem[propertyName].toLowerCase();

      if (str.indexOf(searchStr) != -1) {
        //found matching
        resultArr.push(elem);
      }

    }

    return resultArr;

  }

}
</code>```

category pipe

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'category'
})
export class CategoryPipe implements PipeTransform {

  transform(value: string, propertyName: string, categoryID: number): any {
    let resultArr = [];
    if (categoryID == 0) {
      return value;
    }
    else {
      for (let x of value) {
        if (x[propertyName] == categoryID) {
          resultArr.push(x)
        }

      }
      return resultArr;
    }

  }

}
</code>```

答:
You forgot to send "property Contact" param to "find" pipe, "find" transform function looks forward for 4 params (product and 3 args).</p>

```<code>  *ngFor="let product of productList | find: 'name': searchName: **"propertyContact**" | category: 'categoryID': searchCat">
</code>```

Body:
ng serve

then there was an error, was working fine previously. But after updating @angular/cli there was a problem with the ng serve.

ERROR in src/app/pages/products/products.component.html:17:32 - error
  TS2554: Expected 4 arguments, but got 3.

17         *ngFor="let product of productList | find: 'name':
  searchName | category: 'categoryID': searchCat">
                                    ~~~~~~~~~~~~~

src/app/pages/products/products.component.ts:10:16
      10   templateUrl: './products.component.html',
                        ~~~~~~~~~
      Error occurs in the template of component ProductsComponent.

This is the product.component.html

Products

    <select [(ngModel)]="searchCat">
        <option value='0'>
            No Filter
        </option>
        <option *ngFor="let x of categoryList" value="{{x.categoryID}}">
            {{x.name}}
        </option>
    </select>

    Search: <input type="text" [(ngModel)]="searchName">

 {{product.name}}
 {{product.brand}}

<button (click)="onViewDetail(product.productID)" class="btn btn-success">View
                Detail</button>

This is the product.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { CategoryService } from "../../services/category.service";
import { ProductService } from "../../services/product.service";
import { Product } from "../../models/product.model"
import { Router } from '@angular/router';
import { Category } from '../../models/category.model'

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
  providers: [CategoryService, ProductService]
})
export class ProductsComponent implements OnInit {

  searchName: string = "";

  productList: Product[] = [];

  categoryList: Category[] = [];

  searchCat: number = 0;

  constructor(public categoryService: CategoryService, public productService: ProductService, public router: Router) { }

  ngOnInit() {

    this.productList = this.productService.getProducts();
    this.categoryList = this.categoryService.getCategories();
    console.log(this.productList)
    console.log(this.categoryList)
  }
  onViewDetail(productID: number) {
    this.router.navigate(['/product-detail', productID])
  }

}

find pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'find'
})
export class FindPipe implements PipeTransform {
  //filter the result by sth
  transform(value: any, propertyName: string, searchStr: string, propertyContact: string): any {

    if (value.length === 0 || searchStr.trim().length === 0) {
      return value;
    }

    //matching
    let resultArr = [];

    searchStr = searchStr.toLowerCase()

    for (let elem of value) {
      const str = elem[propertyName].toLowerCase();

      if (str.indexOf(searchStr) != -1) {
        //found matching
        resultArr.push(elem);
      }

    }

    return resultArr;

  }

}

category pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'category'
})
export class CategoryPipe implements PipeTransform {

  transform(value: string, propertyName: string, categoryID: number): any {
    let resultArr = [];
    if (categoryID == 0) {
      return value;
    }
    else {
      for (let x of value) {
        if (x[propertyName] == categoryID) {
          resultArr.push(x)
        }

      }
      return resultArr;
    }

  }

}

Body:
You forgot to send "property Contact" param to "find" pipe, "find" transform function looks forward for 4 params (product and 3 args).

  *ngFor="let product of productList | find: 'name': searchName: **"propertyContact**" | category: 'categoryID': searchCat">


问:
Is Byte Really The Minimum Addressable Unit?
Section 3.6 of C11 standard defines "byte" as "addressable unit of data storage ... to hold ... character".

Section 1.7 of C++11 standard defines "byte" as "the fundamental storage unit in the C++ memory model ... to contain ... character".

Both definitions does not say that "byte" is the minimum addressable unit. Is this because standards intentionally want to abstract from a specific machine ? Can you provide a real example of machine where C/C++ compiler were decided to have "byte" longer/shorter than the minimum addressable unit ?

答:
A byte is the smallest addressable unit in strictly conforming C code. Whether the machine on which the C implementation executes a program supports addressing smaller units is irrelevant to this; the C implementation must present a view in which bytes are the smallest addressable unit in strictly conforming C code.

A C implementation may support addressing smaller units as an extension, such as simply by defining the results of certain pointer operations that are otherwise undefined by the C standard.


问:
Subscript out of range when using Userform input workbook as reference
I have put together a userform for the user to select an open workbook - ideally would like to have this integrated with a script so that the script runs in reference to the workbook chosen.
However an out of range error presents when running the script:

```<code>
Private Sub Go_Click()

 If ComboBox1.ListIndex = -1 Then
        MsgBox "Please select a workbook name and try again"
        Exit Sub
    End If

    Dim wb As Workbook, copytest As Range, pastetest As Range

    Set wb = Workbooks(ComboBox1.List(ComboBox1.ListIndex))

   Set copytest = wb.Worksheets(2).Columns(6)
   Set pastetest = Workbooks("VBA Workbook.xlsx").Worksheets(1).Columns(1)
   copytest.Copy Destination:=pastetest

        '~~> Do what you want

Debug.Print

End Sub
</code>```

Combo box:

```<code>Private Sub UserForm_Initialize()

    Dim wkb As Workbook
    Me.Label1.Caption = "Please select the relevant workbook"
    With Me.ComboBox1
        '~~> Loop thorugh all open workbooks and add
        '~~> their name to the Combobox
        For Each wkb In Application.Workbooks
            .AddItem wkb.Name
        Next wkb
    End With
End Sub
</code>```

答:
.ListIndex returns a number that goes from 0 to ListCount - 1 (think of it as a Zero based array). So when you pass 0 for the 1st item (if that is what is selected) then Workbooks(0) will fail with the out of range error. Anything else will be off by one item in the list and the last one will never be able to be used.

Adjust your code accordingly (i.e. add 1 to .ListIndex). Hint: that is why -1 means nothing in the combobox is selected.

Generally, you would want to check if wb is not nothing. To be able to do that you'd wrap the assignment line wb = Workbooks(ComboBox1.List(ComboBox1.ListIndex)) with On Error Resume Next/On Error GoTo 0. Which will suspend the error that you got originally and let your code to continue so you can check If Not wb Is Nothing Then and proceed accordingly.

Having said all of that I would suggest you use meaningful names instead of Combobox1. Also, you didn't provide how you .Show your user form. Make sure that you are not using the default instance, and give your user form a meaningful name and the object that you set it to also to have a meaningful name. You will thank yourself later.

Body:
I have put together a userform for the user to select an open workbook - ideally would like to have this integrated with a script so that the script runs in reference to the workbook chosen.
However an out of range error presents when running the script:

Private Sub Go_Click()

 If ComboBox1.ListIndex = -1 Then
        MsgBox "Please select a workbook name and try again"
        Exit Sub
    End If

    Dim wb As Workbook, copytest As Range, pastetest As Range

    Set wb = Workbooks(ComboBox1.List(ComboBox1.ListIndex))

   Set copytest = wb.Worksheets(2).Columns(6)
   Set pastetest = Workbooks("VBA Workbook.xlsx").Worksheets(1).Columns(1)
   copytest.Copy Destination:=pastetest

        '~~> Do what you want

Debug.Print

End Sub

Combo box:

Private Sub UserForm_Initialize()

    Dim wkb As Workbook
    Me.Label1.Caption = "Please select the relevant workbook"
    With Me.ComboBox1
        '~~> Loop thorugh all open workbooks and add
        '~~> their name to the Combobox
        For Each wkb In Application.Workbooks
            .AddItem wkb.Name
        Next wkb
    End With
End Sub


问:
Trying to display JSON data, but JSON Parse Error
I am trying to display JSON data on my screen, the integer 4 to be exact.

But, I am receiving a JSON Parse Error.

I've posted and that works fine as in Webhooksite says it successfully posted. Also, it "gets" fine, but the data doesn't display.

```<code>// JSON Data

{
    "cheetosamount": 4,
    "cookiesvalue": 2
}
</code>```

```<code>export default class ChooseDeliveries extends Component {

  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: []
    }
  }
  componentDidMount(){
    this.handleGetRequest();
  }

  handleGetRequest() {
    fetch ('https://webhook.site/e61dd236-92d5-4b3b-882b-a50d6add6cd3',{
      method: 'GET',
    })
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: responseJson,
        isLoading: false,
      })
    })
    .catch(error => {
      console.error(error);
    });
  };

  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    } else {
      return(
        <View style={{flex: 1, paddingTop:20}}>
          <Text>
            {this.state.dataSource.cheetosamount}
          </Text>
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

答:
The code seems ok having a glimpse at it maybe try and wrap the response with a JSON.parse?? That would be </p>

<pre class="lang-js prettyprint-override"><code>...
this.setState({
  dataSource: JSON.parse(responseJson),   <-- HERE
  isLoading: false,
})
...
</code>```

Body:
I am trying to display JSON data on my screen, the integer 4 to be exact.

But, I am receiving a JSON Parse Error.

I've posted and that works fine as in Webhooksite says it successfully posted. Also, it "gets" fine, but the data doesn't display.

// JSON Data

{
    "cheetosamount": 4,
    "cookiesvalue": 2
}

export default class ChooseDeliveries extends Component {

  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: []
    }
  }
  componentDidMount(){
    this.handleGetRequest();
  }

  handleGetRequest() {
    fetch ('https://webhook.site/e61dd236-92d5-4b3b-882b-a50d6add6cd3',{
      method: 'GET',
    })
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: responseJson,
        isLoading: false,
      })
    })
    .catch(error => {
      console.error(error);
    });
  };

  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    } else {
      return(
        <View style={{flex: 1, paddingTop:20}}>
          <Text>
            {this.state.dataSource.cheetosamount}
          </Text>
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Body:
The code seems ok having a glimpse at it maybe try and wrap the response with a JSON.parse?? That would be

...
this.setState({
  dataSource: JSON.parse(responseJson),   <-- HERE
  isLoading: false,
})
...


问:
R - sql query stored as object name does not work with r dbGetquery
Need a little help with the following R code. I’ve got quite a number of data to load from a Microsoft sql database. I tried to do a few things to make the sql queries manageable.

1) Stored the query as object names with unique prefix
2) Using search to return a vector of the object names with unique prefix
3) using for loop to loop through the vector to load data <- this part didn’t work.

```<code>Library(odbc)
Library(tidyverse)
Library(stringer)

#setting up dB connection, odbc pkg
db<- DBI::dbConnect(odbc::odbc(),Driver =‘SQL Server’, Server=‘Server_name’, Database=‘Datbase name’, UID=‘User ID’, trusted_connection=‘yes’)

#defining the sql query
Sql_query1<-“select * from db1”
Sql_query2<-“select top 100 * from db2”

#the following is to store the sql query object name in a vector by searching for object names with prefix sql_
Sql_list <- ls()[str_detect(ls(),regex(“sql_”,ignore_case=TRUE))]

#This is the part where the code didn’t work
For (i in Sql_list){ i <- dbGetQuery(db, i)}
</code>```

The error I’ve got is “Error:  ‘Sql_query1’ nanodb.cpp:1587: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Could not find stored procedure ‘Sql_query1’

However, if i don’t use the loop, no error occurred! It may be feasible if I’ve only got 2 -3 queries to manage... unfortunately I’ve 20 of them!

```<code>dbGetquery(db,Sql_query1)
</code>```

Can anyone help? Thank you!

答:
@Rohits solution written down:

first part from your side is fine

```<code>#setting up dB connection, odbc pkg
db<- DBI::dbConnect(odbc::odbc(),Driver =‘SQL Server’, Server=‘Server_name’, Database=‘Datbase name’, UID=‘User ID’, trusted_connection=‘yes’)
</code>```

But then it would be more convenient to do something like this:

A more verbose version:

```<code>sqlqry_lst <- vector(mode = 'list', length = 2)#create a list to hold queries the in real life length = 20
names(sqlqry_lst) <- paste0('Sql_query', 1:2)#assign names to your list again jut use 1:20 here in your real life example
#put the SQL code into the list elements
sqlqry_lst['Sql_query1'] <- "select * from db1"
sqlqry_lst['Sql_query2'] <- "select top 100 * from db2"
#if you really want to use for loops
res <- vector(mode = 'list', length(sqlqry_lst))#result list
for (i in length(sqlqry_lst)) res[[i]] <- dbGetquery(db,sqlqry_lst[[i]])
</code>```

Or as a two liner, a bit more R stylish and imho elegant:

```<code>sqlqry_lst <- list(Sql_query1="select * from db1", Sql_query2="select top 100 * from db2")
res <- lapply(sqlqry_lst, FUN = dbGetQuery, conn=db)
</code>```

I suggest you mix and mingle the verbose eg for creating or more precisely for naming the query list and the short version for running the queries against the database as it suits u best.

Body:
Need a little help with the following R code. I’ve got quite a number of data to load from a Microsoft sql database. I tried to do a few things to make the sql queries manageable.

1) Stored the query as object names with unique prefix
2) Using search to return a vector of the object names with unique prefix
3) using for loop to loop through the vector to load data <- this part didn’t work.

Library(odbc)
Library(tidyverse)
Library(stringer)

#setting up dB connection, odbc pkg
db<- DBI::dbConnect(odbc::odbc(),Driver =‘SQL Server’, Server=‘Server_name’, Database=‘Datbase name’, UID=‘User ID’, trusted_connection=‘yes’)

#defining the sql query
Sql_query1<-“select * from db1”
Sql_query2<-“select top 100 * from db2”

#the following is to store the sql query object name in a vector by searching for object names with prefix sql_
Sql_list <- ls()[str_detect(ls(),regex(“sql_”,ignore_case=TRUE))]

#This is the part where the code didn’t work
For (i in Sql_list){ i <- dbGetQuery(db, i)}

The error I’ve got is “Error:  ‘Sql_query1’ nanodb.cpp:1587: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]Could not find stored procedure ‘Sql_query1’

However, if i don’t use the loop, no error occurred! It may be feasible if I’ve only got 2 -3 queries to manage... unfortunately I’ve 20 of them!

dbGetquery(db,Sql_query1)

Can anyone help? Thank you!

Body:
@Rohits solution written down:

first part from your side is fine

#setting up dB connection, odbc pkg
db<- DBI::dbConnect(odbc::odbc(),Driver =‘SQL Server’, Server=‘Server_name’, Database=‘Datbase name’, UID=‘User ID’, trusted_connection=‘yes’)

But then it would be more convenient to do something like this:

A more verbose version:

sqlqry_lst <- vector(mode = 'list', length = 2)#create a list to hold queries the in real life length = 20
names(sqlqry_lst) <- paste0('Sql_query', 1:2)#assign names to your list again jut use 1:20 here in your real life example
#put the SQL code into the list elements
sqlqry_lst['Sql_query1'] <- "select * from db1"
sqlqry_lst['Sql_query2'] <- "select top 100 * from db2"
#if you really want to use for loops
res <- vector(mode = 'list', length(sqlqry_lst))#result list
for (i in length(sqlqry_lst)) res[[i]] <- dbGetquery(db,sqlqry_lst[[i]])

Or as a two liner, a bit more R stylish and imho elegant:

sqlqry_lst <- list(Sql_query1="select * from db1", Sql_query2="select top 100 * from db2")
res <- lapply(sqlqry_lst, FUN = dbGetQuery, conn=db)

I suggest you mix and mingle the verbose eg for creating or more precisely for naming the query list and the short version for running the queries against the database as it suits u best.


问:
Specify the percentColWidth for datagrid column in action script
Tried

```<code>col.setStyle('percentWidth',20) //doesn't work

col.setStyle('percentWidth',0.2)//doesn't work
</code>```

&&

```<code>col.percentWidth //doesnt compile
</code>```

where col is one of the columns in a datagrid

Thanks.

答:
I'd ask you to tell us what "Doesn't work" means; but since percentageWidth is not a property on the DataGridColumn class, I suspect you mean you're seeing a compiler error?  </p>

<p>If you want to size the dataGrid columns using percentages you'll probably have to extend the DataGrid and write the column sizing code yourself.  </p>

Body:
Tried

col.setStyle('percentWidth',20) //doesn't work

col.setStyle('percentWidth',0.2)//doesn't work

&&

col.percentWidth //doesnt compile

where col is one of the columns in a datagrid

Thanks.

Body:
I'd ask you to tell us what "Doesn't work" means; but since percentageWidth is not a property on the DataGridColumn class, I suspect you mean you're seeing a compiler error?

If you want to size the dataGrid columns using percentages you'll probably have to extend the DataGrid and write the column sizing code yourself.


问:
Why does clang require a function to be declared before it's called in a template?
I have the following code example (available online at coliru):

#include <iostream>
#include <utility>

struct Bar {
    int a;
};

template <class T>
void print_arg(const T& arg) {
    std::cout << arg << std::endl;
}

std::ostream& operator<<(std::ostream& os, const Bar& b) {
    os << b.a;
    return os;
}

template <class T1, class T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& pair) {
    os << "Pair(" << pair.first << ',' << pair.second << ")";
    return os;
}

int main()
{
    auto bar = Bar{1};
    print_arg(bar);
    print_arg(std::make_pair(bar, bar));
    print_arg(std::make_pair(bar, 1));
    print_arg(std::make_pair(0, 1));
}
```

<p>The last line in the main function is what's giving me trouble. Compilation with g++ works just fine (with the exact same options as below), I launch the executable and it prints everything as expected. However, Clang++ gives me the following error:</p>

```$ clang++ -std=c++17 -O2 -Wall -Werror -Wpedantic main.cpp && ./a.out
main.cpp:10:15: error: call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup
    std::cout << arg << std::endl;
              ^
main.cpp:29:5: note: in instantiation of function template specialization 'print_arg<std::pair<int, int> >' requested here
    print_arg(std::make_pair(0, 1));
    ^
main.cpp:19:15: note: 'operator<<' should be declared prior to the call site
std::ostream& operator<<(std::ostream& os, const std::pair<T, T>& pair) {
              ^
1 error generated.
```

Furthermore, removing the last line (commenting it out) results in Clang++ compiling everything correctly. Which, as far as I can tell, means that std::pair<int, int> is qualitatively different from other parameter types.

My question is, why does g++ compile it eitherway? And more importantly, why does clang think it is ok to declare operator<<(ostream, pair<Bar, Bar>) later, but it's not ok for operator<<(ostream, pair<int, int>). Is it because the latter only includes standard and basic types?

To me the (somewhat) logical thing seems to be that defining functions only over standard/basic types is UB, but g++ silently ignores it and clang++ gives a weird-looking error message. However, that doesn't make a whole lot of sense to me and I can't find the relevant standard clause.

Note: I understand that moving the declaration up is what clang is asking for, but I don't understand why. I want to provide print_arg function in a separate header and allow the person that includes that header to specialize operator<< while using print_arg.

答:
The C++ standard says that unqualified names are looked up in two ways. According to Clang's documentation on language compatibility:

First, the compiler does unqualified lookup in the scope where the
  name was written. For a template, this means the lookup is done at the
  point where the template is defined, not where it's instantiated.

Second, if the name is called like a function, then the compiler also
  does argument-dependent lookup (ADL). Sometimes unqualified lookup can
  suppress ADL; In ADL, the compiler looks at the types of all the
  arguments to the call. When it finds a class type, it looks up the
  name in that class's namespace; the result is all the declarations it
  finds in those namespaces, plus the declarations from unqualified
  lookup. However, the compiler doesn't do ADL until it knows all the
  argument types.

There are two ways to fix this problem:

Make sure the function you want to call is declared before the template that might call it. This is the only option if none of its argument types contain classes. You can do this either by moving the template definition, or by moving the function definition, or by adding a forward declaration of the function before the template.

Move the function into the same namespace as one of its arguments so
that ADL applies.

↳ see basic.lookup.argdep and temp.dep.candidate

Body:
I have the following code example (available online at coliru):

#include <iostream>
#include <utility>

struct Bar {
    int a;
};

template <class T>
void print_arg(const T& arg) {
    std::cout << arg << std::endl;
}

std::ostream& operator<<(std::ostream& os, const Bar& b) {
    os << b.a;
    return os;
}

template <class T1, class T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& pair) {
    os << "Pair(" << pair.first << ',' << pair.second << ")";
    return os;
}

int main()
{
    auto bar = Bar{1};
    print_arg(bar);
    print_arg(std::make_pair(bar, bar));
    print_arg(std::make_pair(bar, 1));
    print_arg(std::make_pair(0, 1));
}

The last line in the main function is what's giving me trouble. Compilation with g++ works just fine (with the exact same options as below), I launch the executable and it prints everything as expected. However, Clang++ gives me the following error:

$ clang++ -std=c++17 -O2 -Wall -Werror -Wpedantic main.cpp && ./a.out
main.cpp:10:15: error: call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup
    std::cout << arg << std::endl;
              ^
main.cpp:29:5: note: in instantiation of function template specialization 'print_arg<std::pair<int, int> >' requested here
    print_arg(std::make_pair(0, 1));
    ^
main.cpp:19:15: note: 'operator<<' should be declared prior to the call site
std::ostream& operator<<(std::ostream& os, const std::pair<T, T>& pair) {
              ^
1 error generated.

Furthermore, removing the last line (commenting it out) results in Clang++ compiling everything correctly. Which, as far as I can tell, means that std::pair<int, int> is qualitatively different from other parameter types.

My question is, why does g++ compile it eitherway? And more importantly, why does clang think it is ok to declare operator<<(ostream, pair<Bar, Bar>) later, but it's not ok for operator<<(ostream, pair<int, int>). Is it because the latter only includes standard and basic types?

To me the (somewhat) logical thing seems to be that defining functions only over standard/basic types is UB, but g++ silently ignores it and clang++ gives a weird-looking error message. However, that doesn't make a whole lot of sense to me and I can't find the relevant standard clause.

Note: I understand that moving the declaration up is what clang is asking for, but I don't understand why. I want to provide print_arg function in a separate header and allow the person that includes that header to specialize operator<< while using print_arg.


答:
You are truncating your result from a int64_t to an int.  On a typical system these days, you'll truncate a 64 bit integer and store it in a 32 bit value.

If you compile with the warning level increased, the compiler will tell you about this problem.

The solution is to declare result with the proper type:

```<code>int64_t result = ch.MaximumPairProductFast(test);
</code>```

Or, just let the compiler use the correct type with auto:

```<code>auto result = ch.MaximumPairProductFast(test);
</code>```

In your second example, the constants 100000 and 90000 are integers, so the multiplication of them will be done as integers.  When you case one of the values to int64_t, the multiplication will be done with 64 bit ints.  This can also be expressed with 100000LL.

Title: Maximum Pair Product strange results

Body:
I have been trying to learn C++ from a C# background, and I am running in to a very weird mistake in my Maximum Pair Product method.

The method works as expected with small numbers. For products of large numbers it produces a strange rounding and outputs the incorrect output.

int64_t Testing::MaximumPairProductFast(const std::vector<int>& numbers)
{

    int64_t largestIntA = 0;

    int64_t largestIntB = 0;

    for (int  i = 0; i < numbers.size(); i++)
    {
        // find first largest number
        if (numbers[i] > largestIntA) largestIntA =  numbers[i];
    }

    for (int i = 0; i < numbers.size(); i++)
    {
        //find second largest number
        if (numbers[i] > largestIntB && numbers[i]!= largestIntA) largestIntB = numbers[i];
    }

    return  largestIntA * largestIntB;

}

The main program

int main()
{

    Testing ch;

    std::vector<int> test{ 100000,90000 };

    int result= ch.MaximumPairProductFast(test);

    std::cout << result << "\n";

}

The output of the computation will be 410065408 instead of 9000000000 which is the correct answer

The weird thing is when I try to print this:

std::cout << (int64_t) 100000 * 90000 << "\n";

It does give the correct result 9000000000.

But if I don't cast it to int64_t :

std::cout <<  100000 * 90000 << "\n";

The result is 410065408, which is exactly the output from my method even though I have ensured to return an int64_t type.

I have also tried this, but the outcome is the same:

int64_t Test::MaximumPairProductFast(const std::vector<int>& numbers)
{

    int64_t largestIntA = 0;

    int64_t largestIntB = 0;

    for (int  i = 0; i < numbers.size(); i++)
    {
        // find first largest number
        if ((int64_t) numbers[i] > largestIntA) largestIntA = (int64_t) numbers[i];
    }

    for (int i = 0; i < numbers.size(); i++)
    {
        //find second largest number
        if ((int64_t) numbers[i] > largestIntB && (int64_t) numbers[i]!= largestIntA) largestIntB = (int64_t) numbers[i];
    }

    return  largestIntA * largestIntB;

}

Am I missing an obvious detail?

Body:
You are truncating your result from a int64_t to an int.  On a typical system these days, you'll truncate a 64 bit integer and store it in a 32 bit value.

If you compile with the warning level increased, the compiler will tell you about this problem.

The solution is to declare result with the proper type:

int64_t result = ch.MaximumPairProductFast(test);

Or, just let the compiler use the correct type with auto:

auto result = ch.MaximumPairProductFast(test);

In your second example, the constants 100000 and 90000 are integers, so the multiplication of them will be done as integers.  When you case one of the values to int64_t, the multiplication will be done with 64 bit ints.  This can also be expressed with 100000LL.


问:
Angular Dynamic input Width
All,

I have been trying to get my input (type=text) to dynamically resize the input box. I have read multiple posts in SO, but was trying to come up with the simplest solution.

I have my simple component up and running at: https://stackblitz.com/edit/angular-dynamic-textbox-width

Firstly, I do not understand why the width property is not taking effect in the [style.width]. What am I missing?

Any help would be much appreciated!

答:
you forgot to put px at the end

change [style.width]='width' to [style.width.px]='width' :D

Title: Angular Dynamic input Width


问:
Division with if condition
I just start learning ruby with an online course and in my very first exercise, I can't complete the challenge. I have to create functions to sum, subtract, multiply and divide that meet the specs conditions.

For the division, I need to check if it will divide per 0 or not, give the result or a warning. My code is

```<code>def divisao(primeiro_numero, segundo_numero)
    if segundo_numero > 0
        primeiro_numero / segundo_numero
    else
        puts 'Opa! Zero como divisor'
end
</code>```

But when I run the specs, I get the following warning

```<code>0 examples, 0 failures, 1 error occurred outside of examples
</code>```

I have changed all the functions, but this one doesn't seem to work.
I added the complete functions and specs file here:https://gist.github.com/isafloriano/86c170400b2f5fc63dc5e8edd8913525

Can anyone give me a clue why this doesn't work?

答:
You are just missing the end of the if-else block:

```<code>def divisao(primeiro_numero, segundo_numero)
  if segundo_numero > 0
    primeiro_numero / segundo_numero
  else
    puts 'Opa! Zero como divisor'
  end # <= this one was missing
end
</code>```

Some suggestion:

Use English method and variable names. That makes it easier for others to understand your code and to help you.

Try to follow common Ruby conventions right from the start. Ruby code is indented with two spaces.

Title: Division with if condition

Body:
I just start learning ruby with an online course and in my very first exercise, I can't complete the challenge. I have to create functions to sum, subtract, multiply and divide that meet the specs conditions.

For the division, I need to check if it will divide per 0 or not, give the result or a warning. My code is

def divisao(primeiro_numero, segundo_numero)
    if segundo_numero > 0
        primeiro_numero / segundo_numero
    else
        puts 'Opa! Zero como divisor'
end

But when I run the specs, I get the following warning

0 examples, 0 failures, 1 error occurred outside of examples

I have changed all the functions, but this one doesn't seem to work.
I added the complete functions and specs file here:https://gist.github.com/isafloriano/86c170400b2f5fc63dc5e8edd8913525

Can anyone give me a clue why this doesn't work?

Body:
You are just missing the end of the if-else block:

def divisao(primeiro_numero, segundo_numero)
  if segundo_numero > 0
    primeiro_numero / segundo_numero
  else
    puts 'Opa! Zero como divisor'
  end # <= this one was missing
end

Some suggestion:

Use English method and variable names. That makes it easier for others to understand your code and to help you.

Try to follow common Ruby conventions right from the start. Ruby code is indented with two spaces.


问:
Android: Listening for variable changes
I've been searching for a KISS example of how to do this, and while they all seem (and I've gone through them ALL!) simple enough, I still cannot get my head around the concept.  I'm referring to custom listeners (ones that do not extend anything)...  In particular, creating a listener for a boolean variable so that I can set off some methods when its value changes.

this is an example of an example I've tried:
android how to make listener to a custom variable?

If someone has the time to explain a custom listener and how it works in plain English, that would be much appreciated.  I'm hoping that once I understand exactly how the listener is notified of a change, then I'll be able to create my own and understand how the damn thing works.  This is giving me a headache...  Thanks in advance

Here is where I'm at at the moment:

```<code>public class ChangeListener {
    boolean boo = false;

    public ChangeListener(boolean b){
        boo = b;
    }

    private listener l = null;

    public interface listener{
        public void onChange(boolean b);
    }

    public void setChangeListener(listener mListener){
        l = mListener;
    }

    public void somethingChanged(){
        if(l != null){
            l.onChange(boo);
        }
    }

}
</code>```

This is a snapshot of my main activity:

```<code>public class Main extends Activity implements ChangeListener.listener{
    private ChangeListener listener;
    private boolean boo = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        listener = new ChangeListener(boo);
        listener.setChangeListener(this);
        listener.somethingChanged();

    }

    @Override
    public void onChange(boolean b) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "REST = "+b, Toast.LENGTH_SHORT).show();
    }

}
</code>```

Now, when the activity starts, the Toast displays the state of boo... great.  Problem is this only happens within onCreate, which makes sense as .somethingChanged is placed in there.  What I would like is for the Toast to be generated every time boo is changed from false to true, and true to false regardless if its within onCreate or not.  I.e:

Click a button

Causes boo to change from false to true

Listener picks up on the change and runs whatever is in onChange

I know I could just use the button actionListener to do this, but I would like to stay away from this if possible, which at the moment I'm starting to think is impossible.

Any insight would be much appreciated.  Thanks in advance!

答:
There is a much easier solution now. Just wrap your variable in a LiveData Specifically MutableLiveData.

Java Version

```<code>MutableLiveData<String> listen = new MutableLiveData<>();

listen.setValue("Changed value"); //Initilize with a value

listen.observe(context,new Observer<String>() {
    @Override
    public void onChanged(String changedValue) {
        //Do something with the changed value
    }
});
</code>```

Kotlin Version

```<code>val listen : MutableLiveData<String> =  MutableLiveData<>()

listen.setValue("Changed value") //Initilize with a value

listen.observe(context, Observer {

    //Do something with the changed value -> it

})
</code>```

Title: Android: Listening for variable changes

Body:
I've been searching for a KISS example of how to do this, and while they all seem (and I've gone through them ALL!) simple enough, I still cannot get my head around the concept.  I'm referring to custom listeners (ones that do not extend anything)...  In particular, creating a listener for a boolean variable so that I can set off some methods when its value changes.

this is an example of an example I've tried:
android how to make listener to a custom variable?

If someone has the time to explain a custom listener and how it works in plain English, that would be much appreciated.  I'm hoping that once I understand exactly how the listener is notified of a change, then I'll be able to create my own and understand how the damn thing works.  This is giving me a headache...  Thanks in advance

Here is where I'm at at the moment:

public class ChangeListener {
    boolean boo = false;

    public ChangeListener(boolean b){
        boo = b;
    }

    private listener l = null;

    public interface listener{
        public void onChange(boolean b);
    }

    public void setChangeListener(listener mListener){
        l = mListener;
    }

    public void somethingChanged(){
        if(l != null){
            l.onChange(boo);
        }
    }

}

This is a snapshot of my main activity:

public class Main extends Activity implements ChangeListener.listener{
    private ChangeListener listener;
    private boolean boo = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        listener = new ChangeListener(boo);
        listener.setChangeListener(this);
        listener.somethingChanged();

    }

    @Override
    public void onChange(boolean b) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "REST = "+b, Toast.LENGTH_SHORT).show();
    }

}

Now, when the activity starts, the Toast displays the state of boo... great.  Problem is this only happens within onCreate, which makes sense as .somethingChanged is placed in there.  What I would like is for the Toast to be generated every time boo is changed from false to true, and true to false regardless if its within onCreate or not.  I.e:

Click a button

Causes boo to change from false to true

Listener picks up on the change and runs whatever is in onChange

I know I could just use the button actionListener to do this, but I would like to stay away from this if possible, which at the moment I'm starting to think is impossible.

Any insight would be much appreciated.  Thanks in advance!

Body:
There is a much easier solution now. Just wrap your variable in a LiveData Specifically MutableLiveData.

Java Version

MutableLiveData<String> listen = new MutableLiveData<>();

listen.setValue("Changed value"); //Initilize with a value

listen.observe(context,new Observer<String>() {
    @Override
    public void onChanged(String changedValue) {
        //Do something with the changed value
    }
});

Kotlin Version

val listen : MutableLiveData<String> =  MutableLiveData<>()

listen.setValue("Changed value") //Initilize with a value

listen.observe(context, Observer {

    //Do something with the changed value -> it

})


问:
VS Code Multiple Projects in one window (NOT "add project to workspace")
I am trying to solve the problem of too many vscode windows open at once. Looking for a ui solution that will allow me switch between projects quickly (terminals files etc..)

Does VS code or any extension allow us to open multiple projects in one window? I can see we can make a workspace with multiple projects but that wont work because things like cmd+P or find considers all files in every workspace and i also need a set of terminals unique to whatever the 'current project' is

I saw a tutorial where the guy had a master tab bar at the top. when he clicked one an entire new project was loaded; however i cant figure out how that is done.

答: Did you try the Workspace Manager extension? It allows you to open projects in new or same window</p>


问:
Version control for binaries with timestamps
I need a version control system that works like Subversion but is able to keep the 'modified' timestamp (date) of each file.

We need to version our setup projects. In this case it is imporatant that the input files (dll/exe's) keep their timestamp.

What is the best tool to do this? (OS: Windows)

Updated:

Here's an example of what I would like it to do:

put "foo.dll" (modified 1/1/2009) and "bar.dll" (modified 2/2/2009) into the working directory

create/test the setup and do a single commit

when another developer checks out the project both foo.dll and bar.dll should have their orginal modified date (1/1/2009 and 2/2/2009)

Our current workaround is to zip each dll (the modified date is kept in the zip) but I would prefer something easier.

答:
This is one of those requests that the subversion developers have on the radar, but have not yet implemented. As 'Nerdling' suggests, git or mercurial might be a better option, but you have a couple options in Subversion (since you are looking for something like SVN):

There was a discussion and perl script on the SVN website that had some workarounds. It preserved the modified date on the initial commit... thereafter, it uses the commit time, but you could probably modify the script to use the modified time. It is perl, so your mileage on Windows may vary (I've not used cygwin and/or perl on windows): http://svn.haxx.se/users/archive-2006-10/1345.shtml

You can change the svn:date property of each revision after the commit to match the modified time. This will change the modified time of every file in the commit, though, so if that's undesirable, be sure to commit the binaries on their own: http://svnbook.red-bean.com/en/1.5/svn.ref.properties.html and http://svnbook.red-bean.com/en/1.5/svn.advanced.props.html

I think Tortoise SVN on windows may have some options to handle setting the date property on a commit. I've only heard this rumour, and not used it, so this is hearsay :-)

None of these are particularly elegant, and require some extra effort on your part, but they will work if you want to stick with SVN, which is certainly a good product. If you decide to explore another SCM like git or mercurial, note that you CAN use them just like SVN and ignore their other features to help ease the transition.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jarret Hardie


问:
How can I implement clustering with sequelize ORM i.e. multithreading
Below is a piece of code I wrote but isn't working. With this code - how can I refactor it to implement multithreading or clustering so that I can utilize the number of cpus and thus improve the performance of my application?</p>

```<code>if (cluster.isMaster) {
    console.log('Master ${process.pid} is running');
    for (let i = 0; i < numOfCpus; i++) {
        cluster.fork();
    }
    cluster.on('exit', (worker, code, signal) => {
        console.log('worker ${worker.process.pid} died');
    });
} else {
    db.sequelize.sync({
        force: false
    }).then(function () {
        app.listen(PORT, function (req, res) {
            res.writeHead(200);
            res.end('hey');
            console.log("==>   Listening on port %s. Visit http://localhost:%s/ in your browser.", PORT, PORT);
        });
        console.log(' Worker ${process.pid} started');
    });
}
</code>```

答:
I've been working on something similar. I saw in your comment that you moved on to create a Spring Boot application anyways, but just in case, I think your issue came from the callback you passed to the 'listen' method. You wrote the status 200 to the response header then ended the connection with res.end('hey');

Perhaps if you just call the 'listen' method and handle any other logic afterwards with the server.on('listening') method, it will solve your issue? It seems to work when I test it on my application. This is my bin/www so far, where app is an express application, and db is the Sequelize models:

```<code>#!/usr/bin/env node

/**
 * Module dependencies.
 */
const http = require('http');
const cluster = require('cluster');
const os = require('os');
const config = require('../server/config')[process.env.NODE_ENV || 'development'];
const app = require('../server/app')(config);
const db = require('../server/models');

const log = config.log();

const numCPUs = os.cpus().length;

// Helper functions

/**
 * Normalize a port into a number, string, or false.
 */
function normalizePort(val) {
  const port = parseInt(val, 10);

  if (Number.isNaN(port)) {
    // named pipe
    return val;
  }
  if (port >= 0) {
    // port number
    return port;
  }
  return false;
}

/**
 * Get port from environment and store in Express.
 */
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server and listen on the provided port
 */
const server = http.createServer(app);

if (cluster.isMaster) {
  log.info(`Master ${process.pid} is running`);
  for (let i = 0; i < numCPUs; i += 1) {
    cluster.fork();
  }
  cluster.on('exit', (worker) => {
    log.fatal(`Worker ${worker.process.pid} just died`);
    cluster.fork();
  });
} else {
  db.sequelize.sync({ force: false })
    .then(() => {
      log.info('Connected to database');
      server.listen(port);
    })
    .catch((err) => {
      log.fatal(err);
    });
}

server.on('listening', () => {
  const addr = server.address();
  const bind = typeof addr === 'string'
    ? `pipe ${addr}`
    : `port ${addr.port}`;
  log.info(`Listening on ${bind}`);
});

// Handle server errors
server.on('error', (error) => {
  if (error.syscall !== 'listen') {
    throw error;
  }

  const bind = typeof port === 'string'
    ? `Pipe ${port}`
    : `Port ${port}`;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      log.fatal(`${bind} requires elevated privileges`);
      process.exit(1);
      break;
    case 'EADDRINUSE':
      log.fatal(`${bind} is already in use`);
      process.exit(1);
      break;
    default:
      log.info(error);
    // throw error;
  }
});
</code>```

Body:
Below is a piece of code I wrote but isn't working. With this code - how can I refactor it to implement multithreading or clustering so that I can utilize the number of cpus and thus improve the performance of my application?

if (cluster.isMaster) {
    console.log('Master ${process.pid} is running');
    for (let i = 0; i < numOfCpus; i++) {
        cluster.fork();
    }
    cluster.on('exit', (worker, code, signal) => {
        console.log('worker ${worker.process.pid} died');
    });
} else {
    db.sequelize.sync({
        force: false
    }).then(function () {
        app.listen(PORT, function (req, res) {
            res.writeHead(200);
            res.end('hey');
            console.log("==>   Listening on port %s. Visit http://localhost:%s/ in your browser.", PORT, PORT);
        });
        console.log(' Worker ${process.pid} started');
    });
}

Body:
I've been working on something similar. I saw in your comment that you moved on to create a Spring Boot application anyways, but just in case, I think your issue came from the callback you passed to the 'listen' method. You wrote the status 200 to the response header then ended the connection with res.end('hey');

Perhaps if you just call the 'listen' method and handle any other logic afterwards with the server.on('listening') method, it will solve your issue? It seems to work when I test it on my application. This is my bin/www so far, where app is an express application, and db is the Sequelize models:

#!/usr/bin/env node

/**
 * Module dependencies.
 */
const http = require('http');
const cluster = require('cluster');
const os = require('os');
const config = require('../server/config')[process.env.NODE_ENV || 'development'];
const app = require('../server/app')(config);
const db = require('../server/models');

const log = config.log();

const numCPUs = os.cpus().length;

// Helper functions

/**
 * Normalize a port into a number, string, or false.
 */
function normalizePort(val) {
  const port = parseInt(val, 10);

  if (Number.isNaN(port)) {
    // named pipe
    return val;
  }
  if (port >= 0) {
    // port number
    return port;
  }
  return false;
}

/**
 * Get port from environment and store in Express.
 */
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server and listen on the provided port
 */
const server = http.createServer(app);

if (cluster.isMaster) {
  log.info(`Master ${process.pid} is running`);
  for (let i = 0; i < numCPUs; i += 1) {
    cluster.fork();
  }
  cluster.on('exit', (worker) => {
    log.fatal(`Worker ${worker.process.pid} just died`);
    cluster.fork();
  });
} else {
  db.sequelize.sync({ force: false })
    .then(() => {
      log.info('Connected to database');
      server.listen(port);
    })
    .catch((err) => {
      log.fatal(err);
    });
}

server.on('listening', () => {
  const addr = server.address();
  const bind = typeof addr === 'string'
    ? `pipe ${addr}`
    : `port ${addr.port}`;
  log.info(`Listening on ${bind}`);
});

// Handle server errors
server.on('error', (error) => {
  if (error.syscall !== 'listen') {
    throw error;
  }

  const bind = typeof port === 'string'
    ? `Pipe ${port}`
    : `Port ${port}`;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      log.fatal(`${bind} requires elevated privileges`);
      process.exit(1);
      break;
    case 'EADDRINUSE':
      log.fatal(`${bind} is already in use`);
      process.exit(1);
      break;
    default:
      log.info(error);
    // throw error;
  }
});


问:
How to find the length of array within a tuple
I have a tuple of arrays and need to find the length of an array by using the index of the tuple. This tuple is generated from a sparse matrix alternative to numpy where i'm using scipy.sparse.csr_matrix and numpy.unravel_index based on this post

ie:

```<code>>>>T = [(array([0,1,2,3,4,5]),), (array([0,1,2,3,4,5,6,7,8,9]),)]
>>>print(T[1])
(array([0,1,2,3,4,5,6,7,8,9]),)
</code>```

I need to find the length of each array within the tuple for use later. using len() does not work

```<code>>>>len(T[1])
1
</code>```

I am using this within a for loop that iterates through each array using those arrays as an index for other data.

I have searched and searched for how to solve this but found nothing. Please help!

Body:
I have a tuple of arrays and need to find the length of an array by using the index of the tuple. This tuple is generated from a sparse matrix alternative to numpy where i'm using scipy.sparse.csr_matrix and numpy.unravel_index based on this post

ie:

>>>T = [(array([0,1,2,3,4,5]),), (array([0,1,2,3,4,5,6,7,8,9]),)]
>>>print(T[1])
(array([0,1,2,3,4,5,6,7,8,9]),)

I need to find the length of each array within the tuple for use later. using len() does not work

>>>len(T[1])
1

I am using this within a for loop that iterates through each array using those arrays as an index for other data.

I have searched and searched for how to solve this but found nothing. Please help!

Body:
Each item in T is a tuple of length 1, so just index it, like this:

>>> len(T[1][0])
10

To be clear:

>>> T[1]
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),)
>>> T[1][0]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


问:
Pandas merge to list by column
Is there a way to merge two pandas dataframes so that same column names end up as list entries in the merged df?

For example:

```<code>import pandas as pd
df_1 = pd.DataFrame({'A' : [1,2,3], 'B' : [4,5,6], 'C' : [7,8,9]})
df_2 = pd.DataFrame({'A' : [1,2,3], 'B' : ['a','b','c'], 'C' : ['d','e','f']})

df_merged = df_1.merge(df_2, on='A') # This should be changed, I guess
</code>```

results in:

```<code>   A  B_x  C_x B_y C_y
0  1    4    7   a   d
1  2    5    8   b   e
2  3    6    9   c   f
</code>```

I was hoping for:

```<code>   A  B       C
0  1  [4, a]  [7, d]
1  2  [5, b]  [8, e]
2  3  [6, c]  [9, f]
</code>```

So it is similar to the groupby.apply(list) function, but for merging dataframes.

答:
IIUC we can do groupby with axis=1

```<code>s=df_1.merge(df_2, on='A').set_index('A')
s=s.groupby(s.columns.str.split('_').str[0],axis=1).agg(lambda x : x.tolist()).reset_index()
s
   A       B       C
0  1  [4, a]  [7, d]
1  2  [5, b]  [8, e]
2  3  [6, c]  [9, f]
</code>```

Title: Pandas merge to list by column

Body:
Is there a way to merge two pandas dataframes so that same column names end up as list entries in the merged df?

For example:

import pandas as pd
df_1 = pd.DataFrame({'A' : [1,2,3], 'B' : [4,5,6], 'C' : [7,8,9]})
df_2 = pd.DataFrame({'A' : [1,2,3], 'B' : ['a','b','c'], 'C' : ['d','e','f']})

df_merged = df_1.merge(df_2, on='A') # This should be changed, I guess

results in:

   A  B_x  C_x B_y C_y
0  1    4    7   a   d
1  2    5    8   b   e
2  3    6    9   c   f

I was hoping for:

   A  B       C
0  1  [4, a]  [7, d]
1  2  [5, b]  [8, e]
2  3  [6, c]  [9, f]

So it is similar to the groupby.apply(list) function, but for merging dataframes.

Body:
IIUC we can do groupby with axis=1

s=df_1.merge(df_2, on='A').set_index('A')
s=s.groupby(s.columns.str.split('_').str[0],axis=1).agg(lambda x : x.tolist()).reset_index()
s
   A       B       C
0  1  [4, a]  [7, d]
1  2  [5, b]  [8, e]
2  3  [6, c]  [9, f]


问:
how can I spread these arrays properly?
I need to insert an empty item as the first item in an array of data which will be databound to a dropdown.   My code looks like this:

```<code>      let suppliers = response.data[0];
      let defaultSupplier = [{ SupplierId:0, ContactFirstName:''}];
      suppliers = [...defaultSupplier, suppliers];
</code>```

I was thinking that this code would initialize my array with a default item, and then I could simply spread the retrieved suppliers data into this array.  However, the result of this approach is that I have an array where defaultSupplier is the first item in the array and then the second item in the array is an array of the retrieved supplier data.  What approach do I need to take so that the retrieved suppliers data is appended at the same level as the defaultSupplier?

答:
defaultSupplier and supplier are both array of objects.

so, you need to spread both arrays into new array like this

```<code> suppliers = [...defaultSupplier, ...suppliers];
</code>```

Title: how can I spread these arrays properly?

Body:
I need to insert an empty item as the first item in an array of data which will be databound to a dropdown.   My code looks like this:

      let suppliers = response.data[0];
      let defaultSupplier = [{ SupplierId:0, ContactFirstName:''}];
      suppliers = [...defaultSupplier, suppliers];

I was thinking that this code would initialize my array with a default item, and then I could simply spread the retrieved suppliers data into this array.  However, the result of this approach is that I have an array where defaultSupplier is the first item in the array and then the second item in the array is an array of the retrieved supplier data.  What approach do I need to take so that the retrieved suppliers data is appended at the same level as the defaultSupplier?

Body:
defaultSupplier and supplier are both array of objects.

so, you need to spread both arrays into new array like this

 suppliers = [...defaultSupplier, ...suppliers];