答:
It's not working because you are checking if one string is included in the other in entirety. Instead, you need to get each character of blacklist separately and check if it is present in the phrase string.

Also, use toLowerCase on the strings for case-insensitive comparison

function hasNoneLetters(blacklist, phrase) {
  blacklist = blacklist.toLowerCase();
  phrase = phrase.toLowerCase();

  for (const char of blacklist)
    if (phrase.includes(char))
      return false;

  return true
}

console.log(hasNoneLetters('abc', 'This has'))
console.log(hasNoneLetters('XYZ', 'This doesnt'))
console.log(hasNoneLetters('C', 'case insensitive'))```
</div>
</div>
</p>

<hr>

<p>Another option is to create a <code>Set</code> of the blacklisted letters. Use <code>Array.from</code> to convert the string string to an array of characters. Check if <code>some</code> of the letters are included in the set. </p>

<pre class="lang-js prettyprint-override"><code>function hasNoneLetters(blacklist, phrase) {
  const set = new Set(blacklist.toLowerCase());
  return !Array.from(phrase.toLowerCase()).some(c => set.has(c));
}
</code>```

Body:
It's not working because you are checking if one string is included in the other in entirety. Instead, you need to get each character of blacklist separately and check if it is present in the phrase string.

Also, use toLowerCase on the strings for case-insensitive comparison

function hasNoneLetters(blacklist, phrase) {
  blacklist = blacklist.toLowerCase();
  phrase = phrase.toLowerCase();

  for (const char of blacklist)
    if (phrase.includes(char))
      return false;

  return true
}

console.log(hasNoneLetters('abc', 'This has'))
console.log(hasNoneLetters('XYZ', 'This doesnt'))
console.log(hasNoneLetters('C', 'case insensitive'))

Another option is to create a Set of the blacklisted letters. Use Array.from to convert the string string to an array of characters. Check if some of the letters are included in the set.

function hasNoneLetters(blacklist, phrase) {
  const set = new Set(blacklist.toLowerCase());
  return !Array.from(phrase.toLowerCase()).some(c => set.has(c));
}


来源: stackexchange

问:
How does the body of the below java enum class work?
```<code>public enum ID {
 Player(),
 Enemy();
}
</code>```

I've read the entire oracle documentation for java enum, I know how it works and all the basics but I have no clue about the body of the above enum class
Are Player () , Enemy () constants ? functions ?
Also what would this return ID.Player();

答:
Just as with regular classes, you get a default no-arg constructor with enums if you don't declare an explicit constructor.

The language spec says:

In an enum declaration with no constructor declarations, a default constructor is implicitly declared. The default constructor is private, has no formal parameters, and has no throws clause.

Slightly before that, it also says:

An enum constant may be followed by arguments, which are passed to the constructor of the enum ... If the arguments are omitted, an empty argument list is assumed.

As such, these are just enum constants, explicitly invoking that implicit constructor. It's exactly the same as if you omitted the ().

ContentLicense: CC BY-SA 4.0

Body:
public enum ID {
 Player(),
 Enemy();
}

I've read the entire oracle documentation for java enum, I know how it works and all the basics but I have no clue about the body of the above enum class
Are Player () , Enemy () constants ? functions ?
Also what would this return ID.Player();


问:
Program is not asking 3 questions and uses my answer to the first question for the other two
I am trying to ask the user to enter the names of 3 of their friends, however, it only asks one question and writes the answer from my first one in the second and third. </p>

```<code>#include <iostream>
using namespace std;
int main()
{

    char first_name;
    cout << "Please enter a name: ";
    cin >> first_name;
    cout << first_name << endl;

    char second_name;
    cout << "Please enter a name: ";
    cin >> second_name;
    cout << second_name << endl;

    char third_name;
    cout << "Please enter a name: ";
    cin >> third_name;
    cout << third_name << endl;

    return 0;
}
</code>```

答:
You should probably be using string in your code to take the input of names. In names you are probably passing more than one character. The first one is read by first_name and any further character will be read by the following character, specifically cin>>second_name and cin>>third_name would read the 2nd and 3rd character of your input.

```<code>char a;
char b;
cin>>a;            //will only read one character and stop
cin>>b;            //will read the second character of the input...
                   //be that after pressing enter(a Enter b) or continuous input (ab)
cout<<a<<" "<<b;   //will output 1st and 2nd character only
</code>```

This will happen even if you don't press the Enter key explicitly and this is why your program uses the answer of first question(which is probably more than 1 character since it is a name) in your code as the answer to 2nd and 3rd questions as well.

So for your purpose, you are better of using string to take input from the users.

Hope this clears your doubt !

Body:
I am trying to ask the user to enter the names of 3 of their friends, however, it only asks one question and writes the answer from my first one in the second and third.

#include <iostream>
using namespace std;
int main()
{

    char first_name;
    cout << "Please enter a name: ";
    cin >> first_name;
    cout << first_name << endl;

    char second_name;
    cout << "Please enter a name: ";
    cin >> second_name;
    cout << second_name << endl;

    char third_name;
    cout << "Please enter a name: ";
    cin >> third_name;
    cout << third_name << endl;

    return 0;
}

Body:
You should probably be using string in your code to take the input of names. In names you are probably passing more than one character. The first one is read by first_name and any further character will be read by the following character, specifically cin>>second_name and cin>>third_name would read the 2nd and 3rd character of your input.

char a;
char b;
cin>>a;            //will only read one character and stop
cin>>b;            //will read the second character of the input...
                   //be that after pressing enter(a Enter b) or continuous input (ab)
cout<<a<<" "<<b;   //will output 1st and 2nd character only

This will happen even if you don't press the Enter key explicitly and this is why your program uses the answer of first question(which is probably more than 1 character since it is a name) in your code as the answer to 2nd and 3rd questions as well.

So for your purpose, you are better of using string to take input from the users.

Hope this clears your doubt !


问:
How can i add values from the front end to a json file in a react application?
I have built a react application where I have created a file upload mechanism. Now along with the file upload there are three dropdowns 'Controller','Test' and 'Protocol'. Now along with the file upload to the server functionality I am enabling the user to add the values to the dropdown from the front-end itself. I have enforced few validations on the file which is getting uploaded and then

I am adding the controller, test and protocol based on the file name. SO for instance if the filename of the uploaded file is "abc_xyz_sas_uut.config" which is the variable Filename in the script then the three fields 'Controller','Test' and 'Protocol' should only accept 'abc','xyz' and 'sas' as the respective values.

I have written the below script but its getting me an error 'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client'. The problem is I guess that its setting the status twice. Can anyone help to fix this issue, any help is greatly appreciated as I am stuck at this point.

```<code>
    class FileUpload extends Component {
      state = {
        file: "",
        fileName: "Choose File",
        uploadDisabled: true,
        controller: "",
        test: "",
        protocol: "",
      };
      handleFileChange = (e) => {
        let index = e.target.files[0].name.search(/\w+[_]\w+[_]\w+[_]uut.yaml-example/i);
        if (index === 0) {
          this.setState({ file: e.target.files[0] });
          this.setState({ fileName: e.target.files[0].name });
          this.setState({ uploadDisabled: false });
        } else {
          window.alert(
            "File name or format is not correct ! \nCorrect format is controller_test_protocol_uut.yaml-example"
          );

        }
        e.target.value = null;
      };
      handleUpload = async (e) => {
        console.log("Starting upload");
        const formData = new FormData();
        formData.append("file", this.state.file);
        formData.append("controller", this.state.controller);
        formData.append("test", this.state.test);
        formData.append("protocol", this.state.protocol);

        try {
          const res = await axios.post(this.props.url + "/upload", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });

          const { status } = res.data;
          if (status === "ok") {
            this.props.refreshOptions();
            this.setState({ file: "" });
            this.setState({ fileName: "Choose File" });
            this.setState({controller : ""});
            this.setState({test : ""});
            this.setState({protocol : ""});
            alert("File Uploaded Successfully");
            document.getElementById("closeButton").click();
          }
        } catch (err) {
            console.log(err);
        }
      };
 handleTextChange = (e) => {
    this.setState({ ...this.state, [e.target.id]: e.target.value });
  };
</code>```

答:
You have a res.json() statement in your else-block:

```<code>//Writing Config back to disk
}
else {
    res.json({
        status: "Invalidvalues"
    });
}
</code>```

and right after

```<code>res.json({
    status: "ok"
});
</code>```

So in case of hitting the else block res.json() is executed twice which is probably the cause for the error. You should change the statement in the else block to:

```<code>return res.json({
    status: "Invalidvalues"
});
</code>```

Body:
I have built a react application where I have created a file upload mechanism. Now along with the file upload there are three dropdowns 'Controller','Test' and 'Protocol'. Now along with the file upload to the server functionality I am enabling the user to add the values to the dropdown from the front-end itself. I have enforced few validations on the file which is getting uploaded and then

