问:
How can I make my input make a random selection
I need to to figure out how much the viewer spent watching one of the items in my dictionary. First I need to allow them to input how many viewers, which I got. But then I have to have each viewer them randomly select an item (it is allowed to duplicate).

Then show the total time that was spent on ever item that each viewer spent time on. Finally I need to show the total amount of time spent between all the items/vids that all viewers watched, as well as which
items were watched by the viewers (can't be duplicated). I'm very confused on where to begin.

Code:

```<code>n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?")) # You were taking the input of length as a string.
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(my_dict)

print("Your average length is", average)

sub = 0
while sub >= 0:
    sub = int(input("How many subscribers do you currently have? "))

if sub >= 0:
    print('Histogram:')
    for i in range(sub):
        choice = random.choice(list(my_dict))
        for i in range(choice):
                print('*', end=' ')
    print('\n')
</code>```

I'm working on finding a solution, but I don't know where to start so thinking I might as well post here first in case I can't find the answer. (Also I don't need to demonstrate this first part with a histogram technically, I thought it would just be easy, if you have another idea please let me know!)

答:
From what I have understood, you want to know the no. of viewers then get a random video. Finally, tell the amount of time they have spent watching that video,total time spend on each video(by all viewers), and at last total time spent(by all viewers in watching all videos). Correct me If I am wrong. You can use the following code:</p>
```<code>n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?")) # You were taking the input of length as a string.
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(my_dict)

print("Your average length is", average)

sub = int(input("How many subscribers do you currently have? "))
total_time = 0
total_time_eachvid = {}

if sub >= 0:
    print('Histogram:')
    for i in range(sub):
        choice = random.choice(list(my_dict))
        if choice in total_time_eachvid:
            total_time_eachvid[choice] += my_dict[choice] #If the video was already selected by a viewer once then add the time.
        else:
            total_time_eachvid[choice] = my_dict[choice] #If the video appears for first time then enter the length of the video.
        print("You have spent", my_dict[choice], "time.") # Printing the time or length of the video that the viewer selected(got randomly).
        total_time += my_dict[choice]
    print('\n')
print("Total Time spent by all viewers is:", total_time)
print("Total time spent on each video", total_time_eachvid)
</code>```

Body:
I need to to figure out how much the viewer spent watching one of the items in my dictionary. First I need to allow them to input how many viewers, which I got. But then I have to have each viewer them randomly select an item (it is allowed to duplicate).

Then show the total time that was spent on ever item that each viewer spent time on. Finally I need to show the total amount of time spent between all the items/vids that all viewers watched, as well as which
items were watched by the viewers (can't be duplicated). I'm very confused on where to begin.

Code:

n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?")) # You were taking the input of length as a string.
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(my_dict)

print("Your average length is", average)

sub = 0
while sub >= 0:
    sub = int(input("How many subscribers do you currently have? "))

if sub >= 0:
    print('Histogram:')
    for i in range(sub):
        choice = random.choice(list(my_dict))
        for i in range(choice):
                print('*', end=' ')
    print('\n')

I'm working on finding a solution, but I don't know where to start so thinking I might as well post here first in case I can't find the answer. (Also I don't need to demonstrate this first part with a histogram technically, I thought it would just be easy, if you have another idea please let me know!)

Body:
From what I have understood, you want to know the no. of viewers then get a random video. Finally, tell the amount of time they have spent watching that video,total time spend on each video(by all viewers), and at last total time spent(by all viewers in watching all videos). Correct me If I am wrong. You can use the following code:

n = int(input())
my_dict = {}

for i in range(n):
    titles=input("What is the ")
    length=int(input("What is length?")) # You were taking the input of length as a string.
    my_dict[titles] = length
print ("You have", n," on your. The names of your are:", my_dict)

shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(my_dict)

print("Your average length is", average)

sub = int(input("How many subscribers do you currently have? "))
total_time = 0
total_time_eachvid = {}

if sub >= 0:
    print('Histogram:')
    for i in range(sub):
        choice = random.choice(list(my_dict))
        if choice in total_time_eachvid:
            total_time_eachvid[choice] += my_dict[choice] #If the video was already selected by a viewer once then add the time.
        else:
            total_time_eachvid[choice] = my_dict[choice] #If the video appears for first time then enter the length of the video.
        print("You have spent", my_dict[choice], "time.") # Printing the time or length of the video that the viewer selected(got randomly).
        total_time += my_dict[choice]
    print('\n')
print("Total Time spent by all viewers is:", total_time)
print("Total time spent on each video", total_time_eachvid)


来源: stackexchange

问:
Change object parameter by useState() in ReactJS
So I'm trying to change an object parameter that is being called by .map inside curly braces. Here is the code:

```<code>import React, { useEffect, useState } from 'react'

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])

  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{`value.location.${searchQuery}`}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;
</code>```

But it doesn't work, it only return a string. I've tried to :

Remove the Apostrophe ``

Change the curly braces to another brackets []

Make a const outside return() just for value.location.${searchQuery} and put it back to the curly braces

Some other small changes I kinda forgot

How to complete an object parameter by ${}?

Any help would be appreciated, thanks before!

答:
You need to use square brackets to get the computed value of searchQuery value.location[searchQuery]

For example:

```<code>import React, { useEffect, useState } from 'react';

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])

  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{value.location[searchQuery]}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I'm trying to change an object parameter that is being called by .map inside curly braces. Here is the code:

import React, { useEffect, useState } from 'react'

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])

  return (

      <form>
        <input onChange={handSearch}></input>
      </form>

Available Input: city, state, country, postcode

      {
        news.map((value, index) => (

{`value.location.${searchQuery}`}

        ))
      }

{searchQuery}

  );
}

export default App;

But it doesn't work, it only return a string. I've tried to :

Remove the Apostrophe ``

Change the curly braces to another brackets []

Make a const outside return() just for value.location.${searchQuery} and put it back to the curly braces

Some other small changes I kinda forgot

How to complete an object parameter by ${}?

Any help would be appreciated, thanks before!

Body:
You need to use square brackets to get the computed value of searchQuery value.location[searchQuery]

For example:

import React, { useEffect, useState } from 'react';

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])

  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{value.location[searchQuery]}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;


问:
How to disable an Entry on tkinter when a Checkbutton is unchecked using for loop and dictionary
I'm working on a Windows application for my work and my knowledge on Python is very limited, so I didn't know how to figure this out :

I want to make each entry widget inside the frame disabled when its checkbutton is unchecked and enabled when its checkbutton is checked and make them all checked by default.
I tried this code that I took part of it from this tutorial but it didn't work as expected.

```<code>from tkinter import *

class Principal():
    def __init__(self):
        self.root= Tk()
        self.root.geometry('800x800')

        self.prixArticlesFrame = LabelFrame(self.root, text="Prix des articles", width=2000)
        self.prixArticlesFrame.place(relx = 0.75, rely = 0.15,anchor = N)

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(),
            "Remblai" : IntVar(),
            "Blocage" : IntVar(),
            "Beton de propreté": IntVar(),
            "Beton armé": IntVar(),
            "Acier à haute adherence": IntVar(),
            "Joint de dilatation": IntVar(),

        }
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            self.cur_check = Checkbutton(self.prixArticlesFrame,
            text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1,
            offvalue=0,command=self.ArticlesEntryState)
            self.cur_check.grid(row=index, column=0, padx=10, pady=10, sticky="W")

        self.DefautArticlesEntries={
            "Deblai" : StringVar(),
            "Remblai" : StringVar(),
            "Blocage" : StringVar(),
            "Beton de propreté": StringVar(),
            "Beton armé": StringVar(),
            "Acier à haute adherence": StringVar(),
            "Joint de dilatation": StringVar(),

        }

        for index, (key, value) in enumerate(self.DefautArticlesEntries.items()):
            self.cur_entry = 'DefautArticlesEntries' +key

            self.cur_entry=Entry(self.prixArticlesFrame,width=10,
                          textvariable=self.DefautArticlesEntries[key])
            self.cur_entry.grid(row=index,column=2,padx=10)
            self.cur_entry.config(state=NORMAL)
        self.root.mainloop()

    def ArticlesEntryState(self):
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):

            if self.DefautArticlesCheckButton[key].get() == 1:
                self.cur_entry.grid(row=index,column=2,padx=10)
                self.cur_entry.config(state=NORMAL)

            elif self.DefautArticlesCheckButton[key].get() == 0:
                self.cur_entry.config(state=DISABLED)

app = Principal()
</code>```

here is what I got in gif image

What I have done wrong?
Thanks

答:
As per my understanding. you are asking to link check button and Line Edit. i given example code to link.</p>
```<code>import tkinter
from tkinter import *

def test():
    if e['state'] == 'normal':
        e['state'] = 'disabled'
    else:
        e['state'] = 'normal'

