问:
how to seperate 2 classes into seperate .h files and properly set them up
The code works fine in main without separate files for the 2 classes but when I try to separate them I get many errors saying ‘ItemToPurchase’ was not declared in this scope. I assume its because I'm using ItemToPurchase class in ShoppingCart class but I can't get it to recognize where the implementation is located

I tried something like this (below) in the ShoppingCart.h file but it has no effect, I'm not sure if I am missing something else did It incorrectly.

```<code>#ifndef ShoppingCart_h
#define ShoppingCart_h
#ifndef ItemToPurchase_h
#define ItemToPurchase_h
</code>```

I posted the working code below

I'm not sure how to set up the file headers for the 5 files, main and 4 .h files

It would be ideal if someone could show how to set up the headers, I'm a student and a bit lost at this point

```<code>#include <iostream>
#include <vector>
#include <string>
using namespace std;

class ItemToPurchase
{
private:

    string itemName;
    int itemPrice;
    int itemQuantity;
    string itemDescription;

public:

    ItemToPurchase()
    {
        itemName = "";
        itemPrice = 0;
        itemQuantity = 0;
        itemDescription = "none";
    }
    ItemToPurchase(string name, string description, int price, int quantity)
    {
        itemName = name;
        itemDescription = description;
        itemPrice = price;
        itemQuantity = quantity;
    }
    void SetName(string name)
    {
        itemName = name;
    }
    void SetPrice(int price)
    {
        itemPrice = price;
    }
    void SetQuantity(int quantity)
    {
        itemQuantity = quantity;
    }
    string GetName()
    {
        return itemName;
    }
    int GetPrice()
    {
        return itemPrice;
    }
    int GetQuantity()
    {
        return itemQuantity;
    }
    void SetDescription(string description)
    {
        itemDescription = description;
    }
    string GetDescription()
    {
        return itemDescription;
    }
    void PrintItemCost()
    {
        cout << itemName << " " << itemQuantity << " @ $" << itemPrice << " = $" << itemQuantity * itemPrice << endl;
    }
    void PrintItemDescription()
    {
        cout << itemName << ": " << itemDescription << endl;
    }

};

//---------------------------------------------------------------

class ShoppingCart
{

private:

    string customerName;
    string currentDate;
    vector <ItemToPurchase> cartItems;

public:

    ShoppingCart()
    {
        customerName = "none";
        currentDate = "January 1, 2016";
    }
    ShoppingCart(string name, string date)
    {
        customerName = name;
        currentDate = date;
    }
    string GetCustomerName()
    {
        return customerName;
    }
    string GetDate()
    {
        return currentDate;
    }
    void AddItem(ItemToPurchase newItem)
    {
        cartItems.push_back(newItem);
    }
    void RemoveItem(string name)
    {
        bool temp = true;
        for (int i = 0; i < cartItems.size(); i++)
        {
            if (name == cartItems[i].GetName())
            {
                cartItems.erase(cartItems.begin() + i);
                temp = false;
            }
        }
        if (temp == true)
        {
            cout << "Item not found in cart. Nothing removed." << endl << endl;
        }
    else
    {
      cout << endl;
    }
    }
    void ModifyItem(int quantity, string name)
    {
    bool temp = true;
        for (int i = 0; i < cartItems.size(); i++)
        {
            if (name == cartItems[i].GetName())
            {
                cartItems[i].SetQuantity(quantity);
        temp = false;
            }
        }
        if (temp == true)
        {
            cout << "Item not found in cart. Nothing modified." << endl << endl;
        }
    else
    {
      cout << endl;
    }
    }
    int GetNumItemsInCart()
    {
        int total = 0;
        for (int i = 0; i < cartItems.size(); i++)
        {
            total += cartItems[i].GetQuantity();
        }
        return total;
    }
    int GetCostOfCart()
    {
        int total = 0;
        for (int i = 0; i < cartItems.size(); i++)
        {
            total += cartItems[i].GetPrice() * cartItems[i].GetQuantity();
        }
        return total;
    }
    void PrintTotal()
    {
        if (cartItems.size() == 0)
        {
      cout << GetCustomerName() << "'s Shopping Cart - " << GetDate() << endl;
      cout << "Number of Items: 0" << endl << endl;
            cout << "SHOPPING CART IS EMPTY" << endl << endl;
      cout << "Total: $0" << endl << endl;

        }
        else
        {
            cout << customerName << "'s Shopping Cart - " << currentDate << endl;
            cout << "Number of Items: " << GetNumItemsInCart() << endl << endl;
            for (int i = 0; i < cartItems.size(); i++)
            {
                cartItems[i].PrintItemCost();
            }
            cout << endl << "Total: $" << GetCostOfCart() << endl << endl;
        }
    }
    void PrintDescriptions()
    {
        cout << "Item Descriptions" << endl;
        for (int i = 0; i < cartItems.size(); i++)
        {
            cartItems[i].PrintItemDescription();
        }
    cout << endl;
    }

};

int main()
{

    cout << "Enter customer's name:" << endl;
    string name;
    getline(cin, name);

    cout << "Enter today's date:" << endl << endl;
    string date;
    getline(cin, date);

    cout << "Customer name: " << name << endl;
    cout << "Today's date: " << date << endl << endl;

    ShoppingCart customer(name, date);

    bool on = true;
    bool check = true;
    string select;

    while (on)
    {

        cout << "MENU" << endl;
        cout << "a - Add item to cart" << endl;
        cout << "d - Remove item from cart" << endl;
        cout << "c - Change item quantity" << endl;
        cout << "i - Output items' descriptions" << endl;
        cout << "o - Output shopping cart" << endl;
        cout << "q - Quit" << endl << endl;
        cout << "Choose an option:" << endl;
        cin >> select;

        while (check)
        {
            if (select == "a" || select == "d" || select == "c" || select == "i" || select == "o" || select == "q")
            {
                check = false;
            }
            else
            {
                cout << "Choose an option:" << endl;
                cin >> select;
            }
        }
        check = true;

        if (select == "a")
        {
            cout << "ADD ITEM TO CART" << endl;
            cout << "Enter the item name:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the item description:" << endl;
            string description;
            getline(cin, description);
            cout << "Enter the item price:" << endl;
            int price;
            cin >> price;
            cout << "Enter the item quantity:" << endl << endl;
            int quantity;
            cin >> quantity;
            ItemToPurchase temp(name, description, price, quantity);
            customer.AddItem(temp);
        }
        else if (select == "d")
        {
            cout << "REMOVE ITEM FROM CART" << endl;
            cout << "Enter name of item to remove:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            customer.RemoveItem(name);
        }
        else if (select == "c")
        {
            cout << "CHANGE ITEM QUANTITY" << endl;
            cout << "Enter the item name:" << endl;
      cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the new quantity:" << endl;
            int quantity;
            cin >> quantity;
            customer.ModifyItem(quantity, name);

        }
        else if (select == "i")
        {
            cout << "OUTPUT ITEMS' DESCRIPTIONS" << endl;
            cout << customer.GetCustomerName() << "'s Shopping Cart - " << customer.GetDate() << endl << endl;
            customer.PrintDescriptions();
        }
        else if (select == "o")
        {

            cout << "OUTPUT SHOPPING CART" << endl;
            customer.PrintTotal();
        }
        else if (select == "q")
        {
            on = false;
        }

    }

}
</code>```

答:
This is really a start at the bottom and work your way up problem.  Firstly, with a header you'll usually have a header guard, some people use #pragma once some people use #ifndef/#define/#endif.  I prefer the latter personally, but work at a place where #pragma once is the the standard.  So you usually follow the standards of where you're working or what you've been told.

Next bit of help is the use of:

```<code>using namespace std;
</code>```

I personally don't like it as you end up polluting the namespace, but again, it's about the standards and following the coding practises. It's usually only a way of avoiding having to type too many std:: scopes before a class name.

With that being said, let's get onto the code...  At the bottom you have ItemToPurchase this includes no other classes except standard C++ ones, so you end up with:

```<code>// ItemToPurchase.h

#pragma once

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class ItemToPurchase
{
    private:
        string itemName;
        int itemPrice;
        int itemQuantity;
        string itemDescription;

    public:
        ItemToPurchase()
        {
            itemName = "";
            itemPrice = 0;
            itemQuantity = 0;
            itemDescription = "none";
        }
        ItemToPurchase(string name, string description, int price, int quantity)
        {
            itemName = name;
            itemDescription = description;
            itemPrice = price;
            itemQuantity = quantity;
        }
        void SetName(string name) { itemName = name; }
        void SetPrice(int price) { itemPrice = price; }
        void SetQuantity(int quantity) { itemQuantity = quantity; }
        string GetName() { return itemName; }
        int GetPrice() { return itemPrice; }
        int GetQuantity() { return itemQuantity; }
        void SetDescription(string description) { itemDescription = description; }
        string GetDescription() { return itemDescription; }
        void PrintItemCost() {
            cout << itemName << " " << itemQuantity << " @ $" << itemPrice << " = $" << itemQuantity * itemPrice << endl; }
        void PrintItemDescription() { cout << itemName << ": " << itemDescription << endl; }
};
</code>```

Just as a bit of a side-note, you should maybe const qualify the Get methods.  Anyway, the above can be put into a ItemToPurchase.h header file as it contains everything that it needs.

Next you have the ShoppingCart class.  This specifically names ItemToPurchase so it's going to need to include that header.  It should also include the headers for the standard types and classes that it uses.  This is usually the best way to ensure that a header isn't completely dependent on a header that another header may have included.