I am adding the controller, test and protocol based on the file name. SO for instance if the filename of the uploaded file is "abc_xyz_sas_uut.config" which is the variable Filename in the script then the three fields 'Controller','Test' and 'Protocol' should only accept 'abc','xyz' and 'sas' as the respective values.

I have written the below script but its getting me an error 'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client'. The problem is I guess that its setting the status twice. Can anyone help to fix this issue, any help is greatly appreciated as I am stuck at this point.

    class FileUpload extends Component {
      state = {
        file: "",
        fileName: "Choose File",
        uploadDisabled: true,
        controller: "",
        test: "",
        protocol: "",
      };
      handleFileChange = (e) => {
        let index = e.target.files[0].name.search(/\w+[_]\w+[_]\w+[_]uut.yaml-example/i);
        if (index === 0) {
          this.setState({ file: e.target.files[0] });
          this.setState({ fileName: e.target.files[0].name });
          this.setState({ uploadDisabled: false });
        } else {
          window.alert(
            "File name or format is not correct ! \nCorrect format is controller_test_protocol_uut.yaml-example"
          );

        }
        e.target.value = null;
      };
      handleUpload = async (e) => {
        console.log("Starting upload");
        const formData = new FormData();
        formData.append("file", this.state.file);
        formData.append("controller", this.state.controller);
        formData.append("test", this.state.test);
        formData.append("protocol", this.state.protocol);

        try {
          const res = await axios.post(this.props.url + "/upload", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });

          const { status } = res.data;
          if (status === "ok") {
            this.props.refreshOptions();
            this.setState({ file: "" });
            this.setState({ fileName: "Choose File" });
            this.setState({controller : ""});
            this.setState({test : ""});
            this.setState({protocol : ""});
            alert("File Uploaded Successfully");
            document.getElementById("closeButton").click();
          }
        } catch (err) {
            console.log(err);
        }
      };
 handleTextChange = (e) => {
    this.setState({ ...this.state, [e.target.id]: e.target.value });
  };

Body:
You have a res.json() statement in your else-block:

//Writing Config back to disk
}
else {
    res.json({
        status: "Invalidvalues"
    });
}

and right after

res.json({
    status: "ok"
});

So in case of hitting the else block res.json() is executed twice which is probably the cause for the error. You should change the statement in the else block to:

return res.json({
    status: "Invalidvalues"
});


问:
Reload the page just once if a div is above certain position
I want to reload the page only once if a given div is positioned higher than position:absolute; top:15%.

I think this could be done with jQuery's .css method, something like:

```<code>if ('#mydive').css('top') > '15%' {
    //reload the page
}
</code>```

Could someone suggest a simple solution, preferably jQuery or pure JavaScript?

答:
If what you meant is the top of the document, you can probably try:</p>

```<code>var percent = .15; // 15%
if ($('#yourdiv').offset().top > ($(document).height() * percent)) {
    window.location.reload();
}

// if by pixels
var pixels = 10; // 10px
if ($('#yourdiv').offset().top > pixels) {
    window.location.reload();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to reload the page only once if a given div is positioned higher than position:absolute; top:15%.

I think this could be done with jQuery's .css method, something like:

if ('#mydive').css('top') > '15%' {
    //reload the page
}

Could someone suggest a simple solution, preferably jQuery or pure JavaScript?

Body:
If what you meant is the top of the document, you can probably try:

var percent = .15; // 15%
if ($('#yourdiv').offset().top > ($(document).height() * percent)) {
    window.location.reload();
}

// if by pixels
var pixels = 10; // 10px
if ($('#yourdiv').offset().top > pixels) {
    window.location.reload();
}


问:
How can I output the names of rows which are NA in a given column in R?
I am working with panel data, and I've found out that I have 16 NAs in a column I am interested by typing:

```<code>sum(is.na(df$X1995))
[1] 16
</code>```

Now I want to know which rows had missing values for this year. Which rows had these 16 NAs?

I tried this, but it returns NULL:

```<code>rownames(which(is.na(df$X1995)))
</code>```

答:
The row.names needs to be of some object.  The which(is.na returns a numeric index and it is not an object having the row names attribute

```<code>row.names(df)[which(is.na(df$X1995))]
</code>```

Wrapping with which is also not needed as the is.na returns a logical vector which can be used to subset the rownames

```<code>row.names(df)[is.na(df$X1995)]
</code>```

If the rownames are just sequence values, the which itself is enough

```<code>which(is.na(df$X1995))
</code>```

Body:
I am working with panel data, and I've found out that I have 16 NAs in a column I am interested by typing:

sum(is.na(df$X1995))
[1] 16

Now I want to know which rows had missing values for this year. Which rows had these 16 NAs?

I tried this, but it returns NULL:

rownames(which(is.na(df$X1995)))

Body:
The row.names needs to be of some object.  The which(is.na returns a numeric index and it is not an object having the row names attribute

row.names(df)[which(is.na(df$X1995))]

Wrapping with which is also not needed as the is.na returns a logical vector which can be used to subset the rownames

row.names(df)[is.na(df$X1995)]

If the rownames are just sequence values, the which itself is enough

which(is.na(df$X1995))


问:
How to make a dropdown using fonawsome icon
I am new to coding and don't know how to make drop down like fonawsome fa fa-ellipsis-v

I am doing this here but Dont know how the class is overriding

*{
    margin: 0;
    padding :0;
    box-sizing: border-box;

}

 .chat-container{
    height: 100vh;
    width: 100vw;

    display: grid;
    grid-template-rows: 10% 80% 10%;
   grid-template-columns: 75% 25%;
   /* grid: 'search-container chat-title' 50px
            'conversation-list chat-massage-list' 1fr
            'new-massage-container chat-form' 420px/ 320px 1fr;
    overflow-x: hidden;
    border: 1px solid black;
} */
 }
 #search-container
 {

/* height: 60px;
width: 25%;
float: left; */
background-color: #0048aa;
 box-shadow: 0 1px 3px -1px rgba(0, 0, 0, 0.75);
    z-index: 1;

}
#chat-title{
    background-color: rgba(217, 223, 221, 0.945);
    /* height: 60px;
    width: 75%;
    float: left; */
    color: #0048AA;
    font-weight: bold;
    font-size: 2.0rem;
    box-shadow: 0 1px 3px -1px rgba(0, 0, 0, 0.25);
    z-index: 1;

}
#conversation-list{
/*
    height: 85vh;
    width: 25%;
    position: fixed;
    float: left;
    top: 60px;
    left: 0; */
    background-color: #0048aa;

}
#chat-form
 {   /* height: 85vh;
    width: 75%;
    position: fixed;
    float: left;
    top: 60px;
    left: 25%; */
    border-radius: 0 0 10px 0;
    background: #eee;
    border-top: 1px solid rgba(0, 0, 0, 0.25);

}
/*#search-container
{

}*/
#new-massage-container{
    /* height: 40px;
    width: 25%;
    position: fixed;
    float: left;
    bottom: 0;
    left: 0; */
    background-color: #0048aa;

    box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.25);
    z-index: 1;

    /* border-top: 1px solid rgba(0, 0, 0, 0.25);
    border-radius: 0 0 0 10px;
    background-color: rgb(221, 43, 43);*/
}

#chat-list{
    background-color: rgba(217, 223, 221, 0.945);

}
#profile_img{
    margin: 7px 18px;

    border-radius: 50%;

}
i{
}
.dropbtn {
    font-size: 16px;
    border: none;
    cursor: pointer;

    background: transparent;
    border: 0 none;
    font-weight: inherit;
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    vertical-align: top;
  }

  .dropbtn:hover, .dropbtn:focus {
    background-color: #2980B9;
  }

.dropdown {
    position: relative;
    display: inline-block;
    margin-left: 190px;
  }

  .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;

  }

  .dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
  }

  .dropdown a:hover {background-color: #ddd;}

  .show {display: block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="css/chat.css" >
    <title>Chatkaro1</title>
</head>
<body>

    <div class="chat-container">
        <div id="chat-title">
            chat
        </div>
        <div id="search-container">
            <img id="profile_img" src="images/2.png" alt="image" style="width: 50px;">
            <div class="dropdown">
                <button  href=""><i  onclick="myFunction()" style="float: right;" class="fa fa-ellipsis-v fa-lg dropbtn"></i></button>
                <div id="myDropdown" class="dropdown-content">
                  Home
                  About
                  Contact
                </div>
              </div>

              <script>
              /* When the user clicks on the button,
              toggle between hiding and showing the dropdown content */
              function myFunction() {
                document.getElementById("myDropdown").classList.toggle("show");
              }

              // Close the dropdown if the user clicks outside of it
              window.onclick = function(event) {
                if (!event.target.matches('.dropbtn')) {
                  var dropdowns = document.getElementsByClassName("dropdown-content");
                  var i;
                  for (i = 0; i < dropdowns.length; i++) {
                    var openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                      openDropdown.classList.remove('show');
                    }
                  }
                }
              }
              </script>

        </div>
        <div id="chat-form">
            form
        </div>
        <div id="conversation-list">
            conversation
        </div>
        <div id="chat-list">
            list
        </div>
        <div id="new-massage-container">
            massage
        </div>

    </div>

</body>
</html></code>```