w=Tk()
e=Entry()
e.pack()
cb=Checkbutton(command=test)
cb.select()
cb.pack()
w.mainloop()
</code>```

Body:
I'm working on a Windows application for my work and my knowledge on Python is very limited, so I didn't know how to figure this out :

I want to make each entry widget inside the frame disabled when its checkbutton is unchecked and enabled when its checkbutton is checked and make them all checked by default.
I tried this code that I took part of it from this tutorial but it didn't work as expected.

from tkinter import *

class Principal():
    def __init__(self):
        self.root= Tk()
        self.root.geometry('800x800')

        self.prixArticlesFrame = LabelFrame(self.root, text="Prix des articles", width=2000)
        self.prixArticlesFrame.place(relx = 0.75, rely = 0.15,anchor = N)

        self.DefautArticlesCheckButton={
            "Deblai" : IntVar(),
            "Remblai" : IntVar(),
            "Blocage" : IntVar(),
            "Beton de propreté": IntVar(),
            "Beton armé": IntVar(),
            "Acier à haute adherence": IntVar(),
            "Joint de dilatation": IntVar(),

        }
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):
            self.cur_check = Checkbutton(self.prixArticlesFrame,
            text=key,variable=self.DefautArticlesCheckButton[key], onvalue=1,
            offvalue=0,command=self.ArticlesEntryState)
            self.cur_check.grid(row=index, column=0, padx=10, pady=10, sticky="W")

        self.DefautArticlesEntries={
            "Deblai" : StringVar(),
            "Remblai" : StringVar(),
            "Blocage" : StringVar(),
            "Beton de propreté": StringVar(),
            "Beton armé": StringVar(),
            "Acier à haute adherence": StringVar(),
            "Joint de dilatation": StringVar(),

        }

        for index, (key, value) in enumerate(self.DefautArticlesEntries.items()):
            self.cur_entry = 'DefautArticlesEntries' +key

            self.cur_entry=Entry(self.prixArticlesFrame,width=10,
                          textvariable=self.DefautArticlesEntries[key])
            self.cur_entry.grid(row=index,column=2,padx=10)
            self.cur_entry.config(state=NORMAL)
        self.root.mainloop()

    def ArticlesEntryState(self):
        for index, (key, value) in enumerate(self.DefautArticlesCheckButton.items()):

            if self.DefautArticlesCheckButton[key].get() == 1:
                self.cur_entry.grid(row=index,column=2,padx=10)
                self.cur_entry.config(state=NORMAL)

            elif self.DefautArticlesCheckButton[key].get() == 0:
                self.cur_entry.config(state=DISABLED)

app = Principal()

here is what I got in gif image

What I have done wrong?
Thanks

Body:
As per my understanding. you are asking to link check button and Line Edit. i given example code to link.

import tkinter
from tkinter import *

def test():
    if e['state'] == 'normal':
        e['state'] = 'disabled'
    else:
        e['state'] = 'normal'

w=Tk()
e=Entry()
e.pack()
cb=Checkbutton(command=test)
cb.select()
cb.pack()
w.mainloop()


问:
How to put a loop in a switch statement
I can't seem to figure out how to loop back to the selection if the value is invalid. Currently making a currency conversion calculator. Can't seem to make the terminal let the user input another number so they could convert freely. Thnx in advance!</p>
```<code>int main()
{
    int value;
    cout << "Please select your conversion." << endl;
    cout << "Press 1 to convert PHP to US Dollars" << endl;
    cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << endl;
    cout << "Press 3 to convert US Dollars to PHP" << endl;
    cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << endl;

    cin>>value;
    /* test loop
    while (int value > 4) {
        cout << "Invalid Input." << endl;
        cout << "Please input another number." << endl;
        }
    */
    float amount;
    float result;

    switch (value){
    case 1:
        cout << "Enter PHP Value: ";
        cin >> amount;
        result=amount*0.020;
        cout << amount << " PHP = " << result <<
    "USD";

    break;

    case 2:
        cout << "Enter PHP Value: ";
        cin >> amount;
        result=amount*0.014;
        cout << amount << " PHP = " << result << " GBP";

    break;

    case 3:
        cout << "Enter USD Value: ";
        cin >> amount;
        result=amount*51.27;
        cout << amount << " USD = " << result << " PHP";
    break;

    case 4:
        cout << "Enter GBP (Pound Sterling) Value: ";
        cin >> amount;
        result=amount*69.57;
        cout << amount << " GBP = " << result << " PHP";

    break;

    default:
        cout << "Invalid Input." << endl;
        cout << "Please input another number." << endl;
        break;

    }
    return 0;
}
</code>```

答:
Wrap everything in a while loop as such:

```<code>#include <iostream>

int main()
{
    while (true) // While loop
    {
        int value;
        std::cout << "Please select your conversion." << std::endl;
        std::cout << "Press 1 to convert PHP to US Dollars" << std::endl;
        std::cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << std::endl;
        std::cout << "Press 3 to convert US Dollars to PHP" << std::endl;
        std::cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << std::endl;

        std::cin >> value;
        /* test loop
    while (int value > 4) {
        std::cout << "Invalid Input." << endl;
        std::cout << "Please input another number." << endl;
        }
    */
        float amount;
        float result;

        switch (value) {
        case 1:
            std::cout << "Enter PHP Value: ";
            std::cin >> amount;
            result = amount * 0.020;
            std::cout << amount << " PHP = " << result <<
                "USD";

            break;

        case 2:
            std::cout << "Enter PHP Value: ";
            std::cin >> amount;
            result = amount * 0.014;
            std::cout << amount << " PHP = " << result << " GBP";

            break;

        case 3:
            std::cout << "Enter USD Value: ";
            std::cin >> amount;
            result = amount * 51.27;
            std::cout << amount << " USD = " << result << " PHP";
            break;

        case 4:
            std::cout << "Enter GBP (Pound Sterling) Value: ";
            std::cin >> amount;
            result = amount * 69.57;
            std::cout << amount << " GBP = " << result << " PHP";

            break;

        default:
            std::cout << "Invalid Input." << std::endl;
            std::cout << "Please input another number." << std::endl;
            break;
        }

        std::cout << std::endl; // Add this line to skip an extra line (for looks)
    }
    // Removed 'return 0;'
}
</code>```

Also, don't use the following in your code:

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

...as it's considered as bad practice. Type out std:: everytime instead.

Also consider refactoring your code by moving the code inside the while loop to a new function as such:

```<code>#include <iostream>

bool currency_conversion()
{
    int value;
    std::cout << "Please select your conversion." << std::endl;
    std::cout << "Press 1 to convert PHP to US Dollars" << std::endl;
    std::cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << std::endl;
    std::cout << "Press 3 to convert US Dollars to PHP" << std::endl;
    std::cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << std::endl;

    std::cin >> value;
    /* test loop
while (int value > 4) {
    std::cout << "Invalid Input." << endl;
    std::cout << "Please input another number." << endl;
    }
*/
    float amount;
    float result;

    switch (value) {
    case 1:
        std::cout << "Enter PHP Value: ";
        std::cin >> amount;
        result = amount * 0.020;
        std::cout << amount << " PHP = " << result <<
            "USD";

        break;

    case 2:
        std::cout << "Enter PHP Value: ";
        std::cin >> amount;
        result = amount * 0.014;
        std::cout << amount << " PHP = " << result << " GBP";

        break;

    case 3:
        std::cout << "Enter USD Value: ";
        std::cin >> amount;
        result = amount * 51.27;
        std::cout << amount << " USD = " << result << " PHP";
        break;

    case 4:
        std::cout << "Enter GBP (Pound Sterling) Value: ";
        std::cin >> amount;
        result = amount * 69.57;
        std::cout << amount << " GBP = " << result << " PHP";

        break;

    default:
        std::cout << "Invalid Input." << std::endl;
        std::cout << "Please input another number." << std::endl;
        break;
    }

    std::cout << std::endl;
    return true;
}