```<code>// ShoppingCart.h

#pragma once

#include "ItemToPurchase.h"
#include <vector>
#include <iostream>
#include <string>

class ShoppingCart
{
    private:
        string customerName;
        string currentDate;
        vector <ItemToPurchase> cartItems;

    public:
        ShoppingCart()
        {
            customerName = "none";
            currentDate = "January 1, 2016";
        }
        ShoppingCart(string name, string date)
        {
            customerName = name;
            currentDate = date;
        }
        string GetCustomerName() { return customerName; }
        string GetDate() { return currentDate; }
        void AddItem(ItemToPurchase newItem) { cartItems.push_back(newItem); }
        void RemoveItem(string name)
        {
            bool temp = true;
            for (int i = 0; i < cartItems.size(); i++)
            {
                if (name == cartItems[i].GetName())
                {
                    cartItems.erase(cartItems.begin() + i);
                    temp = false;
                }
            }
            if (temp == true)
            {
                cout << "Item not found in cart. Nothing removed." << endl << endl;
            }
            else
            {
                cout << endl;
            }
        }
        void ModifyItem(int quantity, string name)
        {
            bool temp = true;
            for (int i = 0; i < cartItems.size(); i++)
            {
                if (name == cartItems[i].GetName())
                {
                    cartItems[i].SetQuantity(quantity);
                    temp = false;
                }
            }
            if (temp == true)
            {
                cout << "Item not found in cart. Nothing modified." << endl << endl;
            }
            else
            {
                cout << endl;
            }
        }
        int GetNumItemsInCart()
        {
            int total = 0;
            for (int i = 0; i < cartItems.size(); i++)
            {
                total += cartItems[i].GetQuantity();
            }
            return total;
        }
        int GetCostOfCart()
        {
            int total = 0;
            for (int i = 0; i < cartItems.size(); i++)
            {
                total += cartItems[i].GetPrice() * cartItems[i].GetQuantity();
            }
            return total;
        }
        void PrintTotal()
        {
            if (cartItems.size() == 0)
            {
                cout << GetCustomerName() << "'s Shopping Cart - " << GetDate() << endl;
                cout << "Number of Items: 0" << endl << endl;
                cout << "SHOPPING CART IS EMPTY" << endl << endl;
                cout << "Total: $0" << endl << endl;
            }
            else
            {
                cout << customerName << "'s Shopping Cart - " << currentDate << endl;
                cout << "Number of Items: " << GetNumItemsInCart() << endl << endl;
                for (int i = 0; i < cartItems.size(); i++)
                {
                    cartItems[i].PrintItemCost();
                }
                cout << endl << "Total: $" << GetCostOfCart() << endl << endl;
            }
        }
        void PrintDescriptions()
        {
            cout << "Item Descriptions" << endl;
            for (int i = 0; i < cartItems.size(); i++)
            {
                cartItems[i].PrintItemDescription();
            }
            cout << endl;
        }
};
</code>```

Now we're done with the ShoppingCart.h and the ItemToPurchase.h header files and both are protected with #pragma once.

Finally, we're onto our main function which will be contained in a .cpp file.  Now this function names both ItemToPurchase and ShoppingCart by name, so it should include both header files.  You could get away with just including ShoppingCart.h as it includes ItemToPurcahse.h, but it's good practice to include all of headers of the types that you name.

Finally this gives you a main.cpp file which should be:

```<code>// main.cpp

#include "ItemToPurchase.h"
#include "ShoppingCart.h"
#include <iostream>
#include <string>

int main()
{
    cout << "Enter customer's name:" << endl;
    string name;
    getline(cin, name);

    cout << "Enter today's date:" << endl << endl;
    string date;
    getline(cin, date);

    cout << "Customer name: " << name << endl;
    cout << "Today's date: " << date << endl << endl;

    ShoppingCart customer(name, date);

    bool on = true;
    bool check = true;
    string select;

    while (on)
    {

        cout << "MENU" << endl;
        cout << "a - Add item to cart" << endl;
        cout << "d - Remove item from cart" << endl;
        cout << "c - Change item quantity" << endl;
        cout << "i - Output items' descriptions" << endl;
        cout << "o - Output shopping cart" << endl;
        cout << "q - Quit" << endl << endl;
        cout << "Choose an option:" << endl;
        cin >> select;

        while (check)
        {
            if (select == "a" || select == "d" || select == "c" || select == "i" || select == "o" || select == "q")
            {
                check = false;
            }
            else
            {
                cout << "Choose an option:" << endl;
                cin >> select;
            }
        }
        check = true;

        if (select == "a")
        {
            cout << "ADD ITEM TO CART" << endl;
            cout << "Enter the item name:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the item description:" << endl;
            string description;
            getline(cin, description);
            cout << "Enter the item price:" << endl;
            int price;
            cin >> price;
            cout << "Enter the item quantity:" << endl << endl;
            int quantity;
            cin >> quantity;
            ItemToPurchase temp(name, description, price, quantity);
            customer.AddItem(temp);
        }
        else if (select == "d")
        {
            cout << "REMOVE ITEM FROM CART" << endl;
            cout << "Enter name of item to remove:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            customer.RemoveItem(name);
        }
        else if (select == "c")
        {
            cout << "CHANGE ITEM QUANTITY" << endl;
            cout << "Enter the item name:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the new quantity:" << endl;
            int quantity;
            cin >> quantity;
            customer.ModifyItem(quantity, name);

        }
        else if (select == "i")
        {
            cout << "OUTPUT ITEMS' DESCRIPTIONS" << endl;
            cout << customer.GetCustomerName() << "'s Shopping Cart - " << customer.GetDate() << endl << endl;
            customer.PrintDescriptions();
        }
        else if (select == "o")
        {

            cout << "OUTPUT SHOPPING CART" << endl;
            customer.PrintTotal();
        }
        else if (select == "q")
        {
            on = false;
        }
    }
}
</code>```

And that should all work, with your class definitions separated out into their respective .h files.

Body:
The code works fine in main without separate files for the 2 classes but when I try to separate them I get many errors saying ‘ItemToPurchase’ was not declared in this scope. I assume its because I'm using ItemToPurchase class in ShoppingCart class but I can't get it to recognize where the implementation is located

I tried something like this (below) in the ShoppingCart.h file but it has no effect, I'm not sure if I am missing something else did It incorrectly.

#ifndef ShoppingCart_h
#define ShoppingCart_h
#ifndef ItemToPurchase_h
#define ItemToPurchase_h

I posted the working code below

I'm not sure how to set up the file headers for the 5 files, main and 4 .h files

It would be ideal if someone could show how to set up the headers, I'm a student and a bit lost at this point

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class ItemToPurchase
{
private:

    string itemName;
    int itemPrice;
    int itemQuantity;
    string itemDescription;

public:

    ItemToPurchase()
    {
        itemName = "";
        itemPrice = 0;
        itemQuantity = 0;
        itemDescription = "none";
    }
    ItemToPurchase(string name, string description, int price, int quantity)
    {
        itemName = name;
        itemDescription = description;
        itemPrice = price;
        itemQuantity = quantity;
    }
    void SetName(string name)
    {
        itemName = name;
    }
    void SetPrice(int price)
    {
        itemPrice = price;
    }
    void SetQuantity(int quantity)
    {
        itemQuantity = quantity;
    }
    string GetName()
    {
        return itemName;
    }
    int GetPrice()
    {
        return itemPrice;
    }
    int GetQuantity()
    {
        return itemQuantity;
    }
    void SetDescription(string description)
    {
        itemDescription = description;
    }
    string GetDescription()
    {
        return itemDescription;
    }
    void PrintItemCost()
    {
        cout << itemName << " " << itemQuantity << " @ $" << itemPrice << " = $" << itemQuantity * itemPrice << endl;
    }
    void PrintItemDescription()
    {
        cout << itemName << ": " << itemDescription << endl;
    }

};

//---------------------------------------------------------------

class ShoppingCart
{

private:

    string customerName;
    string currentDate;
    vector <ItemToPurchase> cartItems;

public:

    ShoppingCart()
    {
        customerName = "none";
        currentDate = "January 1, 2016";
    }
    ShoppingCart(string name, string date)
    {
        customerName = name;
        currentDate = date;
    }
    string GetCustomerName()
    {
        return customerName;
    }
    string GetDate()
    {
        return currentDate;
    }
    void AddItem(ItemToPurchase newItem)
    {
        cartItems.push_back(newItem);
    }
    void RemoveItem(string name)
    {
        bool temp = true;
        for (int i = 0; i < cartItems.size(); i++)
        {
            if (name == cartItems[i].GetName())
            {
                cartItems.erase(cartItems.begin() + i);
                temp = false;
            }
        }
        if (temp == true)
        {
            cout << "Item not found in cart. Nothing removed." << endl << endl;
        }
    else
    {
      cout << endl;
    }
    }
    void ModifyItem(int quantity, string name)
    {
    bool temp = true;
        for (int i = 0; i < cartItems.size(); i++)
        {
            if (name == cartItems[i].GetName())
            {
                cartItems[i].SetQuantity(quantity);
        temp = false;
            }
        }
        if (temp == true)
        {
            cout << "Item not found in cart. Nothing modified." << endl << endl;
        }
    else
    {
      cout << endl;
    }
    }
    int GetNumItemsInCart()
    {
        int total = 0;
        for (int i = 0; i < cartItems.size(); i++)
        {
            total += cartItems[i].GetQuantity();
        }
        return total;
    }
    int GetCostOfCart()
    {
        int total = 0;
        for (int i = 0; i < cartItems.size(); i++)
        {
            total += cartItems[i].GetPrice() * cartItems[i].GetQuantity();
        }
        return total;
    }
    void PrintTotal()
    {
        if (cartItems.size() == 0)
        {
      cout << GetCustomerName() << "'s Shopping Cart - " << GetDate() << endl;
      cout << "Number of Items: 0" << endl << endl;
            cout << "SHOPPING CART IS EMPTY" << endl << endl;
      cout << "Total: $0" << endl << endl;

        }
        else
        {
            cout << customerName << "'s Shopping Cart - " << currentDate << endl;
            cout << "Number of Items: " << GetNumItemsInCart() << endl << endl;
            for (int i = 0; i < cartItems.size(); i++)
            {
                cartItems[i].PrintItemCost();
            }
            cout << endl << "Total: $" << GetCostOfCart() << endl << endl;
        }
    }
    void PrintDescriptions()
    {
        cout << "Item Descriptions" << endl;
        for (int i = 0; i < cartItems.size(); i++)
        {
            cartItems[i].PrintItemDescription();
        }
    cout << endl;
    }

};