enter image description here

Thank you!

答:
replace this

```<code> <a >
<i  onclick="myFunction()" style="float: right;" class="fa fa-ellipsis-v fa-lg dropbtn"></i>
</a>

</code>```

instead of

```<code> <button >
<i  onclick="myFunction()" style="float: right;" class="fa fa-ellipsis-v fa-lg dropbtn"></i>
</button>
</code>```

Because its taking style of button when you use  inside button. Button has its over inherited stylesheet. You can use but then you have override button default stylesheet.

You can changes style of  like color, font-size etc.

Body:
I am new to coding and don't know how to make drop down like fonawsome fa fa-ellipsis-v

I am doing this here but Dont know how the class is overriding

*{
    margin: 0;
    padding :0;
    box-sizing: border-box;

}

 .chat-container{
    height: 100vh;
    width: 100vw;

    display: grid;
    grid-template-rows: 10% 80% 10%;
   grid-template-columns: 75% 25%;
   /* grid: 'search-container chat-title' 50px
            'conversation-list chat-massage-list' 1fr
            'new-massage-container chat-form' 420px/ 320px 1fr;
    overflow-x: hidden;
    border: 1px solid black;
} */
 }
 #search-container
 {

/* height: 60px;
width: 25%;
float: left; */
background-color: #0048aa;
 box-shadow: 0 1px 3px -1px rgba(0, 0, 0, 0.75);
    z-index: 1;

}
#chat-title{
    background-color: rgba(217, 223, 221, 0.945);
    /* height: 60px;
    width: 75%;
    float: left; */
    color: #0048AA;
    font-weight: bold;
    font-size: 2.0rem;
    box-shadow: 0 1px 3px -1px rgba(0, 0, 0, 0.25);
    z-index: 1;

}
#conversation-list{
/*
    height: 85vh;
    width: 25%;
    position: fixed;
    float: left;
    top: 60px;
    left: 0; */
    background-color: #0048aa;

}
#chat-form
 {   /* height: 85vh;
    width: 75%;
    position: fixed;
    float: left;
    top: 60px;
    left: 25%; */
    border-radius: 0 0 10px 0;
    background: #eee;
    border-top: 1px solid rgba(0, 0, 0, 0.25);

}
/*#search-container
{

}*/
#new-massage-container{
    /* height: 40px;
    width: 25%;
    position: fixed;
    float: left;
    bottom: 0;
    left: 0; */
    background-color: #0048aa;

    box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.25);
    z-index: 1;

    /* border-top: 1px solid rgba(0, 0, 0, 0.25);
    border-radius: 0 0 0 10px;
    background-color: rgb(221, 43, 43);*/
}

#chat-list{
    background-color: rgba(217, 223, 221, 0.945);

}
#profile_img{
    margin: 7px 18px;

    border-radius: 50%;

}
i{
}
.dropbtn {
    font-size: 16px;
    border: none;
    cursor: pointer;

    background: transparent;
    border: 0 none;
    font-weight: inherit;
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    vertical-align: top;
  }

  .dropbtn:hover, .dropbtn:focus {
    background-color: #2980B9;
  }

.dropdown {
    position: relative;
    display: inline-block;
    margin-left: 190px;
  }

  .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;

  }

  .dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
  }

  .dropdown a:hover {background-color: #ddd;}

  .show {display: block;}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="css/chat.css" >
    <title>Chatkaro1</title>

            chat

                <button  href=""></button>

                  Home
                  About
                  Contact

            form

            conversation

            list

            massage

enter image description here

Thank you!

Body:
replace this

 <a >
<i  onclick="myFunction()" style="float: right;" class="fa fa-ellipsis-v fa-lg dropbtn"></i>
</a>

instead of

 <button >
<i  onclick="myFunction()" style="float: right;" class="fa fa-ellipsis-v fa-lg dropbtn"></i>
</button>

Because its taking style of button when you use <i> inside button. Button has its over inherited stylesheet. You can use but then you have override button default stylesheet.

You can changes style of <i> like color, font-size etc.


问:
Show Dialog In InitState Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe
At first time screen appears, i want check if user GPS is enable and Location Permission is granted. Then if one of them is not fulfilled , i show dialog to open app setting.

Source Code

```<code>_initPermission(BuildContext context) async {
    final geolocationStatus = await commonF.getGeolocationPermission();
    final gpsStatus = await commonF.getGPSService();
    if (geolocationStatus != GeolocationStatus.granted) {
      showDialog(
        context: context,
        builder: (ctx) {
          return commonF.showPermissionLocation(ctx);
        },
      );
    } else if (!gpsStatus) {
      showDialog(
        context: context,
        builder: (ctx) {
          return commonF.showPermissionGPS(ctx);
        },
      );
    }
  }
</code>```

Then i called this function in initState like this :

InitState

```<code>void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission(context));
  }
</code>```

The problem is , every first time the screen appears it will give me error like this :

Error

```<code>[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
</code>```

What i have done :

Change InitState like this

```<code>//1
 WidgetsBinding.instance.addPostFrameCallback((_) {
      _initPermission(context);
 });
//2
  SchedulerBinding.instance.addPostFrameCallback((_) => _initPermission(context));
//3
Timer.run(() {
      _initPermission(context);
  })
</code>```

Adding Global Key For Scaffold

```<code>final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
 Scaffold(
        key: _scaffoldKey,
</code>```

Searching similiar problem with me

Show Dialog In Initstate

Looking up a deactivated widget's ancestor is unsafe

Load Data In Initstate

The results that I have done is nothing , the error still appear in first time screen appear.

But strangely, this only happens when first time screen appear . When i do Hot Restart the error message is gone.

[Failed if screen first time appear]

[Hot restart , error gone]

答:
I have no way to test it (I dont have the GPS package) but try changing

```<code>Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission(context));
</code>```

to

```<code>Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission()); //this inside the initstate

_initPermission() async{
final geolocationStatus = await commonF.getGeolocationPermission();
final gpsStatus = await commonF.getGPSService();
if (geolocationStatus != GeolocationStatus.granted) {
  await showDialog(
    context: context,
    builder: (ctx) => commonF.showPermissionLocation
    },
  );
} else if (!gpsStatus) {
  await showDialog(
    context: context,
    builder: (ctx) => commonF.showPermissionGPS
    },
  );
}
} // the stateful widget can use the context in all its methods without passing it as a parameter
</code>```

The error dissapears in hot restart because it just refresh the state of the widget, but it's already created (If you do hot restart and print something inside the initState, for example print('This is init');, you wont see it either because the refresh doesn't dispose and init the widget, so it won't run that piece of code again)

EDIT

Based on your gist I just made a minimal reproducible example and run with no problem in DartPad, later I will try it on VS but for now can you check if there is anything different

```<code>enum GeolocationStatus{granted, denied} //this is just for example

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {

showPermissionGPS() {
    return AlertDialog(
        title: Text('GPSStatus'),
      );
  }

  _showPermissionLocation() {
    return AlertDialog(
        title: Text('Permission Localization'),
      );
  }

  @override
  initState(){
    super.initState();
    Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission());
  }

_initPermission() async{
  final geolocationStatus = await Future<GeolocationStatus>.value(GeolocationStatus.granted); //mocked future with a response to test
  final gpsStatus = await Future<bool>.value(false); //mocked future with a response to test
  if (geolocationStatus != GeolocationStatus.granted) {
   await showDialog(
      context: context,
      builder: (ctx) => _showPermissionLocation() //this mock commonF.showPermissionLocation and returns an AlertDialog
   );
  } else if (!gpsStatus) {
   await showDialog(
    context: context,
    builder: (ctx) => _showPermissionGPS() //this mock commonF.showPermissionGPS and returns an AlertDialog
  );
 }
}

  @override
  Widget build(BuildContext context) {
    return Text('My text');
  }
}
</code>```

Body:
At first time screen appears, i want check if user GPS is enable and Location Permission is granted. Then if one of them is not fulfilled , i show dialog to open app setting.

Source Code

_initPermission(BuildContext context) async {
    final geolocationStatus = await commonF.getGeolocationPermission();
    final gpsStatus = await commonF.getGPSService();
    if (geolocationStatus != GeolocationStatus.granted) {
      showDialog(
        context: context,
        builder: (ctx) {
          return commonF.showPermissionLocation(ctx);
        },
      );
    } else if (!gpsStatus) {
      showDialog(
        context: context,
        builder: (ctx) {
          return commonF.showPermissionGPS(ctx);
        },
      );
    }
  }

Then i called this function in initState like this :

InitState

void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission(context));
  }

