问:
Mix useEffect and Firebase's onValue
When working with Firebase and React, in order to fetch data based on state changes or on inner database changes (from another user for example), I often rely on pieces of code like this one:

```<code>    useEffect(() => {

    const getGamesInSelectedGroup = () => {

        if (!state.currentGroup) {
            return
        }

        const db = getDatabase();
        const resp = ref(db, `/games/${state.currentGroup.name}`);

        onValue(resp, (snap) => {
            if (snap.exists()) {
                const data = snap.val()
                const games = Object.keys(data).map(k => ({id: k, group: state.currentGroup.name, ...data[k]}))

                setState((prev) => ({
                    ...prev,
                    games: games,
                    isLoaded: true,
                }));
                return

            }
            setState((prev) => ({
                ...prev,
                games: null,
                isLoaded: true,
            }));
            toast.warning("no data for " + state.currentGroup.name)

        })
    }

    getGamesInSelectedGroup();

}, [state.currentGroup])
</code>```

However, I am wondering if, whenever state.currentGroup changes, a new listener to /games/${state.currentGroup.name} is created? If so, is there a mean to unsubscribe to previous listener before creating a new one?

I have thinking about replacing onValue by a get call, still conditioned on state.currentGroup and using onValue outside useEffectto reflect "inner" database change.

答:
Rather than nest everything in your getGamesInSelectedGroup function (which is the pattern you would use for Promise-based APIs), just call it in the body of the useEffect to make managing the listener simpler:

```<code>useEffect(() => {
    if (!state.currentGroup) {
        return
    }

    const db = getDatabase();
    const resp = ref(db, `/games/${state.currentGroup.name}`);

    return onValue(resp, (snap) => { // <--- return the unsubscriber!
        if (snap.exists()) {
            const data = snap.val()
            const games = Object.keys(data)
                 .map(k => ({
                     id: k,
                     group: state.currentGroup.name,
                     ...data[k]
                 }));

            setState((prev) => ({
                ...prev,
                games, // you can use this instead of "games: games"
                isLoaded: true,
            }));
            return
        }
        setState((prev) => ({
            ...prev,
            games: null,
            isLoaded: true,
        }));
        toast.warning("no data for " + state.currentGroup.name)
    });
}, [state.currentGroup])
</code>```

I would also recommend using a "snapshot to array of children" function rather than using Object.keys(snapshot.val()) to maintain the sort order from the query (it would be ignored using the code as-is). Unfortunately, at the time of writing, there is no equivalent of Firestore's QuerySnapshot#docs for the RTDB just yet. But it's pretty easy to make our own:

```<code>// returns array of DataSnapshot objects under this DataSnapshot
// put this outside of your component, like in a common function library file
const getSnapshotChildren = (snapshot) => {
    const children = [];
    // note: the curly braces on the next line are important! If the
    // callback returns a truthy value, forEach will stop iterating
    snapshot.forEach(child => { children.push(child) })
    return children;
}

useEffect(() => {
    if (!state.currentGroup) {
        return
    }

    const db = getDatabase();
    const resp = ref(db, `/games/${state.currentGroup.name}`);

    return onValue(resp, (snap) => { // <--- return the unsubscriber!
        if (snap.exists()) {
            const games = getSnapshotChildren(snap)
                 .map(child => ({
                     id: child.key,
                     group: state.currentGroup.name,
                     ...child.val()
                 }));

            setState((prev) => ({
                ...prev,
                games, // you can use this instead of "games: games"
                isLoaded: true,
            }));
            return
        }
        setState((prev) => ({
            ...prev,
            games: null,
            isLoaded: true,
        }));
        toast.warning("no data for " + state.currentGroup.name)
    });
}, [state.currentGroup])
</code>```

Title: Mix useEffect and Firebase's onValue

Body:
When working with Firebase and React, in order to fetch data based on state changes or on inner database changes (from another user for example), I often rely on pieces of code like this one:

    useEffect(() => {

    const getGamesInSelectedGroup = () => {

        if (!state.currentGroup) {
            return
        }

        const db = getDatabase();
        const resp = ref(db, `/games/${state.currentGroup.name}`);

        onValue(resp, (snap) => {
            if (snap.exists()) {
                const data = snap.val()
                const games = Object.keys(data).map(k => ({id: k, group: state.currentGroup.name, ...data[k]}))

                setState((prev) => ({
                    ...prev,
                    games: games,
                    isLoaded: true,
                }));
                return

            }
            setState((prev) => ({
                ...prev,
                games: null,
                isLoaded: true,
            }));
            toast.warning("no data for " + state.currentGroup.name)

        })
    }

    getGamesInSelectedGroup();

}, [state.currentGroup])

However, I am wondering if, whenever state.currentGroup changes, a new listener to /games/${state.currentGroup.name} is created? If so, is there a mean to unsubscribe to previous listener before creating a new one?

I have thinking about replacing onValue by a get call, still conditioned on state.currentGroup and using onValue outside useEffectto reflect "inner" database change.

Body:
Rather than nest everything in your getGamesInSelectedGroup function (which is the pattern you would use for Promise-based APIs), just call it in the body of the useEffect to make managing the listener simpler:

useEffect(() => {
    if (!state.currentGroup) {
        return
    }

    const db = getDatabase();
    const resp = ref(db, `/games/${state.currentGroup.name}`);

    return onValue(resp, (snap) => { // <--- return the unsubscriber!
        if (snap.exists()) {
            const data = snap.val()
            const games = Object.keys(data)
                 .map(k => ({
                     id: k,
                     group: state.currentGroup.name,
                     ...data[k]
                 }));

            setState((prev) => ({
                ...prev,
                games, // you can use this instead of "games: games"
                isLoaded: true,
            }));
            return
        }
        setState((prev) => ({
            ...prev,
            games: null,
            isLoaded: true,
        }));
        toast.warning("no data for " + state.currentGroup.name)
    });
}, [state.currentGroup])

I would also recommend using a "snapshot to array of children" function rather than using Object.keys(snapshot.val()) to maintain the sort order from the query (it would be ignored using the code as-is). Unfortunately, at the time of writing, there is no equivalent of Firestore's QuerySnapshot#docs for the RTDB just yet. But it's pretty easy to make our own:

// returns array of DataSnapshot objects under this DataSnapshot
// put this outside of your component, like in a common function library file
const getSnapshotChildren = (snapshot) => {
    const children = [];
    // note: the curly braces on the next line are important! If the
    // callback returns a truthy value, forEach will stop iterating
    snapshot.forEach(child => { children.push(child) })
    return children;
}

useEffect(() => {
    if (!state.currentGroup) {
        return
    }

    const db = getDatabase();
    const resp = ref(db, `/games/${state.currentGroup.name}`);

    return onValue(resp, (snap) => { // <--- return the unsubscriber!
        if (snap.exists()) {
            const games = getSnapshotChildren(snap)
                 .map(child => ({
                     id: child.key,
                     group: state.currentGroup.name,
                     ...child.val()
                 }));

            setState((prev) => ({
                ...prev,
                games, // you can use this instead of "games: games"
                isLoaded: true,
            }));
            return
        }
        setState((prev) => ({
            ...prev,
            games: null,
            isLoaded: true,
        }));
        toast.warning("no data for " + state.currentGroup.name)
    });
}, [state.currentGroup])


来源: stackexchange

问:
Xpath element not found
I can't find my link using this Xpath //a[contains(text(),'My stuff')]

Though I can find it through DOM :

HTML :

```<code><li _ngcontent-c8="">
  <a _ngcontent-c8="" href="my-stuff">
    {" "}
    My Stuff{" "}
  </a>
</li>;
</code>```

When executed :

```<code>try:
    my_stuff = WebDriverWait(driver, 8).until(
                EC.presence_of_element_located((By.XPATH, "//a[contains(text(),'My stuff')]"))
    )
    my_stuff.click()
except:
    print("not found")

</code>```

returns not found

There was a modal messing with my selection that needed to be dissmissed.

答:
i will try to analyse the problem and give you most answer

. first : if you have Xpath Helper "google chrome extension" try to put your Xpath there

=> if you find it then the problem in your code . we will try to change it

=> if you can't find it with Xpath helper ,than there is multiple choice:

first try to find if there is a "table" or new "form" above your Xpath , that you can't get it with absolute path
. you must get inside the "table" or "form", then find the path inside it
, tell me if that didn't work

ContentLicense: CC BY-SA 4.0

Title: Xpath element not found

Body:
I can't find my link using this Xpath //a[contains(text(),'My stuff')]

Though I can find it through DOM :

HTML :

    {" "}
    My Stuff{" "}

;

When executed :

try:
    my_stuff = WebDriverWait(driver, 8).until(
                EC.presence_of_element_located((By.XPATH, "//a[contains(text(),'My stuff')]"))
    )
    my_stuff.click()
except:
    print("not found")

returns not found

There was a modal messing with my selection that needed to be dissmissed.


问:
Device specific constraints Xcode 13
I'm having some issues setting up device specific constraints. I know how to use Vary for Traits, but it isn't advanced enough for what I need to do.

Basically, my app displays perfectly fine on any notched device (eg. iPhone 11), but fails to space correctly on any non notched device (eg. iPhone 6s).

Do you know any way to achieve what I need? Thank you!

答:
It tends to be better practice to use constraints that are universal. If I understand correctly, a good solution would be to add an equal height constraint to the view in order to make sure that a portion of the screen is always available for the buttons. I added the following constraints:
list of constraints

In the view controller the result is this:
view controller

And the live preview for notched and not notched devices is this:
notched
not notched

Alternatively, if you are building a camera app, you can use the object 'UIImagePickerController' with the 'sourceType' attribute set to '.camera' which will create a pop-up view controller displaying the camera app.

Title: Device specific constraints Xcode 13


问:
Failure: (ID: 838926df) did not find any jar files with a Main-Class manifest entry
when running gcloud app deploy on my spring boot app, this error happens in Cloud Build.

答:
I was able to fix it for my AppEngine + Gradle project by adding

```<code>jar {
    enabled = false
    archiveClassifier = ''
}
</code>```

to the build.gradle file.

Body:
I was able to fix it for my AppEngine + Gradle project by adding

jar {
    enabled = false
    archiveClassifier = ''
}