int main()
{
    while (currency_conversion()) { /* Loop */ }
}
</code>```

Anytime you wish to exit the application, return false from the currency_conversion function.

Title: How to put a loop in a switch statement

Body:
I can't seem to figure out how to loop back to the selection if the value is invalid. Currently making a currency conversion calculator. Can't seem to make the terminal let the user input another number so they could convert freely. Thnx in advance!

int main()
{
    int value;
    cout << "Please select your conversion." << endl;
    cout << "Press 1 to convert PHP to US Dollars" << endl;
    cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << endl;
    cout << "Press 3 to convert US Dollars to PHP" << endl;
    cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << endl;

    cin>>value;
    /* test loop
    while (int value > 4) {
        cout << "Invalid Input." << endl;
        cout << "Please input another number." << endl;
        }
    */
    float amount;
    float result;

    switch (value){
    case 1:
        cout << "Enter PHP Value: ";
        cin >> amount;
        result=amount*0.020;
        cout << amount << " PHP = " << result <<
    "USD";

    break;

    case 2:
        cout << "Enter PHP Value: ";
        cin >> amount;
        result=amount*0.014;
        cout << amount << " PHP = " << result << " GBP";

    break;

    case 3:
        cout << "Enter USD Value: ";
        cin >> amount;
        result=amount*51.27;
        cout << amount << " USD = " << result << " PHP";
    break;

    case 4:
        cout << "Enter GBP (Pound Sterling) Value: ";
        cin >> amount;
        result=amount*69.57;
        cout << amount << " GBP = " << result << " PHP";

    break;

    default:
        cout << "Invalid Input." << endl;
        cout << "Please input another number." << endl;
        break;

    }
    return 0;
}

Body:
Wrap everything in a while loop as such:

#include <iostream>

int main()
{
    while (true) // While loop
    {
        int value;
        std::cout << "Please select your conversion." << std::endl;
        std::cout << "Press 1 to convert PHP to US Dollars" << std::endl;
        std::cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << std::endl;
        std::cout << "Press 3 to convert US Dollars to PHP" << std::endl;
        std::cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << std::endl;

        std::cin >> value;
        /* test loop
    while (int value > 4) {
        std::cout << "Invalid Input." << endl;
        std::cout << "Please input another number." << endl;
        }
    */
        float amount;
        float result;

        switch (value) {
        case 1:
            std::cout << "Enter PHP Value: ";
            std::cin >> amount;
            result = amount * 0.020;
            std::cout << amount << " PHP = " << result <<
                "USD";

            break;

        case 2:
            std::cout << "Enter PHP Value: ";
            std::cin >> amount;
            result = amount * 0.014;
            std::cout << amount << " PHP = " << result << " GBP";

            break;

        case 3:
            std::cout << "Enter USD Value: ";
            std::cin >> amount;
            result = amount * 51.27;
            std::cout << amount << " USD = " << result << " PHP";
            break;

        case 4:
            std::cout << "Enter GBP (Pound Sterling) Value: ";
            std::cin >> amount;
            result = amount * 69.57;
            std::cout << amount << " GBP = " << result << " PHP";

            break;

        default:
            std::cout << "Invalid Input." << std::endl;
            std::cout << "Please input another number." << std::endl;
            break;
        }

        std::cout << std::endl; // Add this line to skip an extra line (for looks)
    }
    // Removed 'return 0;'
}

Also, don't use the following in your code:

using namespace std;

...as it's considered as bad practice. Type out std:: everytime instead.

Also consider refactoring your code by moving the code inside the while loop to a new function as such:

#include <iostream>

bool currency_conversion()
{
    int value;
    std::cout << "Please select your conversion." << std::endl;
    std::cout << "Press 1 to convert PHP to US Dollars" << std::endl;
    std::cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << std::endl;
    std::cout << "Press 3 to convert US Dollars to PHP" << std::endl;
    std::cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << std::endl;

    std::cin >> value;
    /* test loop
while (int value > 4) {
    std::cout << "Invalid Input." << endl;
    std::cout << "Please input another number." << endl;
    }
*/
    float amount;
    float result;

    switch (value) {
    case 1:
        std::cout << "Enter PHP Value: ";
        std::cin >> amount;
        result = amount * 0.020;
        std::cout << amount << " PHP = " << result <<
            "USD";

        break;

    case 2:
        std::cout << "Enter PHP Value: ";
        std::cin >> amount;
        result = amount * 0.014;
        std::cout << amount << " PHP = " << result << " GBP";

        break;

    case 3:
        std::cout << "Enter USD Value: ";
        std::cin >> amount;
        result = amount * 51.27;
        std::cout << amount << " USD = " << result << " PHP";
        break;

    case 4:
        std::cout << "Enter GBP (Pound Sterling) Value: ";
        std::cin >> amount;
        result = amount * 69.57;
        std::cout << amount << " GBP = " << result << " PHP";

        break;

    default:
        std::cout << "Invalid Input." << std::endl;
        std::cout << "Please input another number." << std::endl;
        break;
    }

    std::cout << std::endl;
    return true;
}

int main()
{
    while (currency_conversion()) { /* Loop */ }
}

Anytime you wish to exit the application, return false from the currency_conversion function.


问:
Typescript: Can someone explain what's the square bracket [P] after {} does?
I was reading this article about what's new in typescript 4.6 and I came across this weird syntax.

Could someone please explain what it does?

type UnionRecord
 = { [K in P]:
    {
        kind: K;
        v: TypeMap[K];
        f: (p: TypeMap[K]) => void;
    }
}[P];
```
<p>The {}[P] : this [P] followed by the {}. Why is it there?</p>
<p>The full typescript code is given below.</p>
```interface TypeMap {
    "number": number;
    "string": string;
    "boolean": boolean;
}

type UnionRecord
 = { [K in P]:
    {
        kind: K;
        v: TypeMap[K];
        f: (p: TypeMap[K]) => void;
    }
}[P];

function processRecord<K extends keyof TypeMap>(record: UnionRecord<K>) {
    return record.f(record.v);
}

processRecord({
    kind: "string",
    v: "hello!",

    // 'val' used to implicitly have the type 'string | number | boolean',
    // but now is correctly inferred to just 'string'.
    f: val => {
        console.log(val.toUpperCase());
    }
})
```

答:
Without the [P] you'd get a map with keys from P, in this example this would be a map with a subset of the keys "number", "string" and "boolean".

By adding an index lookup with the entire set of keys P this instead evaluates to a union type of all possible values for the given keys or explicit: Inter["number"] | Inter["string"] | Inter["boolean"] where

```<code>type Inter<P extends keyof TypeMap> = {
    [K in P]: {
        kind: K;
        v: TypeMap[K];
        f: (p: TypeMap[K]) => void;
    }
}
</code>```

For another example consider:

```<code>interface User {
  firstName: string;
  lastName: string;
  active: boolean;
}

type UserFieldTypes = User[keyof User]
// UserFieldTypes is User['fistName'] | User['lastName'] | User['active']
// which equals string | string | boolean
</code>```

Feel free to ask when there's still something unclear to you.

Body:
I was reading this article about what's new in typescript 4.6 and I came across this weird syntax.

Could someone please explain what it does?

type UnionRecord
 = { [K in P]:
    {
        kind: K;
        v: TypeMap[K];
        f: (p: TypeMap[K]) => void;
    }
}[P];

The {}[P] : this [P] followed by the {}. Why is it there?

The full typescript code is given below.

interface TypeMap {
    "number": number;
    "string": string;
    "boolean": boolean;
}

type UnionRecord
 = { [K in P]:
    {
        kind: K;
        v: TypeMap[K];
        f: (p: TypeMap[K]) => void;
    }
}[P];

function processRecord<K extends keyof TypeMap>(record: UnionRecord<K>) {
    return record.f(record.v);
}

processRecord({
    kind: "string",
    v: "hello!",

    // 'val' used to implicitly have the type 'string | number | boolean',
    // but now is correctly inferred to just 'string'.
    f: val => {
        console.log(val.toUpperCase());
    }
})

Body:
Without the [P] you'd get a map with keys from P, in this example this would be a map with a subset of the keys "number", "string" and "boolean".

By adding an index lookup with the entire set of keys P this instead evaluates to a union type of all possible values for the given keys or explicit: Inter["number"] | Inter["string"] | Inter["boolean"] where

type Inter<P extends keyof TypeMap> = {
    [K in P]: {
        kind: K;
        v: TypeMap[K];
        f: (p: TypeMap[K]) => void;
    }
}

For another example consider:

interface User {
  firstName: string;
  lastName: string;
  active: boolean;
}

type UserFieldTypes = User[keyof User]
// UserFieldTypes is User['fistName'] | User['lastName'] | User['active']
// which equals string | string | boolean

Feel free to ask when there's still something unclear to you.


问:
Setting up postgres database for recipes
I am new to PostgreSQL and trying to plan a database that will allow me to query recipes based on id, ingredients etc from a provided dataset, example below.

I am getting a bit thrownoff by the nested ingredients and how to lay out my tables.

I was initially thinking two tables one for instructions and image and another for the ingredients.

i was now wondering if i am on the right lines and if so how to loop through the nested ingredients to produce a useful second table

enter code here

```<code>  [  {
 "id": "recipe-88",
 "imageUrl": "http://www.images.com/12",
 "instructions": "blend with oat milk and ice, sprinkle with
 salt",
 "ingredients": [
   { "name": "blueberries", "grams": 114 },
   { "name": "coffee", "grams": 20 },
   { "name": "kale", "grams": 48 }
 ]
},
{
 "id": "recipe-74",
 "imageUrl": "http://www.images.com/2",
 "instructions": "crush ingredients with mortar and pestle, mix
 with whole milk, serve in bowl",
 "ingredients": [
   { "name": "coffee", "grams": 25 },
   { "name": "lime", "grams": 140 },
   { "name": "strawberries", "grams": 3 },
   { "name": "apricots", "grams": 24 },
   { "name": "kale", "grams": 50 }
 ]
},
{
 "id": "recipe-77",
 "imageUrl": "http://www.images.com/25",
 "instructions": "blend with oat milk and ice, sprinkle with
  salt",
 "ingredients": [
   { "name": "coconut", "grams": 14 },
   { "name": "coconut", "grams": 57 },
   { "name": "lime", "grams": 153 },
   { "name": "oat milk", "grams": 31 }
 ]
},]

</code>```

答:
I have parsed the json you provided and loaded it in a table.
Check the dbfiddle link.

Here is the parsed content loaded into a table.

```<code>postgres=# select * from parsedjj;
 id | recipe_id |        imageurl         |                                 instructions                                  |                                                                                ingredients
----+-----------+-------------------------+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  1 | recipe-88 | http//www.images.com/12 | blend with oat milk and ice, sprinkle with salt                               | [{"name": "blueberries", "grams": 114}, {"name": "coffee", "grams": 20}, {"name": "kale", "grams": 48}]
  2 | recipe-74 | http//www.images.com/2  | crush ingredients with mortar and pestle, mix  with whole milk, serve in bowl | [{"name": "coffee", "grams": 25}, {"name": "lime", "grams": 140}, {"name": "strawberries", "grams": 3}, {"name": "apricots", "grams": 24}, {"name": "kale", "grams": 50}]
  3 | recipe-77 | http//www.images.com/25 | blend with oat milk and ice, sprinkle with   salt                             | [{"name": "coconut", "grams": 14}, {"name": "coconut", "grams": 57}, {"name": "lime", "grams": 153}, {"name": "oat milk", "grams": 31}]
(3 rows)
</code>```