The problem is , every first time the screen appears it will give me error like this :

Error

[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

What i have done :

Change InitState like this

//1
 WidgetsBinding.instance.addPostFrameCallback((_) {
      _initPermission(context);
 });
//2
  SchedulerBinding.instance.addPostFrameCallback((_) => _initPermission(context));
//3
Timer.run(() {
      _initPermission(context);
  })

Adding Global Key For Scaffold

final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
 Scaffold(
        key: _scaffoldKey,

Searching similiar problem with me

Show Dialog In Initstate

Looking up a deactivated widget's ancestor is unsafe

Load Data In Initstate

The results that I have done is nothing , the error still appear in first time screen appear.

But strangely, this only happens when first time screen appear . When i do Hot Restart the error message is gone.

[Failed if screen first time appear]

[Hot restart , error gone]

Body:
I have no way to test it (I dont have the GPS package) but try changing

Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission(context));

to

Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission()); //this inside the initstate

_initPermission() async{
final geolocationStatus = await commonF.getGeolocationPermission();
final gpsStatus = await commonF.getGPSService();
if (geolocationStatus != GeolocationStatus.granted) {
  await showDialog(
    context: context,
    builder: (ctx) => commonF.showPermissionLocation
    },
  );
} else if (!gpsStatus) {
  await showDialog(
    context: context,
    builder: (ctx) => commonF.showPermissionGPS
    },
  );
}
} // the stateful widget can use the context in all its methods without passing it as a parameter

The error dissapears in hot restart because it just refresh the state of the widget, but it's already created (If you do hot restart and print something inside the initState, for example print('This is init');, you wont see it either because the refresh doesn't dispose and init the widget, so it won't run that piece of code again)

EDIT

Based on your gist I just made a minimal reproducible example and run with no problem in DartPad, later I will try it on VS but for now can you check if there is anything different

enum GeolocationStatus{granted, denied} //this is just for example

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {

showPermissionGPS() {
    return AlertDialog(
        title: Text('GPSStatus'),
      );
  }

  _showPermissionLocation() {
    return AlertDialog(
        title: Text('Permission Localization'),
      );
  }

  @override
  initState(){
    super.initState();
    Future.delayed(Duration(milliseconds: 50)).then((_) => _initPermission());
  }

_initPermission() async{
  final geolocationStatus = await Future<GeolocationStatus>.value(GeolocationStatus.granted); //mocked future with a response to test
  final gpsStatus = await Future<bool>.value(false); //mocked future with a response to test
  if (geolocationStatus != GeolocationStatus.granted) {
   await showDialog(
      context: context,
      builder: (ctx) => _showPermissionLocation() //this mock commonF.showPermissionLocation and returns an AlertDialog
   );
  } else if (!gpsStatus) {
   await showDialog(
    context: context,
    builder: (ctx) => _showPermissionGPS() //this mock commonF.showPermissionGPS and returns an AlertDialog
  );
 }
}

  @override
  Widget build(BuildContext context) {
    return Text('My text');
  }
}


问:
Delete a single record from Entity Framework?
I have a SQL Server table in Entity Framework named employ with a single key column named ID.

How do I delete a single record from the table using Entity Framework?

答:
The best way is to check and then delete</p>

```<code>        if (ctx.Employ.Any(r=>r.Id == entity.Id))
        {
            Employ rec = new Employ() { Id = entity.Id };
            ctx.Entry(rec).State = EntityState.Deleted;
            ctx.SaveChanges();
        }
</code>```

Body:
The best way is to check and then delete

        if (ctx.Employ.Any(r=>r.Id == entity.Id))
        {
            Employ rec = new Employ() { Id = entity.Id };
            ctx.Entry(rec).State = EntityState.Deleted;
            ctx.SaveChanges();
        }


问:
working of fork in c language
Now I have a problem in understanding the working of fork() system call.
I write a code which is following :

```<code>#include<stdio.h>
int main()
{
    int a, b;
    b=fork();

    printf("\n the value of b = %d",b);
}
</code>```

The output of  this code is following :

Now I don't understand why the output is like this ?

After that i just add a line to my  code and output is completely different.
my code is following:

```<code>int main()
{
    int a, b;
    b=fork();
</code>```

When i run the code the output is following
 2389my name is manish

```<code> the value of b = 0
</code>```

Now I'm totally confused about the working of fork() call.

My question are following:

How fork() works?

Where the control goes after the fork() call?

Can any body explain why the outputs of codes written in problem?

Why the output of b occurring at different places means in first code
the output of b = 2260 is just before the output b = 0 while the value of b = 2389 is not just before the b = 0?

Please explain me the working of fork in the code written in the problem so that I can learn it properly .

答:
You'd better start from this.

Here you find explanation and code example.

Title: working of fork in c language

Body:
Now I have a problem in understanding the working of fork() system call.
I write a code which is following :

#include<stdio.h>
int main()
{
    int a, b;
    b=fork();

    printf("\n the value of b = %d",b);
}

The output of  this code is following :

Now I don't understand why the output is like this ?

After that i just add a line to my  code and output is completely different.
my code is following:

int main()
{
    int a, b;
    b=fork();

When i run the code the output is following
 2389my name is manish

 the value of b = 0

Now I'm totally confused about the working of fork() call.

My question are following:

How fork() works?

Where the control goes after the fork() call?

Can any body explain why the outputs of codes written in problem?

Why the output of b occurring at different places means in first code
the output of b = 2260 is just before the output b = 0 while the value of b = 2389 is not just before the b = 0?

Please explain me the working of fork in the code written in the problem so that I can learn it properly .


问:
GraphQL and Data Loader Using the graphql-java-kickstart library
I am attempting to use the DataLoader feature within the graphql-java-kickstart library:

https://github.com/graphql-java-kickstart

My application is a Spring Boot application using 2.3.0.RELEASE. And I using version 7.0.1 of the graphql-spring-boot-starter library.

The library is pretty easy to use and it works when I don't use the data loader. However, I am plagued by the N+1 SQL problem and as a result need to use the data loader to help alleviate this issue. When I execute a request, I end up getting this:

```<code>Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer
</code>```

I am sure I am missing something in the configuration but really don't know what that is.

Here is my graphql schema:

```<code>type Account {
  id: ID!
  accountNumber: String!
  customers: [Customer]
}

type Customer {
  id: ID!
  fullName: String
}
</code>```

I have created a CustomGraphQLContextBuilder:

```<code>@Component
public class CustomGraphQLContextBuilder implements GraphQLServletContextBuilder {

    private final CustomerRepository customerRepository;

    public CustomGraphQLContextBuilder(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public GraphQLContext build(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        return DefaultGraphQLServletContext.createServletContext(buildDataLoaderRegistry(), null).with(httpServletRequest).with(httpServletResponse).build();
    }

    @Override
    public GraphQLContext build(Session session, HandshakeRequest handshakeRequest) {
        return DefaultGraphQLWebSocketContext.createWebSocketContext(buildDataLoaderRegistry(), null).with(session).with(handshakeRequest).build();
    }

    @Override
    public GraphQLContext build() {
        return new DefaultGraphQLContext(buildDataLoaderRegistry(), null);
    }

    private DataLoaderRegistry buildDataLoaderRegistry() {
        DataLoaderRegistry dataLoaderRegistry = new DataLoaderRegistry();

        dataLoaderRegistry.register("customerDataLoader",
                new DataLoader<Long, Customer>(accountIds ->
                        CompletableFuture.supplyAsync(() ->
                                customerRepository.findCustomersByAccountIds(accountIds), new SyncTaskExecutor())));

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

I also have create an AccountResolver:

```<code>public CompletableFuture<List<Customer>> customers(Account account, DataFetchingEnvironment dfe) {
    final DataLoader<Long, List<Customer>> dataloader = ((GraphQLContext) dfe.getContext())
            .getDataLoaderRegistry().get()
            .getDataLoader("customerDataLoader");

     return dataloader.load(account.getId());
}
</code>```

And here is the Customer Repository:

```<code>public List<Customer> findCustomersByAccountIds(List<Long> accountIds) {

    Instant begin = Instant.now();

    MapSqlParameterSource namedParameters = new MapSqlParameterSource();
    String inClause = getInClauseParamFromList(accountIds, namedParameters);

    String sql = StringUtils.replace(SQL_FIND_CUSTOMERS_BY_ACCOUNT_IDS,"__ACCOUNT_IDS__", inClause);

    List<Customer> customers = jdbcTemplate.query(sql, namedParameters, new CustomerRowMapper());

    Instant end = Instant.now();

    LOGGER.info("Total Time in Millis to Execute findCustomersByAccountIds: " + Duration.between(begin, end).toMillis());

    return customers;
}
</code>```

I can put a break point in the Customer Repository and see the SQL execute and it returns a List of Customer objects. You can also see that the schema wants an array of customers. If I remove the code above and put in the resolver to get the customers one by one....it works....but is really slow.

What am I missing in the configuration that would cause this?

```<code>Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer
</code>```

Thanks for your help!

Dan

答:
In the CustomGraphQLContextBuilder,
I think you should have registered the DataLoader as :

```<code>...

dataLoaderRegistry.register("customerDataLoader",
                new DataLoader<Long, List<Customer>>(accountIds ->

...
</code>```

because, you are expecting a list of Customers for one account Id.

That should work I guess.

Body:
I am attempting to use the DataLoader feature within the graphql-java-kickstart library:

https://github.com/graphql-java-kickstart

My application is a Spring Boot application using 2.3.0.RELEASE. And I using version 7.0.1 of the graphql-spring-boot-starter library.

The library is pretty easy to use and it works when I don't use the data loader. However, I am plagued by the N+1 SQL problem and as a result need to use the data loader to help alleviate this issue. When I execute a request, I end up getting this:

Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer

I am sure I am missing something in the configuration but really don't know what that is.

Here is my graphql schema:

type Account {
  id: ID!
  accountNumber: String!
  customers: [Customer]
}

type Customer {
  id: ID!
  fullName: String
}

I have created a CustomGraphQLContextBuilder:

@Component
public class CustomGraphQLContextBuilder implements GraphQLServletContextBuilder {

    private final CustomerRepository customerRepository;

    public CustomGraphQLContextBuilder(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public GraphQLContext build(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        return DefaultGraphQLServletContext.createServletContext(buildDataLoaderRegistry(), null).with(httpServletRequest).with(httpServletResponse).build();
    }

    @Override
    public GraphQLContext build(Session session, HandshakeRequest handshakeRequest) {
        return DefaultGraphQLWebSocketContext.createWebSocketContext(buildDataLoaderRegistry(), null).with(session).with(handshakeRequest).build();
    }

    @Override
    public GraphQLContext build() {
        return new DefaultGraphQLContext(buildDataLoaderRegistry(), null);
    }

    private DataLoaderRegistry buildDataLoaderRegistry() {
        DataLoaderRegistry dataLoaderRegistry = new DataLoaderRegistry();

        dataLoaderRegistry.register("customerDataLoader",
                new DataLoader<Long, Customer>(accountIds ->
                        CompletableFuture.supplyAsync(() ->
                                customerRepository.findCustomersByAccountIds(accountIds), new SyncTaskExecutor())));

        return dataLoaderRegistry;
    }
}

I also have create an AccountResolver:

public CompletableFuture<List<Customer>> customers(Account account, DataFetchingEnvironment dfe) {
    final DataLoader<Long, List<Customer>> dataloader = ((GraphQLContext) dfe.getContext())
            .getDataLoaderRegistry().get()
            .getDataLoader("customerDataLoader");

     return dataloader.load(account.getId());
}

And here is the Customer Repository:

public List<Customer> findCustomersByAccountIds(List<Long> accountIds) {

    Instant begin = Instant.now();

    MapSqlParameterSource namedParameters = new MapSqlParameterSource();
    String inClause = getInClauseParamFromList(accountIds, namedParameters);

    String sql = StringUtils.replace(SQL_FIND_CUSTOMERS_BY_ACCOUNT_IDS,"__ACCOUNT_IDS__", inClause);

    List<Customer> customers = jdbcTemplate.query(sql, namedParameters, new CustomerRowMapper());

    Instant end = Instant.now();

    LOGGER.info("Total Time in Millis to Execute findCustomersByAccountIds: " + Duration.between(begin, end).toMillis());

    return customers;
}

I can put a break point in the Customer Repository and see the SQL execute and it returns a List of Customer objects. You can also see that the schema wants an array of customers. If I remove the code above and put in the resolver to get the customers one by one....it works....but is really slow.

What am I missing in the configuration that would cause this?

Can't resolve value (/findAccountById[0]/customers) : type mismatch error, expected type LIST got class com.daluga.api.account.domain.Customer

Thanks for your help!

Dan

Body:
In the CustomGraphQLContextBuilder,
I think you should have registered the DataLoader as :

...

dataLoaderRegistry.register("customerDataLoader",
                new DataLoader<Long, List<Customer>>(accountIds ->

...

because, you are expecting a list of Customers for one account Id.

That should work I guess.


问:
How do I use the meslo font for visual studio code
I opened the integrated terminal on visual studio code and I did not like the editor font value that it defaults to. I want to change it to Meslo Regular Z Powerline.
Here is the gist: when I entered this value "Meslo Regular Z Powerline", it turns out that visual studio code does not recognize it. I think the issue is because of the space characters it contains. I have it installed on my Mac but it is still not recognizing it.
What is the workaround for this?

答:
In my case, I have to put MesloLGS NF, Regular.

On Manjaro GNOME Terminal.


问:
Kafka consumer message commit issue
Kafka newbie.

Kafka version: 2.3.1

I am trying to consume Kafka message from two topics using spring cloud. I have not done much configuration apart from kafka binder and some simple config like below. Whenever (Group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null) is unavailable or invalid, will attempt rediscovery)happen, bunch of message which has already processed is getting processed again. Not sure what is happening.

```<code>spring.cloud.stream.kafka.binder.brokers: xxxxx:9094
spring:
  cloud:
    stream:
      default:
        group: bbb-bl-kyc
      bindings:
        input:
          destination: bbb.core.sar.blul.events,bbb.core.sar.bluloc.events
          contentType: application/json
          consumer:
            headerMode: embeddedHeaders

spring.kafka.consumer.properties.spring.json.trusted.packages: "*"
spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.ms: 1000
#Custom Serializer configurations to secure data
spring.cloud.stream.kafka.binder.configuration:
  key.serializer: org.apache.kafka.common.serialization.StringSerializer
  value.serializer: pnc.aop.core.kafka.serialization.MessageSecuredByteArraySerializer
  value.deserializer: pnc.aop.core.kafka.serialization.MessageSecuredByteArrayDeserializer
  key.deserializer: org.apache.kafka.common.serialization.StringDeserializer

2020-05-29 07:01:11.389  INFO 1 --- [container-0-C-1] p.a.b.k.service.KYCOrchestrationService  : Done with Customer xxxx MS call response handling  Confm Id: 159073553171893 Appln Id: HSUKQJDJNZNMWVZZ
2020-05-29 07:01:11.393  INFO 1 --- [container-0-C-1] p.a.b.kyc.service.DMSIntegrationService  : Message written to the DMS topic successfully 159073553171893
2020-05-29 07:01:11.394  INFO 1 --- [container-0-C-1] p.a.b.k.s.AdminConsoleProducerService    : Message written to Admin console Application Log topic successfully  Confm Id: 159073553171893 Appln Id: HSUKQJDJNZNMWVZZ
2020-05-30 17:21:13.140  INFO 1 --- [ad | bbb-bl-kyc] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null) is unavailable or invalid, will attempt rediscovery
2020-05-30 17:21:13.122  INFO 1 --- [ad | bbb-bl-kyc] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null) is unavailable or invalid, will attempt rediscovery
2020-05-30 17:21:14.522  INFO 1 --- [ad | bbb-bl-kyc] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Discovered group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null)
2020-05-30 17:21:14.692  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Discovered group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null)
2020-05-30 17:21:15.151  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Attempt to heartbeat failed for since member id consumer-4-f5a03efd-75cd-425b-94e1-efd3d728d7ca is not valid.
2020-05-30 17:21:15.152  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Revoking previously assigned partitions [bbb.core.sar.bluloc.events-0]
2020-05-30 17:21:15.173  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions revoked: [bbb.core.sar.bluloc.events-0]
2020-05-30 17:21:15.141  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Attempt to heartbeat failed for since member id consumer-2-52012bae-1b22-4211-b107-803fb3765720 is not valid.
2020-05-30 17:21:15.175  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] (Re-)joining group
2020-05-30 17:21:15.176  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Revoking previously assigned partitions [bbb.core.sar.blul.events-0]
2020-05-30 17:21:15.184  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions revoked: [bbb.core.sar.blul.events-0]
2020-05-30 17:21:15.184  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] (Re-)joining group
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Successfully joined group with generation 66
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Successfully joined group with generation 66
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Setting newly assigned partitions: bbb.core.sar.bluloc.events-0
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Setting newly assigned partitions: bbb.core.sar.blul.events-0
2020-05-30 17:21:18.203  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Found no committed offset for partition bbb.core.sar.blul.events-0
2020-05-30 17:21:18.203  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Found no committed offset for partition bbb.core.sar.bluloc.events-0
2020-05-30 17:21:18.537  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Resetting offset for partition bbb.core.sar.blul.events-0 to offset 4.
2020-05-30 17:21:18.538  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Resetting offset for partition bbb.core.sar.bluloc.events-0 to offset 0.
2020-05-30 17:21:18.621  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions assigned: [bbb.core.sar.blul.events-0]
2020-05-30 17:21:18.625  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions assigned: [bbb.core.sar.bluloc.events-0]
2020-05-30 17:21:18.822  INFO 1 --- [container-0-C-1] p.a.b.k.stream.KYCbbbCoreEventsListener  : Initiating KYC Orchestration 159071814927374
2020-05-30 17:21:18.826  INFO 1 --- [container-0-C-1] p.a.b.k.stream.KYCbbbCoreEventsListener  : Initiating KYC Orchestration null
2020-05-30 17:21:18.928  INFO 1 --- [container-0-C-1] p.a.b.k.s.AdminConsoleProducerService    : Message written to Admin console Application topic successfully Confm Id: null Appln Id: XQZ58K3H3XZADTAT
</code>```

答:
Without changing much of the consumer configurations, you will have at least once delivery semantics.

When the Group Coordinator is temporarly not available your consumer won't be able to commit the messages it  processed. After re-joining your consumer will again process same messages (as they were not committed yet) leading to duplicates.

You can find more details on GroupCoordinator and delivery semantics here

Title: Kafka consumer message commit issue

Body:
Kafka newbie.

Kafka version: 2.3.1

I am trying to consume Kafka message from two topics using spring cloud. I have not done much configuration apart from kafka binder and some simple config like below. Whenever (Group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null) is unavailable or invalid, will attempt rediscovery)happen, bunch of message which has already processed is getting processed again. Not sure what is happening.

spring.cloud.stream.kafka.binder.brokers: xxxxx:9094
spring:
  cloud:
    stream:
      default:
        group: bbb-bl-kyc
      bindings:
        input:
          destination: bbb.core.sar.blul.events,bbb.core.sar.bluloc.events
          contentType: application/json
          consumer:
            headerMode: embeddedHeaders

spring.kafka.consumer.properties.spring.json.trusted.packages: "*"
spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.ms: 1000
#Custom Serializer configurations to secure data
spring.cloud.stream.kafka.binder.configuration:
  key.serializer: org.apache.kafka.common.serialization.StringSerializer
  value.serializer: pnc.aop.core.kafka.serialization.MessageSecuredByteArraySerializer
  value.deserializer: pnc.aop.core.kafka.serialization.MessageSecuredByteArrayDeserializer
  key.deserializer: org.apache.kafka.common.serialization.StringDeserializer

2020-05-29 07:01:11.389  INFO 1 --- [container-0-C-1] p.a.b.k.service.KYCOrchestrationService  : Done with Customer xxxx MS call response handling  Confm Id: 159073553171893 Appln Id: HSUKQJDJNZNMWVZZ
2020-05-29 07:01:11.393  INFO 1 --- [container-0-C-1] p.a.b.kyc.service.DMSIntegrationService  : Message written to the DMS topic successfully 159073553171893
2020-05-29 07:01:11.394  INFO 1 --- [container-0-C-1] p.a.b.k.s.AdminConsoleProducerService    : Message written to Admin console Application Log topic successfully  Confm Id: 159073553171893 Appln Id: HSUKQJDJNZNMWVZZ
2020-05-30 17:21:13.140  INFO 1 --- [ad | bbb-bl-kyc] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null) is unavailable or invalid, will attempt rediscovery
2020-05-30 17:21:13.122  INFO 1 --- [ad | bbb-bl-kyc] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null) is unavailable or invalid, will attempt rediscovery
2020-05-30 17:21:14.522  INFO 1 --- [ad | bbb-bl-kyc] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Discovered group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null)
2020-05-30 17:21:14.692  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Discovered group coordinator lbbb111a.uat.pncint.net:9092 (id: 2147483641 rack: null)
2020-05-30 17:21:15.151  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Attempt to heartbeat failed for since member id consumer-4-f5a03efd-75cd-425b-94e1-efd3d728d7ca is not valid.
2020-05-30 17:21:15.152  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Revoking previously assigned partitions [bbb.core.sar.bluloc.events-0]
2020-05-30 17:21:15.173  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions revoked: [bbb.core.sar.bluloc.events-0]
2020-05-30 17:21:15.141  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Attempt to heartbeat failed for since member id consumer-2-52012bae-1b22-4211-b107-803fb3765720 is not valid.
2020-05-30 17:21:15.175  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] (Re-)joining group
2020-05-30 17:21:15.176  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Revoking previously assigned partitions [bbb.core.sar.blul.events-0]
2020-05-30 17:21:15.184  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions revoked: [bbb.core.sar.blul.events-0]
2020-05-30 17:21:15.184  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] (Re-)joining group
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Successfully joined group with generation 66
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Successfully joined group with generation 66
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Setting newly assigned partitions: bbb.core.sar.bluloc.events-0
2020-05-30 17:21:18.200  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Setting newly assigned partitions: bbb.core.sar.blul.events-0
2020-05-30 17:21:18.203  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Found no committed offset for partition bbb.core.sar.blul.events-0
2020-05-30 17:21:18.203  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Found no committed offset for partition bbb.core.sar.bluloc.events-0
2020-05-30 17:21:18.537  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=consumer-2, groupId=bbb-bl-kyc] Resetting offset for partition bbb.core.sar.blul.events-0 to offset 4.
2020-05-30 17:21:18.538  INFO 1 --- [container-0-C-1] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=consumer-4, groupId=bbb-bl-kyc] Resetting offset for partition bbb.core.sar.bluloc.events-0 to offset 0.
2020-05-30 17:21:18.621  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions assigned: [bbb.core.sar.blul.events-0]
2020-05-30 17:21:18.625  INFO 1 --- [container-0-C-1] o.s.c.s.b.k.KafkaMessageChannelBinder$1  : bbb-bl-kyc: partitions assigned: [bbb.core.sar.bluloc.events-0]
2020-05-30 17:21:18.822  INFO 1 --- [container-0-C-1] p.a.b.k.stream.KYCbbbCoreEventsListener  : Initiating KYC Orchestration 159071814927374
2020-05-30 17:21:18.826  INFO 1 --- [container-0-C-1] p.a.b.k.stream.KYCbbbCoreEventsListener  : Initiating KYC Orchestration null
2020-05-30 17:21:18.928  INFO 1 --- [container-0-C-1] p.a.b.k.s.AdminConsoleProducerService    : Message written to Admin console Application topic successfully Confm Id: null Appln Id: XQZ58K3H3XZADTAT


问:
What is efficient way to check if current word is close to a word in string?
consider examples below :

Example 1 :

```<code>str1 = "wow...it  looks amazing"
str2 = "looks amazi"
</code>```

You see that amazi is close to amazing, str2 is mistyped, i wanted to write a program that will tell me that amazi is close to amazing then in str2 i will replace amazi with amazing

Example 2 :

```<code>str1 = "is looking good"
str2 = "looks goo"
</code>```

In this case updated str2 will be "looking good"

Example 3 :

```<code>str1 = "you are really looking good"
str2 = "lok goo"
</code>```

In this case str2 will be "good" as lok is not close to looking (or even if program can convert in this case lok to looking then it's just fine for my  problem's solution)

Example 4 :

```<code>str1 = "Stu is actually SEVERLY sunburnt....it hurts!!!"
str2 = "hurts!!"
</code>```

Updated str2 will be "hurts!!!"

Example 5 :

```<code>str1 = "you guys were absolutely amazing tonight, a..."
str2 = "ly amazin"
</code>```

Updated str2 will be "amazing", "ly" shall be removed or replace by absolutely.

What will be the  algo and  code for this?

Maybe we can do it by looking at character lexicographically and set a
threshold like 0.8 or 80% so if word2 gets 80% sequential characters of word1 from str1 then we replace word2 in str2 with word of str1?
Any other efficient solution with python code please?

答:
There are a lot of ways to approach this.  This one solves all of your examples.  I added a minimum similarity filter to return only the higher quality matches.  This is what allows the 'ly' to be dropped in the last sample, as it is not all that close any any of the words.

Documentation

You can install levenshtein with pip install python-Levenshtein

```<code>import Levenshtein