to the build.gradle file.


问:
Security tokens with unreadable private keys?
I'd like to uniquely identify users by issuing security tokens to them. In order to guarantee non-repudiation I'd like to ensure that no one has access to the user's private key, not even the person who issues the tokens.

What's the cheapest/most-secure way to implement this?

答:
The standard way to handle non-repudiation in a digital signature app is to use a trusted third party, a 3rd party cert authority.

Be careful trying to create your own system--since you're not an expert in the field, you'll most probably end up either losing the non-repudiation ability that you seek or some other flaw.

The reason the standards for digital signatures exist is that this stuff is very hard to get right in a provable way. See "Schneier's Law"

Also, eventually, non-repudiation comes down to someone being sued--you say that "B" did it (signed the agreement, pressed the button, etc), but "B" denies it. You say you can "prove" that B did it. But so what, you'll need to prove in court that B did it, to get the court to grant you relief (to order B to do something such as pay damages.)

But it will be very very expensive to sue someone and to prove their case due to a digital sig system. And if you went to all that trouble and then the digital sig system was some homebrew system, not a standard, then your odds of relief would drop down to about 0%.

Conclusion: if you care enough about the digital sig to sue people, then use a standard for digital sig. If you will ultimately negotiate rather than sue, then look at the different options.

For example, why not use a hardware security token They're now available as apps for people's phones, too.

ContentLicense: CC BY-SA 3.0


问:
How to maintain the dimensions of container after some text is added dynamically in it?
This is a form that I created and I am adding a warning if the password entered doesn't match using javascript. The problem is that when the text is appended it makes the container items move upward or maybe the bottom downward. Is there a way to make it so that I can add the text without the effect of other items being pushed up or the container bottom being pushed downwards?

let password = document.querySelector("input#password");
let confirmPassword = document.querySelector("input#confirmPassword");
let warningDiv = document.getElementsByClassName("warning");
password.addEventListener("input", getPassword);
confirmPassword.addEventListener("input", getPassword);

let pp, cp;
let warnInserted = false;