int main()
{

    cout << "Enter customer's name:" << endl;
    string name;
    getline(cin, name);

    cout << "Enter today's date:" << endl << endl;
    string date;
    getline(cin, date);

    cout << "Customer name: " << name << endl;
    cout << "Today's date: " << date << endl << endl;

    ShoppingCart customer(name, date);

    bool on = true;
    bool check = true;
    string select;

    while (on)
    {

        cout << "MENU" << endl;
        cout << "a - Add item to cart" << endl;
        cout << "d - Remove item from cart" << endl;
        cout << "c - Change item quantity" << endl;
        cout << "i - Output items' descriptions" << endl;
        cout << "o - Output shopping cart" << endl;
        cout << "q - Quit" << endl << endl;
        cout << "Choose an option:" << endl;
        cin >> select;

        while (check)
        {
            if (select == "a" || select == "d" || select == "c" || select == "i" || select == "o" || select == "q")
            {
                check = false;
            }
            else
            {
                cout << "Choose an option:" << endl;
                cin >> select;
            }
        }
        check = true;

        if (select == "a")
        {
            cout << "ADD ITEM TO CART" << endl;
            cout << "Enter the item name:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the item description:" << endl;
            string description;
            getline(cin, description);
            cout << "Enter the item price:" << endl;
            int price;
            cin >> price;
            cout << "Enter the item quantity:" << endl << endl;
            int quantity;
            cin >> quantity;
            ItemToPurchase temp(name, description, price, quantity);
            customer.AddItem(temp);
        }
        else if (select == "d")
        {
            cout << "REMOVE ITEM FROM CART" << endl;
            cout << "Enter name of item to remove:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            customer.RemoveItem(name);
        }
        else if (select == "c")
        {
            cout << "CHANGE ITEM QUANTITY" << endl;
            cout << "Enter the item name:" << endl;
      cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the new quantity:" << endl;
            int quantity;
            cin >> quantity;
            customer.ModifyItem(quantity, name);

        }
        else if (select == "i")
        {
            cout << "OUTPUT ITEMS' DESCRIPTIONS" << endl;
            cout << customer.GetCustomerName() << "'s Shopping Cart - " << customer.GetDate() << endl << endl;
            customer.PrintDescriptions();
        }
        else if (select == "o")
        {

            cout << "OUTPUT SHOPPING CART" << endl;
            customer.PrintTotal();
        }
        else if (select == "q")
        {
            on = false;
        }

    }

}

Body:
This is really a start at the bottom and work your way up problem.  Firstly, with a header you'll usually have a header guard, some people use #pragma once some people use #ifndef/#define/#endif.  I prefer the latter personally, but work at a place where #pragma once is the the standard.  So you usually follow the standards of where you're working or what you've been told.

Next bit of help is the use of:

using namespace std;

I personally don't like it as you end up polluting the namespace, but again, it's about the standards and following the coding practises. It's usually only a way of avoiding having to type too many std:: scopes before a class name.

With that being said, let's get onto the code...  At the bottom you have ItemToPurchase this includes no other classes except standard C++ ones, so you end up with:

// ItemToPurchase.h

#pragma once

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class ItemToPurchase
{
    private:
        string itemName;
        int itemPrice;
        int itemQuantity;
        string itemDescription;

    public:
        ItemToPurchase()
        {
            itemName = "";
            itemPrice = 0;
            itemQuantity = 0;
            itemDescription = "none";
        }
        ItemToPurchase(string name, string description, int price, int quantity)
        {
            itemName = name;
            itemDescription = description;
            itemPrice = price;
            itemQuantity = quantity;
        }
        void SetName(string name) { itemName = name; }
        void SetPrice(int price) { itemPrice = price; }
        void SetQuantity(int quantity) { itemQuantity = quantity; }
        string GetName() { return itemName; }
        int GetPrice() { return itemPrice; }
        int GetQuantity() { return itemQuantity; }
        void SetDescription(string description) { itemDescription = description; }
        string GetDescription() { return itemDescription; }
        void PrintItemCost() {
            cout << itemName << " " << itemQuantity << " @ $" << itemPrice << " = $" << itemQuantity * itemPrice << endl; }
        void PrintItemDescription() { cout << itemName << ": " << itemDescription << endl; }
};

Just as a bit of a side-note, you should maybe const qualify the Get methods.  Anyway, the above can be put into a ItemToPurchase.h header file as it contains everything that it needs.

Next you have the ShoppingCart class.  This specifically names ItemToPurchase so it's going to need to include that header.  It should also include the headers for the standard types and classes that it uses.  This is usually the best way to ensure that a header isn't completely dependent on a header that another header may have included.

// ShoppingCart.h

#pragma once

#include "ItemToPurchase.h"
#include <vector>
#include <iostream>
#include <string>

class ShoppingCart
{
    private:
        string customerName;
        string currentDate;
        vector <ItemToPurchase> cartItems;

    public:
        ShoppingCart()
        {
            customerName = "none";
            currentDate = "January 1, 2016";
        }
        ShoppingCart(string name, string date)
        {
            customerName = name;
            currentDate = date;
        }
        string GetCustomerName() { return customerName; }
        string GetDate() { return currentDate; }
        void AddItem(ItemToPurchase newItem) { cartItems.push_back(newItem); }
        void RemoveItem(string name)
        {
            bool temp = true;
            for (int i = 0; i < cartItems.size(); i++)
            {
                if (name == cartItems[i].GetName())
                {
                    cartItems.erase(cartItems.begin() + i);
                    temp = false;
                }
            }
            if (temp == true)
            {
                cout << "Item not found in cart. Nothing removed." << endl << endl;
            }
            else
            {
                cout << endl;
            }
        }
        void ModifyItem(int quantity, string name)
        {
            bool temp = true;
            for (int i = 0; i < cartItems.size(); i++)
            {
                if (name == cartItems[i].GetName())
                {
                    cartItems[i].SetQuantity(quantity);
                    temp = false;
                }
            }
            if (temp == true)
            {
                cout << "Item not found in cart. Nothing modified." << endl << endl;
            }
            else
            {
                cout << endl;
            }
        }
        int GetNumItemsInCart()
        {
            int total = 0;
            for (int i = 0; i < cartItems.size(); i++)
            {
                total += cartItems[i].GetQuantity();
            }
            return total;
        }
        int GetCostOfCart()
        {
            int total = 0;
            for (int i = 0; i < cartItems.size(); i++)
            {
                total += cartItems[i].GetPrice() * cartItems[i].GetQuantity();
            }
            return total;
        }
        void PrintTotal()
        {
            if (cartItems.size() == 0)
            {
                cout << GetCustomerName() << "'s Shopping Cart - " << GetDate() << endl;
                cout << "Number of Items: 0" << endl << endl;
                cout << "SHOPPING CART IS EMPTY" << endl << endl;
                cout << "Total: $0" << endl << endl;
            }
            else
            {
                cout << customerName << "'s Shopping Cart - " << currentDate << endl;
                cout << "Number of Items: " << GetNumItemsInCart() << endl << endl;
                for (int i = 0; i < cartItems.size(); i++)
                {
                    cartItems[i].PrintItemCost();
                }
                cout << endl << "Total: $" << GetCostOfCart() << endl << endl;
            }
        }
        void PrintDescriptions()
        {
            cout << "Item Descriptions" << endl;
            for (int i = 0; i < cartItems.size(); i++)
            {
                cartItems[i].PrintItemDescription();
            }
            cout << endl;
        }
};

Now we're done with the ShoppingCart.h and the ItemToPurchase.h header files and both are protected with #pragma once.

Finally, we're onto our main function which will be contained in a .cpp file.  Now this function names both ItemToPurchase and ShoppingCart by name, so it should include both header files.  You could get away with just including ShoppingCart.h as it includes ItemToPurcahse.h, but it's good practice to include all of headers of the types that you name.

Finally this gives you a main.cpp file which should be:

// main.cpp

#include "ItemToPurchase.h"
#include "ShoppingCart.h"
#include <iostream>
#include <string>

int main()
{
    cout << "Enter customer's name:" << endl;
    string name;
    getline(cin, name);

    cout << "Enter today's date:" << endl << endl;
    string date;
    getline(cin, date);

    cout << "Customer name: " << name << endl;
    cout << "Today's date: " << date << endl << endl;

    ShoppingCart customer(name, date);

    bool on = true;
    bool check = true;
    string select;

    while (on)
    {

        cout << "MENU" << endl;
        cout << "a - Add item to cart" << endl;
        cout << "d - Remove item from cart" << endl;
        cout << "c - Change item quantity" << endl;
        cout << "i - Output items' descriptions" << endl;
        cout << "o - Output shopping cart" << endl;
        cout << "q - Quit" << endl << endl;
        cout << "Choose an option:" << endl;
        cin >> select;

        while (check)
        {
            if (select == "a" || select == "d" || select == "c" || select == "i" || select == "o" || select == "q")
            {
                check = false;
            }
            else
            {
                cout << "Choose an option:" << endl;
                cin >> select;
            }
        }
        check = true;

        if (select == "a")
        {
            cout << "ADD ITEM TO CART" << endl;
            cout << "Enter the item name:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the item description:" << endl;
            string description;
            getline(cin, description);
            cout << "Enter the item price:" << endl;
            int price;
            cin >> price;
            cout << "Enter the item quantity:" << endl << endl;
            int quantity;
            cin >> quantity;
            ItemToPurchase temp(name, description, price, quantity);
            customer.AddItem(temp);
        }
        else if (select == "d")
        {
            cout << "REMOVE ITEM FROM CART" << endl;
            cout << "Enter name of item to remove:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            customer.RemoveItem(name);
        }
        else if (select == "c")
        {
            cout << "CHANGE ITEM QUANTITY" << endl;
            cout << "Enter the item name:" << endl;
            cin.ignore();
            string name;
            getline(cin, name);
            cout << "Enter the new quantity:" << endl;
            int quantity;
            cin >> quantity;
            customer.ModifyItem(quantity, name);

        }
        else if (select == "i")
        {
            cout << "OUTPUT ITEMS' DESCRIPTIONS" << endl;
            cout << customer.GetCustomerName() << "'s Shopping Cart - " << customer.GetDate() << endl << endl;
            customer.PrintDescriptions();
        }
        else if (select == "o")
        {

            cout << "OUTPUT SHOPPING CART" << endl;
            customer.PrintTotal();
        }
        else if (select == "q")
        {
            on = false;
        }
    }
}

And that should all work, with your class definitions separated out into their respective .h files.


来源: stackexchange

问:
What is the difference between class: 'item' and :class => "item" in Ruby on Rails? Which style should I use?
I am pretty new to Rails and I'm working with a new code base that sometimes uses two different syntax for the same thing.

```<code>class: 'item'
</code>```

vs

```<code>:class => "item"
</code>```

However, I have have not been able to find what the difference is or which style I should use as best-practice.

I assume that it has something to do with the Rails version. We are planning to move to Rails 6. Can somebody shed some insight on this for me?

答:
This question does not concern Rails, it's a pure Ruby syntax.

The basic answer is that the syntax

```<code>:class => "item"
</code>```

is simply from the older version of Ruby — mainly pre-1.9.

Ruby versions 1.9 and newer all support the new syntax, which is more compact and is borrowed from the JSON format.

I noticed you used double quotes in one example and single quotes in another. In Ruby we try to use single quotes whenever we have a string without interpolation, and double quotes when we use interpolation.

Therefore both of your examples should be using single quotes.

Having said that, this is a style guide that is hotly debated. See this link for more info:

https://dockyard.com/blog/ruby/2012/02/16/single-quotes-or-double-quotes

ContentLicense: CC BY-SA 4.0

Body:
I am pretty new to Rails and I'm working with a new code base that sometimes uses two different syntax for the same thing.