Note: I had changed the  JSON key value from "imageUrl" to "image" because possibly "url" which is a keyword for postgres might have been impeding the parsing.

Body:
I am new to PostgreSQL and trying to plan a database that will allow me to query recipes based on id, ingredients etc from a provided dataset, example below.

I am getting a bit thrownoff by the nested ingredients and how to lay out my tables.

I was initially thinking two tables one for instructions and image and another for the ingredients.

i was now wondering if i am on the right lines and if so how to loop through the nested ingredients to produce a useful second table

enter code here

  [  {
 "id": "recipe-88",
 "imageUrl": "http://www.images.com/12",
 "instructions": "blend with oat milk and ice, sprinkle with
 salt",
 "ingredients": [
   { "name": "blueberries", "grams": 114 },
   { "name": "coffee", "grams": 20 },
   { "name": "kale", "grams": 48 }
 ]
},
{
 "id": "recipe-74",
 "imageUrl": "http://www.images.com/2",
 "instructions": "crush ingredients with mortar and pestle, mix
 with whole milk, serve in bowl",
 "ingredients": [
   { "name": "coffee", "grams": 25 },
   { "name": "lime", "grams": 140 },
   { "name": "strawberries", "grams": 3 },
   { "name": "apricots", "grams": 24 },
   { "name": "kale", "grams": 50 }
 ]
},
{
 "id": "recipe-77",
 "imageUrl": "http://www.images.com/25",
 "instructions": "blend with oat milk and ice, sprinkle with
  salt",
 "ingredients": [
   { "name": "coconut", "grams": 14 },
   { "name": "coconut", "grams": 57 },
   { "name": "lime", "grams": 153 },
   { "name": "oat milk", "grams": 31 }
 ]
},]

Body:
I have parsed the json you provided and loaded it in a table.
Check the dbfiddle link.

Here is the parsed content loaded into a table.

postgres=# select * from parsedjj;
 id | recipe_id |        imageurl         |                                 instructions                                  |                                                                                ingredients
----+-----------+-------------------------+-------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  1 | recipe-88 | http//www.images.com/12 | blend with oat milk and ice, sprinkle with salt                               | [{"name": "blueberries", "grams": 114}, {"name": "coffee", "grams": 20}, {"name": "kale", "grams": 48}]
  2 | recipe-74 | http//www.images.com/2  | crush ingredients with mortar and pestle, mix  with whole milk, serve in bowl | [{"name": "coffee", "grams": 25}, {"name": "lime", "grams": 140}, {"name": "strawberries", "grams": 3}, {"name": "apricots", "grams": 24}, {"name": "kale", "grams": 50}]
  3 | recipe-77 | http//www.images.com/25 | blend with oat milk and ice, sprinkle with   salt                             | [{"name": "coconut", "grams": 14}, {"name": "coconut", "grams": 57}, {"name": "lime", "grams": 153}, {"name": "oat milk", "grams": 31}]
(3 rows)

Note: I had changed the  JSON key value from "imageUrl" to "image" because possibly "url" which is a keyword for postgres might have been impeding the parsing.


问:
What's the difference between these functions
What's the difference between these functions

create_task and call_soon

call_soon_threadsafe and run_coroutine_threadsafe

create_task vs call_soon

these two functions schedule the execution of a Coroutines, not thread-safe.

create_task returns a Task object, and call_soon returns Handle object, but is there any difference other than this, especially in usage?

call_soon_threadsafe vs run_coroutine_threadsafe

these two functions are meant to be called from a different OS thread than the one where the event loop is running. And in most cases, I can use any of them.

答:
create_task vs call_soon - these two functions schedule the execution of a Coroutines

No, only create_task schedules the execution of a coroutine (async function). call_soon schedules the one-shot execution of an ordinary function.

So, if you have a coroutine x defined with async def that you want executed "in the background", you call asyncio.create_task(x()). If you have a function f defined with def that you want executed as soon as the event loop is next idle, you call loop.call_soon(f).

The same difference in usage applies to run_coroutine_threadsafe and call_soon_threadsafe, which allow submitting work to a running event loop from a different thread.


问:
Converting HTML in PHP File to PDF File
I have a php file which queries a database and then writes and updates the html accordingly.

I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:

```<code>FPDF error: Unable to create output file: Entry Report
</code>```

I suspect the problem is because I am passing a php file instead of a html file:

```<code><?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>
</code>```

Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...

Or is there a direct way to convert a php file into a pdf file...

EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...

I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?

Here is the php page:

```<code><?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src = "jQuery.js"></script>
   <script>
   $(document).ready(function(){
       $("#export").click(function(e){
       //post to html2pdfconverter.php
       $("#link").val("Testers/viewentryreport.php");
       $("#nm").val("Entry Report.pdf");
       $("form#sendanswers").submit();
       });
   });
  </script>
  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
  </head>
  <body>
  <h1>Entry Report - <?php echo($date); ?></h1>
  <div id = "buttons">
  <form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
  <input type = "hidden" name = "link" id = "link" value = "">
  <input type = "hidden" name = "nm" id = "nm" value = "">
  <input type = "button" name = "export" id = "export" value = "Export As PDF"/>
  </form>
  </div>
  <h3>Biological Information</h3>
  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("<br/>");
      echo($value['question']." <br/> "."<img src = \"$image\"/>");
      echo("<br/>");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("<br/>");
    $i++;
      }
  ?>
  <h3>Fatigue and Recovery</h3>
  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Illness and Injury</h3>
  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>Training Sessions</h3>
  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("<br/>");
      }
  ?>
  <h3>General Feedback</h3>
  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       $sectionFive = "User didn't leave any feedback";
       echo("User didn't leave any feedback");
     }
     echo("<br/>");
  ?>
  </body>
</html>
<?php
}
?>
</code>```

and html2pdfconverter.php

```<code><?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>
</code>```

EDIT @TIMFERRIS

I changed my convert function to this based on @TimeFerris' answer:

```<code>function convert($link, $name){

  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $content = file_get_contents( $link ); //shorter than what you did
  ob_start();
  echo $content;
  $pdf->WriteHTML( ob_get_contents() );
  ob_end_clean();
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
</code>```

The PDF file is created but still blank

答:
The php file you are supplying has to run through a parser before it's valid html code.</p>