def find_match(str1,str2):
    min_similarity = .75
    output = []
    results = [[Levenshtein.jaro_winkler(x,y) for x in str1.split()] for y in str2.split()]
    for x in results:
        if max(x) >= min_similarity:
            output.append(str1.split()[x.index(max(x))])
    return output
</code>```

Each sample you proposed.

```<code>find_match("is looking good", "looks goo")

['looking','good']

find_match("you are really looking good", "lok goo")

['looking','good']

find_match("Stu is actually SEVERLY sunburnt....it hurts!!!", "hurts!!")

['hurts!!!']

find_match("you guys were absolutely amazing tonight, a...", "ly amazin")

['amazing']
</code>```

Body:
consider examples below :

Example 1 :

str1 = "wow...it  looks amazing"
str2 = "looks amazi"

You see that amazi is close to amazing, str2 is mistyped, i wanted to write a program that will tell me that amazi is close to amazing then in str2 i will replace amazi with amazing

Example 2 :

str1 = "is looking good"
str2 = "looks goo"

In this case updated str2 will be "looking good"

Example 3 :

str1 = "you are really looking good"
str2 = "lok goo"

In this case str2 will be "good" as lok is not close to looking (or even if program can convert in this case lok to looking then it's just fine for my  problem's solution)

Example 4 :

str1 = "Stu is actually SEVERLY sunburnt....it hurts!!!"
str2 = "hurts!!"

Updated str2 will be "hurts!!!"

Example 5 :

str1 = "you guys were absolutely amazing tonight, a..."
str2 = "ly amazin"

Updated str2 will be "amazing", "ly" shall be removed or replace by absolutely.

What will be the  algo and  code for this?

Maybe we can do it by looking at character lexicographically and set a
threshold like 0.8 or 80% so if word2 gets 80% sequential characters of word1 from str1 then we replace word2 in str2 with word of str1?
Any other efficient solution with python code please?

Body:
There are a lot of ways to approach this.  This one solves all of your examples.  I added a minimum similarity filter to return only the higher quality matches.  This is what allows the 'ly' to be dropped in the last sample, as it is not all that close any any of the words.

Documentation

You can install levenshtein with pip install python-Levenshtein

import Levenshtein

def find_match(str1,str2):
    min_similarity = .75
    output = []
    results = [[Levenshtein.jaro_winkler(x,y) for x in str1.split()] for y in str2.split()]
    for x in results:
        if max(x) >= min_similarity:
            output.append(str1.split()[x.index(max(x))])
    return output

Each sample you proposed.

find_match("is looking good", "looks goo")

['looking','good']

find_match("you are really looking good", "lok goo")

['looking','good']

find_match("Stu is actually SEVERLY sunburnt....it hurts!!!", "hurts!!")

['hurts!!!']

find_match("you guys were absolutely amazing tonight, a...", "ly amazin")

['amazing']


问:
How to use CSS counter increment for dynamic page numbers
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="SetupMainTable">
  <thead>
    <tr>
       <td colspan="4">Company Name</td>
       <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
       <td colspan="1"><div class="page-number"></div></td>
    </tr>
  </thead>
</table>  </code>```

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