function getPassword(e) {
  let p = e.target;
  if (p.id === "password") {
    pp = e.target.value;
  } else if (p.id === "confirmPassword") {
    cp = e.target.value;
  }
  if (pp !== cp && !warnInserted) {
    let warning = document.createElement("p");
    warning.textContent += "*Passwords do not match.";
    warning.classList.add("warning");
    confirmPassword.insertAdjacentHTML("afterend", warning.outerHTML);
    warnInserted = true;
  } else if (pp == cp) {
    warningDiv[0].style.display = "none";
    warnInserted = false;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: Arial, Helvetica, sans-serif;
}

body {
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  background-image: url(https://images.unsplash.com/photo-1643836973129-015e3c240612?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: absolute;
}

#main {
  width: 40%;
  margin: 0 auto;
  text-transform: uppercase;
}

.wrapper {
  display: flex;
  justify-content: space-between;
  flex-flow: row wrap;
  background-color: rgba(177, 173, 173, 0.514);
  border-radius: 5px;
}

.firstname,
.email,
.lastname,
.phone,
.password {
  display: flex;
  flex-direction: column;
  flex-basis: 40%;
  margin: 3% 2%;
  font-size: 0.9rem;
}

.submitbtn {
  margin-top: 4%;
  text-align: start;
}

button {
  border: 2px solid rgba(211, 207, 207, 0.747);
  height: 35px;
  width: 8rem;
  font-size: 0.9rem;
  font-weight: normal;
  background-color: rgba(190, 190, 197, 0.726);
  color: black;
  border-radius: 4px;
}

button:hover {
  transform: translateY(-4px);
  box-shadow: 1px 1px 6px 2px black;
}

input {
  appearance: none;
  height: 23px;
  border-radius: 4px;
  border: 2px solid rgba(211, 210, 210, 0.726);
}

input:invalid {
  appearance: none;
  border: 1px solid red
}

.warning {
  color: red;
  margin: 1px 6px;
  font-size: 0.55rem;
  font-weight: 600;
  text-transform: none;
}

@media (max-width: 960px) {
  .wrapper {
    display: block;
    padding: 20px;
  }
  .firstname,
  .email,
  .lastname,
  .phone {
    margin: 3% 2%;
  }
}

@media (max-width: 500px) {
  #main {
    min-width: 200px;
  }
  input {
    min-width: 120px;
  }
  .submitbtn {
    margin-top: 12%;
  }
  .firstname,
  .email,
  .lastname,
  .phone,
  .password {
    line-height: 1.6rem;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Sign-Up Form</title>

    <form>

          First Name
          <input type="text" name="firstname" id="firstname" required>

          Last Name
          <input type="text" name="lastname" id="lastname" required>

          Email
          <input type="email" name="email" id="email" required>

          Phone Number
          <input type="tel" name="tel" id="tel" required>

          Password
          <input type="password" name="password" id="password" required>

          Confirm Password
          <input type="password" name="confirmPassword" id="confirmPassword" required>

        <button type="submit">Submit</button>

    </form>

```

答:
try to add:

```<code>position: relative;
</code>```

to your input wrappers, and:

```<code>position: absolute;
bottom: -14px;
</code>```

to your .warning block.

I also changed border width to 2px in invalid state so, it is the same as in normal state

let password = document.querySelector("input#password");
let confirmPassword = document.querySelector("input#confirmPassword");
let warningDiv = document.getElementsByClassName("warning");
password.addEventListener("input", getPassword);
confirmPassword.addEventListener("input", getPassword);

let pp, cp;
let warnInserted = false;

function getPassword(e) {
  let p = e.target;
  if (p.id === "password") {
    pp = e.target.value;
  } else if (p.id === "confirmPassword") {
    cp = e.target.value;
  }
  if (pp !== cp && !warnInserted) {
    let warning = document.createElement("p");
    warning.textContent += "*Passwords do not match.";
    warning.classList.add("warning");
    confirmPassword.insertAdjacentHTML("afterend", warning.outerHTML);
    warnInserted = true;
  } else if (pp == cp) {
    warningDiv[0].style.display = "none";
    warnInserted = false;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: Arial, Helvetica, sans-serif;
}

body {
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  background-image: url(https://images.unsplash.com/photo-1643836973129-015e3c240612?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: absolute;
}

#main {
  width: 40%;
  margin: 0 auto;
  text-transform: uppercase;
}

.wrapper {
  display: flex;
  justify-content: space-between;
  flex-flow: row wrap;
  background-color: rgba(177, 173, 173, 0.514);
  border-radius: 5px;
}

.firstname,
.email,
.lastname,
.phone,
.password {
  display: flex;
  flex-direction: column;
  flex-basis: 40%;
  margin: 3% 2%;
  font-size: 0.9rem;
  position: relative; // <--- ADDED
}

.submitbtn {
  margin-top: 4%;
  text-align: start;
}

button {
  border: 2px solid rgba(211, 207, 207, 0.747);
  height: 35px;
  width: 8rem;
  font-size: 0.9rem;
  font-weight: normal;
  background-color: rgba(190, 190, 197, 0.726);
  color: black;
  border-radius: 4px;
}

button:hover {
  transform: translateY(-4px);
  box-shadow: 1px 1px 6px 2px black;
}

input {
  appearance: none;
  height: 23px;
  border-radius: 4px;
  border: 2px solid rgba(211, 210, 210, 0.726);
}

input:invalid {
  appearance: none;
  border: 2px solid red // <--- MODIFIED
}

.warning {
  color: red;
  margin: 1px 6px;
  font-size: 0.55rem;
  font-weight: 600;
  text-transform: none;
  position: absolute; // <--- ADDED
  bottom: -14px; // <--- ADDED
}

@media (max-width: 960px) {
  .wrapper {
    display: block;
    padding: 20px;
  }
  .firstname,
  .email,
  .lastname,
  .phone {
    margin: 3% 2%;
  }
}

@media (max-width: 500px) {
  #main {
    min-width: 200px;
  }
  input {
    min-width: 120px;
  }
  .submitbtn {
    margin-top: 12%;
  }
  .firstname,
  .email,
  .lastname,
  .phone,
  .password {
    line-height: 1.6rem;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Sign-Up Form</title>

    <form>

          First Name
          <input type="text" name="firstname" id="firstname" required>

          Last Name
          <input type="text" name="lastname" id="lastname" required>

          Email
          <input type="email" name="email" id="email" required>

          Phone Number
          <input type="tel" name="tel" id="tel" required>

          Password
          <input type="password" name="password" id="password" required>

          Confirm Password
          <input type="password" name="confirmPassword" id="confirmPassword" required>

        <button type="submit">Submit</button>

    </form>

```

Body:
This is a form that I created and I am adding a warning if the password entered doesn't match using javascript. The problem is that when the text is appended it makes the container items move upward or maybe the bottom downward. Is there a way to make it so that I can add the text without the effect of other items being pushed up or the container bottom being pushed downwards?

let password = document.querySelector("input#password");
let confirmPassword = document.querySelector("input#confirmPassword");
let warningDiv = document.getElementsByClassName("warning");
password.addEventListener("input", getPassword);
confirmPassword.addEventListener("input", getPassword);

let pp, cp;
let warnInserted = false;

function getPassword(e) {
  let p = e.target;
  if (p.id === "password") {
    pp = e.target.value;
  } else if (p.id === "confirmPassword") {
    cp = e.target.value;
  }
  if (pp !== cp && !warnInserted) {
    let warning = document.createElement("p");
    warning.textContent += "*Passwords do not match.";
    warning.classList.add("warning");
    confirmPassword.insertAdjacentHTML("afterend", warning.outerHTML);
    warnInserted = true;
  } else if (pp == cp) {
    warningDiv[0].style.display = "none";
    warnInserted = false;
  }
}

* {
  font-family: Arial, Helvetica, sans-serif;
}

body {
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  background-image: url(https://images.unsplash.com/photo-1643836973129-015e3c240612?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: absolute;
}

#main {
  width: 40%;
  margin: 0 auto;
  text-transform: uppercase;
}

.wrapper {
  display: flex;
  justify-content: space-between;
  flex-flow: row wrap;
  background-color: rgba(177, 173, 173, 0.514);
  border-radius: 5px;
}

.firstname,
.email,
.lastname,
.phone,
.password {
  display: flex;
  flex-direction: column;
  flex-basis: 40%;
  margin: 3% 2%;
  font-size: 0.9rem;
}

.submitbtn {
  margin-top: 4%;
  text-align: start;
}

button {
  border: 2px solid rgba(211, 207, 207, 0.747);
  height: 35px;
  width: 8rem;
  font-size: 0.9rem;
  font-weight: normal;
  background-color: rgba(190, 190, 197, 0.726);
  color: black;
  border-radius: 4px;
}

button:hover {
  transform: translateY(-4px);
  box-shadow: 1px 1px 6px 2px black;
}

input {
  appearance: none;
  height: 23px;
  border-radius: 4px;
  border: 2px solid rgba(211, 210, 210, 0.726);
}

input:invalid {
  appearance: none;
  border: 1px solid red
}

.warning {
  color: red;
  margin: 1px 6px;
  font-size: 0.55rem;
  font-weight: 600;
  text-transform: none;
}

@media (max-width: 960px) {
  .wrapper {
    display: block;
    padding: 20px;
  }
  .firstname,
  .email,
  .lastname,
  .phone {
    margin: 3% 2%;
  }
}

@media (max-width: 500px) {
  #main {
    min-width: 200px;
  }
  input {
    min-width: 120px;
  }
  .submitbtn {
    margin-top: 12%;
  }
  .firstname,
  .email,
  .lastname,
  .phone,
  .password {
    line-height: 1.6rem;
  }
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Sign-Up Form</title>

    <form>

          First Name
          <input type="text" name="firstname" id="firstname" required>

          Last Name
          <input type="text" name="lastname" id="lastname" required>

          Email
          <input type="email" name="email" id="email" required>

          Phone Number
          <input type="tel" name="tel" id="tel" required>

          Password
          <input type="password" name="password" id="password" required>

          Confirm Password
          <input type="password" name="confirmPassword" id="confirmPassword" required>

        <button type="submit">Submit</button>

    </form>

Body:
try to add:

position: relative;

to your input wrappers, and:

position: absolute;
bottom: -14px;

to your .warning block.

I also changed border width to 2px in invalid state so, it is the same as in normal state

let password = document.querySelector("input#password");
let confirmPassword = document.querySelector("input#confirmPassword");
let warningDiv = document.getElementsByClassName("warning");
password.addEventListener("input", getPassword);
confirmPassword.addEventListener("input", getPassword);

let pp, cp;
let warnInserted = false;

function getPassword(e) {
  let p = e.target;
  if (p.id === "password") {
    pp = e.target.value;
  } else if (p.id === "confirmPassword") {
    cp = e.target.value;
  }
  if (pp !== cp && !warnInserted) {
    let warning = document.createElement("p");
    warning.textContent += "*Passwords do not match.";
    warning.classList.add("warning");
    confirmPassword.insertAdjacentHTML("afterend", warning.outerHTML);
    warnInserted = true;
  } else if (pp == cp) {
    warningDiv[0].style.display = "none";
    warnInserted = false;
  }
}

* {
  font-family: Arial, Helvetica, sans-serif;
}

body {
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  background-image: url(https://images.unsplash.com/photo-1643836973129-015e3c240612?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: absolute;
}

#main {
  width: 40%;
  margin: 0 auto;
  text-transform: uppercase;
}

.wrapper {
  display: flex;
  justify-content: space-between;
  flex-flow: row wrap;
  background-color: rgba(177, 173, 173, 0.514);
  border-radius: 5px;
}

.firstname,
.email,
.lastname,
.phone,
.password {
  display: flex;
  flex-direction: column;
  flex-basis: 40%;
  margin: 3% 2%;
  font-size: 0.9rem;
  position: relative; // <--- ADDED
}

.submitbtn {
  margin-top: 4%;
  text-align: start;
}

button {
  border: 2px solid rgba(211, 207, 207, 0.747);
  height: 35px;
  width: 8rem;
  font-size: 0.9rem;
  font-weight: normal;
  background-color: rgba(190, 190, 197, 0.726);
  color: black;
  border-radius: 4px;
}

button:hover {
  transform: translateY(-4px);
  box-shadow: 1px 1px 6px 2px black;
}

input {
  appearance: none;
  height: 23px;
  border-radius: 4px;
  border: 2px solid rgba(211, 210, 210, 0.726);
}

input:invalid {
  appearance: none;
  border: 2px solid red // <--- MODIFIED
}

.warning {
  color: red;
  margin: 1px 6px;
  font-size: 0.55rem;
  font-weight: 600;
  text-transform: none;
  position: absolute; // <--- ADDED
  bottom: -14px; // <--- ADDED
}

@media (max-width: 960px) {
  .wrapper {
    display: block;
    padding: 20px;
  }
  .firstname,
  .email,
  .lastname,
  .phone {
    margin: 3% 2%;
  }
}

@media (max-width: 500px) {
  #main {
    min-width: 200px;
  }
  input {
    min-width: 120px;
  }
  .submitbtn {
    margin-top: 12%;
  }
  .firstname,
  .email,
  .lastname,
  .phone,
  .password {
    line-height: 1.6rem;
  }
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Sign-Up Form</title>
</head>

<body>
  <div id="main">
    <form>
      <div class="wrapper">
        <div class="firstname">
          <label for="firstname">First Name</label>
          <input type="text" name="firstname" id="firstname" required>
        </div>
        <div class="lastname">
          <label for="lastname">Last Name</label>
          <input type="text" name="lastname" id="lastname" required>
        </div>
        <div class="email">
          <label for="email">Email</label>
          <input type="email" name="email" id="email" required>
        </div>
        <div class="phone">
          <label for="tel">Phone Number</label>
          <input type="tel" name="tel" id="tel" required>
        </div>
        <div class="password">
          <label for="password">Password</label>
          <input type="password" name="password" id="password" required>
        </div>
        <div class="password">
          <label for="password">Confirm Password</label>
          <input type="password" name="confirmPassword" id="confirmPassword" required>
        </div>
      </div>
      <div class="submitbtn">
        <button type="submit">Submit</button>
      </div>
    </form>
  </div>
  <script src="form.js" defer></script>
</body>

</html>


问:
How to determine the size of collectionviewcell (xib)
Is there a way to measure the width and height of a cell defined in xib from within "sizeforitemat" function or any other function of viewcontroller, once data is dynamically generated? The default layout of the collection view makes it very shabby as depicted in output. Principally layout should have maximally two columns, and the rest of the empty spaces should be divided between cells within a row. So I want to loop over all the items, once it is filled with data to determine the maximum size of amongst cells to generate a layout according to its size. I'll highly appreciate the response.

viewcontroller.swift

```<code>    import UIKit

    class ViewController: UIViewController, UICollectionViewDelegate,
    UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!
    let myCell: String = "CollectionViewCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.collectionView.register(UINib(nibName:myCell, bundle: nil), forCellWithReuseIdentifier: myCell)

        self.collectionView.delegate = self
        self.collectionView.dataSource = self
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        150
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: myCell, for: indexPath) as! CollectionViewCell
        cell.lbl1.text = "\(indexPath.row)"
        cell.lbl2.text = "\(String(describing: cell.lbl2.text))\(indexPath.row)"
        print ("***", indexPath.item, cell.bounds.size, collectionView.frame.size)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        // TODO: measure width and heigth of each cell to find number of columns

        return collectionView.frame.size
    }
}
</code>```

collectionviewcell.swift

```<code>
    import UIKit

    class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var lbl1: UILabel!
    @IBOutlet weak var lbl2: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

}

</code>```

viewcontroller's code

xib file's code

collection view cell

output

答:
To find the "widest" cell, you can:

create an instance of your cell

loop through your data, setting the label values

get the width

track the maximum width

Something like this:

```<code>    let theData: [String] = [
        "Short",
        "Longer",
        "A bit longer",
        "ABC",
        "This is the longest one",
        "Another medium",
        "Last one"
    ]

    let nib: UINib = UINib(nibName: "CollectionViewCell", bundle: nil)
    let c = nib.instantiate(withOwner: nil, options: nil).first as! CollectionViewCell

    var sz: CGSize = .zero
    var maxW: CGFloat = 0

    for i in 0..<theData.count {

        c.lbl1.text = "\(i)"
        c.lbl2.text = theData[i]

        sz = c.systemLayoutSizeFitting(CGSize(width: .greatestFiniteMagnitude, height: 60.0),
                                       withHorizontalFittingPriority: .defaultLow,
                                       verticalFittingPriority: .required)

        maxW = max(maxW, sz.width)

        print("Row: \(i)", sz)

    }

    print("Max Width:", maxW)

</code>```

Could give this in the debug output:

```<code>Row: 0 (50.0, 60.0)
Row: 1 (61.5, 60.0)
Row: 2 (95.5, 60.0)
Row: 3 (42.0, 60.0)
Row: 4 (179.5, 60.0)
Row: 5 (134.5, 60.0)
Row: 6 (73.5, 60.0)
Max Width: 179.5
</code>```

Body:
Is there a way to measure the width and height of a cell defined in xib from within "sizeforitemat" function or any other function of viewcontroller, once data is dynamically generated? The default layout of the collection view makes it very shabby as depicted in output. Principally layout should have maximally two columns, and the rest of the empty spaces should be divided between cells within a row. So I want to loop over all the items, once it is filled with data to determine the maximum size of amongst cells to generate a layout according to its size. I'll highly appreciate the response.

viewcontroller.swift

    import UIKit

    class ViewController: UIViewController, UICollectionViewDelegate,
    UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!
    let myCell: String = "CollectionViewCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.collectionView.register(UINib(nibName:myCell, bundle: nil), forCellWithReuseIdentifier: myCell)

        self.collectionView.delegate = self
        self.collectionView.dataSource = self
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        150
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: myCell, for: indexPath) as! CollectionViewCell
        cell.lbl1.text = "\(indexPath.row)"
        cell.lbl2.text = "\(String(describing: cell.lbl2.text))\(indexPath.row)"
        print ("***", indexPath.item, cell.bounds.size, collectionView.frame.size)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        // TODO: measure width and heigth of each cell to find number of columns

        return collectionView.frame.size
    }
}