```<code>$content = file_get_contents( $filename ); //shorter than what you did
ob_start();
echo $content;
$pdf->WriteHTML( ob_get_contents() );
ob_end_clean();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Converting HTML in PHP File to PDF File

Body:
I have a php file which queries a database and then writes and updates the html accordingly.

I have a button on this page "Export As PDF"..I am trying to convert this page to a pdf using HTML2FPDF, but I get the following error:

FPDF error: Unable to create output file: Entry Report

I suspect the problem is because I am passing a php file instead of a html file:

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

Does anyone know how I can get around this? perhaps by either converting php to html then html to pdf...

Or is there a direct way to convert a php file into a pdf file...

EDIT: OK so the problem was that I didn't allow public write permissions. Upon changing this, I managed it to create the pdf file...The problem is this....the pdf file is blank...

I know this has something to do with the fact that I am passing a php page which is probably empty when it is being passed...How do I capture the html content within the html so the pdf output isn't blank?

Here is the php page:

<?php

function connect() {
  $dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db("PDS", $dbh);
  return $dbh;
}

session_start();

if(isset($_SESSION['username'])){
  if(isset($_POST['entryId'])){
    //do something
    $dbh = connect();
    $ide = $_POST['entryId'];
    $usertab = $_POST['usertable'];
    $answertable = $usertab . "Answers";
    $entrytable = $usertab . "Entries";
    $query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());

    if($query){
      //set variables

      $sectionOne = array();
      $sectionTwo = array();
      $sectionThree = array();
      $sectionFour = array();
      $sectionFive = array();
      while($row=mysql_fetch_assoc($query)){
    $date = $row['date'];
    $section = $row['sectionId'];
    switch($section){
    case '1':
      $sectionOne[] = $row;
      break;
    case '2':
      $sectionTwo[] = $row;
      break;
    case '3':
      $sectionThree[] = $row;
      break;
        case '4':
      $sectionFour[] = $row;
      break;
        case '5':
      $sectionFive[] = $row;
      break;
        default:
      break;
    }
      }
    }else{
      //error - sql failed
    }
  }

?>

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

  <title>Personal Diary System - Entry Report - <?php echo($date); ?></title>

Entry Report - <?php echo($date); ?>

  <form id = "sendanswers" name = "sendanswers" action="Testers/html2pdfconverter.php" method="post">
  <input type = "hidden" name = "link" id = "link" value = "">
  <input type = "hidden" name = "nm" id = "nm" value = "">
  <input type = "button" name = "export" id = "export" value = "Export As PDF"/>
  </form>

Biological Information

  <?php
      $i = 0;
      foreach($sectionOne as &$value){
    if($i == 1 || $i == 3){
      $image = "assets/urine".$i.".png";
      echo("
");
      echo($value['question']."
 "."");
      echo("
");
    }else{
      echo($value['question'].' : '.$value['answer']);
    }
    echo("
");
    $i++;
      }
  ?>

Fatigue and Recovery

  <?php
      foreach($sectionTwo as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Illness and Injury

  <?php
      foreach($sectionThree as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

Training Sessions

  <?php
      foreach($sectionFour as &$value){
    echo($value['question'].' : '.$value['answer']);
    echo("
");
      }
  ?>

General Feedback

  <?php
     if(count($sectionFive)>0){
      foreach($sectionFive as &$value){
    echo($value['question'].' : '.$value['answer']);
      }
     }else{
       $sectionFive = "User didn't leave any feedback";
       echo("User didn't leave any feedback");
     }
     echo("
");
  ?>

<?php
}
?>

and html2pdfconverter.php

<?php
require('html2fpdf.php');

if(isset($_POST['link'])){
  $url = $_POST['link'];
  $nm = $_POST['nm'];
  convert($url, $nm);
}

function convert($link, $name){
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $fp = fopen($link,"r");
  $strContent = fread($fp, filesize($link));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}
?>

EDIT @TIMFERRIS

I changed my convert function to this based on @TimeFerris' answer:

function convert($link, $name){

  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $content = file_get_contents( $link ); //shorter than what you did
  ob_start();
  echo $content;
  $pdf->WriteHTML( ob_get_contents() );
  ob_end_clean();
  $pdf->Output($name);
  echo ("PDF file generated successfully!");
}

The PDF file is created but still blank

Body:
The php file you are supplying has to run through a parser before it's valid html code.

$content = file_get_contents( $filename ); //shorter than what you did
ob_start();
echo $content;
$pdf->WriteHTML( ob_get_contents() );
ob_end_clean();


问:
react native error while installing react-native-razorpay
can anyone help me with this error...im getting this error while installing the https://www.npmjs.com/package/react-native-razorpay v- 2.8.8 "react": "17.0.2", and "react-native": "0.67.1",

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: easylab@0.0.1
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.5.0" from react-native-razorpay@2.2.8
npm ERR! node_modules/react-native-razorpay
npm ERR!   react-native-razorpay@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\afsha\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\afsha\AppData\Local\npm-cache_logs\2022-02-12T08_50_50_495Z-debug.log

答:
Automatically installing peer dependencies is an exciting new feature introduced in npm 7. In previous versions of npm (4-6), peer dependencies conflicts presented a warning that versions were not compatible, but would still install dependencies without an error. npm 7 will block installations if an upstream dependency conflict is present that cannot be automatically resolved.

You have the option to retry with --force to bypass the conflict or --legacy-peer-deps command to ignore peer dependencies entirely (this behavior is similar to versions 4-6)

Try install with

```<code>npm install react-native-razorpay --force
</code>```

or

```<code>npm install react-native-razorpay --legacy-peer-deps
</code>```

Body:
Automatically installing peer dependencies is an exciting new feature introduced in npm 7. In previous versions of npm (4-6), peer dependencies conflicts presented a warning that versions were not compatible, but would still install dependencies without an error. npm 7 will block installations if an upstream dependency conflict is present that cannot be automatically resolved.

You have the option to retry with --force to bypass the conflict or --legacy-peer-deps command to ignore peer dependencies entirely (this behavior is similar to versions 4-6)

Try install with

npm install react-native-razorpay --force

or

npm install react-native-razorpay --legacy-peer-deps


问:
Where could I update Laravel Migration files Foreign key scripts
working with Laravel project and need update titles table new columns like employee_id and create new migration command php artisan make:migration add_employee_id_to_titles_table --table=titles and create new migration file like add_employee_id_to_titles_tables.php now I need add following foreign key relationship with new columns and the titles table

```<code> Schema::table('titles', function ($table){
             $table->foreign('employee_id')->references('id')->on('titles')->onDelete('cascade');
        });
</code>```

my problem is in witch migration files titles or new add_employee_id_to_titles_tables should I add this scripts?

答:
First thing why your employee_id reference to the same table title ID. it should reference to either employee table or whatever you're getting this employee_id from.

In order to update your existing Title table you need to create a new migration just like you said php artisan make:migration add_employee_id_to_titles_table --table=titles and than

```<code>Schema::table('titles', function ($table){
    $table->unsignedBigInteger('employee_id');
    $table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
});
</code>```

Body:
working with Laravel project and need update titles table new columns like employee_id and create new migration command php artisan make:migration add_employee_id_to_titles_table --table=titles and create new migration file like add_employee_id_to_titles_tables.php now I need add following foreign key relationship with new columns and the titles table

 Schema::table('titles', function ($table){
             $table->foreign('employee_id')->references('id')->on('titles')->onDelete('cascade');
        });

my problem is in witch migration files titles or new add_employee_id_to_titles_tables should I add this scripts?

Body:
First thing why your employee_id reference to the same table title ID. it should reference to either employee table or whatever you're getting this employee_id from.

In order to update your existing Title table you need to create a new migration just like you said php artisan make:migration add_employee_id_to_titles_table --table=titles and than

Schema::table('titles', function ($table){
    $table->unsignedBigInteger('employee_id');
    $table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
});


问:
Join multiple rows having a common column Pandas
I'm working on Covid data from Our World in Data. The data is very well-documented from the start. It is adding record for every progress(for every vaccination/deaths etc). It has 67 columns and more than 161K records.

For every record that is being added, life_expectancy is calculated. I wanted to calculate the average life_expectancy per location till date. For eg: Mexico has around 750 entries and has life_expectancy for every record. I want to take average for all the 750 life_expectancy. For this, I planned to pick up entry of each country and then calculate the average of life_expectancy and then add it to new dictionary. My way got me incorrect data  and also took more than 1 min to complete.

covid.head():

Here's what I tried:

```<code>import time
t = time.process_time()

avg_life_exp = {}
for i in covid['location']:
    count = 0
    avg = 0
    loc = i
    if i == loc:
        avg += covid['life_expectancy']
        count += 1
    else:
        avg = avg/count
    avg_life_exp[i] = avg

print(avg_life_exp)

elapsed_time = time.process_time() - t
print(elapsed_time)
</code>```

Output (I got repeated values of the added screenshot):

答:
Use groupby and compute mean on life_expectancy,:

```<code>out = df.groupby('location')['life_expectancy'].mean().reset_index()
print(out)

# Output
              location  life_expectancy
0          Afghanistan            64.83
1               Africa              NaN
2              Albania            78.57
3              Algeria            76.88
4              Andorra            83.73
..                 ...              ...
233  Wallis and Futuna            79.94
234              World            72.58
235              Yemen            66.12
236             Zambia            63.89
237           Zimbabwe            61.49