答:
[Updated Answer]

Try this. It's working fine as you wanted it to work

var counter = 1;

function printPageCounter(){
        document.title="Page "+counter+"";

        $("#pageNumber").append("Page Number : "+counter+"");
        window.print();
        $("#pageNumber").empty();
        counter++;
        return true;
 }

jQuery(document).bind("keyup keydown", function(e){
    if(e.ctrlKey && e.keyCode == 80){
     printPageCounter();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
    <head>
    <title>My title</title>
    </head>
    <body>
    <div id="pageNumber"></div>
    <H1>Just press ctrl + p  Or Just press this button <H1>

<button onClick="printPageCounter();">Try it</button>

    </body>
    </html></code>```

Body:
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }

       Company Name
       Daily Time Ticket

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

Body:
[Updated Answer]

Try this. It's working fine as you wanted it to work

var counter = 1;

function printPageCounter(){
        document.title="Page "+counter+"";

        $("#pageNumber").append("Page Number : "+counter+"");
        window.print();
        $("#pageNumber").empty();
        counter++;
        return true;
 }

jQuery(document).bind("keyup keydown", function(e){
    if(e.ctrlKey && e.keyCode == 80){
     printPageCounter();
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
    <head>
    <title>My title</title>
    </head>
    <body>
    <div id="pageNumber"></div>
    <H1>Just press ctrl + p  Or Just press this button <H1>

<button onClick="printPageCounter();">Try it</button>

    </body>
    </html>


问:
Return true if none of the letters in the blacklist
Return true if none of the letters in the blacklist
are present in the phrase. If at least one letter from
blacklist is present in the phrase return false;

Comparison should be case insensitive. Meaning 'A' == 'a'.

```<code>/**
     *
     * @param {string} blacklist
     * @param {string} phrase
     *
     * @returns {boolean}
     */
    function hasNoneLetters(blacklist, phrase) {
      console.log(blacklist)
      var x = phrase.includes(blacklist);
      if(x === false){
        return true
      }
      else{
        return false
      }

    }
</code>```

答:
The shortest one answer

```<code>function hasNoneLetters(blacklist, phrase) {
    return !blacklist.split('').find(b => phrase.includes(b))
 }
</code>```

    function hasNoneLetters(blacklist, phrase) {
        return !blacklist.split('').find(b => phrase.includes(b))
     }

console.log(hasNoneLetters('Abc', 'the Phrase'))

console.log(hasNoneLetters('Abc', 'the PhrAse'))
console.log(hasNoneLetters('abc', 'the Phrase'))```

Body:
Return true if none of the letters in the blacklist
are present in the phrase. If at least one letter from
blacklist is present in the phrase return false;

Comparison should be case insensitive. Meaning 'A' == 'a'.

/**
     *
     * @param {string} blacklist
     * @param {string} phrase
     *
     * @returns {boolean}
     */
    function hasNoneLetters(blacklist, phrase) {
      console.log(blacklist)
      var x = phrase.includes(blacklist);
      if(x === false){
        return true
      }
      else{
        return false
      }

    }

Body:
The shortest one answer

function hasNoneLetters(blacklist, phrase) {
    return !blacklist.split('').find(b => phrase.includes(b))
 }

    function hasNoneLetters(blacklist, phrase) {
        return !blacklist.split('').find(b => phrase.includes(b))
     }

console.log(hasNoneLetters('Abc', 'the Phrase'))

console.log(hasNoneLetters('Abc', 'the PhrAse'))
console.log(hasNoneLetters('abc', 'the Phrase'))


问:
Exporting state from functional components. Bad practice?
When building components related to user input, the two ways I've done it is with controlled components or uncontrolled components with refs.
However, one way that it could be done by declaring the variable that will hold the state outside the component and exporting it.

```<code>export let input;
let setInput;
const Form = props => {
  [input, setInput] = useState("");
  const handleInput = e => setInput(e.currentTarget.value)
  ...
  return <input value={input} onChange={handleInput} />
}
</code>```

Would this be considered bad practice? Are there any issues with this?

答:
State of a component is a supposed to be an instance property, by declaring state outside of the component you restrict each component instance to have its own state

If you are looking to use state across your App, consider using ContextAPI or Redux

Body:
When building components related to user input, the two ways I've done it is with controlled components or uncontrolled components with refs.
However, one way that it could be done by declaring the variable that will hold the state outside the component and exporting it.

export let input;
let setInput;
const Form = props => {
  [input, setInput] = useState("");
  const handleInput = e => setInput(e.currentTarget.value)
  ...
  return <input value={input} onChange={handleInput} />
}

Would this be considered bad practice? Are there any issues with this?


问:
resize images in php with imagemagick on 1&1 hosting
I am running out of memory when allowing users to resize images of modern day 12MP or higher cameras. Even some pictures that are only 900kb in size take up a lot more room in memory because it's based on pixel size (i think) so ...

I have SSH access to a 1&1 shared server and I followed their instructions to upload imagemagick and configure/make/install it into a directory on my server. Now what do I have to do in php to do the same thing as

```<code>$originalImage = imagecreatefromjpeg($src);
$finalImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled($finalImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagejpeg($finalImage,$saveDest,$jpeg_quality);
</code>```

the variables are hopefully self explanitory. I was trying to find my way through installing the imagick extension but i got really lost when i read about PECL and PEAR and I really don't want to screw up the working php installation somehow.

答:
```<code>exec('/path/to/your/home/imagemagick/installation/bin/convert '.$src.' -resize '.$newWidth.'x'.$newHeight.' '.$saveDest);
</code>```

But make sure you have all variables coming from user site escaped. And $saveDest is writable by your webserver.

Changes are high that you run in to the same memory limit problems, couse apache/php is invoking a script which limits its memory usage to its parent.

Body:
I am running out of memory when allowing users to resize images of modern day 12MP or higher cameras. Even some pictures that are only 900kb in size take up a lot more room in memory because it's based on pixel size (i think) so ...

I have SSH access to a 1&1 shared server and I followed their instructions to upload imagemagick and configure/make/install it into a directory on my server. Now what do I have to do in php to do the same thing as

$originalImage = imagecreatefromjpeg($src);
$finalImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled($finalImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagejpeg($finalImage,$saveDest,$jpeg_quality);

the variables are hopefully self explanitory. I was trying to find my way through installing the imagick extension but i got really lost when i read about PECL and PEAR and I really don't want to screw up the working php installation somehow.

Body:
exec('/path/to/your/home/imagemagick/installation/bin/convert '.$src.' -resize '.$newWidth.'x'.$newHeight.' '.$saveDest);

But make sure you have all variables coming from user site escaped. And $saveDest is writable by your webserver.

Changes are high that you run in to the same memory limit problems, couse apache/php is invoking a script which limits its memory usage to its parent.


问:
How do I show pie graph in 2 row and 2 column in Python
I have a problem about showing pie graphs in 2 row and 2 column. They are listed in one column.

How can I fix the issue?

Here is my code snippets shown below.

```<code>plt.figure(figsize = (8,8))
ax1 = plt.subplot(2,2,1)
coursera_df_beginner["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1, 0, 0), startangle=90,autopct='%1.1f%%', ax=ax1)
plt.title('Difficulty in Courses')
plt.ylabel("")

plt.figure(figsize = (8,8))
ax2 = plt.subplot(2,2,2)
coursera_df_intermediate["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1, 0, 0), startangle=90,autopct='%1.1f%%', ax=ax2)
plt.title('Difficulty in Courses')
plt.ylabel("")

plt.figure(figsize = (8,8))
ax3 = plt.subplot(2,2,3)
coursera_df_mixed["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1,), startangle=90,autopct='%1.1f%%', ax=ax3)
plt.title('Difficulty in Courses')
plt.ylabel("")

plt.figure(figsize = (8,8))
ax4 = plt.subplot(2,2,4)
coursera_df_advanced["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1, 0), startangle=90,autopct='%1.1f%%', ax=ax4)
plt.title('Difficulty in Courses')
plt.ylabel("")
</code>```

答:
Here is my answer</p>

```<code>f,a = plt.subplots(2,2,figsize=(8,8))
f.subplots_adjust(wspace = .8)

coursera_df_beginner["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                    shadow=True,
                                                                    explode=(0.1, 0, 0),
                                                                    startangle=90,
                                                                    autopct='%1.1f%%', ax=a[0,0])
a[0,0].set_title('Beginner Course')
a[0,0].set_ylabel('');

coursera_df_intermediate["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                        shadow=True,
                                                                        explode=(0.1, 0, 0),
                                                                        startangle=90,
                                                                        autopct='%1.1f%%', ax=a[0,1])

a[0,1].set_title('Intermediate Course')
a[0,1].set_ylabel('');

coursera_df_mixed["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                 shadow=True,
                                                                 explode=(0.1,),
                                                                 startangle=90,
                                                                 autopct='%1.1f%%',
                                                                 ax=a[1,0])
a[1,0].set_title('Mixed Course')
a[1,0].set_ylabel('');

coursera_df_advanced["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                    shadow=True,
                                                                    explode=(0.1, 0),
                                                                    startangle=90,
                                                                    autopct='%1.1f%%',
                                                                    ax=a[1,1])

a[1,1].set_title('Advanced Course')
a[1,1].set_ylabel('');
</code>```

Body:
I have a problem about showing pie graphs in 2 row and 2 column. They are listed in one column.

How can I fix the issue?

Here is my code snippets shown below.

plt.figure(figsize = (8,8))
ax1 = plt.subplot(2,2,1)
coursera_df_beginner["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1, 0, 0), startangle=90,autopct='%1.1f%%', ax=ax1)
plt.title('Difficulty in Courses')
plt.ylabel("")

plt.figure(figsize = (8,8))
ax2 = plt.subplot(2,2,2)
coursera_df_intermediate["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1, 0, 0), startangle=90,autopct='%1.1f%%', ax=ax2)
plt.title('Difficulty in Courses')
plt.ylabel("")

plt.figure(figsize = (8,8))
ax3 = plt.subplot(2,2,3)
coursera_df_mixed["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1,), startangle=90,autopct='%1.1f%%', ax=ax3)
plt.title('Difficulty in Courses')
plt.ylabel("")

plt.figure(figsize = (8,8))
ax4 = plt.subplot(2,2,4)
coursera_df_advanced["course_Certificate_type"].value_counts().plot(kind='pie',shadow=True, explode=(0.1, 0), startangle=90,autopct='%1.1f%%', ax=ax4)
plt.title('Difficulty in Courses')
plt.ylabel("")

Body:
Here is my answer

f,a = plt.subplots(2,2,figsize=(8,8))
f.subplots_adjust(wspace = .8)

coursera_df_beginner["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                    shadow=True,
                                                                    explode=(0.1, 0, 0),
                                                                    startangle=90,
                                                                    autopct='%1.1f%%', ax=a[0,0])
a[0,0].set_title('Beginner Course')
a[0,0].set_ylabel('');

coursera_df_intermediate["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                        shadow=True,
                                                                        explode=(0.1, 0, 0),
                                                                        startangle=90,
                                                                        autopct='%1.1f%%', ax=a[0,1])

a[0,1].set_title('Intermediate Course')
a[0,1].set_ylabel('');

coursera_df_mixed["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                 shadow=True,
                                                                 explode=(0.1,),
                                                                 startangle=90,
                                                                 autopct='%1.1f%%',
                                                                 ax=a[1,0])
a[1,0].set_title('Mixed Course')
a[1,0].set_ylabel('');

coursera_df_advanced["course_Certificate_type"].value_counts().plot(kind='pie',
                                                                    shadow=True,
                                                                    explode=(0.1, 0),
                                                                    startangle=90,
                                                                    autopct='%1.1f%%',
                                                                    ax=a[1,1])

a[1,1].set_title('Advanced Course')
a[1,1].set_ylabel('');


问:
Why do pids jump in a container?
Entering a container (e.g. docker run or docker exec) makes the PID of next created process jump ahead, why is that?

For example, in the image below the second process in the container (ps) is assigned PID 10, not PID 2:

According to this answer, Linux appears to be allocating PIDs in a sequence, is that not always the case?

答:
Talked with once of runc's maintainers, Aleksa Sarai, and he explained why this is happening.

By design, the golang runtime spawns several threads to manage a process. runc is written in golang, and when building/execing into the container, there is a short time where the runc process is running inside the container (before execing the user requested executable, e.g. bash in docker exec bash). In Linux, threads and processes are both identified with ids from the same pool, so the go runtime threads are counted in the container pid namespace, leading to the pid jump I described.

Title: Why do pids jump in a container?


问:
Column "dbo" is not allowed in this context, and the user-defined function or aggregate "dbo.getListOfConference" could not be found
I've got problem with my custom function. I want it to get back table of names of my conference users. Here is the code:

```<code>CREATE FUNCTION dbo.getListOfConference(@idConference int)
RETURNS Table
AS
RETURN
SELECT Employee_name FROM dbo.Employee WHERE ID_Employee
    IN (SELECT ID_Employee FROM dbo.Conference WHERE ID_Conference LIKE @idConference);
</code>```

And the message:

Column "dbo" is not allowed in this context, and the user-defined function or aggregate "dbo.getListOfConference" could not be found.

This message showed when I want to check this function like that:

```<code>PRINT dbo.getListOfConference(254712);
</code>```

答:
You have a table valued function, but you are want to use it as a scalar function.  No-can-do.

You can select from it:

```<code>select *
from dbo.getListOfConference(254712);
</code>```

Body:
I've got problem with my custom function. I want it to get back table of names of my conference users. Here is the code:

CREATE FUNCTION dbo.getListOfConference(@idConference int)
RETURNS Table
AS
RETURN
SELECT Employee_name FROM dbo.Employee WHERE ID_Employee
    IN (SELECT ID_Employee FROM dbo.Conference WHERE ID_Conference LIKE @idConference);

And the message:

Column "dbo" is not allowed in this context, and the user-defined function or aggregate "dbo.getListOfConference" could not be found.

This message showed when I want to check this function like that:

PRINT dbo.getListOfConference(254712);

Body:
You have a table valued function, but you are want to use it as a scalar function.  No-can-do.

You can select from it:

select *
from dbo.getListOfConference(254712);