collectionviewcell.swift

    import UIKit

    class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var lbl1: UILabel!
    @IBOutlet weak var lbl2: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

}

viewcontroller's code

xib file's code

collection view cell

output

Body:
To find the "widest" cell, you can:

create an instance of your cell

loop through your data, setting the label values

get the width

track the maximum width

Something like this:

    let theData: [String] = [
        "Short",
        "Longer",
        "A bit longer",
        "ABC",
        "This is the longest one",
        "Another medium",
        "Last one"
    ]

    let nib: UINib = UINib(nibName: "CollectionViewCell", bundle: nil)
    let c = nib.instantiate(withOwner: nil, options: nil).first as! CollectionViewCell

    var sz: CGSize = .zero
    var maxW: CGFloat = 0

    for i in 0..<theData.count {

        c.lbl1.text = "\(i)"
        c.lbl2.text = theData[i]

        sz = c.systemLayoutSizeFitting(CGSize(width: .greatestFiniteMagnitude, height: 60.0),
                                       withHorizontalFittingPriority: .defaultLow,
                                       verticalFittingPriority: .required)

        maxW = max(maxW, sz.width)

        print("Row: \(i)", sz)

    }

    print("Max Width:", maxW)

Could give this in the debug output:

Row: 0 (50.0, 60.0)
Row: 1 (61.5, 60.0)
Row: 2 (95.5, 60.0)
Row: 3 (42.0, 60.0)
Row: 4 (179.5, 60.0)
Row: 5 (134.5, 60.0)
Row: 6 (73.5, 60.0)
Max Width: 179.5


问:
What is the meanig of P() and V() operation in semaphore being atomic in nature? What does the the term atomic mean here?
I am studying operating systems. I am reading about critrical section problem and i came accross semaphore. There are two operations p() also known as down operation and v() operation which is also known as up operation.

Its written that p() and v() are atomic in nature. What is the meaning of being atomic.

答:
Atomic simply means that whatever happens in this operation: It will fail completely and steps until failing will be reverted in some kind or end successfully. No steps in between are possible.

In context of semaphores we are talking about e.g. sharing resources between different consumers. Consumer A and B want to access a shared resource, e.g. a list containing data objects. The access on this list would be atomic if the list access is blocked while A accesses the list, so B needs to wait until A is done with the list and finished it's atomic operation.

It would be bad if the operation on the list would not be atomic: The list is blocked while A is working on it and suddenly something happens, so A simply dies, leaving the list blocked. B would wait forever, since the list access will not be unblocked. This is a classic deadlock scenario.


问:
Global Type Declarations within a NX and NextJS monorepo
I've been looking around the web to try and find s nice solution to my problem but so far I have not.

I have a NX monorepo with NextJS and I am trying to create a global types/ folder that can be used by all of my apps and libs.

I had thought this would be quite simple, I would add a folder to the root and put all my .d.ts files in there. Then in the tsconfig.base.json I would add

```<code>"typeRoots": [
  "node_modules/@types",
  "node_modules/next/types",
  "types/"
]
</code>```

I was hoping it would be as simple as that.

Allowing me to use my typing anywhere within the monorepo without having to import them.

Unfortunately, this didn't work. After lots of messing around I did manage to get it to work but only if the types/ folder was inside of the app, for example:

```<code>apps/
    /myApp/
          /types/            <- types here were detected
types/                       <- types here were not detected
tsconfig.base.json
</code>```

This is no good for me as it would mean I would have to duplicate my types across all apps and libs.

The official recommendation from NX is to add a new lib just to store your types and then import it and use it in each of your apps and libs but this feels really clunky to me. Also, this doesn't really work with the idea of adding it to typeRoots within the tsbase.config.json

If anyone knows a better way this can be done I would love to hear about it.

Cheers.

答:
Below setup works fine for all apps but not libs...

I have index.d.ts in a root directory:

```<code>
    // /index.d.ts
    declare global {
      namespace MyNamespace {
         interface MyInterface { ... }
      }
    }

</code>```

In tsconfig.base.json I have added "esModuleInterop": true, and "typeRoots": ["index.d.ts"] in compilerOptions.
Then in each /apps/my-app/tsconfg.json I added "../../index.d.ts" in include array.

This allows me to use global declarations in apps without the need to import anything.

const myVar: MyNamespace.MyInterface = ...

I tried to do the same for libs but it does not work.

There are three tsconfig.jsons in lib directory:

tsconfig.json (main)

tsconfig.lib.json (lib)

tsconfig.spec.json (spec)

and if i use a storybook for a lib then there is fourth /.storybook/tsconfig.json (storybook).

lib, spec and storybook configs extend main config.

There is error in the file:

```<code>Referenced project '/.../libs/shared-one/tsconfig.lib.json' must have setting "composite": true.
</code>```

if i set composite to true for lib, spec, storybook configs then I get following error there:

```<code>Composite projects may not disable declaration emit.
</code>```

What is wrong? How do I share global type declarations among nx libs? I hoped this will work out of the box.

example of tsconfig.lib.json (lib)

```<code>
    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "composite": true,
        "outDir": "../../dist/out-tsc",
        "types": ["node"]
      },
      "files": [
        "../../node_modules/@nrwl/react/typings/cssmodule.d.ts",
        "../../node_modules/@nrwl/react/typings/image.d.ts"
      ],
      "exclude": [
        "**/*.spec.ts",
        "**/*.spec.tsx",
        "**/*.stories.ts",
        "**/*.stories.js",
        "**/*.stories.jsx",
        "**/*.stories.tsx"
      ],
      "include": ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx"]
    }

</code>```

/libs/my-lib tsconfig.json (main)

```<code>    {
      "extends": "../../tsconfig.base.json",
      "compilerOptions": {
        "jsx": "react-jsx",
        "allowJs": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
      },
      "files": [],
      "include": ["../../index.d.ts"],
      "references": [
        {
          "path": "./tsconfig.lib.json"
        },
        {
          "path": "./tsconfig.spec.json"
        },
        {
          "path": "./.storybook/tsconfig.json"
        }
      ]
    }

</code>```

tsconfig.base.json: (base)

```<code>
    {
      "compileOnSave": false,
      "compilerOptions": {
        "rootDir": ".",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "esModuleInterop": true,
        "importHelpers": true,
        "target": "es2015",
        "module": "esnext",
        "lib": ["es2017", "dom"],
        "skipLibCheck": true,
        "skipDefaultLibCheck": true,
        "baseUrl": ".",
        "paths": {
          "@my-org/shared-one": ["libs/shared-one/src/index.ts"],
          "@my-org/shared-two": ["libs/shared-two/src/index.ts"]
        }
      },
      "exclude": ["node_modules", "tmp"],
      "include": ["index.d.ts"]
    }

</code>```

Body:
I've been looking around the web to try and find s nice solution to my problem but so far I have not.

I have a NX monorepo with NextJS and I am trying to create a global types/ folder that can be used by all of my apps and libs.

I had thought this would be quite simple, I would add a folder to the root and put all my .d.ts files in there. Then in the tsconfig.base.json I would add

"typeRoots": [
  "node_modules/@types",
  "node_modules/next/types",
  "types/"
]

I was hoping it would be as simple as that.

Allowing me to use my typing anywhere within the monorepo without having to import them.

Unfortunately, this didn't work. After lots of messing around I did manage to get it to work but only if the types/ folder was inside of the app, for example:

apps/
    /myApp/
          /types/            <- types here were detected
types/                       <- types here were not detected
tsconfig.base.json

This is no good for me as it would mean I would have to duplicate my types across all apps and libs.

The official recommendation from NX is to add a new lib just to store your types and then import it and use it in each of your apps and libs but this feels really clunky to me. Also, this doesn't really work with the idea of adding it to typeRoots within the tsbase.config.json

If anyone knows a better way this can be done I would love to hear about it.

Cheers.

Body:
Below setup works fine for all apps but not libs...

I have index.d.ts in a root directory:

    // /index.d.ts
    declare global {
      namespace MyNamespace {
         interface MyInterface { ... }
      }
    }

In tsconfig.base.json I have added "esModuleInterop": true, and "typeRoots": ["index.d.ts"] in compilerOptions.
Then in each /apps/my-app/tsconfg.json I added "../../index.d.ts" in include array.

This allows me to use global declarations in apps without the need to import anything.

const myVar: MyNamespace.MyInterface = ...

I tried to do the same for libs but it does not work.

There are three tsconfig.jsons in lib directory:

tsconfig.json (main)

tsconfig.lib.json (lib)

tsconfig.spec.json (spec)

and if i use a storybook for a lib then there is fourth /.storybook/tsconfig.json (storybook).

lib, spec and storybook configs extend main config.

There is error in the file:

Referenced project '/.../libs/shared-one/tsconfig.lib.json' must have setting "composite": true.

if i set composite to true for lib, spec, storybook configs then I get following error there:

Composite projects may not disable declaration emit.

What is wrong? How do I share global type declarations among nx libs? I hoped this will work out of the box.

example of tsconfig.lib.json (lib)

    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "composite": true,
        "outDir": "../../dist/out-tsc",
        "types": ["node"]
      },
      "files": [
        "../../node_modules/@nrwl/react/typings/cssmodule.d.ts",
        "../../node_modules/@nrwl/react/typings/image.d.ts"
      ],
      "exclude": [
        "**/*.spec.ts",
        "**/*.spec.tsx",
        "**/*.stories.ts",
        "**/*.stories.js",
        "**/*.stories.jsx",
        "**/*.stories.tsx"
      ],
      "include": ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx"]
    }

/libs/my-lib tsconfig.json (main)

    {
      "extends": "../../tsconfig.base.json",
      "compilerOptions": {
        "jsx": "react-jsx",
        "allowJs": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
      },
      "files": [],
      "include": ["../../index.d.ts"],
      "references": [
        {
          "path": "./tsconfig.lib.json"
        },
        {
          "path": "./tsconfig.spec.json"
        },
        {
          "path": "./.storybook/tsconfig.json"
        }
      ]
    }