[238 rows x 2 columns]
</code>```

Body:
I'm working on Covid data from Our World in Data. The data is very well-documented from the start. It is adding record for every progress(for every vaccination/deaths etc). It has 67 columns and more than 161K records.

For every record that is being added, life_expectancy is calculated. I wanted to calculate the average life_expectancy per location till date. For eg: Mexico has around 750 entries and has life_expectancy for every record. I want to take average for all the 750 life_expectancy. For this, I planned to pick up entry of each country and then calculate the average of life_expectancy and then add it to new dictionary. My way got me incorrect data  and also took more than 1 min to complete.

covid.head():

Here's what I tried:

import time
t = time.process_time()

avg_life_exp = {}
for i in covid['location']:
    count = 0
    avg = 0
    loc = i
    if i == loc:
        avg += covid['life_expectancy']
        count += 1
    else:
        avg = avg/count
    avg_life_exp[i] = avg

print(avg_life_exp)

elapsed_time = time.process_time() - t
print(elapsed_time)

Output (I got repeated values of the added screenshot):

Body:
Use groupby and compute mean on life_expectancy,:

out = df.groupby('location')['life_expectancy'].mean().reset_index()
print(out)

# Output
              location  life_expectancy
0          Afghanistan            64.83
1               Africa              NaN
2              Albania            78.57
3              Algeria            76.88
4              Andorra            83.73
..                 ...              ...
233  Wallis and Futuna            79.94
234              World            72.58
235              Yemen            66.12
236             Zambia            63.89
237           Zimbabwe            61.49

[238 rows x 2 columns]


问:
Deleting localStorage data
What vulnerabilities do i face, when coding a web app utilising localStorage, of a user inadvertently or deliberately delete localStorage data?

I'm happy to put a button saying "Delete my data", this is under my control, but are there ways beyond my control that localStorage data may be deleted? Or not used (ie. Incognito mode/private browsing mode)?

Thanks

答:
Anyone can call localStorage.clear() from the console or location bar at any time. It's possible for a bookmarklet to be used to do the same thing.

Treat localStorage with the same volatility you'd treat a cookie. Assume that it can disappear at any time. It's best used for user-settings and temporary data. If a user clears it, be prepared to use default fall-backs or start the process over.

Title: Deleting localStorage data


问:
compareTo: treat two nulls as equal
I would like my compare method to work so that in the case where field1 == null in both objects, comparation would not be determined, but field2 would be checked, and so on. How to do it in the simplest way? The method below does not work well: when the fields from both objects are null, the comparison is always determined (without Ordering.natural().NullsFirst() I get NPE):

```<code>import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class MyClass implements Comparable<MyClass> {

    String field1;
    Integer field2;
    String field3;

    @Override
    public int compareTo(MyClass myClass) {
        return ComparisonChain.start()
            .compare(field1, myClass.field1, Ordering.natural().nullsFirst())
            .compare(field2, myClass.field2, Ordering.natural().nullsFirst())
            .compare(field3, myClass.field3, Ordering.natural().nullsFirst())
            .result();
    }
}
</code>```

答:
Having Ordering.natural().nullsFirst() as third parameter is the expected way.

The documentation shows it rather clearly:

```<code>public int compareTo(Foo that) {
  return ComparisonChain.start()
      .compare(this.aString, that.aString)
      .compare(this.anInt, that.anInt)
      .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
      .result();
}
</code>```

Furthermore, ComparisonChain is in com.google.common.collect, which is annotated with @ParametersAreNonnullByDefault, and here are the complete definition of the two compare methods used for custom objects:

abstract ComparisonChain compare(Comparable left, Comparable right)

And

abstract <T extends @Nullable Object> ComparisonChain compare(T left, T right, Comparator comparator)

The first doesn't have any parameter marked with @Nullable while the second, with the ordering does.

Therefore, there are no simpler way of doing what you do.

Title: compareTo: treat two nulls as equal

Body:
I would like my compare method to work so that in the case where field1 == null in both objects, comparation would not be determined, but field2 would be checked, and so on. How to do it in the simplest way? The method below does not work well: when the fields from both objects are null, the comparison is always determined (without Ordering.natural().NullsFirst() I get NPE):

import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class MyClass implements Comparable<MyClass> {

    String field1;
    Integer field2;
    String field3;

    @Override
    public int compareTo(MyClass myClass) {
        return ComparisonChain.start()
            .compare(field1, myClass.field1, Ordering.natural().nullsFirst())
            .compare(field2, myClass.field2, Ordering.natural().nullsFirst())
            .compare(field3, myClass.field3, Ordering.natural().nullsFirst())
            .result();
    }
}

Body:
Having Ordering.natural().nullsFirst() as third parameter is the expected way.

The documentation shows it rather clearly:

public int compareTo(Foo that) {
  return ComparisonChain.start()
      .compare(this.aString, that.aString)
      .compare(this.anInt, that.anInt)
      .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
      .result();
}

Furthermore, ComparisonChain is in com.google.common.collect, which is annotated with @ParametersAreNonnullByDefault, and here are the complete definition of the two compare methods used for custom objects:

abstract ComparisonChain compare(Comparable left, Comparable right)

And

abstract <T extends @Nullable Object> ComparisonChain compare(T left, T right, Comparator comparator)

The first doesn't have any parameter marked with @Nullable while the second, with the ordering does.

Therefore, there are no simpler way of doing what you do.


问:
Unexpected behaviour when inserting values into jobjectArray in JNI
Im trying to create a 1D jobjectArray. When printing from inside the loop, "args" array prints correct values but once it is out of the loop, only the last element gets printed repeatedly.

This is "args" jobjectArray declaration:

```<code>//Declare an object array
jobjectArray args;

//Get the class of the object, generally ava/lang/Object is enough
jclass objClass = (*env)->FindClass(env,"java/lang/Object");

//New object array
args = (*env)->NewObjectArray(env,unum, objClass, 0);
</code>```

This is the loop used to insert values into the jobjectArray:
( rec_msg[] struct array has correct values and there are no problems creating or inserting a jobject)

```<code>for(int i=0; i < unum; i++ )
{
       printf("\ni-%d---", i);
       (*env)->SetShortField(env,obj,stat,1);
       (*env)->SetShortField(env,obj,fnumber,rec_msg[i].filenum );
       str = (*env)->NewStringUTF(env, rec_msg[i].username);
       (*env)->SetObjectField(env,obj,user, str);

       (*env)->SetObjectArrayElement(env,args, i, obj);
       printf("args fnum%d\n", (*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args, i), fnumber));

 }
</code>```

The printf in here prints the values of fnum (a field in jobject) correctly as:

```<code>i-0-args fnum3

i-1-args fnum2

i-2-args fnum9
</code>```

but after the lopp, I wrote a new simple loop as:

```<code>for(int i=0; i < unum; i++ )
    {
    printf("\ni-%d ARGS fnum%d",i, (*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args, i), fnumber));
  }
</code>```

this prints:

```<code>i-0 ARGS fnum9
i-1 ARGS fnum9
i-2 ARGS fnum9
</code>```

ie the last object repeats. There are no statements between this loop and the previous. Im unable to know why the "args" jobjectrray repeats the last element when it prints fine inside the first loop. Please let me know if any other details are required.

答:
You populate your array with three refetences to the same object. In the first loop the values of obj are changing on each iteration, that's why you get different values printed. Try to add the printing command

```<code>printf("\ni-%d ARGS fnum%d",0,(*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args,0), fnumber));
</code>```

as the last sentence in the first loop. You'll see that the value of the first element of the array is being updated on each iteration, because it's still referencing the same object.

Body:
Im trying to create a 1D jobjectArray. When printing from inside the loop, "args" array prints correct values but once it is out of the loop, only the last element gets printed repeatedly.

This is "args" jobjectArray declaration:

//Declare an object array
jobjectArray args;

//Get the class of the object, generally ava/lang/Object is enough
jclass objClass = (*env)->FindClass(env,"java/lang/Object");

//New object array
args = (*env)->NewObjectArray(env,unum, objClass, 0);

This is the loop used to insert values into the jobjectArray:
( rec_msg[] struct array has correct values and there are no problems creating or inserting a jobject)

for(int i=0; i < unum; i++ )
{
       printf("\ni-%d---", i);
       (*env)->SetShortField(env,obj,stat,1);
       (*env)->SetShortField(env,obj,fnumber,rec_msg[i].filenum );
       str = (*env)->NewStringUTF(env, rec_msg[i].username);
       (*env)->SetObjectField(env,obj,user, str);

       (*env)->SetObjectArrayElement(env,args, i, obj);
       printf("args fnum%d\n", (*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args, i), fnumber));

 }

The printf in here prints the values of fnum (a field in jobject) correctly as:

i-0-args fnum3

i-1-args fnum2

i-2-args fnum9

but after the lopp, I wrote a new simple loop as:

for(int i=0; i < unum; i++ )
    {
    printf("\ni-%d ARGS fnum%d",i, (*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args, i), fnumber));
  }

this prints:

i-0 ARGS fnum9
i-1 ARGS fnum9
i-2 ARGS fnum9

ie the last object repeats. There are no statements between this loop and the previous. Im unable to know why the "args" jobjectrray repeats the last element when it prints fine inside the first loop. Please let me know if any other details are required.

Body:
You populate your array with three refetences to the same object. In the first loop the values of obj are changing on each iteration, that's why you get different values printed. Try to add the printing command

printf("\ni-%d ARGS fnum%d",0,(*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args,0), fnumber));

as the last sentence in the first loop. You'll see that the value of the first element of the array is being updated on each iteration, because it's still referencing the same object.


问:
Using Case Statement in SQL
I have been learning SQL,and I was trying to learn about the CASE on Oracle LiveSQL:

This is the query I am trying to use:

```<code>SELECT FIRST_NAME,LAST_NAME, CASE
WHEN SALARY>10000 THEN 'Salary is greater than 10000'
WHEN SALARY<10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS 'SALARY STATEMENT'
FROM hr.employees;
</code>```

This query gives me the output as:

```<code>ORA-00923: FROM keyword not found where expected
</code>```

Can anyone explain what's wrong?

答:
Oracle database object names, when escaped, should appear inside double quotes, not single quotes.  Single quotes denote string literals, not aliases.  The following version should work:

SELECT FIRST_NAME, LAST_NAME,
       CASE WHEN SALARY > 10000 THEN 'Salary is greater than 10000'
            WHEN SALARY < 10000 THEN 'Salary is less than 10000'
            ELSE 'Salary is equal to 10000'
       END AS "SALARY STATEMENT"
FROM hr.employees;
```

Title: Using Case Statement in SQL

Body:
I have been learning SQL,and I was trying to learn about the CASE on Oracle LiveSQL:

This is the query I am trying to use:

SELECT FIRST_NAME,LAST_NAME, CASE
WHEN SALARY>10000 THEN 'Salary is greater than 10000'
WHEN SALARY<10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS 'SALARY STATEMENT'
FROM hr.employees;

This query gives me the output as:

ORA-00923: FROM keyword not found where expected

Can anyone explain what's wrong?


问:
How can i make these shapes different in loop with python?
So I have this code here, everything is good but it has to make 20 different shapes, at the moment it makes 20 same shapes. Can somebody help me plz?

import random
from turtle import*

def func(lenght, nr_of_sides):
    i = 0
    while i in range(20):
        i += 1
        for element in range(nr_of_sides):
            forward(lenght)
            angle = 360/nr_of_sides
            left(angle)

a = random.randint(1, 100)
b = random.randint(3, 10)
func(a, b)

exitonclick()
```

答: Well you're creating a and b as random values and you're passing them to your function. But once passed, the values won't change. Try putting the random.randint bits inside your while loop to have it generate a new random value with each iteration of the loop.</p>


问:
twilio error "The from phone number is not valid"
I just made an account and tried testing the twilio API via the python helper library. I am getting the error :

twilio.base.exceptions.TwilioRestException: HTTP 400 error: Unable to create record: The From phone number + is not a valid, SMS-capable inbound phone number or short code for your account.

I am using the SMS enabled number purchased via the twilio CLI. I am using the following code:

```<code>from twilio.rest import Client