class: 'item'

vs

:class => "item"

However, I have have not been able to find what the difference is or which style I should use as best-practice.

I assume that it has something to do with the Rails version. We are planning to move to Rails 6. Can somebody shed some insight on this for me?

Body:
This question does not concern Rails, it's a pure Ruby syntax.

The basic answer is that the syntax

:class => "item"

is simply from the older version of Ruby — mainly pre-1.9.

Ruby versions 1.9 and newer all support the new syntax, which is more compact and is borrowed from the JSON format.

I noticed you used double quotes in one example and single quotes in another. In Ruby we try to use single quotes whenever we have a string without interpolation, and double quotes when we use interpolation.

Therefore both of your examples should be using single quotes.

Having said that, this is a style guide that is hotly debated. See this link for more info:

https://dockyard.com/blog/ruby/2012/02/16/single-quotes-or-double-quotes


问:
Symfony 4 - Import ChartJS with webpack encore?
I downloaded the ChartJS package on Symfony, and I would like to be able to use it with webpack-encore

In my Twig template, I can use Chart with :

```<code>new Chart(document.getElementById("myChart"), { ..... }
</code>```

It works with CDN, but now I would like to use it with webpack-encore.

So in my app.js I tried :

```<code>//1er essai
import Chart from "chart.js";
global.Chart = Chart

//2eme essai
const Chart = require("chart.js");
global.Chart = Chart;
</code>```

But neither works. Each time in the browser I get the following error :

Uncaught ReferenceError: Chart is not defined

Can someone help me please ?

答:
When using webpack encore I find it easier to install different modules via npm.
In the documentation it says that bower and npm are recommended.
So you basically write this

```<code>npm install chart.js --save
</code>```

And for usage you simply import it.

Body:
I downloaded the ChartJS package on Symfony, and I would like to be able to use it with webpack-encore

In my Twig template, I can use Chart with :