tsconfig.base.json: (base)

    {
      "compileOnSave": false,
      "compilerOptions": {
        "rootDir": ".",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "esModuleInterop": true,
        "importHelpers": true,
        "target": "es2015",
        "module": "esnext",
        "lib": ["es2017", "dom"],
        "skipLibCheck": true,
        "skipDefaultLibCheck": true,
        "baseUrl": ".",
        "paths": {
          "@my-org/shared-one": ["libs/shared-one/src/index.ts"],
          "@my-org/shared-two": ["libs/shared-two/src/index.ts"]
        }
      },
      "exclude": ["node_modules", "tmp"],
      "include": ["index.d.ts"]
    }


问:
GET Request in For Loop only returning response from the final loop index. Preceding ones return empty
I'm running get requests to a URL, using lines in a text file as arguments in said get requests. The issue I'm finding is that the responseind.json() is only returning the get request related to the LAST line of the txt file. All preceding lines return []. Code below, any ideas?</p>
```<code>with open('industries.txt') as industry_file:
       for line in industry_file:
        start = time.time()
        responseind = requests.get("https:URL" + "".join(line) + "?token=My key")
        print(responseind.json())
</code>```

答:
The reason why your requests are not working properly is that you are just using the entire line in the text file (which ends in a new line character '\n'). The reason why your last request may be getting a response is that there is no new line after that id (the file ends) therefore not having that character which gives a valid id to look for.</p>
```<code>with open('industries.txt') as industry_file:
    for line in industry_file:
        start = time.time()
        responseind = requests.get("https:URL" + "".join(line).replace('\n', '') + "?token=My key")
        print(responseind.json())
</code>```

Body:
I'm running get requests to a URL, using lines in a text file as arguments in said get requests. The issue I'm finding is that the responseind.json() is only returning the get request related to the LAST line of the txt file. All preceding lines return []. Code below, any ideas?

with open('industries.txt') as industry_file:
       for line in industry_file:
        start = time.time()
        responseind = requests.get("https:URL" + "".join(line) + "?token=My key")
        print(responseind.json())

Body:
The reason why your requests are not working properly is that you are just using the entire line in the text file (which ends in a new line character '\n'). The reason why your last request may be getting a response is that there is no new line after that id (the file ends) therefore not having that character which gives a valid id to look for.

with open('industries.txt') as industry_file:
    for line in industry_file:
        start = time.time()
        responseind = requests.get("https:URL" + "".join(line).replace('\n', '') + "?token=My key")
        print(responseind.json())


问:
Typescript show error for .mdx extension file in nextjs
It work fine for render component to website but typescript show error for import mdx file.

typescript error message: Cannot find module '@/articles/good.mdx' or its corresponding type declarations.

I found a ton of comment in stack overflow. But it still don't solve this issue. Tried installed @mdx-js/mdx, same not work.

```<code>import React from "react";

import Layout from "@/components/Layout/index";
import Good from "@/articles/good.mdx"; // this line show typescript error

const index = () => {
  return (
    <Layout>
      <Good />
    </Layout>
  );
};

export default index;

</code>```

Package.json (removed some unrelated)

```<code>{
  "dependencies": {
    "@next/mdx": "^10.2.0",
    "@types/react-transition-group": "^4.4.1",
    "next": "10.1.3",
    "next-seo": "^4.24.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-query": "^3.13.11",
    "react-transition-group": "^4.4.1"
  },
  "devDependencies": {
    "@mdx-js/loader": "^1.6.22",
    "@types/node": "^15.0.1",
    "@types/react": "^17.0.4",
    "@types/webpack-env": "^1.16.0",
    "autoprefixer": "^10.2.5",
    "typescript": "^4.2.4"
  }
}

</code>```

tsconfig.json (removed some unrelated)

```<code>{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "types": [
      "node",
      "webpack-env"
     ]
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/*.mdx",
  ],
  "exclude": [
    "node_modules"
  ]
}

</code>```

答:
More convinient way is to install types yarn add @types/mdx. Then just include those types in your tsconfig.ts

```<code>{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "types": [
      "node",
      "webpack-env",
      "mdx"
     ]
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/*.mdx",
  ],
  "exclude": [
    "node_modules"
  ]
}
</code>```

You will still get type errors if you want to reexport a custom component from mdx file like

import YourMdxContent, { SomeComponent } from './YourMdxFile.mdx'

You will get an error:

Module '"*.mdx"' has no exported member 'SomeComponent'. Did you mean to use 'import SomeComponent from "*.mdx"' instead?

If this happens you will need to redeclare mdx module:

```<code>declare module '*.mdx' {
  export function SomeComponent(): JSX.Element;
}
</code>```

No need to redeclare MDXContent as it is already inherited from types.

Body:
It work fine for render component to website but typescript show error for import mdx file.

typescript error message: Cannot find module '@/articles/good.mdx' or its corresponding type declarations.

I found a ton of comment in stack overflow. But it still don't solve this issue. Tried installed @mdx-js/mdx, same not work.

import React from "react";

import Layout from "@/components/Layout/index";
import Good from "@/articles/good.mdx"; // this line show typescript error

const index = () => {
  return (
    <Layout>
      <Good />
    </Layout>
  );
};

export default index;

Package.json (removed some unrelated)

{
  "dependencies": {
    "@next/mdx": "^10.2.0",
    "@types/react-transition-group": "^4.4.1",
    "next": "10.1.3",
    "next-seo": "^4.24.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-query": "^3.13.11",
    "react-transition-group": "^4.4.1"
  },
  "devDependencies": {
    "@mdx-js/loader": "^1.6.22",
    "@types/node": "^15.0.1",
    "@types/react": "^17.0.4",
    "@types/webpack-env": "^1.16.0",
    "autoprefixer": "^10.2.5",
    "typescript": "^4.2.4"
  }
}