# Your Account SID from twilio.com/console
account_sid = "####################"
# Your Auth Token from twilio.com/console
auth_token  = "###################"

client = Client(account_sid, auth_token)

message = client.messages.create(
    to="+1xxxxxxxx",
    from_="+1xxxxxxxx",
    body="Test message")

print(message.sid)
</code>```

答: turned out the step by step guide on Twilio site is not accurate (sufficient). One first needs to create a messaging service via the dashboard and bind the phone number to it</p>

Body:
I just made an account and tried testing the twilio API via the python helper library. I am getting the error :

twilio.base.exceptions.TwilioRestException: HTTP 400 error: Unable to create record: The From phone number + is not a valid, SMS-capable inbound phone number or short code for your account.

I am using the SMS enabled number purchased via the twilio CLI. I am using the following code:

from twilio.rest import Client

# Your Account SID from twilio.com/console
account_sid = "####################"
# Your Auth Token from twilio.com/console
auth_token  = "###################"

client = Client(account_sid, auth_token)

message = client.messages.create(
    to="+1xxxxxxxx",
    from_="+1xxxxxxxx",
    body="Test message")

print(message.sid)


问:
Memory allocation in c problem
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

```<code>#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}
</code>```

Warning message:

```<code>|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|
</code>```

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!

答: The first argument to realloc should be the previously allocated pointer

Title: Memory allocation in c problem

Body:
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}

Warning message:

|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!


答:
This is working,</p>
```<code>#include <iostream>

using namespace std;

int main(){
    int value;
    do{
    cout << "Please select your conversion." << endl;
    cout << "Press 1 to convert PHP to US Dollars" << endl;
    cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << endl;
    cout << "Press 3 to convert US Dollars to PHP" << endl;
    cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << endl;

    cin>>value;
    /* test loop
while (int value > 4) {
    cout << "Invalid Input." << endl;
    cout << "Please input another number." << endl;
    }
*/
    float amount;
    float result;

    switch (value){
case 1:
    cout << "Enter PHP Value: ";
    cin >> amount;
    result=amount*0.020;
    cout << amount << " PHP = " << result <<"USD";
     break;

case 2:
    cout << "Enter PHP Value: ";
    cin >> amount;
    result=amount*0.014;
    cout << amount << " PHP = " << result << " GBP";
    break;

case 3:
    cout << "Enter USD Value: ";
    cin >> amount;
    result=amount*51.27;
    cout << amount << " USD = " << result << " PHP";
    break;

case 4:
    cout << "Enter GBP (Pound Sterling) Value: ";
    cin >> amount;
    result=amount*69.57;
    cout << amount << " GBP = " << result << " PHP";

    break;

default:
    cout << "Invalid Input." << endl;
    cout << "Please input another number." << endl;
    break;

    }
    }while(value !=0);
    return 0;
}
</code>```

Title: How to put a loop in a switch statement

Body:
I can't seem to figure out how to loop back to the selection if the value is invalid. Currently making a currency conversion calculator. Can't seem to make the terminal let the user input another number so they could convert freely. Thnx in advance!

int main()
{
    int value;
    cout << "Please select your conversion." << endl;
    cout << "Press 1 to convert PHP to US Dollars" << endl;
    cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << endl;
    cout << "Press 3 to convert US Dollars to PHP" << endl;
    cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << endl;

    cin>>value;
    /* test loop
    while (int value > 4) {
        cout << "Invalid Input." << endl;
        cout << "Please input another number." << endl;
        }
    */
    float amount;
    float result;

    switch (value){
    case 1:
        cout << "Enter PHP Value: ";
        cin >> amount;
        result=amount*0.020;
        cout << amount << " PHP = " << result <<
    "USD";

    break;

    case 2:
        cout << "Enter PHP Value: ";
        cin >> amount;
        result=amount*0.014;
        cout << amount << " PHP = " << result << " GBP";

    break;

    case 3:
        cout << "Enter USD Value: ";
        cin >> amount;
        result=amount*51.27;
        cout << amount << " USD = " << result << " PHP";
    break;

    case 4:
        cout << "Enter GBP (Pound Sterling) Value: ";
        cin >> amount;
        result=amount*69.57;
        cout << amount << " GBP = " << result << " PHP";

    break;

    default:
        cout << "Invalid Input." << endl;
        cout << "Please input another number." << endl;
        break;

    }
    return 0;
}

Body:
This is working,

#include <iostream>

using namespace std;

int main(){
    int value;
    do{
    cout << "Please select your conversion." << endl;
    cout << "Press 1 to convert PHP to US Dollars" << endl;
    cout << "Press 2 to convert PHP to GBP (Pound Sterling)" << endl;
    cout << "Press 3 to convert US Dollars to PHP" << endl;
    cout << "Press 4 to convert GBP (Pound Sterling) to PHP" << endl;

    cin>>value;
    /* test loop
while (int value > 4) {
    cout << "Invalid Input." << endl;
    cout << "Please input another number." << endl;
    }
*/
    float amount;
    float result;

    switch (value){
case 1:
    cout << "Enter PHP Value: ";
    cin >> amount;
    result=amount*0.020;
    cout << amount << " PHP = " << result <<"USD";
     break;

case 2:
    cout << "Enter PHP Value: ";
    cin >> amount;
    result=amount*0.014;
    cout << amount << " PHP = " << result << " GBP";
    break;

case 3:
    cout << "Enter USD Value: ";
    cin >> amount;
    result=amount*51.27;
    cout << amount << " USD = " << result << " PHP";
    break;

case 4:
    cout << "Enter GBP (Pound Sterling) Value: ";
    cin >> amount;
    result=amount*69.57;
    cout << amount << " GBP = " << result << " PHP";

    break;

default:
    cout << "Invalid Input." << endl;
    cout << "Please input another number." << endl;
    break;

    }
    }while(value !=0);
    return 0;
}


问:
kubelet failed with kubelet cgroup driver: "cgroupfs" is different from docker cgroup driver: "systemd"
Configuration for cgroup driver is right in /etc/systemd/system/kubelet.service.d/10-kubeadm.conf

```<code>Environment="KUBELET_CGROUP_ARGS=--cgroup-driver=systemd"
</code>```

I also checked the Environment with cli

```<code>$ systemctl show --property=Environment kubelet | cat
Environment=KUBELET_KUBECONFIG_ARGS=--kubeconfig=/etc/kubernetes/kubelet.conf\x20--require-kubeconfig=true KUBELET_SYSTEM_PODS_ARGS=--pod-manifest-path=/etc/kubernetes/manifests\x20--allow-privileged=true KUBELET_NETWORK_ARGS=--network-plugin=cni\x20--cni-conf-dir=/etc/cni/net.d\x20--cni-bin-dir=/opt/cni/bin KUBELET_DNS_ARGS=--cluster-dns=10.96.0.10\x20--cluster-domain=cluster.local KUBELET_AUTHZ_ARGS=--authorization-mode=Webhook\x20--client-ca-file=/etc/kubernetes/pki/ca.crt KUBELET_CADVISOR_ARGS=--cadvisor-port=0 KUBELET_CGROUP_ARGS=--cgroup-driver=systemd
</code>```

KUBELET_CGROUP_ARGS=--cgroup-driver=systemd

How to reproduce it:

yum install -y docker-1.12.6

systemctl enable docker && systemctl start docker

setenforce 0

yum install -y kubelet kubeadm

systemctl enable kubelet && systemctl start kubelet

systemctl daemon-reload

systemctl restart kubelet

kubelet log

Environment:

Kubernetes version (use kubectl version): 1.7.3

Cloud provider or hardware configuration**:   4 core 16G RAM

OS (e.g. from /etc/os-release):  CentOS Linux 7 (Core)

Kernel (e.g. uname -a): Linux 10-8-108-92 3.10.0-327.22.2.el7.x86_64 #1 SMP Thu Jun 23 17:05:11 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Install tools: kubeadm

答:
I followed below steps in Ubuntu 18.04 LTS with Kubernetes v1.22.6 and latest version of Docker CE and Containerd.

I have changed the docker service file to change it to systemd. In the older version of kubeadm, kubectl and kubelet till 1.21.1 there was no problem.

And going forward docker service should use systemd by default.

Step 1: Stop docker service

```<code>    `systemctl stop docker`
</code>```

Step 2: change on files /etc/systemd/system/multi-user.target.wants/docker.service and /usr/lib/systemd/system/docker.service

Note: the file /usr/lib/systemd/system/docker.service is not avilable in my system.

From :

```<code>    `ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock`
</code>```

TO:

```<code>    `ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --exec-opt native.cgroupdriver=systemd`
</code>```

Step 3: Start docker service and kubelet service

```<code>    `systemctl daemon-reload`
    `systemctl start docker`