new Chart(document.getElementById("myChart"), { ..... }

It works with CDN, but now I would like to use it with webpack-encore.

So in my app.js I tried :

//1er essai
import Chart from "chart.js";
global.Chart = Chart

//2eme essai
const Chart = require("chart.js");
global.Chart = Chart;

But neither works. Each time in the browser I get the following error :

Uncaught ReferenceError: Chart is not defined

Can someone help me please ?

Body:
When using webpack encore I find it easier to install different modules via npm.
In the documentation it says that bower and npm are recommended.
So you basically write this

npm install chart.js --save

And for usage you simply import it.


问:
React/Redux: Effectively change a component's corresponding state in Redux's tree
So I essentially have a similar hierarchy between my components and Redux state, represented below, where each component has a id, name, details, etc:

```<code>Redux hierarchy:
parent -> child1 -> element1
                    element2
                    element3
          child2 -> element1
                    element2

React hierarchy:
ParentComponent -> ChildComponent -> ElementComponent
</code>```

Suppose I wanted to element2 of child1 to change its name, with it being reflected in the Redux state, how would I go about doing this efficiently?

What I want is to somehow create a link using the id of element2 of child1 and the id in the state so I can change the corresponding Redux state without doing a deep search inside the Redux store in order to change the corresponding state.

I could effectively create this using React's state model and have each component manage its own state but but since I need this state elsewhere, how would I tackle this in Redux state? Thanks in advance.

答:
Normally you could just go down a predicted object path but because the object path may be variable due to the nature of elements, I decided to use a combination of brute force and the predicted object path.

In this particular scenario Parent is the common node between all the elements so a brute force search for id would work well enough.

This reusable function would provide a brute force recursive search in the root node for each object and provide a callback to perform on each object.

export const iterateNodes = (obj, callback) => {
    if (!obj) return undefined

    for (let property in obj) {
        if (obj.hasOwnProperty(property) && obj[property] != null) {
            if (obj[property].constructor === Object) {
                iterateNodes(obj[property], callback)
                callback(obj[property])
            } else if (obj[property].constructor === Array) {
                for (let i = 0; i < obj[property].length; i++) {
                    iterateNodes(obj[property][i], callback)
                    callback(obj[property][i])
                }
            } else {
                // console.log(obj[property])
            }
        }
    }
    return obj
}
```

<p><em>This was pulled from another StackOverflow question and modified a bit. I can't seem to find the source.</em></p>

<p>Then you can create another function to modify the node with particular options. This snippet has <code>overwrite</code> options in case the whole object needs to be overwritten.</p>

<pre class="lang-js prettyprint-override"><code>export const modifyNodeById = (
    root,
    id,
    modification,
    options = {}
) => {
    if (!id) throw new Error('id not specified')

    return iterateNodes(root, node => {
        if (node.id === id) {
            if (options.overwrite)
                Object.getOwnPropertyNames(node).forEach(key => delete node[key])
            Object.assign(node, { ...modification })
        }
    })
}
</code>```

Import note: This function mutates the object.

State mutation should be 100% avoided so the easy way out for this one is just to use lodash's cloneDeep function to create a deep copy. You probably could optimize to copy only the needed branches in the state but unless your state is thicc, it probably isn't worth it.

So a final answer could be:

```<code>modifyNodeById(parent, 13, { isUnlocked: true })
</code>```

To append the properties to the object node with id: 13 starting the search under parent.

Body:
So I essentially have a similar hierarchy between my components and Redux state, represented below, where each component has a id, name, details, etc:

Redux hierarchy:
parent -> child1 -> element1
                    element2
                    element3
          child2 -> element1
                    element2

React hierarchy:
ParentComponent -> ChildComponent -> ElementComponent

Suppose I wanted to element2 of child1 to change its name, with it being reflected in the Redux state, how would I go about doing this efficiently?

What I want is to somehow create a link using the id of element2 of child1 and the id in the state so I can change the corresponding Redux state without doing a deep search inside the Redux store in order to change the corresponding state.

I could effectively create this using React's state model and have each component manage its own state but but since I need this state elsewhere, how would I tackle this in Redux state? Thanks in advance.

Body:
Normally you could just go down a predicted object path but because the object path may be variable due to the nature of elements, I decided to use a combination of brute force and the predicted object path.

In this particular scenario Parent is the common node between all the elements so a brute force search for id would work well enough.

This reusable function would provide a brute force recursive search in the root node for each object and provide a callback to perform on each object.

export const iterateNodes = (obj, callback) => {
    if (!obj) return undefined

    for (let property in obj) {
        if (obj.hasOwnProperty(property) && obj[property] != null) {
            if (obj[property].constructor === Object) {
                iterateNodes(obj[property], callback)
                callback(obj[property])
            } else if (obj[property].constructor === Array) {
                for (let i = 0; i < obj[property].length; i++) {
                    iterateNodes(obj[property][i], callback)
                    callback(obj[property][i])
                }
            } else {
                // console.log(obj[property])
            }
        }
    }
    return obj
}

This was pulled from another StackOverflow question and modified a bit. I can't seem to find the source.

Then you can create another function to modify the node with particular options. This snippet has overwrite options in case the whole object needs to be overwritten.

export const modifyNodeById = (
    root,
    id,
    modification,
    options = {}
) => {
    if (!id) throw new Error('id not specified')

    return iterateNodes(root, node => {
        if (node.id === id) {
            if (options.overwrite)
                Object.getOwnPropertyNames(node).forEach(key => delete node[key])
            Object.assign(node, { ...modification })
        }
    })
}

Import note: This function mutates the object.

State mutation should be 100% avoided so the easy way out for this one is just to use lodash's cloneDeep function to create a deep copy. You probably could optimize to copy only the needed branches in the state but unless your state is thicc, it probably isn't worth it.

So a final answer could be:

modifyNodeById(parent, 13, { isUnlocked: true })

To append the properties to the object node with id: 13 starting the search under parent.


问:
Gnuplot plotting with image using non-square datablocks
I have run into a strange problem.  Every time I try to plot "with image" using a non-square data file I get very unexpected results.  Nowhere in any of the sources I've read  mentioned anything about whether the domain needed to have the same dimensions.

For example, I have a file called plate which consists of many datablocks each with 4 tab-separated columns.  The second and third columns represent x and y coordinates respectively. The first datablock in plate goes like:

```<code>0       0       0       293
0       0       0.1     293
.       .       .       .
.       .       .       .
.       .       .       .
0       5       4.9     293
0       5       5       293
</code>```

When I plot "plate" index 0 using 2:3:4 with image I get the expected result.  This works for every index and the result is a square heat map with the 4th column as the heat value.  I want to do the same with my file called pipe, which uses the same format except for different ranges on columns 2 and 3.

```<code>0       5       2.2     293
0       5       2.3     293
.       .       .       .
.       .       .       .
.       .       .       .
0       10      2.9     293
0       10      3       293
</code>```

Currently, I get the following:

The output should show a solid horizontal bar adjacent to the square but instead it is distorted.

I have tried other non-square data files and the results were even different from the attached image.  One attempt basically doubled the image but kept it square, even when the data wasn't.

Below is a truncated sample of pipe for testing.

```<code>0       5       2.2     293
0       5       2.3     293
0       5       2.4     293
0       5       2.5     293
0       5       2.6     293
0       5       2.7     293
0       5       2.8     293
0       5       2.9     293
0       5       3       293
0       5.1     2.2     293
0       5.1     2.3     293
0       5.1     2.4     293
0       5.1     2.5     293
0       5.1     2.6     293
0       5.1     2.7     293
0       5.1     2.8     293
0       5.1     2.9     293
0       5.1     3       293
</code>```

答:
Ok I stumbled upon a solution, but I don't really know why it is the case or how to avoid it using gnuplot instead of rewriting the entire data file.

In the case of non-square data the problem seems to be that the column to be read first in the using statement needs also to be the column that is iterated over first.

For data that goes

```<code>1       1       1
1       2       2
1       3       3
2       1       4
2       2       5
2       3       6
</code>```

Plotting by using 1:2:3 with image will result in a parallelogram, but plotting with using 2:1:3 with image will plot with the proper dimensions.  However, in the latter case the desired x-axis will be plotted on the y and vice versa.  I also added sequential test points in the above data to see where each square is drawn.

Attached below are results from the test data listed above.

Body:
I have run into a strange problem.  Every time I try to plot "with image" using a non-square data file I get very unexpected results.  Nowhere in any of the sources I've read  mentioned anything about whether the domain needed to have the same dimensions.

For example, I have a file called plate which consists of many datablocks each with 4 tab-separated columns.  The second and third columns represent x and y coordinates respectively. The first datablock in plate goes like:

0       0       0       293
0       0       0.1     293
.       .       .       .
.       .       .       .
.       .       .       .
0       5       4.9     293
0       5       5       293

When I plot "plate" index 0 using 2:3:4 with image I get the expected result.  This works for every index and the result is a square heat map with the 4th column as the heat value.  I want to do the same with my file called pipe, which uses the same format except for different ranges on columns 2 and 3.

0       5       2.2     293
0       5       2.3     293
.       .       .       .
.       .       .       .
.       .       .       .
0       10      2.9     293
0       10      3       293

Currently, I get the following:

The output should show a solid horizontal bar adjacent to the square but instead it is distorted.

I have tried other non-square data files and the results were even different from the attached image.  One attempt basically doubled the image but kept it square, even when the data wasn't.

Below is a truncated sample of pipe for testing.

0       5       2.2     293
0       5       2.3     293
0       5       2.4     293
0       5       2.5     293
0       5       2.6     293
0       5       2.7     293
0       5       2.8     293
0       5       2.9     293
0       5       3       293
0       5.1     2.2     293
0       5.1     2.3     293
0       5.1     2.4     293
0       5.1     2.5     293
0       5.1     2.6     293
0       5.1     2.7     293
0       5.1     2.8     293
0       5.1     2.9     293
0       5.1     3       293

Body:
Ok I stumbled upon a solution, but I don't really know why it is the case or how to avoid it using gnuplot instead of rewriting the entire data file.

In the case of non-square data the problem seems to be that the column to be read first in the using statement needs also to be the column that is iterated over first.

For data that goes

1       1       1
1       2       2
1       3       3
2       1       4
2       2       5
2       3       6

Plotting by using 1:2:3 with image will result in a parallelogram, but plotting with using 2:1:3 with image will plot with the proper dimensions.  However, in the latter case the desired x-axis will be plotted on the y and vice versa.  I also added sequential test points in the above data to see where each square is drawn.

Attached below are results from the test data listed above.


问:
Can't perform I/O in foldr?
I have a Data.Map structure that maps Strings to Stringss. For whatever reason, I want to print the contents of the map in the format key: value using foldrWithKey, like so:

```<code>M.foldrWithKey (\k v b -> putStrLn (k++": "++v++"\n")) (return ()) data
</code>```

However, only the first element of the map appears in the output (even though the map has more than one element). But when I try to construct a list using foldrWithKey and then print it, all of the elements show up:

```<code>print (M.foldrWithKey (\k v b -> k:b) [] data)
</code>```

So, why don't the other elemnts show up when trying to perform I/O? Is it the way foldr works or is there some subtle lazy-io-related quirk that I'm missing?

答:
Here is a clearer example of what is happening, without using I/O.

```<code>foldr (\x b -> x) 9 [8,7,6,5,4,3,2,1,0]
</code>```

This expression returns 8, the head of the list.  Where does the rest of the list go?  Well, the result of processing the rest of the list is passed in 'b', which is not used, so the rest of the list is simply ignored.

The same thing is happening in your case.  By ignoring the accumulator 'b', you are constructing an I/O action that only uses one element of the map.  Basically you have said, "to print a map, print its first key and value."  What you should say is, "to print a map, print its first key and value, then print the rest of the map."  To do that, you need to arrange for the contents of variable 'b' to run after the call to putStrLn runs:

```<code>M.foldrWithKey (\k v b -> do {putStrLn (k ++ ": " ++ v ++ "\n"); b}) (return ()) d
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can't perform I/O in foldr?

Body:
I have a Data.Map structure that maps Strings to Stringss. For whatever reason, I want to print the contents of the map in the format key: value using foldrWithKey, like so:

M.foldrWithKey (\k v b -> putStrLn (k++": "++v++"\n")) (return ()) data

However, only the first element of the map appears in the output (even though the map has more than one element). But when I try to construct a list using foldrWithKey and then print it, all of the elements show up:

print (M.foldrWithKey (\k v b -> k:b) [] data)

So, why don't the other elemnts show up when trying to perform I/O? Is it the way foldr works or is there some subtle lazy-io-related quirk that I'm missing?

Body:
Here is a clearer example of what is happening, without using I/O.

foldr (\x b -> x) 9 [8,7,6,5,4,3,2,1,0]

This expression returns 8, the head of the list.  Where does the rest of the list go?  Well, the result of processing the rest of the list is passed in 'b', which is not used, so the rest of the list is simply ignored.

The same thing is happening in your case.  By ignoring the accumulator 'b', you are constructing an I/O action that only uses one element of the map.  Basically you have said, "to print a map, print its first key and value."  What you should say is, "to print a map, print its first key and value, then print the rest of the map."  To do that, you need to arrange for the contents of variable 'b' to run after the call to putStrLn runs:

M.foldrWithKey (\k v b -> do {putStrLn (k ++ ": " ++ v ++ "\n"); b}) (return ()) d


问:
Passing data from JS to Laravel
i have a parameter in my function JS .. The goal is when i click on my button the  parameter should be assigned on new variable Laravel  .. i want to pass my data from JS to Laravel </p>

```<code><script type="text/javascript"  >

    function change_theme(color) {

        {{ $idc = color }}//somthing like this

        document.getElementById('iframe').setAttribute("src","{{(route('generate.pdfColor', ['slug' => 'student', 'id' => '56', 'color' => '$idc']))}}");
    }

</script>
</code>```

Title: Passing data from JS to Laravel

Body:
<script type="text/javascript">
    function change_theme(color) {
    var url = "{{(route('generate.pdfColor', ['slug' => 'student', 'id' => '56', 'color' => ':id']))}}";
        url = url.replace('%3Aid',color);
        document.getElementById('iframe').setAttribute("src", url);
    }
</script>


问:
how to improve performance of nested for loops when comparing values in an array
```<code>var twoSum = function(nums, target) {
  for(let i = 0; i < nums.length; i++){
    for(let j = i + 1; j < nums.length; j++){
      if(nums[i] + nums[j] === target){
        return [nums.indexOf(nums[i]), nums.lastIndexOf(nums[j])]
      }
    }
  }
}
function([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9
</code>```

This is a Javascript function and it's iterating over the array of numbers with nested for loops and find a pair that when summed, it equals the target and return their indexes. Since it has a nested for loop it I believe it has O(n^2) or quadratic time complexity, and I was wondering if there is a faster way to do this. I'm just trying to get the first pass solution and after improve upon it.  Thanks in advance!

答:
Create an object that maps each element to its last index. Then loop over each element, and see if target - element is in the object with a different index.

function twoSums(nums, target) {
  const last_index = {};
  nums.forEach((num, i) => last_index[num] = i);
  for (let i = 0; i < nums.length; i++) {
    const diff = target - nums[i];
    if (diff in last_index && last_index[diff] != i) {
      return [i, last_index[diff]];
    }
  }
}

const list = [3,5,3,7,2];
console.log(twoSums(list, 9));
console.log(twoSums(list, 6));
console.log(twoSums(list, 15));```

Looking up an object property is O(1), so this algorithm is O(n).

Body:
var twoSum = function(nums, target) {
  for(let i = 0; i < nums.length; i++){
    for(let j = i + 1; j < nums.length; j++){
      if(nums[i] + nums[j] === target){
        return [nums.indexOf(nums[i]), nums.lastIndexOf(nums[j])]
      }
    }
  }
}
function([3,5,3,7,2], 9) //It should return [3, 4] since 7 + 2 = 9

This is a Javascript function and it's iterating over the array of numbers with nested for loops and find a pair that when summed, it equals the target and return their indexes. Since it has a nested for loop it I believe it has O(n^2) or quadratic time complexity, and I was wondering if there is a faster way to do this. I'm just trying to get the first pass solution and after improve upon it.  Thanks in advance!

Body:
Create an object that maps each element to its last index. Then loop over each element, and see if target - element is in the object with a different index.

function twoSums(nums, target) {
  const last_index = {};
  nums.forEach((num, i) => last_index[num] = i);
  for (let i = 0; i < nums.length; i++) {
    const diff = target - nums[i];
    if (diff in last_index && last_index[diff] != i) {
      return [i, last_index[diff]];
    }
  }
}

const list = [3,5,3,7,2];
console.log(twoSums(list, 9));
console.log(twoSums(list, 6));
console.log(twoSums(list, 15));

Looking up an object property is O(1), so this algorithm is O(n).


问:
Trying to prevent an implicit conversion using arithmetic operators
Is there a way to force a compile time error when there is a implicit conversion using the arithmetic operators. For example:

```<code>class A:
public:
A operator + (const A tmp) const;
void setX(const int X)
void setY(const int Y)
void setZ(const int Z)
private:
template <typename Y>
Y operator +(const Y tmp);

main:
int a1 {2};
int a2 {3};
int a3 {4}'

char b1 {2};
char v2 {3};
char b3 {4};

A a;
a.setX(a1);
a.sety(a2);
a.setz(a3);

A b;
b.setx(b1);
b.sety(b2);
b.setz(b3);
A d= a+b; //more or so of what i mean. This should be an error
A e= a+a;  // this should not be because its the same type

</code>```

the problem is that when i create a template for the operator both a+b and a+c generate an error. Which is confusing to me because a+c is the only one that should generate an error.

答:
An implicit conversion will take place whenever the types of both parameters does not match. Yo can check this when compiling with something like</p>

```<code>static_assert(std::is_same<decltype(a), decltype(c)>::value);
</code>```

Body:
Is there a way to force a compile time error when there is a implicit conversion using the arithmetic operators. For example:

class A:
public:
A operator + (const A tmp) const;
void setX(const int X)
void setY(const int Y)
void setZ(const int Z)
private:
template <typename Y>
Y operator +(const Y tmp);

main:
int a1 {2};
int a2 {3};
int a3 {4}'

char b1 {2};
char v2 {3};
char b3 {4};

A a;
a.setX(a1);
a.sety(a2);
a.setz(a3);

A b;
b.setx(b1);
b.sety(b2);
b.setz(b3);
A d= a+b; //more or so of what i mean. This should be an error
A e= a+a;  // this should not be because its the same type

the problem is that when i create a template for the operator both a+b and a+c generate an error. Which is confusing to me because a+c is the only one that should generate an error.

Body:
An implicit conversion will take place whenever the types of both parameters does not match. Yo can check this when compiling with something like

static_assert(std::is_same<decltype(a), decltype(c)>::value);


问:
F# - Extract option from Expr
Is there a way to extract a parameter from an Expr?

An example:

```<code>let hasStringOption (e:Expr<string option>) =
    let myOption : string option = ..some code to get the string option from e
</code>```

How would I get the string option inside the Expr and assign it to myOption?

答:
In your example, string option represents the expression return type, so the expression itself could be arbitrarily complex and requires some kind of evaluation strategy like the PowerPack's as @wmeyer has shown.

But if you actually have a string option expression you can use the standard library quotation active patterns and reflection to implement your own evaluation strategy (generic option shown here):

```<code>module P = Microsoft.FSharp.Quotations.Patterns

let extract (expr:Expr<'a option>) =
    match expr with
    | P.NewUnionCase (uci, args) ->
        if uci.Name = "Some" then
            match args.Head with
            | P.Value(value, ty) -> Some(value :?> 'a)
        else
            None:('a option)

let example1 = extract <@ None:int option @>
let example2 = extract <@ Some("hello world") @>
</code>```

and indeed, such an approach may be a piece of your own strategy for recursively evaluating arbitrary expressions using reflection and active patterns rather than PowerPack's slow and limited intermediate LINQ strategy.

Title: F# - Extract option from Expr

Body:
Is there a way to extract a parameter from an Expr?

An example:

let hasStringOption (e:Expr<string option>) =
    let myOption : string option = ..some code to get the string option from e

How would I get the string option inside the Expr and assign it to myOption?

Body:
In your example, string option represents the expression return type, so the expression itself could be arbitrarily complex and requires some kind of evaluation strategy like the PowerPack's as @wmeyer has shown.

But if you actually have a string option expression you can use the standard library quotation active patterns and reflection to implement your own evaluation strategy (generic option shown here):

module P = Microsoft.FSharp.Quotations.Patterns

let extract (expr:Expr<'a option>) =
    match expr with
    | P.NewUnionCase (uci, args) ->
        if uci.Name = "Some" then
            match args.Head with
            | P.Value(value, ty) -> Some(value :?> 'a)
        else
            None:('a option)

let example1 = extract <@ None:int option @>
let example2 = extract <@ Some("hello world") @>

and indeed, such an approach may be a piece of your own strategy for recursively evaluating arbitrary expressions using reflection and active patterns rather than PowerPack's slow and limited intermediate LINQ strategy.


问:
How to remove 'autocomplete disabled' from input field
I have a field in which the user is ask to input a year. My html looks like this

```<code><div class="form-group {% if form_search2.year_search.errors %} error {% endif %}" style="padding: 0px;">
    <label class="col-xs-3 col-sm-2 control-label">{{ form_search2.year_search.label }}</label>
    <div class="col-xs-6" style="max-width:320px;display: inline;">
                            {{ form_search2.year_search(class='form-control', style="max-width: 300px;", placeholder="e.g. 1996-2001", autocomplete="on", type="text") }}
    </div>
    <div class="col-xs-3" style="display: inline;">
    </div>
</div>
</code>```

with the form defined as

```<code>year_search = TextField("Year:")
</code>```

when I look at this form in the browser (Chrome) I get the message

```<code>Automatic credit card filling is disabled because this form does not use a secure connection
</code>```

How can I get rid of this?
I have other fields which are defined in the same why, but they remember what has been typed before and help the user by suggesting old inputs.

答: Change your field name or field id to something else. Somehow, google detects Year as a credit card field and helps you auto-fill it.

Body:
I have a field in which the user is ask to input a year. My html looks like this

    {{ form_search2.year_search.label }}

                            {{ form_search2.year_search(class='form-control', style="max-width: 300px;", placeholder="e.g. 1996-2001", autocomplete="on", type="text") }}

with the form defined as

year_search = TextField("Year:")

when I look at this form in the browser (Chrome) I get the message

Automatic credit card filling is disabled because this form does not use a secure connection

How can I get rid of this?
I have other fields which are defined in the same why, but they remember what has been typed before and help the user by suggesting old inputs.


问:
Azure policy - Cosmos DB SQL (Core) API - Restricting RU (Throughput) to not morethan 500
I am trying to implement an azure policy for Cosmos DB (SQL API) to deny if the user is creating more than 500 throughputs.

Here I used JSON for the policy rule,

```<code>{
  "mode": "All",
    "policyRule":{
         "if": {
          "allOf": [
             {
                "field": "type",
                "equals": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases"
             },
             {
                "not": {
                    "field": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/throughputSettings/default.resource.minimumThroughput",
                    "greater": 500
                }
             }
          ]
       },
       "then": {
          "effect": "deny"
       }
    }
}
</code>```

this is not working and not able to find issue what am doing.

Could you please help?

答: Your policy is set up to deny any throughput that are not greater than 500. </p>

Body:
I am trying to implement an azure policy for Cosmos DB (SQL API) to deny if the user is creating more than 500 throughputs.

Here I used JSON for the policy rule,

{
  "mode": "All",
    "policyRule":{
         "if": {
          "allOf": [
             {
                "field": "type",
                "equals": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases"
             },
             {
                "not": {
                    "field": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/throughputSettings/default.resource.minimumThroughput",
                    "greater": 500
                }
             }
          ]
       },
       "then": {
          "effect": "deny"
       }
    }
}

this is not working and not able to find issue what am doing.

Could you please help?


问:
Convert list of weekdays into intervals
I'm looking for a function that drops days of the week from a sequence of weekdays if 3 or more consecutive days follow each other. This is my test code (uses Test::More test framework)</p>

```<code>// function is($result, $expected, $message)
is(drop_days(""), "", 'Empty');
is(drop_days("Mo"), "Mo", 'One Day');
is(drop_days("Mo,Tu"), "Mo,Tu", 'Two Days');
is(drop_days("Mo,Tu,We"), "Mo-We", 'Three Days');
is(drop_days("Mo,Tu,We,Th,Fr,Sa,Su"), "Mo-Su", 'Seven Days');
is(drop_days("Mo,Tu,Th,Fr"), "Mo,Tu,Th,Fr", 'Four days with gap');
is(drop_days("Mo,Tu,We,Fr"), "Mo-We,Fr", '3 consecutive days, one single day');
is(drop_days("Mo,Tu,We,Fr,Sa,Su"), "Mo-We,Fr-Su", '2 pairs of 3 consecutive days');
</code>```

Title: Convert list of weekdays into intervals

Body:
I'm looking for a function that drops days of the week from a sequence of weekdays if 3 or more consecutive days follow each other. This is my test code (uses Test::More test framework)

// function is($result, $expected, $message)
is(drop_days(""), "", 'Empty');
is(drop_days("Mo"), "Mo", 'One Day');
is(drop_days("Mo,Tu"), "Mo,Tu", 'Two Days');
is(drop_days("Mo,Tu,We"), "Mo-We", 'Three Days');
is(drop_days("Mo,Tu,We,Th,Fr,Sa,Su"), "Mo-Su", 'Seven Days');
is(drop_days("Mo,Tu,Th,Fr"), "Mo,Tu,Th,Fr", 'Four days with gap');
is(drop_days("Mo,Tu,We,Fr"), "Mo-We,Fr", '3 consecutive days, one single day');
is(drop_days("Mo,Tu,We,Fr,Sa,Su"), "Mo-We,Fr-Su", '2 pairs of 3 consecutive days');

Body:
Another approach:

function drop_days( $str, $days = 'mo,tu,we,th,fr,sa,su' ) {
    $days_i_s = array_flip( explode( ',', $days ) );
    $days_i_n = explode( ',', $days );
    $day_string = str_replace( array_keys( $days_i_s ), array_values( $days_i_s ), strtolower( $str ) );
    return str_replace( array_values( $days_i_s ), array_keys( $days_i_s ), preg_replace_callback( '~(0,1,2,3,4,5,6)|(1,2,3,4,5,6)|(0,1,2,3,4,5)|(1,2,3,4,5)|(2,3,4,5,6)|(0,1,2,3,4)|(0,1,2,3)|(0,1,2)|(3,4,5,6)|(2,3,4,5)|(2,3,4)|(3,4,5)|(1,2,3,4)|(1,2,3)|(2,3,4)|(4,5,6)~', function($m) use($days_i_n){return $days_i_n[$m[0][0]].'-'.$days_i_n[$m[0][strlen($m[0])-1]] ;}, $day_string ) );
}

echo drop_days( "Mo,Tu,We,Fr,Sa,Su" );


问:
zsh completion: Disable ssh username completion
I am using the completion scripts that ship with ZSH (5.7.1) and I would like to turn off the autocompletion for usernames, but keep the completion for hostnames.

How can I do this?

Currently, there's an erroneous user that I can't figure out why it's being included (not in ~/.ssh/config, any identities, /etc/ssh, or any other location) and I figure it's probably easier to just disable username completion.

Example output is below; I want to remove the entire "login name" section rather than try and hunt down where unwanted-username is coming from.

```<code>$ ssh <tab>
 -- login name --
unwanted-username
 -- host --
example-host-1      example-host-1
</code>```

I expect there is a zstyle command which can disable it, but I'm not sure the correct incantation.  I expect this is the relevant configuration that needs to be changed:

```<code>$ zstyle | grep completion | grep ssh
        :completion:*:ssh:* users hosts-domain hosts-host users hosts-ipaddr
</code>```

However, I can't seem to get the correct incantation to remove the login name section.

答:
To disable completion of login names, in that context, try:

```<code>zstyle ':completion:*:ssh:argument-1:*' tag-order hosts
</code>```

or to merely hide them, try:

```<code>zstyle ':completion:*:ssh:*:users' hidden true
</code>```

Pressing Ctrl-X h instead of tab is a good way to determine the relevant tags and context strings.

Seems odd that you have an erroneous user being completed. Check for a users-hosts style being set, possibly without mention of ssh in the context. The ignored-patterns style could be another way to deal with an erroneous match in the general case, for example:

```<code>zstyle ':completion:*:ssh:*:users' ignored-patterns erroneous-username
</code>```

As you might discern from the name of the style, the last argument here can be a shell pattern with *, ? etc.

Body:
I am using the completion scripts that ship with ZSH (5.7.1) and I would like to turn off the autocompletion for usernames, but keep the completion for hostnames.

How can I do this?

Currently, there's an erroneous user that I can't figure out why it's being included (not in ~/.ssh/config, any identities, /etc/ssh, or any other location) and I figure it's probably easier to just disable username completion.

Example output is below; I want to remove the entire "login name" section rather than try and hunt down where unwanted-username is coming from.

$ ssh <tab>
 -- login name --
unwanted-username
 -- host --
example-host-1      example-host-1

I expect there is a zstyle command which can disable it, but I'm not sure the correct incantation.  I expect this is the relevant configuration that needs to be changed:

$ zstyle | grep completion | grep ssh
        :completion:*:ssh:* users hosts-domain hosts-host users hosts-ipaddr

However, I can't seem to get the correct incantation to remove the login name section.

Body:
To disable completion of login names, in that context, try:

zstyle ':completion:*:ssh:argument-1:*' tag-order hosts

or to merely hide them, try:

zstyle ':completion:*:ssh:*:users' hidden true

Pressing Ctrl-X h instead of tab is a good way to determine the relevant tags and context strings.

Seems odd that you have an erroneous user being completed. Check for a users-hosts style being set, possibly without mention of ssh in the context. The ignored-patterns style could be another way to deal with an erroneous match in the general case, for example:

zstyle ':completion:*:ssh:*:users' ignored-patterns erroneous-username

As you might discern from the name of the style, the last argument here can be a shell pattern with *, ? etc.


问:
How to use expect with nested hashes in rspec
In my code I have several conditions that look like:

```<code>if condition1
   a = some_hash["a"]["b"]
elsif condition2
   b = some_hash["c"]["d"]
</code>```

How do I test and mock these nested hash assignments with expect or some similar rspec function to ensure the proper assignment is occurring?

答:
Please see the following answer, which I believe answers your question: RSpec partial match against a nested hash

In a nutshell, you can use the following syntax:

```<code>expect(object).to receive(:method).with(hash_including(some: 'value'))
</code>```

But comment by @anothermh is valid — you do not have a proper RSpec setup there. You need something like the following:

```<code>RSpec.describe ClassName do
  it 'should have nested value' do
     expect(object).to receive(:method).with(hash_including(some: 'value'))
  end
end
</code>```

Body:
In my code I have several conditions that look like:

if condition1
   a = some_hash["a"]["b"]
elsif condition2
   b = some_hash["c"]["d"]

How do I test and mock these nested hash assignments with expect or some similar rspec function to ensure the proper assignment is occurring?

Body:
Please see the following answer, which I believe answers your question: RSpec partial match against a nested hash

In a nutshell, you can use the following syntax:

expect(object).to receive(:method).with(hash_including(some: 'value'))

But comment by @anothermh is valid — you do not have a proper RSpec setup there. You need something like the following:

RSpec.describe ClassName do
  it 'should have nested value' do
     expect(object).to receive(:method).with(hash_including(some: 'value'))
  end
end


问:
Scala failing to resolve a type mismatch problem in a complicated generated code
I have the following setup and I am trying to pass the compile type checking of the code with preferably minimal modification as the code is being generated by a tool and not by hand.

I think the problem is I need to come up with a better definition for T_MAX_LATTICE[T] or T_IntegerMaxLattice in M_TEST_COLL.

The code is kind of large so I can't post the whole code here but I put the repo URL at the bottom. I am struggling to visualize the type hierarchy.

I know the question is too general but all I am looking for is being able to compile the code without using uncheck cast and minimal modification to runtime code (or basic.handcode.scala)

Errors (1 and 2):

```<code>Type mismatch. Required:
  C_NUMERIC [ T_IntegerMaxLattice ]
  Found: M_MAX_LATTICE [ T_Integer ]

Type mismatch. Required:
   C_NUMERIC [ T_IntegerMaxLattice ]
   Found: M_MAX_LATTICE [ T_Integer ]
</code>```

Generated code:

Problem #1:

```<code>class M_TEST_COLL[T_T](name : String,val t_T : C_TYPE[T_T] with C_TINY[T_T])
  extends Module(name)
    with C_TEST_COLL[T_T,T_T]
{
  type T_Result = T_T;
  val v_equal = t_T.v_equal;
  val v_string = t_T.v_string;
  val v_assert = t_T.v_assert;
  val v_node_equivalent = t_T.v_node_equivalent;
  type T_Root = t_T.T_Root;
  val t_Root = t_T.t_Root;
  type T_Wood = t_T.T_Wood;
  val t_Wood = t_T.t_Wood;
  val p_root = t_T.p_root;
  val v_root = t_T.v_root;
  val p_branch = t_T.p_branch;
  val v_branch = t_T.v_branch;
  val p_leaf = t_T.p_leaf;
  val v_leaf = t_T.v_leaf;

  val t_Result : this.type = this;
  val t_IntegerMaxLattice = new M_MAX_LATTICE[T_Integer]("IntegerMaxLattice",t_Integer,0);
  type T_IntegerMaxLattice = /*TI*/T_MAX_LATTICE[T_Integer];
  private class E_foo(anchor : Null) extends Evaluation[Null,T_IntegerMaxLattice](anchor,"foo") {
    override def getDefault = new M__basic_4[ T_IntegerMaxLattice](t_IntegerMaxLattice).v__op_s(1,2);
    override def compute : ValueType = c_foo();
  }
</code>```

Problem #2:

```<code>  def c_foo() : T_IntegerMaxLattice = {
    Debug.begin("foo");
    try {
      return new M__basic_4[ T_IntegerMaxLattice](t_IntegerMaxLattice).v__op_s(1,2);
    } finally { Debug.end(); }
  }
</code>```

Repo url

答:
Try to make M_MAX_LATTICE extend not only C_TYPE as in previous question but also C_NUMERIC

```<code>class M_MAX_LATTICE[T_TO]
(name : String, t_TO:C_ORDERED[T_TO],v_min_element : T_TO)
  extends M_MAKE_LATTICE[T_TO](name,t_TO,v_min_element,
    new M__basic_3[ T_TO](t_TO).v__op_z,
    new M__basic_3[ T_TO](t_TO).v__op_z0,
    new M__basic_13[ T_TO](t_TO).v_max,
    new M__basic_13[ T_TO](t_TO).v_min)
    with C_MAX_LATTICE[T_TO,T_TO] with C_ORDERED[T_TO]
    with C_TYPE[T_TO] with C_NUMERIC[T_TO]
{
  val v_less = t_TO.v_less;
  val v_less_equal = t_TO.v_less_equal;
  override val v_assert: T_TO => Unit = ???
  override val v_node_equivalent: (T_TO, T_TO) => T_OrLattice = ???
  override val v_string: T_TO => String = ???
  override def v_zero: T_TO = ???
  override def v_one: T_TO = ???
  override val v_plus: (T_TO, T_TO) => T_TO = ???
  override val v_minus: (T_TO, T_TO) => T_TO = ???
  override val v_times: (T_TO, T_TO) => T_TO = ???
  override val v_divide: (T_TO, T_TO) => T_TO = ???
  override val v_unary_plus: T_TO => T_TO = ???
  override val v_unary_minus: T_TO => T_TO = ???
  override val v_unary_times: T_TO => T_TO = ???
  override val v_unary_divide: T_TO => T_TO = ???
}
</code>```

Body:
I have the following setup and I am trying to pass the compile type checking of the code with preferably minimal modification as the code is being generated by a tool and not by hand.

I think the problem is I need to come up with a better definition for T_MAX_LATTICE[T] or T_IntegerMaxLattice in M_TEST_COLL.

The code is kind of large so I can't post the whole code here but I put the repo URL at the bottom. I am struggling to visualize the type hierarchy.

I know the question is too general but all I am looking for is being able to compile the code without using uncheck cast and minimal modification to runtime code (or basic.handcode.scala)

Errors (1 and 2):

Type mismatch. Required:
  C_NUMERIC [ T_IntegerMaxLattice ]
  Found: M_MAX_LATTICE [ T_Integer ]

Type mismatch. Required:
   C_NUMERIC [ T_IntegerMaxLattice ]
   Found: M_MAX_LATTICE [ T_Integer ]

Generated code:

Problem #1:

class M_TEST_COLL[T_T](name : String,val t_T : C_TYPE[T_T] with C_TINY[T_T])
  extends Module(name)
    with C_TEST_COLL[T_T,T_T]
{
  type T_Result = T_T;
  val v_equal = t_T.v_equal;
  val v_string = t_T.v_string;
  val v_assert = t_T.v_assert;
  val v_node_equivalent = t_T.v_node_equivalent;
  type T_Root = t_T.T_Root;
  val t_Root = t_T.t_Root;
  type T_Wood = t_T.T_Wood;
  val t_Wood = t_T.t_Wood;
  val p_root = t_T.p_root;
  val v_root = t_T.v_root;
  val p_branch = t_T.p_branch;
  val v_branch = t_T.v_branch;
  val p_leaf = t_T.p_leaf;
  val v_leaf = t_T.v_leaf;

  val t_Result : this.type = this;
  val t_IntegerMaxLattice = new M_MAX_LATTICE[T_Integer]("IntegerMaxLattice",t_Integer,0);
  type T_IntegerMaxLattice = /*TI*/T_MAX_LATTICE[T_Integer];
  private class E_foo(anchor : Null) extends Evaluation[Null,T_IntegerMaxLattice](anchor,"foo") {
    override def getDefault = new M__basic_4[ T_IntegerMaxLattice](t_IntegerMaxLattice).v__op_s(1,2);
    override def compute : ValueType = c_foo();
  }

Problem #2:

  def c_foo() : T_IntegerMaxLattice = {
    Debug.begin("foo");
    try {
      return new M__basic_4[ T_IntegerMaxLattice](t_IntegerMaxLattice).v__op_s(1,2);
    } finally { Debug.end(); }
  }

Repo url

Body:
Try to make M_MAX_LATTICE extend not only C_TYPE as in previous question but also C_NUMERIC

class M_MAX_LATTICE[T_TO]
(name : String, t_TO:C_ORDERED[T_TO],v_min_element : T_TO)
  extends M_MAKE_LATTICE[T_TO](name,t_TO,v_min_element,
    new M__basic_3[ T_TO](t_TO).v__op_z,
    new M__basic_3[ T_TO](t_TO).v__op_z0,
    new M__basic_13[ T_TO](t_TO).v_max,
    new M__basic_13[ T_TO](t_TO).v_min)
    with C_MAX_LATTICE[T_TO,T_TO] with C_ORDERED[T_TO]
    with C_TYPE[T_TO] with C_NUMERIC[T_TO]
{
  val v_less = t_TO.v_less;
  val v_less_equal = t_TO.v_less_equal;
  override val v_assert: T_TO => Unit = ???
  override val v_node_equivalent: (T_TO, T_TO) => T_OrLattice = ???
  override val v_string: T_TO => String = ???
  override def v_zero: T_TO = ???
  override def v_one: T_TO = ???
  override val v_plus: (T_TO, T_TO) => T_TO = ???
  override val v_minus: (T_TO, T_TO) => T_TO = ???
  override val v_times: (T_TO, T_TO) => T_TO = ???
  override val v_divide: (T_TO, T_TO) => T_TO = ???
  override val v_unary_plus: T_TO => T_TO = ???
  override val v_unary_minus: T_TO => T_TO = ???
  override val v_unary_times: T_TO => T_TO = ???
  override val v_unary_divide: T_TO => T_TO = ???
}


问:
Recover SSH Key from GITHUB
I had an ssh key in git. Now that I reinstall my operating system, how can I recover my old github ssh key and put it in /home/user/.ssh/id_rsa?

I tried to generate a new password but in this case I would have to re-register my public key again in both gitlab and github, right?

答:
If you don't have a backup of your old key, then it was probably lost when you reinstalled your OS, since typically doing so reformats the hard drive.  GitHub wouldn't have your private key, since that's stored only on your computer.  GitHub holds only the public portion of the key, which can be used to verify connections, but not to make them.

However, it's fine to simply generate a new SSH key and add it to GitHub and GitLab, removing the old key.  Part of the idea behind SSH keys is that they can be rotated more easily than other types of credentials if needed.

The easiest way to do that is to run ssh-keygen -t ed25519, which will generate you a Ed25519 key, which is the preferred key form these days.  You can then add it to GitHub and GitLab as normal by copying the contents of ~/.ssh/id_ed25519.pub into the web interface.

Title: Recover SSH Key from GITHUB


问:
How to find which Database Roles are associated with a given User?
In SSMS I have a User X and there are Y, Z and P Database Roles available, how may I check what roles are added to a user X?

What have I tried:

In SSMS right click on database -> properties -> Permissions and see Explicit tab for a user X. I can see Permissions not association between role and the user. The same is for role I'm interested in, I see only permissions for role.

EDIT: Regarding GUI solution, I have no Properties option available for Users nor Roles.

答:
I do it this way:</p>

```<code>select user_name(role_principal_id)
from sys.database_role_members
where member_principal_id = user_id('your_user');
</code>```

Body:
I do it this way:

select user_name(role_principal_id)
from sys.database_role_members
where member_principal_id = user_id('your_user');


问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答:
You've gotten a number of answers to your original question, but I feel obliged to add one minor detail: both the original and the modified version suffer from a couple of what I'd consider problems. First, they don't really detect white-space correctly (e.g., they ignore vertical tabs, and any other white-space as defined by the locale), and they produce blank lines if words are separated by more than one white-space character.

For the first problem, I'd use isspace instead of directly comparing to the white-space characters you know about (incidentally, eliminating the source of the problem you encountered). For the second, you could add some logic to skip all consecutive white-space characters when you encounter the first, or you could add a flag to write out a new-line if and only if the current character is a space and the previous character you wrote was not a new-line.

Alternatively, you could read words using scanf with the %s conversion:

```<code>char buffer[256];

while (scanf("%255s", buffer))
    printf("%s\n", buffer);
</code>```

This approach, however, imposes an upper limit on the size of a single word. Under normal circumstances, that's rarely problem, but depending on the nature of the input it could/can be.

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}

Body:
You've gotten a number of answers to your original question, but I feel obliged to add one minor detail: both the original and the modified version suffer from a couple of what I'd consider problems. First, they don't really detect white-space correctly (e.g., they ignore vertical tabs, and any other white-space as defined by the locale), and they produce blank lines if words are separated by more than one white-space character.

For the first problem, I'd use isspace instead of directly comparing to the white-space characters you know about (incidentally, eliminating the source of the problem you encountered). For the second, you could add some logic to skip all consecutive white-space characters when you encounter the first, or you could add a flag to write out a new-line if and only if the current character is a space and the previous character you wrote was not a new-line.

Alternatively, you could read words using scanf with the %s conversion:

char buffer[256];

while (scanf("%255s", buffer))
    printf("%s\n", buffer);

This approach, however, imposes an upper limit on the size of a single word. Under normal circumstances, that's rarely problem, but depending on the nature of the input it could/can be.


问:
Best way to store timezone-independent time in JPA MySql
I can't find a good solution in JPA to store timezone-independent time in a mysql db.

I have a shift table, where I need to store the start and the end time for each shift.

```<code>+-------------+--------------+------+-----+----------+----------------+
| Field       | Type         | Null | Key | Default  | Extra          |
+-------------+--------------+------+-----+----------+----------------+
| id          | int(11)      | NO   | PRI | NULL     | auto_increment |
| name        | varchar(64)  | NO   |     | NULL     |                |
| start_time  | time         | NO   |     | 00:00:00 |                |
| end_time    | time         | NO   |     | 00:00:00 |                |
+-------------+--------------+------+-----+----------+----------------+
</code>```

So, the start/end times retrived from mysql have to be treated as strings (without applying a particular timezone). But if I store them as varchar(8) I cannot use the following query (without applying any type conversion from varchar to time).

```<code>select * from shift where ('21:30:00' BETWEEN start_time and end_time );
</code>```

So, I want to preserve the ability to compare them as times.

I tried to model the shift table as following:

```<code>    @Entity
    public class Shift {
      @Id
      private Long id;

      @Column(name = "name")
      private String name;

      @Column(name = "start_time")
      private LocalTime startTime;

      @Column(name = "end_time")
      private LocalTime endTime;

...
</code>```

The start_time and the end_time are mapped as LocalTime because the LocalTime doesn't store the timezone info. But, Hibernate convert the java.util.Date of each record retrived to a LocalTime applying the system default timezone, as following:

```<code>    if ( Date.class.isInstance( value ) ) {
        final Date ts = (Date) value;
        final Instant instant = Instant.ofEpochMilli( ts.getTime() );
        return LocalDateTime.ofInstant( instant, ZoneId.systemDefault() ).toLocalTime();
    }
</code>```

So, the resulting start/end time is relative to the timezone of the server.

A solution is to store them as integers and split hours from minutes. In this way, the shift table will have four columns: start_hours, start_minutes, end_hours, end_minutes. But it's tedious to make query using them in JPA.
There is a better solution?

UPDATE

I have to fetch the current shift using the timezone of the server. So, if I store times as UTC in the DB and then I query them converting the current server time to UTC doesn't work because during the Daylight Saving Time (DST) the server timezone increases by one. So, in the winter the 07:00:00+01 is converted to 06:00:00 UTC. But, in the summer 07:00:00+02 is converted to 05:00:00 UTC.

答:
Welcome to SO

It's always better to store dates with UTC TimeZone in database and do the conversion on client-side. You can set below property to force JPA To use UTC

spring.jpa.properties.hibernate.jdbc.time_zone=UTC

Hope this  hleps

You can take a look at this blog

Body:
I can't find a good solution in JPA to store timezone-independent time in a mysql db.

I have a shift table, where I need to store the start and the end time for each shift.

+-------------+--------------+------+-----+----------+----------------+
| Field       | Type         | Null | Key | Default  | Extra          |
+-------------+--------------+------+-----+----------+----------------+
| id          | int(11)      | NO   | PRI | NULL     | auto_increment |
| name        | varchar(64)  | NO   |     | NULL     |                |
| start_time  | time         | NO   |     | 00:00:00 |                |
| end_time    | time         | NO   |     | 00:00:00 |                |
+-------------+--------------+------+-----+----------+----------------+

So, the start/end times retrived from mysql have to be treated as strings (without applying a particular timezone). But if I store them as varchar(8) I cannot use the following query (without applying any type conversion from varchar to time).

select * from shift where ('21:30:00' BETWEEN start_time and end_time );

So, I want to preserve the ability to compare them as times.

I tried to model the shift table as following:

    @Entity
    public class Shift {
      @Id
      private Long id;

      @Column(name = "name")
      private String name;

      @Column(name = "start_time")
      private LocalTime startTime;

      @Column(name = "end_time")
      private LocalTime endTime;

...

The start_time and the end_time are mapped as LocalTime because the LocalTime doesn't store the timezone info. But, Hibernate convert the java.util.Date of each record retrived to a LocalTime applying the system default timezone, as following:

    if ( Date.class.isInstance( value ) ) {
        final Date ts = (Date) value;
        final Instant instant = Instant.ofEpochMilli( ts.getTime() );
        return LocalDateTime.ofInstant( instant, ZoneId.systemDefault() ).toLocalTime();
    }

So, the resulting start/end time is relative to the timezone of the server.

A solution is to store them as integers and split hours from minutes. In this way, the shift table will have four columns: start_hours, start_minutes, end_hours, end_minutes. But it's tedious to make query using them in JPA.
There is a better solution?

UPDATE

I have to fetch the current shift using the timezone of the server. So, if I store times as UTC in the DB and then I query them converting the current server time to UTC doesn't work because during the Daylight Saving Time (DST) the server timezone increases by one. So, in the winter the 07:00:00+01 is converted to 06:00:00 UTC. But, in the summer 07:00:00+02 is converted to 05:00:00 UTC.


问:
Found conflict between System.Runtime as well as System.IO
I upgraded my .Net framework on my solution from 4.5.2 to 4.8. I got some warnings initially and to fix them I did Update-Package -Id some.package –reinstall for all the packages in the warning.

Then it showed a generic warning and after looking in the diagnostics build log, I saw the following 4 warnings:

There was a conflict between "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" and "mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes".

and:

There was a conflict between "System.Net.Http, Version=4.1.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

and:

There was a conflict between "System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

and finally:

There was a conflict between "System.IO, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.IO, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

I have seen the solutions here and here and unfortunately they didn't help.

Now I managed to fix the System.Net.Http issue by changing the following in my *.csproj file as per suggestion of this post:

```<code>    <Reference Include="System.Net.Http">
      <HintPath>..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll</HintPath>
      <Private>True</Private>
    </Reference>
</code>```

changed to:

```<code><Reference Include="System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll</HintPath>
      <Private>True</Private>
    </Reference>
</code>```

However, I don't seem to figure out how to fix the System.Runtime and System.IO issues.

答: I ended up installing Visual Studio 2019, then updated the properties on each project to use .Net framework 4.8 and ran through the updates and it just worked.</p>

Body:
I upgraded my .Net framework on my solution from 4.5.2 to 4.8. I got some warnings initially and to fix them I did Update-Package -Id some.package –reinstall for all the packages in the warning.

Then it showed a generic warning and after looking in the diagnostics build log, I saw the following 4 warnings:

There was a conflict between "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" and "mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes".

and:

There was a conflict between "System.Net.Http, Version=4.1.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

and:

There was a conflict between "System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

and finally:

There was a conflict between "System.IO, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.IO, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

I have seen the solutions here and here and unfortunately they didn't help.

Now I managed to fix the System.Net.Http issue by changing the following in my *.csproj file as per suggestion of this post:

    <Reference Include="System.Net.Http">
      <HintPath>..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll</HintPath>
      <Private>True</Private>
    </Reference>

changed to:

<Reference Include="System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll</HintPath>
      <Private>True</Private>
    </Reference>

However, I don't seem to figure out how to fix the System.Runtime and System.IO issues.