tsconfig.json (removed some unrelated)

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "types": [
      "node",
      "webpack-env"
     ]
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/*.mdx",
  ],
  "exclude": [
    "node_modules"
  ]
}

Body:
More convinient way is to install types yarn add @types/mdx. Then just include those types in your tsconfig.ts

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "types": [
      "node",
      "webpack-env",
      "mdx"
     ]
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/*.mdx",
  ],
  "exclude": [
    "node_modules"
  ]
}

You will still get type errors if you want to reexport a custom component from mdx file like

import YourMdxContent, { SomeComponent } from './YourMdxFile.mdx'

You will get an error:

Module '"*.mdx"' has no exported member 'SomeComponent'. Did you mean to use 'import SomeComponent from "*.mdx"' instead?

If this happens you will need to redeclare mdx module:

declare module '*.mdx' {
  export function SomeComponent(): JSX.Element;
}

No need to redeclare MDXContent as it is already inherited from types.


问:
How to make a dataframe from images python pandas
I ran into a problem - to make a dataframe of images. I have a lot of folders, there are more folders in them, and then images. The whole point is that I don't understand how I can upload images to the pandas dataframe. I looked through many different options, not one did not fit. The layout of the images:

```<code>.../Volvo/V60/0.png, 1.png ... 101.png
</code>```

I want to have a pandas dataframe or any other one to which it will be possible to read and take data with images from it. Example:

```<code>     Automaker     Model     Images
0    Volvo         V60       0.png
1    Volvo         V60       1.png
...
999  BMW           M4        302.png
</code>```

At the same time, there should be no files other than df (csv).
Is it possible to implement this or something like this? I will be very glad to answer.

答:
Yes, you can use pathlib to search for files like this.

Here's an example of how to recursively search the current directory for .png files.

```<code>from pathlib import Path
image_dir_path = '.'
print(Path(image_dir_path).rglob('*.png'))
</code>```

Then, you just need to reformat that into a dataframe. Here's how to do that:

```<code>import pandas as pd
from pathlib import Path

image_dir_path = '.'
paths = [path.parts[-3:] for path in
         Path(image_dir_path).rglob('*.png')]
df = pd.DataFrame(data=paths, columns=['Automaker', 'Model', 'Images'])
print(df)
</code>```

Note: you'll probably need to change image_dir_path to the directory of images on your computer.

Body:
I ran into a problem - to make a dataframe of images. I have a lot of folders, there are more folders in them, and then images. The whole point is that I don't understand how I can upload images to the pandas dataframe. I looked through many different options, not one did not fit. The layout of the images:

.../Volvo/V60/0.png, 1.png ... 101.png

I want to have a pandas dataframe or any other one to which it will be possible to read and take data with images from it. Example:

     Automaker     Model     Images
0    Volvo         V60       0.png
1    Volvo         V60       1.png
...
999  BMW           M4        302.png

At the same time, there should be no files other than df (csv).
Is it possible to implement this or something like this? I will be very glad to answer.

Body:
Yes, you can use pathlib to search for files like this.

Here's an example of how to recursively search the current directory for .png files.

from pathlib import Path
image_dir_path = '.'
print(Path(image_dir_path).rglob('*.png'))

Then, you just need to reformat that into a dataframe. Here's how to do that:

import pandas as pd
from pathlib import Path

image_dir_path = '.'
paths = [path.parts[-3:] for path in
         Path(image_dir_path).rglob('*.png')]
df = pd.DataFrame(data=paths, columns=['Automaker', 'Model', 'Images'])
print(df)

Note: you'll probably need to change image_dir_path to the directory of images on your computer.


问:
Calling a method of a class before creating an object
Let's say we have a class, and we are calling it's method before creating an object:

```<code>class ParentClass:
    def MyMethod(self):
        self.a=5
        print("I am Method")

ParentClass.MyMethod(ParentClass)
</code>```

Why do we get a result?
Also, why hasattr(ParentClass,'a') is showing that instance variable is created?

答:
You get a result because you ParentClass.MyMethod evaluates to a regular function that takes one argument, which you supplied. The function doesn't care what the type of self is, as long as you can define an attribute named a for it. The result of ParentClass.MyMethod(ParentClass) is to add an attribute named a to ParentClass.

ParentClass().MyMethod, on the other hand, produces an instance of method that wraps the function, due to the descriptor protocol. The method, when called, simply calls the function with the instance as the first argument and the rest of its own arguments. Because the function doesn't expect any more arguments, you would get a TypeError.

Body:
Let's say we have a class, and we are calling it's method before creating an object:

class ParentClass:
    def MyMethod(self):
        self.a=5
        print("I am Method")

ParentClass.MyMethod(ParentClass)

Why do we get a result?
Also, why hasattr(ParentClass,'a') is showing that instance variable is created?


问:
why is the location string not showing in the window. tkinter python?
im trying to write a code that will tell you if the location is a file or directory. if its a file, then it will read the file. here is my code (ik its very bad, im sorry)

import os
import tkinter as tk

screen = tk.Tk()
screen.title("files and directories")
screen.geometry("300x100")

def FileDir():
    path = location.get(1.0, "end-1c")
    location.delete(1.0, tk.END)

    if os.path.exists(path):
        print("✔ - this location exists")

        info_location = tk.Label(screen, text=f"location: {location}")
        info_location.pack()

        if os.path.isfile(path):
            print("\tthis is a file")
            type = 'file'

            info_type = tk.Label(screen, text=f"type: {type}")
            info_type.pack()

            while True:
                open_file = input("\nDo you want to read this file? ")

                if open_file.lower() == 'yes':
                    with open(path) as file:
                        contents = file.read()
                    print(contents)
                    break

                elif open_file.lower() == 'no':
                    print("goodbye!")
                    break

                else:
                    print("invalid input")
                    continue

        elif os.path.isdir(path):
            print("\tthis is a directory")
            type = 'directory'

            info_type = tk.Label(screen, text=f"type: {type}")
            info_type.pack()

    else:
        print("✘ - this location doesn't exist")

text = tk.Label(screen, text="Enter file/directory location: ")
text.pack()

location = tk.Text(screen, height = 1, width = 25)
location.pack()

enter_btn = tk.Button(screen, text="Enter", command=FileDir)
enter_btn.pack()

screen.mainloop()
```

so when putting the location of a string, everything works fine except that the location doesnt show and instead it shows ".!text". anyone know why?

答:
location is a widget rather than a string. The string representation of a tkinter widget is its internal name. Thus, when you do text=f"location: {location}" you are creating a string that contains the name of the widget rather than the contents.

To display the contents you must fetch them from the widget.  You're already doing that when you define path, so you just need to use {path} rather than {location}

```<code>text=f"location: {path}"
</code>```

Body:
im trying to write a code that will tell you if the location is a file or directory. if its a file, then it will read the file. here is my code (ik its very bad, im sorry)

import os
import tkinter as tk

screen = tk.Tk()
screen.title("files and directories")
screen.geometry("300x100")

def FileDir():
    path = location.get(1.0, "end-1c")
    location.delete(1.0, tk.END)

    if os.path.exists(path):
        print("✔ - this location exists")

        info_location = tk.Label(screen, text=f"location: {location}")
        info_location.pack()

        if os.path.isfile(path):
            print("\tthis is a file")
            type = 'file'

            info_type = tk.Label(screen, text=f"type: {type}")
            info_type.pack()

            while True:
                open_file = input("\nDo you want to read this file? ")

                if open_file.lower() == 'yes':
                    with open(path) as file:
                        contents = file.read()
                    print(contents)
                    break

                elif open_file.lower() == 'no':
                    print("goodbye!")
                    break

                else:
                    print("invalid input")
                    continue

        elif os.path.isdir(path):
            print("\tthis is a directory")
            type = 'directory'

            info_type = tk.Label(screen, text=f"type: {type}")
            info_type.pack()

    else:
        print("✘ - this location doesn't exist")

text = tk.Label(screen, text="Enter file/directory location: ")
text.pack()

location = tk.Text(screen, height = 1, width = 25)
location.pack()

enter_btn = tk.Button(screen, text="Enter", command=FileDir)
enter_btn.pack()

screen.mainloop()

so when putting the location of a string, everything works fine except that the location doesnt show and instead it shows ".!text". anyone know why?

Body:
location is a widget rather than a string. The string representation of a tkinter widget is its internal name. Thus, when you do text=f"location: {location}" you are creating a string that contains the name of the widget rather than the contents.

To display the contents you must fetch them from the widget.  You're already doing that when you define path, so you just need to use {path} rather than {location}

text=f"location: {path}"


问:
Laravel Relationship Can Not Get Data From Other Model
I've 2 tables (students and accounts).

```<code>students
+----+-----+------+
| id | nik | name |
+----+-----+------+

accounts
+----+-----+----------+----------+
| id | nik | username | password |
+----+-----+----------+----------+
</code>```

When I want to get the account data from the relationship $student->account->username is running perfectly. But, when i try $account->student->name, i get an error :

Trying to get property of non-object

I've check the data already and All were existed. What should I Do?

```<code>public function account()
{
    return $this->hasOne(Account::class, 'nik', 'nik');
}

public function student()
{
    return $this->belongsTo(Student::class, 'nik', 'nik');
}
</code>```

答:
Change the method belongsTo() in the model Account to:

```<code>hasOne(Student::class, 'nik', 'nik')
</code>```

Body:
I've 2 tables (students and accounts).

students
+----+-----+------+
| id | nik | name |
+----+-----+------+

accounts
+----+-----+----------+----------+
| id | nik | username | password |
+----+-----+----------+----------+

When I want to get the account data from the relationship $student->account->username is running perfectly. But, when i try $account->student->name, i get an error :

Trying to get property of non-object

I've check the data already and All were existed. What should I Do?

public function account()
{
    return $this->hasOne(Account::class, 'nik', 'nik');
}

public function student()
{
    return $this->belongsTo(Student::class, 'nik', 'nik');
}

Body:
Change the method belongsTo() in the model Account to:

hasOne(Student::class, 'nik', 'nik')


问:
Google Data Studio Scoreboard SUM calculation
I have my data on Excel and I uploaded in Google Sheets so I can use Google Data Studio, everything in Data Studio so far working good, but I am having trouble in a case.

Few of my fields in Data source have values in numbers from 1 to 1000+ and I chose cell formatting in excel as Numbers with 1000 Separator(,).
In Data Studio data source I changed same field with "Number" but when I try to create a simple Scoreboard on Data Studio, it seems like it's only doing SUM with values lower than 1000, meaning any value with 1000 or above are being skipped.

I can feel this is because of separator(,) which is troubling and I can use:

```<code>CAST(REGEXP_REPLACE)
</code>```

but I want to know that why it's making trouble, even after choosing correct Cell Format?

Sample Data Link: https://datastudio.google.com/reporting/abafc2cb-9033-4851-9f72-02896a91384c

答:
The field ITEM SUPPLIED is a text field and contains numbers formated as text. However, there is a  1000 separator (,) in the text.

Therefore, every , in the field has to be removed. This can be done by the REPLACE function. Then the CAST converts the text to a number.

```<code>CAST(REPLACE(ITEM SUPPLIED, ",", "") AS number )
</code>```

Body:
I have my data on Excel and I uploaded in Google Sheets so I can use Google Data Studio, everything in Data Studio so far working good, but I am having trouble in a case.

Few of my fields in Data source have values in numbers from 1 to 1000+ and I chose cell formatting in excel as Numbers with 1000 Separator(,).
In Data Studio data source I changed same field with "Number" but when I try to create a simple Scoreboard on Data Studio, it seems like it's only doing SUM with values lower than 1000, meaning any value with 1000 or above are being skipped.

I can feel this is because of separator(,) which is troubling and I can use:

CAST(REGEXP_REPLACE)

but I want to know that why it's making trouble, even after choosing correct Cell Format?

Sample Data Link: https://datastudio.google.com/reporting/abafc2cb-9033-4851-9f72-02896a91384c

Body:
The field ITEM SUPPLIED is a text field and contains numbers formated as text. However, there is a  1000 separator (,) in the text.

Therefore, every , in the field has to be removed. This can be done by the REPLACE function. Then the CAST converts the text to a number.

CAST(REPLACE(ITEM SUPPLIED, ",", "") AS number )


问:
replace list of sentence to the text
I am trying to replace the text if it contains the sentences from a list1.

I tried the following code, but it's not working:

```<code>text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
  if i in text:
    text.replace(i,"")

#wrong output:
'what a lovely car it is , i love it by the way it looks and the color is so good. i am feeling very happy after seeing it'
</code>```

Expected output:

```<code>'what a , i love it by the way it looks and the . i am feeling very seeing it'
</code>```

答:
replace will create a new string so use.</p>
```<code>text = text.replace(i,"")
</code>```

Title: replace list of sentence to the text

Body:
I am trying to replace the text if it contains the sentences from a list1.

I tried the following code, but it's not working:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
  if i in text:
    text.replace(i,"")

#wrong output:
'what a lovely car it is , i love it by the way it looks and the color is so good. i am feeling very happy after seeing it'

Expected output:

'what a , i love it by the way it looks and the . i am feeling very seeing it'

Body:
replace will create a new string so use.

text = text.replace(i,"")


问:
Dynamically changing URL's in an HTML File - Google Apps Scripts / Google Sheets
I have written a script that creates a new "Report" every time it is ran. This is done by generating a new Google Spreadsheet, which then displays a filtered set of values based off inputs in the original spreadsheet it is tied to. Below is the code:

Report Script

The script is activated by a custom menu bar. An example of the menu bar is here below:

Menu Bar Code

Upon clicking into the custom menu bar, I would like the newly generated "report" spreadsheet to open. Since this script creates a new spreadsheet each time it is ran, the URL will be different each time, therefore, I am not sure how to incorporate the variable URL into an HTML file. Below are some lines of code I have used to open files upon using the custom menu bar:

HTML File Code

In the above image, "+ ssNewURL +" is where the known URL to the desired destination would go. I attempted to reference a variable I used earlier (ssNewURL) which gets the URL of the newly generated sheet, but it did not work. I have tried to get around the formatting issue of the HTML file which requires the URL to be a string; I've tried changing locations of double "" quotations,
and single '' quotations. Whatever I have tried, the HTML file refuses to open.

I am extremely new to coding, I understand the logic behind it, however, I am very unfamiliar with every function/formatting of Google Scripts coding.

Any suggestions or workarounds for getting the HTML part of the code to open the dynamically changing URL would be greatly appreciated!

答:
When you call window.open(), the URL also needs to be enclosed in quotation marks.

```<code> let htmlOutput = HtmlService.createHtmlOutput(
      "<script type='text/javascript'>" +
      "window.open('" + url + "', '_blank');" +
      "google.script.host.close();" +
      "</script> "
  );
</code>```

Another option would be to pass the URL of your spreadsheet to the HtmlTemplate object as a property:

```<code>  let template = HtmlService.createTemplateFromFile("popup");
  template.url = url;
  return SpreadsheetApp.getUi().showDialog(template.evaluate());
</code>```

Calling evaluate() on an HtmlTemplate object will execute the embedded JS code and place all variables you passed to the template in scope.

popup.html

```<code><body>
    Opening your spreadsheet...
    <input type='hidden' id="hidden-field" value='<?!= url ?>' />
    <script>
      var url = document.getElementById("hidden-field").value;
      window.open(url, "_blank");
      google.script.host.close();
    </script>
  </body>
</code>```

Body:
When you call window.open(), the URL also needs to be enclosed in quotation marks.

 let htmlOutput = HtmlService.createHtmlOutput(
      "<script type='text/javascript'>" +
      "window.open('" + url + "', '_blank');" +
      "google.script.host.close();" +
      "</script> "
  );

Another option would be to pass the URL of your spreadsheet to the HtmlTemplate object as a property:

  let template = HtmlService.createTemplateFromFile("popup");
  template.url = url;
  return SpreadsheetApp.getUi().showDialog(template.evaluate());

Calling evaluate() on an HtmlTemplate object will execute the embedded JS code and place all variables you passed to the template in scope.

popup.html

<body>
    Opening your spreadsheet...
    <input type='hidden' id="hidden-field" value='<?!= url ?>' />
    <script>
      var url = document.getElementById("hidden-field").value;
      window.open(url, "_blank");
      google.script.host.close();
    </script>
  </body>


问:
How do I display a back-end error in the front-end in Angular?
I'm trying to display an error, generated by the back-end, in the front-end developed in Angular material. I want that the error message is displayed into an alert window. My problem is that the error message is displayed only in the console, while the message displayed in the alert window is "undefined". How can I deal with this problem?

service.ts:

```<code>export class UserService {

  constructor(private http: HttpClient) { }

  public createUser(user: User): Observable<User> {
    return this.http.post<User>('http://localhost:8080/users/reg', user)
    .pipe(
      catchError(this.handleError)
    );;
  }
private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      // A client-side or network error occurred.
      console.error('An error occurred:', error.error);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, body was: `, error.error);

    }

    return throwError(
      'Something bad happened; please try again later.');
  }

}
</code>```

component.ts:

```<code>public createUser(message: string, action: string, createForm:NgForm ) {
    this.userService.createUser(createForm.value).subscribe(
      (response: User) => {
        this.user=response;
        console.log(response);
        console.log(createForm.value);
        this._snackBar.open(message, action);
        createForm.reset();
      },
      (error: HttpErrorResponse)=>{
        alert(error.message);
        createForm.reset();
      }
    )
  }
</code>```

The following is the screenshot of the console which displays the message error that I want to show in the alert window:

When I change alert(error.message) with console.error('foo', error); the console says:

答:
In the method "handleError", you are returning a string:

```<code>return throwError(
      'Something bad happened; please try again later.');
</code>```

So, when you subscribe, you'll receive the string 'Something bad happened; please try again later.'

If you want the subscriber to receive the message, change your handleMessage return value:

```<code>return throwError(error);
</code>```

Body:
I'm trying to display an error, generated by the back-end, in the front-end developed in Angular material. I want that the error message is displayed into an alert window. My problem is that the error message is displayed only in the console, while the message displayed in the alert window is "undefined". How can I deal with this problem?

service.ts:

export class UserService {

  constructor(private http: HttpClient) { }

  public createUser(user: User): Observable<User> {
    return this.http.post<User>('http://localhost:8080/users/reg', user)
    .pipe(
      catchError(this.handleError)
    );;
  }
private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      // A client-side or network error occurred.
      console.error('An error occurred:', error.error);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, body was: `, error.error);

    }

    return throwError(
      'Something bad happened; please try again later.');
  }

}

component.ts:

public createUser(message: string, action: string, createForm:NgForm ) {
    this.userService.createUser(createForm.value).subscribe(
      (response: User) => {
        this.user=response;
        console.log(response);
        console.log(createForm.value);
        this._snackBar.open(message, action);
        createForm.reset();
      },
      (error: HttpErrorResponse)=>{
        alert(error.message);
        createForm.reset();
      }
    )
  }

The following is the screenshot of the console which displays the message error that I want to show in the alert window:

When I change alert(error.message) with console.error('foo', error); the console says:

Body:
In the method "handleError", you are returning a string:

return throwError(
      'Something bad happened; please try again later.');

So, when you subscribe, you'll receive the string 'Something bad happened; please try again later.'

If you want the subscriber to receive the message, change your handleMessage return value:

return throwError(error);


问:
Show or hide Carousel item depending on index | React
I'm using React Slick centerMode as my image carousel and trying to show 3 images at a time. Also, I would like to show the title of the image when it is centered (current index) only. The problem is it will show all the title at the same time. How can I hide left and right images' title and only shows the middle image's title?

What I made

What I want

my code:

```<code>function ImageSlider({ imageList }) {
  const [currentSlide, setCurrentSlide] = useState(0);
  const [indexSlide, setIndexSlide] = useState(0);

  function ShowTitle(title) {
      // If the index is on focused
      if (currentSlide === indexSlide) {
        return <p>{title}</p>;
      }
      // Otherwise return empty
      return <p></p>;
    }

  function handleAfterChange(index) {
      setIndexSlide(index);
      const centerSlide = document.querySelector(
        "div.slick-slide.slick-active.slick-center.slick-current"
      );
      setCurrentSlide(parseInt(centerSlide.getAttribute("data-index")));
  }

  return (
    <Slider
      className="center"
      centerMode={true}
      infinite={true}
      autoplay={true}
      autoplaySpeed={2000}
      slidesToShow={3}
      slidesToScroll={1}
      afterChange={handleAfterChange}
    >
      {imageList.map((image) => (
        <div key={image.id} id={image.id}>
          <img
            alt="image"
            width={270}
            height={120}
            src={image.url}
          />
// I want this to show when it's centered, and hidden when it's not centred
          <ShowTitle title={image.title} key={image.id} />
        </div>
      ))}
    </Slider>
  );
}

</code>```

The carousel html when index number 2 (out of 5) is centered:

```<code><div class="slick-list" style="padding:0px 60px">
  <div class="slick-track" style="width: 3640px; opacity: 1; transform: translate3d(-1040px, 0px, 0px); transition: -webkit-transform 500ms ease 0s;">
    <div data-index="-4" tabindex="-1" class="slick-slide slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="-3" tabindex="-1" class="slick-slide slick-center slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="-2" tabindex="-1" class="slick-slide slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="-1" tabindex="-1" class="slick-slide slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="0" class="slick-slide" tabindex="-1" aria-hidden="true" style="outline: none; width: 260px;">...</div>
    <div data-index="1" class="slick-slide slick-active" tabindex="-1" aria-hidden="true" style="outline: none; width: 260px;">...</div>
    <div data-index="2" class="slick-slide slick-active slick-center slick-current" tabindex="-1" aria-hidden="true" style="outline: none; width: 260px;">...</div>
    <div data-index="3" class="slick-slide slick-active" tabindex="-1" aria-hidden="true" style="outline: none; width: 260px;">...</div>
    <div data-index="4" class="slick-slide" tabindex="-1" aria-hidden="true" style="outline: none; width: 260px;">...</div>
    <div data-index="5" tabindex="-1" class="slick-slide slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="6" tabindex="-1" class="slick-slide slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="7" tabindex="-1" class="slick-slide slick-center slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="8" tabindex="-1" class="slick-slide slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
    <div data-index="9" tabindex="-1" class="slick-slide slick-cloned" aria-hidden="true" style="width: 260px;">...</div>
  </div>
</div>
</code>```

答:
The problem

Your problem stems from how you're trying to do your logic against state variables. There's no connection between your state and your ShowTitle component, other than referring to them. Whenever you page through the carousel, you're changing both state variables so they will always be the same.

Unfortunately, the library you've chosen for your carousel forces you to rely on an index, so I would suggest you use the index argument on the map function to assign indexes to your ShowTitle components.
Note: React will warn you if you try to use indexes for keys, as that has the potential for strange behavior. Keep using the id for that.

The solution

function ImageSlider({ imageList }) {
  const [currentSlide, setCurrentSlide] = useState(0);

  // Since this is a component, you need to destructure props
  function ShowTitle({ title, id }) {
      // If the index is on focused
      if (id === currentSlide) {
        return
{title}
;
      }
      // Otherwise return empty
      return

;
    }

  // I'm not sure what props you're going to get here; it'll be whatever
  // the Slider provides you with when afterChange is fired
  function handleAfterChange(index) {
      setCurrentSlide(index);
  }

  return (
    <Slider
      className="center"
      centerMode={true}
      infinite={true}
      autoplay={true}
      autoplaySpeed={2000}
      slidesToShow={3}
      slidesToScroll={1}
      afterChange={handleAfterChange}
    >
      {/* Add index argument to map here (this is provided automatically) */}
      {imageList.map((image, index) => (

          {/* Add index prop to ShowTitle */}
          <ShowTitle title={image.title} index={index} />

      ))}
    </Slider>
  );
}
```
<h2>A suggestion</h2>
<p>If you want to optimize this you can completely do away with the <code>ShowTitle</code> component and conditionally render your <code>p</code> tag.</p>
<pre class="lang-js prettyprint-override"><code>...
{index === currentSlide ? <p>{image.title}</p> : <p></p>}
...
</code>```