</code>```

Step 4: Since I had run kubeadm reset, I had to run kubeadm init. But it worked.

Step 0: Before all these, several commands need to run to enable containerd to use systemd.

cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf overlay br_netfilter EOF

sudo modprobe overlay
sudo modprobe br_netfilter

Setup required sysctl params, these persist across reboots.

cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-iptables  = 1
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF

Apply sysctl params without reboot

sudo sysctl --system

Kubernetes Container Runtime

Body:
Configuration for cgroup driver is right in /etc/systemd/system/kubelet.service.d/10-kubeadm.conf

Environment="KUBELET_CGROUP_ARGS=--cgroup-driver=systemd"

I also checked the Environment with cli

$ systemctl show --property=Environment kubelet | cat
Environment=KUBELET_KUBECONFIG_ARGS=--kubeconfig=/etc/kubernetes/kubelet.conf\x20--require-kubeconfig=true KUBELET_SYSTEM_PODS_ARGS=--pod-manifest-path=/etc/kubernetes/manifests\x20--allow-privileged=true KUBELET_NETWORK_ARGS=--network-plugin=cni\x20--cni-conf-dir=/etc/cni/net.d\x20--cni-bin-dir=/opt/cni/bin KUBELET_DNS_ARGS=--cluster-dns=10.96.0.10\x20--cluster-domain=cluster.local KUBELET_AUTHZ_ARGS=--authorization-mode=Webhook\x20--client-ca-file=/etc/kubernetes/pki/ca.crt KUBELET_CADVISOR_ARGS=--cadvisor-port=0 KUBELET_CGROUP_ARGS=--cgroup-driver=systemd

KUBELET_CGROUP_ARGS=--cgroup-driver=systemd

How to reproduce it:

yum install -y docker-1.12.6

systemctl enable docker && systemctl start docker

setenforce 0

yum install -y kubelet kubeadm

systemctl enable kubelet && systemctl start kubelet

systemctl daemon-reload

systemctl restart kubelet

kubelet log

Environment:

Kubernetes version (use kubectl version): 1.7.3

Cloud provider or hardware configuration**:   4 core 16G RAM

OS (e.g. from /etc/os-release):  CentOS Linux 7 (Core)

Kernel (e.g. uname -a): Linux 10-8-108-92 3.10.0-327.22.2.el7.x86_64 #1 SMP Thu Jun 23 17:05:11 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Install tools: kubeadm

Body:
I followed below steps in Ubuntu 18.04 LTS with Kubernetes v1.22.6 and latest version of Docker CE and Containerd.

I have changed the docker service file to change it to systemd. In the older version of kubeadm, kubectl and kubelet till 1.21.1 there was no problem.

And going forward docker service should use systemd by default.

Step 1: Stop docker service

    `systemctl stop docker`

Step 2: change on files /etc/systemd/system/multi-user.target.wants/docker.service and /usr/lib/systemd/system/docker.service

Note: the file /usr/lib/systemd/system/docker.service is not avilable in my system.

From :

    `ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock`

TO:

    `ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --exec-opt native.cgroupdriver=systemd`

Step 3: Start docker service and kubelet service

    `systemctl daemon-reload`
    `systemctl start docker`

Step 4: Since I had run kubeadm reset, I had to run kubeadm init. But it worked.

Step 0: Before all these, several commands need to run to enable containerd to use systemd.

cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf overlay br_netfilter EOF

sudo modprobe overlay
sudo modprobe br_netfilter

Setup required sysctl params, these persist across reboots.

cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-iptables  = 1
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF

Apply sysctl params without reboot

sudo sysctl --system

Kubernetes Container Runtime


问:
write() argument must be str not stringvar
I don't know what can I do, so I'm asking for help. When I click that "submitting_button" error occur "write() argument must be str not stringvar"</p>
```<code>import tkinter as tk

from tkinter import ttk, Label, Button, Entry, Place, Pack, StringVar

class Datasaver:
    def __init__(self, GUI,):
        self.GUI = GUI
        GUI.title("Dataver")

        self.label = Label(GUI, text="More comfortable method for saving data!",font=("Arial", 20))
        self.label.place(relx = 0.1, rely = 0.5, anchor = 'sw')
        self.submitting_button = Button(GUI, text="submit", command=self.submitting_button)
        self.submitting_button.place(relx = 0.9, rely = 0.9, anchor = 'sw')
        self.close_button = Button(GUI, text="Exit", command=GUI.quit)
        self.close_button.place(relx = 0.9, rely = 1.0, anchor = 'sw')
        self.butt = Button(GUI, text="create", command=self.create)
        self.butt.place(relx = 0.9, rely = 0.8, anchor = 'sw')
        self.labelel = Label(GUI, text="Username:")
        self.labelel.place(relx = 0.0, rely = 0.8, anchor = 'sw')
        self.labelel = Label(GUI, text="Password:")
        self.labelel.place(relx = 0.0, rely = 0.9, anchor = 'sw')
        self.labelel = Label(GUI, text="E-mail:")
        self.labelel.place(relx = 0.0, rely = 1.0, anchor = 'sw')
        self.entry = Entry(GUI, textvariable = name_variable, show="*", font=("Arial", 10))
        self.entry.place(relx = 0.2, rely = 0.9, anchor = 'sw')
        self.entry2 = Entry(GUI, textvariable = password_var, font=("Arial", 10))
        self.entry2.place(relx = 0.2, rely = 1.0, anchor='sw')
        self.entry3 = Entry(GUI, textvariable = Email_var, font=("Arial", 10))
        self.entry3.place(relx = 0.2, rely = 0.8, anchor='sw')

    def create(self):
        f = open("myfile.txt", "x")

    def submitting_button(self):
        file = open("myfile.txt", "w", encoding="utf8")
        file.write(name_variable)
        file.write(password_var)
        file.write(Email_var)
        file.close()

        name=name_variable.get()
        password=password_var.get()
        Email=Email_var.get()
        print("Nickname: " + name)
        print("Password: " + password)
        print("Email: " + Email)
        name_variable.set("")
        password_var.set("")
        Email_var.set("")

root = tk.Tk()
root.resizable(False, False)
root.geometry('600x350')

name_variable=StringVar()
password_var=StringVar()
Email_var=StringVar()

my_gui = Datasaver(root)

root.mainloop()
</code>```

答:
To extend on Barmar's answer:

StringVar is a Tkinter class that helps manage the values of a widget. As such a StringVar object holds a string (in it's value attribute) but is not a string itself.

file.write() on the other hand expects a string.

As explained here Access StringVar() as a normal string in python you can get the value of the StringVar variable by using the get() method.

To make it short, all you need to do is change the following lines:

```<code>def submitting_button(self):
    # ...
    file.write(name_variable.get())
    file.write(password_var.get())
    file.write(Email_var.get())
    # ...
</code>```

Body:
I don't know what can I do, so I'm asking for help. When I click that "submitting_button" error occur "write() argument must be str not stringvar"

import tkinter as tk

from tkinter import ttk, Label, Button, Entry, Place, Pack, StringVar

class Datasaver:
    def __init__(self, GUI,):
        self.GUI = GUI
        GUI.title("Dataver")

        self.label = Label(GUI, text="More comfortable method for saving data!",font=("Arial", 20))
        self.label.place(relx = 0.1, rely = 0.5, anchor = 'sw')
        self.submitting_button = Button(GUI, text="submit", command=self.submitting_button)
        self.submitting_button.place(relx = 0.9, rely = 0.9, anchor = 'sw')
        self.close_button = Button(GUI, text="Exit", command=GUI.quit)
        self.close_button.place(relx = 0.9, rely = 1.0, anchor = 'sw')
        self.butt = Button(GUI, text="create", command=self.create)
        self.butt.place(relx = 0.9, rely = 0.8, anchor = 'sw')
        self.labelel = Label(GUI, text="Username:")
        self.labelel.place(relx = 0.0, rely = 0.8, anchor = 'sw')
        self.labelel = Label(GUI, text="Password:")
        self.labelel.place(relx = 0.0, rely = 0.9, anchor = 'sw')
        self.labelel = Label(GUI, text="E-mail:")
        self.labelel.place(relx = 0.0, rely = 1.0, anchor = 'sw')
        self.entry = Entry(GUI, textvariable = name_variable, show="*", font=("Arial", 10))
        self.entry.place(relx = 0.2, rely = 0.9, anchor = 'sw')
        self.entry2 = Entry(GUI, textvariable = password_var, font=("Arial", 10))
        self.entry2.place(relx = 0.2, rely = 1.0, anchor='sw')
        self.entry3 = Entry(GUI, textvariable = Email_var, font=("Arial", 10))
        self.entry3.place(relx = 0.2, rely = 0.8, anchor='sw')

    def create(self):
        f = open("myfile.txt", "x")

    def submitting_button(self):
        file = open("myfile.txt", "w", encoding="utf8")
        file.write(name_variable)
        file.write(password_var)
        file.write(Email_var)
        file.close()

        name=name_variable.get()
        password=password_var.get()
        Email=Email_var.get()
        print("Nickname: " + name)
        print("Password: " + password)
        print("Email: " + Email)
        name_variable.set("")
        password_var.set("")
        Email_var.set("")

root = tk.Tk()
root.resizable(False, False)
root.geometry('600x350')

name_variable=StringVar()
password_var=StringVar()
Email_var=StringVar()

my_gui = Datasaver(root)

root.mainloop()

Body:
To extend on Barmar's answer:

StringVar is a Tkinter class that helps manage the values of a widget. As such a StringVar object holds a string (in it's value attribute) but is not a string itself.

file.write() on the other hand expects a string.

As explained here Access StringVar() as a normal string in python you can get the value of the StringVar variable by using the get() method.

To make it short, all you need to do is change the following lines:

def submitting_button(self):
    # ...
    file.write(name_variable.get())
    file.write(password_var.get())
    file.write(Email_var.get())
    # ...