The why of it all

When react renders all of your code, it is going to call the ShowTitle component, because it is, in fact, a component with the way you've written this. A function component is just a function that takes in props as its argument, and returns some JSX. Since it will call this for every loop over map, it will compare the currently set state (which doesn't change until the user does something to invoke afterChange) so it will compare the same state variables every time, hence why all of the titles show. When you do invoke afterChange, it always sets the two state variables to the same thing and changing state causes a rerender. This is why all of the titles are always present.

To rectify this, you need to have the rendering of a particular slide tied to the currently selected index in the carousel, and you need your component to know where it is in the carousel (by way of the index in the map function) to be able to compare to the currently selected index.

Body:
I'm using React Slick centerMode as my image carousel and trying to show 3 images at a time. Also, I would like to show the title of the image when it is centered (current index) only. The problem is it will show all the title at the same time. How can I hide left and right images' title and only shows the middle image's title?

What I made

What I want

my code:

function ImageSlider({ imageList }) {
  const [currentSlide, setCurrentSlide] = useState(0);
  const [indexSlide, setIndexSlide] = useState(0);

  function ShowTitle(title) {
      // If the index is on focused
      if (currentSlide === indexSlide) {
        return
{title}
;
      }
      // Otherwise return empty
      return

;
    }

  function handleAfterChange(index) {
      setIndexSlide(index);
      const centerSlide = document.querySelector(
        "div.slick-slide.slick-active.slick-center.slick-current"
      );
      setCurrentSlide(parseInt(centerSlide.getAttribute("data-index")));
  }

  return (
    <Slider
      className="center"
      centerMode={true}
      infinite={true}
      autoplay={true}
      autoplaySpeed={2000}
      slidesToShow={3}
      slidesToScroll={1}
      afterChange={handleAfterChange}
    >
      {imageList.map((image) => (

// I want this to show when it's centered, and hidden when it's not centred
          <ShowTitle title={image.title} key={image.id} />

      ))}
    </Slider>
  );
}

The carousel html when index number 2 (out of 5) is centered:

...

...

...

...

...

...

...

...

...

...

...

...

...

...

Body:
The problem

Your problem stems from how you're trying to do your logic against state variables. There's no connection between your state and your ShowTitle component, other than referring to them. Whenever you page through the carousel, you're changing both state variables so they will always be the same.

Unfortunately, the library you've chosen for your carousel forces you to rely on an index, so I would suggest you use the index argument on the map function to assign indexes to your ShowTitle components.
Note: React will warn you if you try to use indexes for keys, as that has the potential for strange behavior. Keep using the id for that.

The solution

function ImageSlider({ imageList }) {
  const [currentSlide, setCurrentSlide] = useState(0);

  // Since this is a component, you need to destructure props
  function ShowTitle({ title, id }) {
      // If the index is on focused
      if (id === currentSlide) {
        return <p>{title}</p>;
      }
      // Otherwise return empty
      return <p></p>;
    }

  // I'm not sure what props you're going to get here; it'll be whatever
  // the Slider provides you with when afterChange is fired
  function handleAfterChange(index) {
      setCurrentSlide(index);
  }

  return (
    <Slider
      className="center"
      centerMode={true}
      infinite={true}
      autoplay={true}
      autoplaySpeed={2000}
      slidesToShow={3}
      slidesToScroll={1}
      afterChange={handleAfterChange}
    >
      {/* Add index argument to map here (this is provided automatically) */}
      {imageList.map((image, index) => (
        <div key={image.id} id={image.id}>
          <img
            alt="image"
            width={270}
            height={120}
            src={image.url}
          />
          {/* Add index prop to ShowTitle */}
          <ShowTitle title={image.title} index={index} />
        </div>
      ))}
    </Slider>
  );
}

A suggestion

If you want to optimize this you can completely do away with the ShowTitle component and conditionally render your p tag.

...
{index === currentSlide ? <p>{image.title}</p> : <p></p>}
...

The why of it all

When react renders all of your code, it is going to call the ShowTitle component, because it is, in fact, a component with the way you've written this. A function component is just a function that takes in props as its argument, and returns some JSX. Since it will call this for every loop over map, it will compare the currently set state (which doesn't change until the user does something to invoke afterChange) so it will compare the same state variables every time, hence why all of the titles show. When you do invoke afterChange, it always sets the two state variables to the same thing and changing state causes a rerender. This is why all of the titles are always present.

To rectify this, you need to have the rendering of a particular slide tied to the currently selected index in the carousel, and you need your component to know where it is in the carousel (by way of the index in the map function) to be able to compare to the currently selected index.


问:
Counting Prime Numbers in python
I am trying to make a program that will count prime numbers.
I tried and tried and it didn't work.
This is the code:

```<code>def count_primes(num):
primes = 0
if num % num==0 and num  % 1 == 0:
    primes = primes + 1
else:
    pass
return primes
</code>```

I put 100 as the value for num and the program just gives me one.

答:
```<code>num % num==0 and num  % 1 == 0
</code>```

This won't work, look at the first condition...

```<code>num % num==0
</code>```

Isn't it always true? The remainder of a division between a number and itself is always 0.

A working condition would be:

```<code>for i in range(2, n):
    if (n%i==0):
        # Not prime
</code>```

remember that...

Prime numbers are special numbers that have exactly two factors

one of this factors is the number iself (i never reaches n since the last value of the range is n-1), and the other is 1 (i starts from 2).

Title: Counting Prime Numbers in python

Body:
I am trying to make a program that will count prime numbers.
I tried and tried and it didn't work.
This is the code:

def count_primes(num):
primes = 0
if num % num==0 and num  % 1 == 0:
    primes = primes + 1
else:
    pass
return primes

I put 100 as the value for num and the program just gives me one.

Body:
num % num==0 and num  % 1 == 0

This won't work, look at the first condition...

num % num==0

Isn't it always true? The remainder of a division between a number and itself is always 0.

A working condition would be:

for i in range(2, n):
    if (n%i==0):
        # Not prime

remember that...

Prime numbers are special numbers that have exactly two factors

one of this factors is the number iself (i never reaches n since the last value of the range is n-1), and the other is 1 (i starts from 2).


问:
Angular getting BehaviorSubject value error: Property 'access_token' does not exist on type 'never'
In my Angular project I have authentication methods in the auth.service
I am storing the admin access token I got from the API in a BehaviorSubject

```<code>adminData = new BehaviorSubject(null);

saveAdminData(token:any) {
    let admin:any = new AdminData(token);
    this.adminData.next(admin);
}
</code>```

There is a function that I need to access the access_token of the admin so I tried this

```<code>this.adminData.value.access_token;
</code>```

But it gives me this error Object is possibly 'null' so I tried this

```<code>this.adminData.value!.access_token;
</code>```

But I have different error Property 'access_token' does not exist on type 'never'.

答:
You should initialize the BehaviorSubject. You have to tell typescript the type of object you are trying to implement, try this:

adminData = new BehaviorSubject<any | null>(null);
```

Body:
In my Angular project I have authentication methods in the auth.service
I am storing the admin access token I got from the API in a BehaviorSubject

adminData = new BehaviorSubject(null);

saveAdminData(token:any) {
    let admin:any = new AdminData(token);
    this.adminData.next(admin);
}

There is a function that I need to access the access_token of the admin so I tried this

this.adminData.value.access_token;

But it gives me this error Object is possibly 'null' so I tried this

this.adminData.value!.access_token;

But I have different error Property 'access_token' does not exist on type 'never'.


问:
PHP & MySQL: How can I use "SET @rank=0;" in $query=
In my PHP file, I use this line to pull data from my mySQL database:

```<code>$query = "SET @rank=0; SELECT @rank:=@rank +1 as rank, Blah Blah...";
</code>```

If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.

But, if I use it in PHP, then I get an error. It doesn't like the "SET @rank=0;" bit. Is there a way to use "SET @rank=0;" when it's in "$query=" ? Is there a workaround?

The rest of the code is standard stuff for pulling data from a db:

```<code>public function getmyData() {

 $mysql = mysql_connect(connection stuff);

 $query = "SELECT @rank:=@rank +1 as rank, formatted_school_name,  blah blah";

 $result = mysql_query($query);

            $ret = array();
                 while ($row = mysql_fetch_object($result)) {
                    $tmp = new VOmyData1();
                    $tmp->stuff1 = $row-> stuff1;
                    $tmp->stuff2 = $row->stuff2;

                    $ret[] = $tmp;
                        }
                 mysql_free_result($result);

                 return $ret;

    }
</code>```

Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:

```<code>$query = "SET @rank = 0";

$query .= "SELECT @rank:=@rank +1 as rank...
</code>```

I changed the result to:

```<code>$result = $mysqli_multi_query($query);
</code>```

But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?

答: Try executing it as 2 separate successive queries.</p>

Body:
In my PHP file, I use this line to pull data from my mySQL database:

$query = "SET @rank=0; SELECT @rank:=@rank +1 as rank, Blah Blah...";

If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.

But, if I use it in PHP, then I get an error. It doesn't like the "SET @rank=0;" bit. Is there a way to use "SET @rank=0;" when it's in "$query=" ? Is there a workaround?

The rest of the code is standard stuff for pulling data from a db:

public function getmyData() {

 $mysql = mysql_connect(connection stuff);

 $query = "SELECT @rank:=@rank +1 as rank, formatted_school_name,  blah blah";

 $result = mysql_query($query);

            $ret = array();
                 while ($row = mysql_fetch_object($result)) {
                    $tmp = new VOmyData1();
                    $tmp->stuff1 = $row-> stuff1;
                    $tmp->stuff2 = $row->stuff2;

                    $ret[] = $tmp;
                        }
                 mysql_free_result($result);

                 return $ret;

    }

Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:

$query = "SET @rank = 0";

$query .= "SELECT @rank:=@rank +1 as rank...

I changed the result to:

$result = $mysqli_multi_query($query);

But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?


问:
Solidity Error :: ParserError: Expected ',' but got 'Number'
Hiii, I need help
Getting parser error here in the line
require(msg.value > o.1 ether);

```<code> // SPDX-License-Identifier: MIT
  pragma solidity ^0.8.0;

contract Lottery{
address public manager;
address[] public players;

constructor(){
    manager=msg.sender;
}

function enter() public payable{

    require(msg.value > o.1 ether);  //getting error here
    players.push(msg.sender);
}
</code>```

}

答:
You have a typo, using the letter o instead of the number 0.

Corrected line:

```<code>require(msg.value > 0.1 ether);
</code>```

Body:
Hiii, I need help
Getting parser error here in the line
require(msg.value > o.1 ether);

 // SPDX-License-Identifier: MIT
  pragma solidity ^0.8.0;

contract Lottery{
address public manager;
address[] public players;

constructor(){
    manager=msg.sender;
}

function enter() public payable{

    require(msg.value > o.1 ether);  //getting error here
    players.push(msg.sender);
}

}

Body:
You have a typo, using the letter o instead of the number 0.

Corrected line:

require(msg.value > 0.1 ether);