问:
ReactJS - Uncaught RangeError: Maximum call stack size exceeded
I am trying to make a contact-manager-app from a YouTube video:

https://www.youtube.com/watch?v=0riHps91AzE&lc=Ugybk5M3ofjHsO8uHjd4AaABAg.9WHwkOL6qXV9WJu89p6VTV

Every time, I enter the inputs and click Add, the following error pops-up:
the screen-shot of the main page

I also get "6 moderate severity vulnerabilities" while downloading uuidv4. ( Put just in case, if it might help )

Also got "Module not found: Error: Can't resolve 'util' in 'C:\Users\loki\OneDrive\Desktop\ReactJS-YouTube\contact-app\node_modules\uuidv4\build\lib"

Here are all my files:

index.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha512-8bHTC73gkZ7rZ7vpqUQThUDhqcNFyYi2xgDgPDHc+GXVGHXq+xPjynxIopALmOPqzo9JZj0k6OqqewdGO3EsrQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

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

App.js

```<code>import React, { useState, useEffect } from "react";
import { uuid } from "uuidv4";
import "./App.css";
import Header from "./Header";
import AddContact from "./AddContact";
import ContactList from "./ContactList";

function App() {
  const LOCAL_STORAGE_KEY = "contacts";
  const [contacts, setContacts] = useState([]);

  const addContactHandler = (contact) => {
    console.log(contact);
    setContacts([...contacts, { id: uuid(), ...contact }]);
  };

  const removeContactHandler = (id) => {
    const newContactList = contacts.filter((contact) => {
      return contact.id !== id;
    });

    setContacts(newContactList);
  };

  useEffect(() => {
    const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
    if (retriveContacts) setContacts(retriveContacts);
  }, []);

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  }, [contacts]);

  return (
    <div className="ui container">
      <Header />
      <AddContact addContactHandler={addContactHandler} />
      <ContactList contacts={contacts} getContactId={removeContactHandler} />
    </div>
  );
}

export default App;
</code>```

ContactList.js

```<code>import React from "react";
import ContactCard from "./ContactCard";

const ContactList = (props) => {
    console.log(props);

    const deleteContactHandler = (id) => {
        props.getContactId(id);
    };

    const renderContactList = props.contacts.map((contact) => {
        return(
          <ContactCard contact={contact} clickHandler = { deleteContactHandler } key = { contact.id}/>
        );
    })
    return(
        <div className="ui celled list">
            {renderContactList}
        </div>
    );
}

export default ContactList;
</code>```

ContactCard.js

```<code>import React from "react";
import user from "../images/user.jpg";

const CardContact = (props) => {
    const {id, name, email} = props.contact;
    return(
        <div className="item">
            <img className="ui avatar image" src={user} alt="user" />
              <div className="content">
                  <div className="header">{name}</div>
                  <div>{email}</div>
              </div>
              <i className="trash alternate outline icon"
                style={{color:"red",marginTop:"7px"}}
                onClick={() => props.clickHandler(id)}>
              </i>
          </div>
    );
};

export default CardContact;
</code>```

AddContact.js

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

class AddContact extends React.Component {
  state = {
    name: "",
    email: "",
  };

  add = (e) => {
    e.preventDefault();
    if (this.state.name === "" || this.state.email === "") {
      alert("ALl the fields are mandatory!");
      return;
    }
    this.props.addContactHandler(this.state);
    this.setState({ name: "", email: "" });
  };
  render() {
    return (
      <div className="ui main">
        <h2>Add Contact</h2>
        <form className="ui form" onSubmit={this.add}>
          <div className="field">
            <label>Name</label>
            <input
              type="text"
              name="name"
              placeholder="Name"
              value={this.state.name}
              onChange={(e) => this.setState({ name: e.target.value })}
            />
          </div>
          <div className="field">
            <label>Email</label>
            <input
              type="text"
              name="email"
              placeholder="Email"
              value={this.state.email}
              onChange={(e) => this.setState({ email: e.target.value })}
            />
          </div>
          <button className="ui button blue">Add</button>
        </form>
      </div>
    );
  }
}

export default AddContact;
</code>```

答:
From the uuidv4 npm page:
Most of the functionality of uuidv4 module is already included in uuid since version 8.3.0, so most of the functions of uuidv4 module have already been marked as deprecated.

So, importing uuidv4 module in your App.js is causing this error.

You can upgrade to the latest version of uuid library to get rid of this error.

Run these commands in the terminal in your project directory.

```<code>npm uninstall uuidv4
npm install uuid
</code>```

And now, in App.js import uuid module instead of uuidv4

```<code>import { v4 as uuid } from 'uuid';
</code>```

And now, you can use uuid() function to create UUIDs

To check more about uuid, you can see there documentation: https://github.com/uuidjs/uuid#quickstart

Body:
I am trying to make a contact-manager-app from a YouTube video:

https://www.youtube.com/watch?v=0riHps91AzE&lc=Ugybk5M3ofjHsO8uHjd4AaABAg.9WHwkOL6qXV9WJu89p6VTV

Every time, I enter the inputs and click Add, the following error pops-up:
the screen-shot of the main page

I also get "6 moderate severity vulnerabilities" while downloading uuidv4. ( Put just in case, if it might help )

Also got "Module not found: Error: Can't resolve 'util' in 'C:\Users\loki\OneDrive\Desktop\ReactJS-YouTube\contact-app\node_modules\uuidv4\build\lib"

Here are all my files:

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha512-8bHTC73gkZ7rZ7vpqUQThUDhqcNFyYi2xgDgPDHc+GXVGHXq+xPjynxIopALmOPqzo9JZj0k6OqqewdGO3EsrQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <title>React App</title>

    You need to enable JavaScript to run this app.

App.js

import React, { useState, useEffect } from "react";
import { uuid } from "uuidv4";
import "./App.css";
import Header from "./Header";
import AddContact from "./AddContact";
import ContactList from "./ContactList";

function App() {
  const LOCAL_STORAGE_KEY = "contacts";
  const [contacts, setContacts] = useState([]);

  const addContactHandler = (contact) => {
    console.log(contact);
    setContacts([...contacts, { id: uuid(), ...contact }]);
  };

  const removeContactHandler = (id) => {
    const newContactList = contacts.filter((contact) => {
      return contact.id !== id;
    });

    setContacts(newContactList);
  };

  useEffect(() => {
    const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
    if (retriveContacts) setContacts(retriveContacts);
  }, []);

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  }, [contacts]);

  return (

      <AddContact addContactHandler={addContactHandler} />
      <ContactList contacts={contacts} getContactId={removeContactHandler} />

  );
}

export default App;

ContactList.js

import React from "react";
import ContactCard from "./ContactCard";

const ContactList = (props) => {
    console.log(props);

    const deleteContactHandler = (id) => {
        props.getContactId(id);
    };

    const renderContactList = props.contacts.map((contact) => {
        return(
          <ContactCard contact={contact} clickHandler = { deleteContactHandler } key = { contact.id}/>
        );
    })
    return(

            {renderContactList}

    );
}

export default ContactList;

ContactCard.js

import React from "react";
import user from "../images/user.jpg";

const CardContact = (props) => {
    const {id, name, email} = props.contact;
    return(

{name}

{email}

               props.clickHandler(id)}>

    );
};

export default CardContact;

AddContact.js

import React from "react";

class AddContact extends React.Component {
  state = {
    name: "",
    email: "",
  };

  add = (e) => {
    e.preventDefault();
    if (this.state.name === "" || this.state.email === "") {
      alert("ALl the fields are mandatory!");
      return;
    }
    this.props.addContactHandler(this.state);
    this.setState({ name: "", email: "" });
  };
  render() {
    return (

Add Contact

        <form className="ui form" onSubmit={this.add}>

            Name
            <input
              type="text"
              name="name"
              placeholder="Name"
              value={this.state.name}
              onChange={(e) => this.setState({ name: e.target.value })}
            />

            Email
            <input
              type="text"
              name="email"
              placeholder="Email"
              value={this.state.email}
              onChange={(e) => this.setState({ email: e.target.value })}
            />

          <button className="ui button blue">Add</button>
        </form>

    );
  }
}

export default AddContact;

Body:
From the uuidv4 npm page:
Most of the functionality of uuidv4 module is already included in uuid since version 8.3.0, so most of the functions of uuidv4 module have already been marked as deprecated.

So, importing uuidv4 module in your App.js is causing this error.

You can upgrade to the latest version of uuid library to get rid of this error.

Run these commands in the terminal in your project directory.

npm uninstall uuidv4
npm install uuid

And now, in App.js import uuid module instead of uuidv4

import { v4 as uuid } from 'uuid';

And now, you can use uuid() function to create UUIDs

To check more about uuid, you can see there documentation: https://github.com/uuidjs/uuid#quickstart


来源: stackexchange

问:
How to install the Bumblebee 2021.1.1 Android Studio Patch?
When I open Android Studio I receive a notification saying that an update is available:

```<code>The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes
</code>```

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.

答:
This issue was fixed by Google (10 February 2022).

You can now update Android Studio normally.

Thank you all for helping to bring this problem to Google's attention.

ContentLicense: CC BY-SA 4.0

Body:
When I open Android Studio I receive a notification saying that an update is available:

The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.


问:
How to tokenize a text using tensorflow?
I am trying to use the following code to vectorize a sentence:

```<code>from tensorflow.keras.layers import TextVectorization

text_vectorization_layer =  TextVectorization(max_tokens=10000,
                                              ngrams=5,
                                              standardize='lower_and_strip_punctuation',
                                              output_mode='int',
                                              output_sequence_length = 15
                                              )

text_vectorization_layer(['BlackBerry Limited is a Canadian software'])
</code>```

However, it complains with the following error:

AttributeError: 'NoneType' object has no attribute 'ndims'

答:
You have to first compute the vocabulary of the TextVectorization layer using either the adapt method or by passing a vocabulary array to the vocabulary argument of the layer. Here is a working example:

import tensorflow as tf

text_vectorization_layer =  tf.keras.layers.TextVectorization(max_tokens=10000,
                                              ngrams=5,
                                              standardize='lower_and_strip_punctuation',
                                              output_mode='int',
                                              output_sequence_length = 15
                                              )

text_vectorization_layer.adapt(['BlackBerry Limited is a Canadian software'])
print(text_vectorization_layer(['BlackBerry Limited is a Canadian software']))
```
```tf.Tensor([[18  7 11 21 13  2 17  6 10 20 12 16  5  9 19]], shape=(1, 15), dtype=int64)
```

The strings are tokenized internally. Also, check the docs.

Body:
I am trying to use the following code to vectorize a sentence:

from tensorflow.keras.layers import TextVectorization

text_vectorization_layer =  TextVectorization(max_tokens=10000,
                                              ngrams=5,
                                              standardize='lower_and_strip_punctuation',
                                              output_mode='int',
                                              output_sequence_length = 15
                                              )

text_vectorization_layer(['BlackBerry Limited is a Canadian software'])

However, it complains with the following error:

AttributeError: 'NoneType' object has no attribute 'ndims'

Body:
You have to first compute the vocabulary of the TextVectorization layer using either the adapt method or by passing a vocabulary array to the vocabulary argument of the layer. Here is a working example:

import tensorflow as tf

text_vectorization_layer =  tf.keras.layers.TextVectorization(max_tokens=10000,
                                              ngrams=5,
                                              standardize='lower_and_strip_punctuation',
                                              output_mode='int',
                                              output_sequence_length = 15
                                              )

text_vectorization_layer.adapt(['BlackBerry Limited is a Canadian software'])
print(text_vectorization_layer(['BlackBerry Limited is a Canadian software']))

tf.Tensor([[18  7 11 21 13  2 17  6 10 20 12 16  5  9 19]], shape=(1, 15), dtype=int64)

The strings are tokenized internally. Also, check the docs.


问:
SwiftUI - Get field value from a Firebase document
I'm pretty new to SwiftUI and using Firebase and have stumbled upon retrieving a value from a document on Firebase.
I've done some Googling but have yet to find a way to do this.

My code so far looks like this:

```<code>//Test1: get user info
func readUserInfo(_ uid: String) -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("users").document(uid)
    var returnThis = ""
    docRef.getDocument { (document, error) -> String in
        if let document = document, document.exists {
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            print("Document data: \(dataDescription)")
            returnThis = dataDescription
            return(dataDescription)
        } else {
            print("Document does not exist")
        }
    }
    return returnThis
}

//Test2: get user info
func readUserInfo(_ uid: String) -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("users").document(uid)
    var property = "not found"
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            property = document.get("phoneNumber") as! String
        }
    }
    return property
}
</code>```

Test1:
Got an error saying "Declared closure result 'String' is incompatible with contextual type 'Void'"

Test2:
The returned value is always "not found", so I guess assigning document.get("phoneNumber") as! String to the property variable didn't work.

In both cases, I was able to print the value out. However, I want the value to be passed to a Text element so I can display it on the interface.

Could someone please help? Thanks so much in advance.

答:
The reason why the value is never found is because the network request you are making takes time to retrieve that data. By the time it reaches the return statement the data from firebase has not been been retrieved yet so it will just return the value it was initially set to which was an empty string. What you should do is add a completion handler to the function so that once the data is finally retrieved you can then return it.</p>
```<code>struct ContentView: View {
    @State private var text: String = ""

    var body: some View {
        Text(text)
            .onAppear {
                readUserInfo("sydQu5cpteuhPEgmHepn") { text in
                    self.text = text
                }
            }
    }

    func readUserInfo(_ uid: String, _ completion: @escaping (String) -> Void) {
        let db = Firestore.firestore()
        let docRef = db.collection("users").document(uid)
        docRef.getDocument { document, error in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
                completion(dataDescription)
            } else {
                completion("Document does not exist")
            }
        }
    }
}
</code>```

Body:
I'm pretty new to SwiftUI and using Firebase and have stumbled upon retrieving a value from a document on Firebase.
I've done some Googling but have yet to find a way to do this.

My code so far looks like this:

//Test1: get user info
func readUserInfo(_ uid: String) -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("users").document(uid)
    var returnThis = ""
    docRef.getDocument { (document, error) -> String in
        if let document = document, document.exists {
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            print("Document data: \(dataDescription)")
            returnThis = dataDescription
            return(dataDescription)
        } else {
            print("Document does not exist")
        }
    }
    return returnThis
}

//Test2: get user info
func readUserInfo(_ uid: String) -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("users").document(uid)
    var property = "not found"
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            property = document.get("phoneNumber") as! String
        }
    }
    return property
}

Test1:
Got an error saying "Declared closure result 'String' is incompatible with contextual type 'Void'"

Test2:
The returned value is always "not found", so I guess assigning document.get("phoneNumber") as! String to the property variable didn't work.

In both cases, I was able to print the value out. However, I want the value to be passed to a Text element so I can display it on the interface.

Could someone please help? Thanks so much in advance.

Body:
The reason why the value is never found is because the network request you are making takes time to retrieve that data. By the time it reaches the return statement the data from firebase has not been been retrieved yet so it will just return the value it was initially set to which was an empty string. What you should do is add a completion handler to the function so that once the data is finally retrieved you can then return it.

struct ContentView: View {
    @State private var text: String = ""

    var body: some View {
        Text(text)
            .onAppear {
                readUserInfo("sydQu5cpteuhPEgmHepn") { text in
                    self.text = text
                }
            }
    }

    func readUserInfo(_ uid: String, _ completion: @escaping (String) -> Void) {
        let db = Firestore.firestore()
        let docRef = db.collection("users").document(uid)
        docRef.getDocument { document, error in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
                completion(dataDescription)
            } else {
                completion("Document does not exist")
            }
        }
    }
}


问:
Do APC key timeouts work within a single request?
Here's the body of my PHPUnit test function code:

```<code>$key = 'test:foobar';
$valueIn = 'this is a test string';
$success = apc_store( $key, $valueIn, 1 ); // 1 second expire time
$this->assertTrue( $success );
$valueOut = apc_fetch( $key );
$this->assertEquals( $valueIn, $valueOut );
sleep(2); // wait 2 seconds
$valueOut = apc_fetch( $key );
$this->assertEquals( false, $valueOut ); // <<< This assert fails!
</code>```

My question is, why is $valueOut == $valueIn on the last fetch? Shouldn't the key expire and return false?  I've also tried waiting 10 seconds and it doesn't work.

I've used apc.php to examine the cache, and the key is in there with a 1-second expire. When I examine the key, the value is false, which is as expected.  I'm using APC 3.1.7

答:
No, variables are not expired within a single request.

The PHP documentation for apc_store has the following to say about the ttl (time to live) argument (emphasis mine):

After the ttl has passed, the stored variable will be expunged from the cache (on the next request).

ContentLicense: CC BY-SA 3.0

Body:
Here's the body of my PHPUnit test function code:

$key = 'test:foobar';
$valueIn = 'this is a test string';
$success = apc_store( $key, $valueIn, 1 ); // 1 second expire time
$this->assertTrue( $success );
$valueOut = apc_fetch( $key );
$this->assertEquals( $valueIn, $valueOut );
sleep(2); // wait 2 seconds
$valueOut = apc_fetch( $key );
$this->assertEquals( false, $valueOut ); // <<< This assert fails!

My question is, why is $valueOut == $valueIn on the last fetch? Shouldn't the key expire and return false?  I've also tried waiting 10 seconds and it doesn't work.

I've used apc.php to examine the cache, and the key is in there with a 1-second expire. When I examine the key, the value is false, which is as expected.  I'm using APC 3.1.7


问:
what props are used for in vuejs
I came across this snippet of code:

  props: {
    clicks: {
      type: Object,
      default: null,
    }
    events: {
      type: Object,
      default: null,
    },
  }```

I didn't understand from where props are retreived, from database ? or received from another component ?

答: The props in Vue components always come from the immediate parent component.

Title: what props are used for in vuejs

Body:
I came across this snippet of code:

  props: {
    clicks: {
      type: Object,
      default: null,
    }
    events: {
      type: Object,
      default: null,
    },
  }

I didn't understand from where props are retreived, from database ? or received from another component ?


问:
Venn diagram (4 sets) with R: problem with percentages
I am trying to draw a Venn diagram with four logical variables. I have tried many different R packages but with each of them I have faced some problems. So far, the best result I have achieved by using the ggvenn package. However, the problem is, that it shows the percentages of the intersections based on the observations included in the diagram, instead of all observations in the data.

Below is an example Venn diagram and its code to illustrate the problem. So my question is: is there some way to display the percentages in relation to the total amount of observations in the data. For instance, in the diagram below the intersection of ABCD consists of 45 observation and thus the correct proportion would be 4.5% (i.e. 45/1000) instead of 4.7%.

I would really appreciate if someone could help me out with this.

```<code>library(ggvenn)

a <- sample(x = c(TRUE, TRUE, FALSE), size = 1000, replace = TRUE)
b <- sample(x = c(TRUE,FALSE, FALSE), size = 1000, replace = TRUE)
c <- sample(x = c(TRUE, FALSE, FALSE, FALSE), size = 1000, replace = TRUE)
d <- sample(x = c(TRUE, TRUE, TRUE, FALSE), size = 1000, replace = TRUE)

df <- tibble(values = c(1:1000), A=a, B=b, C=c, D=d)

ggvenn(df,
  fill_color = c("black", "grey70", "grey80", "grey90"),
  show_percentage = TRUE,
  digits = 1,
  text_size = 2.5)

</code>```

答:
A quick fix for this problem would be to use the latest Github version of {ggvenn}:

```<code>remove.packages("ggvenn")
devtools::install_github("yanlinlin82/ggvenn")
</code>```

Then, by default, there will be also a percentage for the observations that are outside A/B/C/D. This gives you the percentages you're looking for:

Body:
I am trying to draw a Venn diagram with four logical variables. I have tried many different R packages but with each of them I have faced some problems. So far, the best result I have achieved by using the ggvenn package. However, the problem is, that it shows the percentages of the intersections based on the observations included in the diagram, instead of all observations in the data.

Below is an example Venn diagram and its code to illustrate the problem. So my question is: is there some way to display the percentages in relation to the total amount of observations in the data. For instance, in the diagram below the intersection of ABCD consists of 45 observation and thus the correct proportion would be 4.5% (i.e. 45/1000) instead of 4.7%.

I would really appreciate if someone could help me out with this.

library(ggvenn)

a <- sample(x = c(TRUE, TRUE, FALSE), size = 1000, replace = TRUE)
b <- sample(x = c(TRUE,FALSE, FALSE), size = 1000, replace = TRUE)
c <- sample(x = c(TRUE, FALSE, FALSE, FALSE), size = 1000, replace = TRUE)
d <- sample(x = c(TRUE, TRUE, TRUE, FALSE), size = 1000, replace = TRUE)

df <- tibble(values = c(1:1000), A=a, B=b, C=c, D=d)

ggvenn(df,
  fill_color = c("black", "grey70", "grey80", "grey90"),
  show_percentage = TRUE,
  digits = 1,
  text_size = 2.5)

Body:
A quick fix for this problem would be to use the latest Github version of {ggvenn}:

remove.packages("ggvenn")
devtools::install_github("yanlinlin82/ggvenn")

Then, by default, there will be also a percentage for the observations that are outside A/B/C/D. This gives you the percentages you're looking for:


问:
Formspree: error message | Can't send an empty form
I've searched on google but I couldn't get anywhere. I've added the Formspree contact form to a website and after initial set up it worked. After I activated and confirmed my email I sent one more email just to be sure it's up and running and when I click send I receive an error message. Error message

This is what the html code looks like

HTML

Not sure what I'm doing wrong. I'm relatively new to web development so any help would be greatly appreciated!

答:
I think this problem occurred due to absence of name attribute in the input fields of the form. It is also given on the "Integration" section of the forms you created in the formspree.io.
It says Finally, ensure that each input has a name attribute.


问:
Trouble changing `upload_max_filesize` on nginx
I've see a few other similar questions on here, but most of the answers are Apache specific (dealing with their .htaccess file) and I'm using nginx.

I'm having trouble making my change to the upload_max_filesize in php.ini stick. I'm using nginx, php5 and wordpress on Debian.

When I run phpinfo() I see the following output:

Loaded Configuration File /etc/php5/cgi/php.ini

I then go to the relevant .ini file, change a few values, and then restart nginx. When I fire up a phpinfo() plugin I got for wordpress, it reports the values as unchanged.

I'm at a loss because phpinfo() reports that it is loading config values from the file that I've changed, but it doesn't report the changes.

答:
```<code>$ sudo service php7.4-fpm restart
</code>```

Resolved my problem. change the php version to the one you using.

Body:
$ sudo service php7.4-fpm restart

Resolved my problem. change the php version to the one you using.


问:
Xcode 'CodeSign error: code signing is required'
I've been working on an iPhone project with iOS 4.0. I just downloaded Xcode 3.2.4 with iOS SDK 4.1 so that I can work with the updated iOS. Upon opening the project in the udpated Xcode, I found that the target read 'Base SDK Missing'. I fixed that by following the instructions here.

Now when I try building targeting any version of iOS, I receive this error (with the corresponding version referenced in the error text):

CodeSign Error: code signing is required for product type 'Application' in SDK 'Device - iOS 4.1'

I have the Team Provisioning Profile created by Xcode installed, that Provisioning Profile has my certificate, and the Code Signing Entity selected is 'iPhone Developer: Aaron Milam'.

Any ideas as to what I could be missing here?

答:
Another possibility - When you Build for Archive make sure your Archive choice in your scheme is set for Distribution, not Release.

Go to Product -> Edit Scheme  This brings up a new dialog.

Select Archive on the left. Make sure the build configuration is Distribution.


问:
jar file doesn't do anything when executed (VSCode)
Here I have a short program, which I would like to export as a .jar file. When I use VSCode's "Export Jar..." option (and select Test as the main class), it creates the jar file without any errors, but when I run it (by double clicking), nothing happens. When I run the code from within VSCode however, it works as expected (the window shows up and says "Hello World").
Here's my code:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setSize(600, 400);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLocationRelativeTo(null);
                    frame.getContentPane().add(new JLabel("Hello World!"));
                    frame.setVisible(true);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

答:
What the OS usually does when you doubleclick an 'executable jar' is to run

```<code>javaw -jar jar-file-name.jar
</code>```

javaw is the 'windowed' version of Java, meaning there is no terminal window where console messages are printed but the application would show it's own windows. That seems to not happen in your case.

To troubleshoot, open a terminal window, cd to the directory containing your jar and execute

```<code>java -jar -jar-file-name.jar
</code>```

Now on the console you can see if errors occurred. But be aware the difference between some jar file and an executable jar file is the META-INF/MANIFEST file. In that java -jar ... finds the information which main class to run, and that may be different from what you run in the IDE.

Body:
What the OS usually does when you doubleclick an 'executable jar' is to run

javaw -jar jar-file-name.jar

javaw is the 'windowed' version of Java, meaning there is no terminal window where console messages are printed but the application would show it's own windows. That seems to not happen in your case.

To troubleshoot, open a terminal window, cd to the directory containing your jar and execute

java -jar -jar-file-name.jar

Now on the console you can see if errors occurred. But be aware the difference between some jar file and an executable jar file is the META-INF/MANIFEST file. In that java -jar ... finds the information which main class to run, and that may be different from what you run in the IDE.


问:
Updating context across components-react.js
I am learning to use useContext with react.js but I now struggle with making it work properly. I am basically trying to create something like a shopping cart, with the cart items being stored in the context. The problem comes when I try to remove an object from the cart because the change doesnt render even tho console.log registers the change...the modal.js apparently just doesnt update.

Modal.js

```<code>import React, { useContext } from "react";
import showModal from "../store/meat-context";
import MeatContext from "../store/meat-context";
import CartItem from "./CartItem";
import styles from "./Modal.module.css";

function Modal() {
  const modal = useContext(showModal);
  const { meatState, dispatchMeatState } = useContext(MeatContext);
  if (!modal.showModal) {
    return null;
  }
  console.log(meatState)
  return (
    <div className={styles.backdrop}>
      <div className={styles.modal}>

        {meatState.map((meat) => {
          return (
            <CartItem
              name={meat.name}
              price={meat.price}
              id={meat.id}
              key={Math.random()}
              description={meat.description}
            />

          );
        })}
      </div>
    </div>
  );
}

export default Modal;
</code>```

when the modal renders for the first time, it correctly displays and consolelogs the expected content of the cart which looks like this for example:

```<code>[
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    },
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    },
    {
        "name": "Schnitzel",
        "description": "A german specialty!",
        "price": 16.5,
        "id": "m2"
    },
    {
        "name": "Barbecue Burger",
        "description": "American, raw, meaty",
        "price": 12.99,
        "id": "m3"
    },
    {
        "name": "Green Bowl",
        "description": "Healthy...and green...",
        "price": 18.99,
        "id": "m4"
    }
]
</code>```

now when I try to add an item by clicking add, it renders without any problem. But when I try to remove an item, the console.log prints the correct updated state but the cart doesnt render any change. Here is the context for reference:

meat-context.js

```<code>import React, { useReducer, useState } from "react";

const MeatContext = React.createContext({ meatState: [] });

export function MeatContextProvider(props) {
  const meatReducer = (state, action) => {
    if (action.type === "ADD_MEAT") {
      return [...state, action.payload];
    }
    if (action.type === "REMOVE_MEAT") {
      for (var i = 0; i < state.length; i++) {
        if (state[i].id == action.payload.id) {
          console.log(state[i].id);

          state.splice(i, 1);
          console.log(state);

          return state;

        }

      }

    }

  };

  const [meatState, dispatchMeatState] = useReducer(meatReducer, []);
  const [showModal, setShowModal] = useState(false);

  if (showModal) {
    document.body.style.overflow = "hidden";
  }

  return (
    <MeatContext.Provider
      value={{
        meatState: meatState,
        dispatchMeatState: dispatchMeatState,
        showModal: showModal,
        setShowModal: setShowModal,
      }}
    >
      {props.children}
    </MeatContext.Provider>
  );
}
export default MeatContext;
</code>```

答: Have you tried something like return [...state] in your REMOVE_MEAT condition ? Not sure how reducer works since I don't often use it but you shouldn't return/update the state directly

Body:
I am learning to use useContext with react.js but I now struggle with making it work properly. I am basically trying to create something like a shopping cart, with the cart items being stored in the context. The problem comes when I try to remove an object from the cart because the change doesnt render even tho console.log registers the change...the modal.js apparently just doesnt update.

Modal.js

import React, { useContext } from "react";
import showModal from "../store/meat-context";
import MeatContext from "../store/meat-context";
import CartItem from "./CartItem";
import styles from "./Modal.module.css";

function Modal() {
  const modal = useContext(showModal);
  const { meatState, dispatchMeatState } = useContext(MeatContext);
  if (!modal.showModal) {
    return null;
  }
  console.log(meatState)
  return (

        {meatState.map((meat) => {
          return (
            <CartItem
              name={meat.name}
              price={meat.price}
              id={meat.id}
              key={Math.random()}
              description={meat.description}
            />

          );
        })}

  );
}

export default Modal;

when the modal renders for the first time, it correctly displays and consolelogs the expected content of the cart which looks like this for example:

[
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    },
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    },
    {
        "name": "Schnitzel",
        "description": "A german specialty!",
        "price": 16.5,
        "id": "m2"
    },
    {
        "name": "Barbecue Burger",
        "description": "American, raw, meaty",
        "price": 12.99,
        "id": "m3"
    },
    {
        "name": "Green Bowl",
        "description": "Healthy...and green...",
        "price": 18.99,
        "id": "m4"
    }
]

now when I try to add an item by clicking add, it renders without any problem. But when I try to remove an item, the console.log prints the correct updated state but the cart doesnt render any change. Here is the context for reference:

meat-context.js

import React, { useReducer, useState } from "react";

const MeatContext = React.createContext({ meatState: [] });

export function MeatContextProvider(props) {
  const meatReducer = (state, action) => {
    if (action.type === "ADD_MEAT") {
      return [...state, action.payload];
    }
    if (action.type === "REMOVE_MEAT") {
      for (var i = 0; i < state.length; i++) {
        if (state[i].id == action.payload.id) {
          console.log(state[i].id);

          state.splice(i, 1);
          console.log(state);

          return state;

        }

      }

    }

  };

  const [meatState, dispatchMeatState] = useReducer(meatReducer, []);
  const [showModal, setShowModal] = useState(false);

  if (showModal) {
    document.body.style.overflow = "hidden";
  }

  return (
    <MeatContext.Provider
      value={{
        meatState: meatState,
        dispatchMeatState: dispatchMeatState,
        showModal: showModal,
        setShowModal: setShowModal,
      }}
    >
      {props.children}
    </MeatContext.Provider>
  );
}
export default MeatContext;


问:
Hiding error messages if writing to a file fails in a Windows .BAT script
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

```<code>:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul
</code>```

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

```<code>Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors
</code>```

Thanks in advance for your help.

Lionel.

答:
As stated already in the comments, the Access is denied message is output to stdOut, as opposed to the expected stdErr.

Since your task is related to a read only issue, (there are other reasons why that message may be output), I'd offer this relatively simple alternative:

@Dir "MyReadOnlyFile.txt" /A:-DR /B 1>NUL 2>&1 || (Echo() 1>>"MyReadOnlyFile.txt"
```
<p>It simply determines if the existing file is read only, and only performs a write operation if it is not.</p>
<p>Alternatively you could use the same method to reset the read only attribute, write to the file, then apply the read only attribute again:</p>
<pre class="lang-sh prettyprint-override"><code>@Set "File=MyReadOnlyFile.txt"
@Dir "%File%" /A:-DR /B 1>NUL 2>&1 && (
    %SystemRoot%\System32\attrib.exe -R "%File%" 2>NUL
    If Not ErrorLevel 1 (
        (Echo() 1>>"%File%"
        %SystemRoot%\System32\attrib.exe +R "%File%"
    )
) || (Echo() 1>>"%File%"
</code>```

Body:
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors

Thanks in advance for your help.

Lionel.

Body:
As stated already in the comments, the Access is denied message is output to stdOut, as opposed to the expected stdErr.

Since your task is related to a read only issue, (there are other reasons why that message may be output), I'd offer this relatively simple alternative:

@Dir "MyReadOnlyFile.txt" /A:-DR /B 1>NUL 2>&1 || (Echo() 1>>"MyReadOnlyFile.txt"

It simply determines if the existing file is read only, and only performs a write operation if it is not.

Alternatively you could use the same method to reset the read only attribute, write to the file, then apply the read only attribute again:

@Set "File=MyReadOnlyFile.txt"
@Dir "%File%" /A:-DR /B 1>NUL 2>&1 && (
    %SystemRoot%\System32\attrib.exe -R "%File%" 2>NUL
    If Not ErrorLevel 1 (
        (Echo() 1>>"%File%"
        %SystemRoot%\System32\attrib.exe +R "%File%"
    )
) || (Echo() 1>>"%File%"


问:
Optionals with @ObservedObject and @Published var
I am getting quite mad with unwrapping optionals on a SwiftUI project. The project has (removed extra lines for readability):

struct Report: Decodable {
    var siteId: String = "nosite"

    enum ReportKeys: String, CodingKey { //some keys here
    }

    init(from decoder: Decoder) throws {
        // all the code for remapping json properties to the struct
    }
}

class ReportCaller: NSObject, URLSessionDelegate, ObservableObject {
    @Published var lastReport: Report?

    override init() {
        super.init()
        loadReport()
    }

    func loadReport() {
        // URL session code that finally returns
        self.lastReport =  try! decoder.decode(Report, from: data)
    }
```
<p>The, in my view, I have</p>
<pre class="lang-swift prettyprint-override"><code>struct ContentView: View {
    @ObservedObject var report = ReportCaller()
</code>```

Now, to make it working, I must unwrap each line, as below:

```<code>Text(report.lastReport?.siteId ?? "")
</code>```

The struct has defaults, so I would expect to not unwrap anything. I recognize I miss some initialization, but I cannot figure out where I should put it. The @ObservedObject calls a class, it seems not the place where to do it. Because the class publishes an optional Report?, I thought to remove the optional there, but I get another problem:

Property 'self.lastReport' not initialized at super.init call
```
<p>I can try to make</p>
<pre class="lang-swift prettyprint-override"><code>    override init() {
        self.lastReport = Metar()
        super.init()
        loadReport()
    }
</code>```

Although the compiler complains the from: is missing, because this is effectively what the init in the struct expects. So, I am getting confused on which should be the best way to manage the problem.

答:
Try removing () after ReportCaller. I'm using a very similar approach that doesn't with (). The code should look like this, I believe:

struct ContentView: View {
    @ObservedObject var report: ReportCaller
```

Body:
I am getting quite mad with unwrapping optionals on a SwiftUI project. The project has (removed extra lines for readability):

struct Report: Decodable {
    var siteId: String = "nosite"

    enum ReportKeys: String, CodingKey { //some keys here
    }

    init(from decoder: Decoder) throws {
        // all the code for remapping json properties to the struct
    }
}

class ReportCaller: NSObject, URLSessionDelegate, ObservableObject {
    @Published var lastReport: Report?

    override init() {
        super.init()
        loadReport()
    }

    func loadReport() {
        // URL session code that finally returns
        self.lastReport =  try! decoder.decode(Report, from: data)
    }

The, in my view, I have

struct ContentView: View {
    @ObservedObject var report = ReportCaller()

Now, to make it working, I must unwrap each line, as below:

Text(report.lastReport?.siteId ?? "")

The struct has defaults, so I would expect to not unwrap anything. I recognize I miss some initialization, but I cannot figure out where I should put it. The @ObservedObject calls a class, it seems not the place where to do it. Because the class publishes an optional Report?, I thought to remove the optional there, but I get another problem:

Property 'self.lastReport' not initialized at super.init call

I can try to make

    override init() {
        self.lastReport = Metar()
        super.init()
        loadReport()
    }

Although the compiler complains the from: is missing, because this is effectively what the init in the struct expects. So, I am getting confused on which should be the best way to manage the problem.


问:
What is the Bash equivalent of the set command in C shell?
I need to run this script in the Bash shell as that is the only shell to which I have access on a high performance computing cluster at my present organization.

答:
What is the Bash equivalent of the set command in C shell?

The equivalent is just assigning the variable. There is no special command for that.

```<code># set var = 'stuff'
var='stuff'
</code>```

Body:
What is the Bash equivalent of the set command in C shell?

The equivalent is just assigning the variable. There is no special command for that.

# set var = 'stuff'
var='stuff'


问:
How I could test location with MemoryRouter on React Router DOM v6?
Using React Router DOM (v6) with React Testing Library, I would like to know if there's a way to deal with "mocked" history from createMemoryHistoryor an alternative like it.

Based on the example of Testing Library, I could mock the history on the Router component but in v6 this component doesn't accept the history prop anymore.

So, my doubt is: how can I test history and location with RTL (React Testing Library) with React Router DOM v6? Should I keep using the MemoryRouter?

答:
Using react router dom v6, Router use navigator prop to accept history.</p>
```<code>const history = createMemoryHistory();
...
<MockedProvider mocks={[]}>
  <Router navigator={history} location={"/"}>
    <Home />
  </Router>
</MockedProvider>
...
await waitFor(() => {
  expect(history.location.pathname).toBe("/");
});
</code>```

Body:
Using react router dom v6, Router use navigator prop to accept history.

const history = createMemoryHistory();
...
<MockedProvider mocks={[]}>
  <Router navigator={history} location={"/"}>
    <Home />
  </Router>
</MockedProvider>
...
await waitFor(() => {
  expect(history.location.pathname).toBe("/");
});


问:
R hold list of variables to supply a function
For a situation of many R processes, using a particular function currently hard coded as follows:

```<code>processa <- c("var1","var2","var3","var4")
processb <- c("var1","var5","var7")
processc <- c("var8")
</code>```

The need is to change it to where the "varX" list is held as value, something like this:

```<code>processa <- c(Value)
processb <- c(Value)
processc <- c(Value)
</code>```

The plan is to import the 'Value' from an Excel file (so configs for the processes can be changed without updating multiple codes), what I end up getting is the following which doesn't work.

```<code>"\"var1\", \"var2\", \"var3\", \"var4\""
</code>```

答:
The comments were becoming a bit of an epic here, so I thought I would post this as a reproducible example of how to get a vector from the given input:

excel_output <- "\"var1\", \"var2\", \"var3\", \"var4\""
excel_output
#> [1] "\"var1\", \"var2\", \"var3\", \"var4\""
```
<p>So now we do:</p>
```strsplit(gsub("\"", "", excel_output), ", ")[[1]]
#> [1] "var1" "var2" "var3" "var4"
```

Body:
For a situation of many R processes, using a particular function currently hard coded as follows:

processa <- c("var1","var2","var3","var4")
processb <- c("var1","var5","var7")
processc <- c("var8")

The need is to change it to where the "varX" list is held as value, something like this:

processa <- c(Value)
processb <- c(Value)
processc <- c(Value)

The plan is to import the 'Value' from an Excel file (so configs for the processes can be changed without updating multiple codes), what I end up getting is the following which doesn't work.

"\"var1\", \"var2\", \"var3\", \"var4\""

Body:
The comments were becoming a bit of an epic here, so I thought I would post this as a reproducible example of how to get a vector from the given input:

excel_output <- "\"var1\", \"var2\", \"var3\", \"var4\""
excel_output
#> [1] "\"var1\", \"var2\", \"var3\", \"var4\""

So now we do:

strsplit(gsub("\"", "", excel_output), ", ")[[1]]
#> [1] "var1" "var2" "var3" "var4"


问:
Java schedule a job to run at certain time for maximum period of time
I'm trying to schedule a task that should run every 10 seconds. However this task should have a dynamical allowed period execution time. In other words, if the max allowed time is 5 seconds and if the task runs for more than 5 secs it should be killed/shutdown.

I have tried to use @Schedule with a cron time but no matter what I try I can't kill once it is running.  However, an advice was given to me to not use the @Schedule and create a normal task with a ScheduledExecutorService but I have no idea how to do it.

My original method looks like that:

```<code>    @Scheduled(cron = "0/10 * * * * ?")
    @Transactional
    public void testMethod(Integer period) {
        ThreadPoolTaskScheduler scheduler;

        scheduler.setAwaitTerminationSeconds(period);
        scheduler.setWaitForTasksToCompleteOnShutdown(false);

        importantMethod();

    }
</code>```

I have tried to rewrite it like so:

```<code>public void testMethod(){
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  scheduler.scheduleAtFixedRate(importantMethod(), delay,
                                  period, TimeUnit.SECONDS);
}
</code>```

However, I'm not sure how to set it up to have no delay to run every 10 seconds or every 5 mins and to only shut it down after the maximum allowed time is exceeded.

Any help will be greatly appreciated.

答:
I am not sure if this is the best way to do it, but here is a working way i came up with.

You would need three types of tasks:

the task itself, which has to run periodically - the important task

another task which will cancel it's execution, i'll call it kill task from now on.

task to submit the important task for execution - the submit task, this is what you will schedule with the ScheduledExecutorService to run periodically

The idea is, when your important task starts execution, it will schedule the kill task to run 5 seconds later. In order to achieve that, it needs to know its' Future instance. And for that, it needs the submit task to do the submission and let it know of its' Future.

Here is important task:

```<code>import java.time.LocalTime;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ImportantTask implements Runnable {

    //that's just to make it easier to track what happens with each task
    private static long NEXT_ID = 1;

    //needed to schedule kill task
    private final ScheduledExecutorService executorService;
    private final long taskId;
    private Future<?> thisTaskFuture;
    //only needed to know when to cancel all tasks and end test
    private CountDownLatch countDownLatch;

    public ImportantTask(ScheduledExecutorService executorService) {
        this.executorService = executorService;
        this.taskId = NEXT_ID++;
    }

    @Override
    public void run() {
        //make half the tasks take too long
        long executionTimeSeconds = this.taskId % 2 == 0 ? 6 : 4;
        System.out.println(this.getLogMessage("started"));

        CancelFutureTask cancelFutureTask = new CancelFutureTask(this.thisTaskFuture);
        //this schedules the kill task for single execution, after 5 seconds delay
        this.executorService.schedule(cancelFutureTask, 5, TimeUnit.SECONDS);
        try {
            //simulating long execution
            Thread.sleep(executionTimeSeconds * 1_000);
        } catch (InterruptedException exc) {
            System.out.println(this.getLogMessage("interrupted"));
            //might need to check Thread.currentThread().isInterrupted(), depends on your exact case
            return;
        } finally {
            this.countDownLatch.countDown();
        }
        //the task is already finished, even if cancel is called, it has no effect
        System.out.println(this.getLogMessage("finished"));
    }

    private String getLogMessage(String taskStatus) {
        return String.format("Task with id - %d, %s at %s", this.taskId, taskStatus, LocalTime.now());
    }

    public void setThisTaskFuture(Future<?> thisTaskFuture) {
        this.thisTaskFuture = thisTaskFuture;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
}
</code>```

The CountDownLatch is here only to make it easier to stop main method after few executions, you probably do not need it. Take note of the comments in the code.

The kill task is quite simple:

```<code>import java.util.concurrent.Future;

public class CancelFutureTask implements Runnable {

    private final Future<?> future;
    private final boolean mayInterrupt;

    public CancelFutureTask(Future<?> future, boolean mayInterrupt) {
        this.future = future;
        this.mayInterrupt = mayInterrupt;
    }

    public CancelFutureTask(Future<?> future) {
        this(future, true);
    }

    @Override
    public void run() {
        this.future.cancel(this.mayInterrupt);
    }
}
</code>```

It just cancels a Future and will have no effect if the future has already finished execution.

And submit task:

```<code>import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;

public class SubmitNewImportantTask implements Runnable {

    private final ScheduledExecutorService executorService;
    private final CountDownLatch countDownLatch;

    public SubmitNewImportantTask(ScheduledExecutorService executorService, CountDownLatch countDownLatch) {
        this.executorService = executorService;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        ImportantTask importantTask = new ImportantTask(this.executorService);
        //obtain Future instance
        Future<?> future = this.executorService.submit(importantTask);
        //let the task know of its Future instance
        importantTask.setThisTaskFuture(future);
        importantTask.setCountDownLatch(this.countDownLatch);
    }
}
</code>```

It submits important task for execution, obtains the Future instance and sets it in important task.

And the main method i used for testing.

```<code>import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FuturesMain {

    public static void main(String[] args) throws Exception {
        CountDownLatch count = new CountDownLatch(6);
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
        SubmitNewImportantTask submitTask = new SubmitNewImportantTask(executorService, count);
        executorService.scheduleAtFixedRate(submitTask, 0, 10, TimeUnit.SECONDS);
        count.await();
        executorService.shutdown();
        boolean allTerminated = executorService.awaitTermination(10, TimeUnit.SECONDS);
        System.out.println("All terminated - " + allTerminated);
    }
}
</code>```

Body:
I'm trying to schedule a task that should run every 10 seconds. However this task should have a dynamical allowed period execution time. In other words, if the max allowed time is 5 seconds and if the task runs for more than 5 secs it should be killed/shutdown.

I have tried to use @Schedule with a cron time but no matter what I try I can't kill once it is running.  However, an advice was given to me to not use the @Schedule and create a normal task with a ScheduledExecutorService but I have no idea how to do it.

My original method looks like that:

    @Scheduled(cron = "0/10 * * * * ?")
    @Transactional
    public void testMethod(Integer period) {
        ThreadPoolTaskScheduler scheduler;

        scheduler.setAwaitTerminationSeconds(period);
        scheduler.setWaitForTasksToCompleteOnShutdown(false);

        importantMethod();

    }

I have tried to rewrite it like so:

public void testMethod(){
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  scheduler.scheduleAtFixedRate(importantMethod(), delay,
                                  period, TimeUnit.SECONDS);
}

However, I'm not sure how to set it up to have no delay to run every 10 seconds or every 5 mins and to only shut it down after the maximum allowed time is exceeded.

Any help will be greatly appreciated.

Body:
I am not sure if this is the best way to do it, but here is a working way i came up with.

You would need three types of tasks:

the task itself, which has to run periodically - the important task

another task which will cancel it's execution, i'll call it kill task from now on.

task to submit the important task for execution - the submit task, this is what you will schedule with the ScheduledExecutorService to run periodically

The idea is, when your important task starts execution, it will schedule the kill task to run 5 seconds later. In order to achieve that, it needs to know its' Future instance. And for that, it needs the submit task to do the submission and let it know of its' Future.

Here is important task:

import java.time.LocalTime;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ImportantTask implements Runnable {

    //that's just to make it easier to track what happens with each task
    private static long NEXT_ID = 1;

    //needed to schedule kill task
    private final ScheduledExecutorService executorService;
    private final long taskId;
    private Future<?> thisTaskFuture;
    //only needed to know when to cancel all tasks and end test
    private CountDownLatch countDownLatch;

    public ImportantTask(ScheduledExecutorService executorService) {
        this.executorService = executorService;
        this.taskId = NEXT_ID++;
    }

    @Override
    public void run() {
        //make half the tasks take too long
        long executionTimeSeconds = this.taskId % 2 == 0 ? 6 : 4;
        System.out.println(this.getLogMessage("started"));

        CancelFutureTask cancelFutureTask = new CancelFutureTask(this.thisTaskFuture);
        //this schedules the kill task for single execution, after 5 seconds delay
        this.executorService.schedule(cancelFutureTask, 5, TimeUnit.SECONDS);
        try {
            //simulating long execution
            Thread.sleep(executionTimeSeconds * 1_000);
        } catch (InterruptedException exc) {
            System.out.println(this.getLogMessage("interrupted"));
            //might need to check Thread.currentThread().isInterrupted(), depends on your exact case
            return;
        } finally {
            this.countDownLatch.countDown();
        }
        //the task is already finished, even if cancel is called, it has no effect
        System.out.println(this.getLogMessage("finished"));
    }

    private String getLogMessage(String taskStatus) {
        return String.format("Task with id - %d, %s at %s", this.taskId, taskStatus, LocalTime.now());
    }

    public void setThisTaskFuture(Future<?> thisTaskFuture) {
        this.thisTaskFuture = thisTaskFuture;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
}

The CountDownLatch is here only to make it easier to stop main method after few executions, you probably do not need it. Take note of the comments in the code.

The kill task is quite simple:

import java.util.concurrent.Future;

public class CancelFutureTask implements Runnable {

    private final Future<?> future;
    private final boolean mayInterrupt;

    public CancelFutureTask(Future<?> future, boolean mayInterrupt) {
        this.future = future;
        this.mayInterrupt = mayInterrupt;
    }

    public CancelFutureTask(Future<?> future) {
        this(future, true);
    }

    @Override
    public void run() {
        this.future.cancel(this.mayInterrupt);
    }
}

It just cancels a Future and will have no effect if the future has already finished execution.

And submit task:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;

public class SubmitNewImportantTask implements Runnable {

    private final ScheduledExecutorService executorService;
    private final CountDownLatch countDownLatch;

    public SubmitNewImportantTask(ScheduledExecutorService executorService, CountDownLatch countDownLatch) {
        this.executorService = executorService;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        ImportantTask importantTask = new ImportantTask(this.executorService);
        //obtain Future instance
        Future<?> future = this.executorService.submit(importantTask);
        //let the task know of its Future instance
        importantTask.setThisTaskFuture(future);
        importantTask.setCountDownLatch(this.countDownLatch);
    }
}

It submits important task for execution, obtains the Future instance and sets it in important task.

And the main method i used for testing.

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FuturesMain {

    public static void main(String[] args) throws Exception {
        CountDownLatch count = new CountDownLatch(6);
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
        SubmitNewImportantTask submitTask = new SubmitNewImportantTask(executorService, count);
        executorService.scheduleAtFixedRate(submitTask, 0, 10, TimeUnit.SECONDS);
        count.await();
        executorService.shutdown();
        boolean allTerminated = executorService.awaitTermination(10, TimeUnit.SECONDS);
        System.out.println("All terminated - " + allTerminated);
    }
}


问:
How can I use sumproduct to gather data on the sum of specific cells on another sheet?
Just trying to create a small tracker to help me at my job. Not experienced in excel but just want to track specific aisles and how many units each aisle contains.
I'm trying to get the sum of specific aisles from another sheet. I kind of have the formula down just want to grab it from the columns in my other worksheet.
This is the code I'm using on cell AB4:

=SUMPRODUCT(--((ISNUMBER(SEARCH("246",A4:A5000))+ISNUMBER(SEARCH("247",A4:A5000)))>0),B4:B5000)

I just want to know where in my code I can put 'USS Waves'! so that my formula grabs cells from my other sheet.

I'm trying to grab from the other sheet to grab only the sums that are from aisles 246.247,248,249, and 250 in column A and get the sum of all of them from column B.

答:
Nice formula!

Insert the sheet name in front of the cell reference.
Also you need to add more conditions 246.247,248,249, and 250
And because you don't want to sum the 246,247, but the column to the right you need to change the column from A to B at the End of the formula.

Exchange the ; to comma ,

```<code>=SUMPRODUCT(--((ISNUMBER(SEARCH("246";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("247";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("248";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("249";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("250";'USS Waves'!$A$4:$A$5000)))>0);'USS Waves'!$B$4:$B$5000)
</code>```

The formula above is mostly for text.
This formula below is for numbers and much shorter. Use this one.

```<code>=SUMPRODUCT(('USS Waves'!$A$4:$A$5000>=246)*('USS Waves'!$A$4:$A$5000<=250)*('USS Waves'!$B$4:$B$5000))
</code>```

So here you have only 2 conditions

```<code>>=246 and  <=250
</code>```

if you want to understand this formula you can search for array formula with condition.
In this formula you also could change the Sumproduct to Sum

First conditon

```<code>('USS Waves'!$A$4:$A$5000>=246)
</code>```

Second condition

```<code>('USS Waves'!$A$4:$A$5000<=250)
</code>```

These results in a lot of False and True, and if you multiply this they turn to 0 and 1.
And wherever there is a match of both conditions you get a 1 and then this 1 i multiplied by the value in column B.

```<code>('USS Waves'!$B$4:$B$5000)
</code>```

The sum function or Sumproduct function will then add all the values together.

Body:
Nice formula!

Insert the sheet name in front of the cell reference.
Also you need to add more conditions 246.247,248,249, and 250
And because you don't want to sum the 246,247, but the column to the right you need to change the column from A to B at the End of the formula.

Exchange the ; to comma ,

=SUMPRODUCT(--((ISNUMBER(SEARCH("246";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("247";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("248";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("249";'USS Waves'!$A$4:$A$5000))+ISNUMBER(SEARCH("250";'USS Waves'!$A$4:$A$5000)))>0);'USS Waves'!$B$4:$B$5000)

The formula above is mostly for text.
This formula below is for numbers and much shorter. Use this one.

=SUMPRODUCT(('USS Waves'!$A$4:$A$5000>=246)*('USS Waves'!$A$4:$A$5000<=250)*('USS Waves'!$B$4:$B$5000))

So here you have only 2 conditions

>=246 and  <=250

if you want to understand this formula you can search for array formula with condition.
In this formula you also could change the Sumproduct to Sum

First conditon

('USS Waves'!$A$4:$A$5000>=246)

Second condition

('USS Waves'!$A$4:$A$5000<=250)

These results in a lot of False and True, and if you multiply this they turn to 0 and 1.
And wherever there is a match of both conditions you get a 1 and then this 1 i multiplied by the value in column B.

('USS Waves'!$B$4:$B$5000)

The sum function or Sumproduct function will then add all the values together.


问:
Align DIV's to bottom or baseline
I'm trying to align a child div tag to the bottom or baseline of the parent div tag.

All I want to do is have the child Div at the baseline of the Parent Div, here is what it looks like now:

HTML

```<code><div id="parentDiv">
<div class="childDiv"></div>
</div>
</code>```

CSS

```<code>#parentDiv
{
  width:300px;
  height:300px;
  background-color:#ccc;
  background-repeat:repeat
}
#parentDiv .childDiv
{
  height:100px;
  width:30px;
  background-color:#999;
}
</code>```

Note

I will have multiple childDivs with varying heights, and I'll need them all to align to the baseline/bottom.

答:
```<code>
<body>
<!-- CSS styles-->

<style>
.parent{
  background-color:gray;
  height:100vh;
  display:flex;
  flex-direction:column;
  justify-content:space-between;
}
</style>

<!-- HTML -->

<div class="parent">
    <div class="child1">
        hello world! this is first child aligned at the top of parent div
    </div>
    <div class="child2">
        hello world! this is first child aligned in the space between first and last child
    </div>
    <div class="child3">
        hello world! this is last child aligned at the bottom of parent div
    </div>
</div>

</body>

</code>```

Title: Align DIV's to bottom or baseline

Body:
I'm trying to align a child div tag to the bottom or baseline of the parent div tag.

All I want to do is have the child Div at the baseline of the Parent Div, here is what it looks like now:

HTML

CSS

#parentDiv
{
  width:300px;
  height:300px;
  background-color:#ccc;
  background-repeat:repeat
}
#parentDiv .childDiv
{
  height:100px;
  width:30px;
  background-color:#999;
}

Note

I will have multiple childDivs with varying heights, and I'll need them all to align to the baseline/bottom.


问:
Synchronising messages from multiple ZeroMQ publishers
I'm trying to create a stock monitoring application. I have two ZeroMQ publishers running that get the current stock price from two respective services. The first service is the major source of information and no message from the service can be dropped.

I want to combine the two prices into one object and push it to the front-end.
Each message has a timestamp that indicates the time of the observation of the price and is the basis of combining the messages.

However, both the messages do not arrive at the same time and the system has to wait until both the messages have arrived and then combine them and subsequently push them to the front-end.

I have been able to get it working using an in-memory map that stores the messages indexed by timestamp and checks if both the messages have arrived. If they haven't, it waits for a certain time before sending the messages. The message delivery is expected to be in order and the data from the first service cannot be dropped.

```<code>const messageQueue = new Map();

monitoringServiceOne.on('message', function (topic, message) {
   synchroniseMessages(topic, message);
});

monitoringServiceTwo.on('message', function (topic, message) {
   synchroniseMessages(topic, message);
});

function synchroniseMessages(topicName, incomingMessage) {

    if (topicName == "ServiceOne") {
        const message = messageQueue.get(message.time);

        // If message exists, it means service two message has been received
        if (message) {
            pushToFE({ ... { message }, "ServiceOne": incomingMessage })
        } else {
            setTimeout(() => {
                const message = messageQueue.get(message.time);
                if (message) {
                    pushToFE({ ... { message }, "ServiceOne": incomingMessage })
                }
            }, DELAY)
        }
        messageQueue.set(message.time, { "ServiceOne": incomingMessage });
    } else {
        const message = messageQueue.get(message.time);

        // If message exists, it means service one message has been received
        if (message) {
            pushToFE({ ... { message }, "ServiceTwo": incomingMessage })
        } else {
            messageQueue.set(message.time, { "ServiceTwo": incomingMessage });
        }
    }

}
</code>```

Even though this is working, I feel like reinventing the wheel. Are there any existing ZeroMQ paradigms or patterns that I can use to improve the code? I have been looking for an event-driven pattern that allows me just define the logic for the sink.

答:
The short answer is no, there's nothing in ZMQ that'll do that for you. It's an actor model system, and all it does is guarantee that whole messages will turn up in the order they were sent machine to machine. There are no timing guarantees.

For example, if there is a PUB / SUB setup and there are two or more PUBlishers (an allowed combo I think), the time order in which messages are PUBlished by different PUBlishers does not necessarily result in them arriving in that order in the SUBscriber. But it does guarantee that multiple messages sent by any one of those PUBlishers won't get swapped around in transit.

So, if your ServiceOne and ServiceTwo were PUBlishers on the same ZMQ socket, you could not be confident of getting messages in the order 1a, 2a, 1b, 2b, 1c, 2c, 1d, 2d, 1e, 2e, 1f, 2f, 1g, 2g. They could arrive as 1a, 2a, 1b, 1c, 2b, 2c, 2d, 1d, 2e, 1e, 1f, 2f, 1g, 2g. The numbers need not be in order, but the letters for any one given number will be.

I like the idea of using a map (a dictionary? My node.js knowledge is very limited...), elegant. Presumably, you'd have to have something to prune the map now and then, e.g. if ServiceOne got disconnected for a while the map could get quite large.

Er, is it supposed to be incomingMessage.time that's used in the call to messageQueue.get(), so messageQueue.get(incomingMessage.time), and similar for the messageQueue.set()?

Body:
I'm trying to create a stock monitoring application. I have two ZeroMQ publishers running that get the current stock price from two respective services. The first service is the major source of information and no message from the service can be dropped.

I want to combine the two prices into one object and push it to the front-end.
Each message has a timestamp that indicates the time of the observation of the price and is the basis of combining the messages.

However, both the messages do not arrive at the same time and the system has to wait until both the messages have arrived and then combine them and subsequently push them to the front-end.

I have been able to get it working using an in-memory map that stores the messages indexed by timestamp and checks if both the messages have arrived. If they haven't, it waits for a certain time before sending the messages. The message delivery is expected to be in order and the data from the first service cannot be dropped.

const messageQueue = new Map();

monitoringServiceOne.on('message', function (topic, message) {
   synchroniseMessages(topic, message);
});

monitoringServiceTwo.on('message', function (topic, message) {
   synchroniseMessages(topic, message);
});

function synchroniseMessages(topicName, incomingMessage) {

    if (topicName == "ServiceOne") {
        const message = messageQueue.get(message.time);

        // If message exists, it means service two message has been received
        if (message) {
            pushToFE({ ... { message }, "ServiceOne": incomingMessage })
        } else {
            setTimeout(() => {
                const message = messageQueue.get(message.time);
                if (message) {
                    pushToFE({ ... { message }, "ServiceOne": incomingMessage })
                }
            }, DELAY)
        }
        messageQueue.set(message.time, { "ServiceOne": incomingMessage });
    } else {
        const message = messageQueue.get(message.time);

        // If message exists, it means service one message has been received
        if (message) {
            pushToFE({ ... { message }, "ServiceTwo": incomingMessage })
        } else {
            messageQueue.set(message.time, { "ServiceTwo": incomingMessage });
        }
    }

}

Even though this is working, I feel like reinventing the wheel. Are there any existing ZeroMQ paradigms or patterns that I can use to improve the code? I have been looking for an event-driven pattern that allows me just define the logic for the sink.


问:
How to search for array of string in each row of another column and get the count in excel
I have a excel with a column Address and another lookup column(List) containing list of lookup strings:-

Address

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom

Baldock Street;  Newton;  ML12   6PZ; United Kingdom

I want to search for all the strigns in List in Address column and return the count of strings matching
What I want to achieve :-

Address
Count_Flag

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom
1

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom
1

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom
1

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom
1

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom
2

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom
1

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom
2

Baldock Street;  Newton;  ML12   6PZ; United Kingdom
1

I tried something like this :

```<code>=--ISNUMBER(SEARCH(@$D$2:$D$6,A2))
</code>```

答:
You can simply use this formula as shown in image below

Formula Used In Cell B2

```<code>=SUMPRODUCT(--ISNUMBER(SEARCH($D$2:$D$6,$A2)))
</code>```

Break Down Of Each Function Used In The Formula:-

```<code>SEARCH($D$2:$D$6,$A2)
</code>```

The SEARCH function returns the position of one text string inside another. SEARCH returns the location of the first character of find_text inside within_text. Unlike FIND, SEARCH allows wildcards, and is not case-sensitive.

```<code>{#VALUE!;#VALUE!;#VALUE!;#VALUE!;45}
</code>```

This is what it return when you select and press F9, i.e. the position

Next, we need to check whether its a number or not, so we use the below

```<code>ISNUMBER(SEARCH($D$2:$D$6,$A2))
</code>```

And Returns an array of TRUE's And FALSE's

```<code>{FALSE;FALSE;FALSE;FALSE;TRUE}
</code>```

To Convert the same into BOOLEAN VALUES we use double negative which coerces TRUE or FALSE values to their numeric equivalents, 1 and 0

```<code>--ISNUMBER(SEARCH($D$2:$D$6,$A2))
</code>```

The above converts to 1 & 0

```<code>{0;0;0;0;1}
</code>```

Now we can simply wrap the whole within SUMPRODUCT to get the counts

Body:
I have a excel with a column Address and another lookup column(List) containing list of lookup strings:-

Address

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom

Baldock Street;  Newton;  ML12   6PZ; United Kingdom

I want to search for all the strigns in List in Address column and return the count of strings matching
What I want to achieve :-

Address
Count_Flag

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom
1

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom
1

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom
1

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom
1

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom
2

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom
1

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom
2

Baldock Street;  Newton;  ML12   6PZ; United Kingdom
1

I tried something like this :

=--ISNUMBER(SEARCH(@$D$2:$D$6,A2))

Body:
You can simply use this formula as shown in image below

Formula Used In Cell B2

=SUMPRODUCT(--ISNUMBER(SEARCH($D$2:$D$6,$A2)))

Break Down Of Each Function Used In The Formula:-

SEARCH($D$2:$D$6,$A2)

The SEARCH function returns the position of one text string inside another. SEARCH returns the location of the first character of find_text inside within_text. Unlike FIND, SEARCH allows wildcards, and is not case-sensitive.

{#VALUE!;#VALUE!;#VALUE!;#VALUE!;45}

This is what it return when you select and press F9, i.e. the position

Next, we need to check whether its a number or not, so we use the below

ISNUMBER(SEARCH($D$2:$D$6,$A2))

And Returns an array of TRUE's And FALSE's

{FALSE;FALSE;FALSE;FALSE;TRUE}

To Convert the same into BOOLEAN VALUES we use double negative which coerces TRUE or FALSE values to their numeric equivalents, 1 and 0

--ISNUMBER(SEARCH($D$2:$D$6,$A2))

The above converts to 1 & 0

{0;0;0;0;1}

Now we can simply wrap the whole within SUMPRODUCT to get the counts


问:
Setinterval is stop working when tab is idle or working on another tab,
I have created a solution for sessiontimeout popup, to check idle time I am using a setInterval as mentioned below

```<code>    // Increment the idle time counter every 1 second.
    idleInterval = setInterval(timerIncrement, 2000, (@warningShowDelayMinutes * 60), (@sessionTimeout * 60), @warningTimeLeft);

function timerIncrement(warningShowDelay, sessionTimeout) {
        idleTime++;
        console.log("before dialog open idleTime - :" + idleTime);
        if (idleTime >= warningShowDelay && idleTime <= sessionTimeout) {
            var isWarningPopupOpened = $('#session-expire-warning').dialog('isOpen');
            if (!isWarningPopupOpened) {
                $("#session-expire-warning").dialog("open");
                //console.log("before dialog after idleTime -:" + idleTime);
            }
        }
    }
</code>```

but when we move to another tab/ another window, setInterval stops working,
I also tried with requestAnimationFrame but it also stop working after we move to another tab or window as mentioned below.

```<code>var last = 0;
function timerIncrement(now) {
     if (!last || now - last >= 1000) {
        last = now;
        //createNewObject();

        idleTime++;
        console.log("before dialog open idleTime - :" + idleTime);
        if (idleTime >= (@warningShowDelayMinutes * 60) && idleTime <=  (@sessionTimeout * 60)) {
            var isWarningPopupOpened = $('#session-expire-warning').dialog('isOpen');
            if (!isWarningPopupOpened) {
                $("#session-expire-warning").dialog("open");
                console.log("before dialog after idleTime -:" + idleTime);
            }
        }
        }
        requestAnimationFrame(timerIncrement);
    }
    requestAnimationFrame(timerIncrement);
</code>```

can anyone help on this to continue the setinetrval or requestAnimationFrame after tab switching ? I am new to javascripts

答: You can use the worker-timers NPM package to overcome this hurdle. It uses Web worker to prevent the timer(s) being throttled by the browser.</p>

Body:
I have created a solution for sessiontimeout popup, to check idle time I am using a setInterval as mentioned below

    // Increment the idle time counter every 1 second.
    idleInterval = setInterval(timerIncrement, 2000, (@warningShowDelayMinutes * 60), (@sessionTimeout * 60), @warningTimeLeft);

function timerIncrement(warningShowDelay, sessionTimeout) {
        idleTime++;
        console.log("before dialog open idleTime - :" + idleTime);
        if (idleTime >= warningShowDelay && idleTime <= sessionTimeout) {
            var isWarningPopupOpened = $('#session-expire-warning').dialog('isOpen');
            if (!isWarningPopupOpened) {
                $("#session-expire-warning").dialog("open");
                //console.log("before dialog after idleTime -:" + idleTime);
            }
        }
    }

but when we move to another tab/ another window, setInterval stops working,
I also tried with requestAnimationFrame but it also stop working after we move to another tab or window as mentioned below.

var last = 0;
function timerIncrement(now) {
     if (!last || now - last >= 1000) {
        last = now;
        //createNewObject();

        idleTime++;
        console.log("before dialog open idleTime - :" + idleTime);
        if (idleTime >= (@warningShowDelayMinutes * 60) && idleTime <=  (@sessionTimeout * 60)) {
            var isWarningPopupOpened = $('#session-expire-warning').dialog('isOpen');
            if (!isWarningPopupOpened) {
                $("#session-expire-warning").dialog("open");
                console.log("before dialog after idleTime -:" + idleTime);
            }
        }
        }
        requestAnimationFrame(timerIncrement);
    }
    requestAnimationFrame(timerIncrement);

can anyone help on this to continue the setinetrval or requestAnimationFrame after tab switching ? I am new to javascripts


问:
order by using join in php
I have two tables Products and Userproducts.
Products table having columns:
id,name,description
and Userproducts table have following columns id,user_id,product_id.
Current query is

```<code>SELECT Products.id,Userproducts.user_id
FROM Products
LEFT JOIN UserProducts ON Productsid = Userproducts.product_id;
</code>```

Now i want to show those products at the top whose users_id = 1 and other products will come after users products

答:
You can add conditional order by clause as</p>
```<code>SELECT p.id,u.user_id
FROM Products p
LEFT JOIN UserProducts u ON p.id = u.product_id
ORDER BY u.user_id = 1 desc, u.user_id asc
</code>```

Title: order by using join in php

Body:
I have two tables Products and Userproducts.
Products table having columns:
id,name,description
and Userproducts table have following columns id,user_id,product_id.
Current query is

SELECT Products.id,Userproducts.user_id
FROM Products
LEFT JOIN UserProducts ON Productsid = Userproducts.product_id;

Now i want to show those products at the top whose users_id = 1 and other products will come after users products

Body:
You can add conditional order by clause as

SELECT p.id,u.user_id
FROM Products p
LEFT JOIN UserProducts u ON p.id = u.product_id
ORDER BY u.user_id = 1 desc, u.user_id asc


问:
What do you recommend for accepting in-browser user drawings?
I need to write an application that accepts very simple doodles by users, kind of like in tenthousandcents and thesheepmarket.

For example, I might want users to write their name using their mouse.

Any suggestions?

I don't even need to host it myself. If there are services offered somewhere that I can just use that is fine.

答:
So far, the best and easiest solution I have found is to use something like this:
http://www.flashnifties.com/flash_guestbook.php</p>

OwnerDisplayName: carrier

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mmyers


问:
Inserting a script dynamically in the DOM
I'm trying to understand why this code doesn't work and the alert output is just blank.

```<code><script type="text/javascript">
(function() {
  ...
  var s = document.getElementsByTagName('script')[0]; alert(s.innerHTML);
  s.parentNode.insertBefore(res, s);
  ...
})();
</script>
</code>```

It should add res before s if I'm not wrong. That's what I specifically need, as I tried to append it to body and it's added successfully (after doing that though I have to run some code inside this function, so if the script is not loaded before it, such code will error).

This function should run when document is loaded or is that the problem? In particular, the getElementsByTagName function seems to not return anything.

Thanks to everyone.

答:
You cannot run this type of code before the document is loaded.  This code has to be loaded before it can be run (see the circular argument here).  And, by then, much of the rest of the document has been loaded.  You can dynamically load scripts AFTER the document has been loaded.  If you need a script loaded before other scripts, then you either have to put them all in the document statically in the order you need them to be run or you need to add them all dynamically in the order you need them to run and you will need to keep track of completion of one load before loading the next.

If you care to describe the broader problem you're trying to solve, we can probably suggest a more elegant solution than what you are pursuing.

Body:
I'm trying to understand why this code doesn't work and the alert output is just blank.

It should add res before s if I'm not wrong. That's what I specifically need, as I tried to append it to body and it's added successfully (after doing that though I have to run some code inside this function, so if the script is not loaded before it, such code will error).

This function should run when document is loaded or is that the problem? In particular, the getElementsByTagName function seems to not return anything.

Thanks to everyone.


问:
How to Validate InputQuery user input before the user clicks OK?
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I show an INPUT DIALOG to the user:

```<code>  var aNewFolderName: string := 'New Project Folder';
  if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
  begin
    // Todo: Create the folder if everything went OK, ELSE REPEAT the input action :-(
  end;
</code>```

Is there a way to VALIDATE the user's input BEFORE he clicks the OK button? (E.g., checking for not allowed characters, existing folder, etc.). Just repeating the whole input action in the case of invalid input AFTER the user clicked OK is not very smart and efficient:

```<code>  var aNewFolderName: string := 'New Project Folder';
  var InputIsValid: Boolean;
  repeat
    if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
    begin
      InputIsValid := CheckInput(aNewFolderName);
      if InputIsValid then CreateTheFolder(aNewFolderName);
    end
    else
      BREAK;
  until InputIsValid;
</code>```

Also, with this method, there is no feedback for the user about the specific cause of any invalid input.

答:
Thanks to the users who explicitly confirmed that there is no predesigned way to validate the input before the user clicks OK. Now the remaining question is: How to provide a meaningful and efficient feedback about the invalidation cause to the user? IMO, showing an ADDITIONAL error dialog does not meet these criteria. So I implemented a solution where the prompt is replaced by the validation error message in the reappearing InputQuery dialog:

```<code>procedure TformMain.menuitemCreateASubProjectGroupClick(Sender: TObject);
begin
  var aNewFolderName: string := 'New Project Group';
  var InputIsValid: Boolean;
  var InputPrompt: string := 'Enter the name of the new Project Group:';
  repeat
    if Vcl.Dialogs.InputQuery('New Project Group', InputPrompt, aNewFolderName) then
    begin
      var NewPrompt: string;
      InputIsValid := CheckInput(aNewFolderName, NewPrompt);
      if not InputIsValid then
        InputPrompt := NewPrompt
      else
      begin
        CreateNewFolder(aNewFolderName);
      end;
    end
    else
      BREAK;
  until InputIsValid;
end;

function PAIsFilenameValid(const AFilename: string; var errorchar: Char): Boolean;
begin
  Result := True;

  for var i := 1 to Length(AFilename) do
  begin
    if not System.IOUtils.TPath.IsValidFileNameChar(AFilename[i]) then
    begin
      errorchar := AFilename[i];
      Result := False;
      BREAK;
    end;
  end;
end;

function TformMain.CheckInput(const aNewFolderName: string; out aNewPrompt: string): Boolean;
begin
  Result := True;
  var errorchar: Char;
  if Trim(aNewFolderName) = '' then
  begin
    aNewPrompt := 'Error: You must enter a Group name:';
    Result := False;
  end
  else if not PAIsFilenameValid(aNewFolderName, errorchar) then
  begin
    aNewPrompt := 'Error: No illegal characters (' + errorchar + '):';
    Result := False;
  end;
  // Todo: else...
end;
</code>```

Example screenshots:

Body:
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I show an INPUT DIALOG to the user:

  var aNewFolderName: string := 'New Project Folder';
  if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
  begin
    // Todo: Create the folder if everything went OK, ELSE REPEAT the input action :-(
  end;

Is there a way to VALIDATE the user's input BEFORE he clicks the OK button? (E.g., checking for not allowed characters, existing folder, etc.). Just repeating the whole input action in the case of invalid input AFTER the user clicked OK is not very smart and efficient:

  var aNewFolderName: string := 'New Project Folder';
  var InputIsValid: Boolean;
  repeat
    if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
    begin
      InputIsValid := CheckInput(aNewFolderName);
      if InputIsValid then CreateTheFolder(aNewFolderName);
    end
    else
      BREAK;
  until InputIsValid;

Also, with this method, there is no feedback for the user about the specific cause of any invalid input.

Body:
Thanks to the users who explicitly confirmed that there is no predesigned way to validate the input before the user clicks OK. Now the remaining question is: How to provide a meaningful and efficient feedback about the invalidation cause to the user? IMO, showing an ADDITIONAL error dialog does not meet these criteria. So I implemented a solution where the prompt is replaced by the validation error message in the reappearing InputQuery dialog:

procedure TformMain.menuitemCreateASubProjectGroupClick(Sender: TObject);
begin
  var aNewFolderName: string := 'New Project Group';
  var InputIsValid: Boolean;
  var InputPrompt: string := 'Enter the name of the new Project Group:';
  repeat
    if Vcl.Dialogs.InputQuery('New Project Group', InputPrompt, aNewFolderName) then
    begin
      var NewPrompt: string;
      InputIsValid := CheckInput(aNewFolderName, NewPrompt);
      if not InputIsValid then
        InputPrompt := NewPrompt
      else
      begin
        CreateNewFolder(aNewFolderName);
      end;
    end
    else
      BREAK;
  until InputIsValid;
end;

function PAIsFilenameValid(const AFilename: string; var errorchar: Char): Boolean;
begin
  Result := True;

  for var i := 1 to Length(AFilename) do
  begin
    if not System.IOUtils.TPath.IsValidFileNameChar(AFilename[i]) then
    begin
      errorchar := AFilename[i];
      Result := False;
      BREAK;
    end;
  end;
end;

function TformMain.CheckInput(const aNewFolderName: string; out aNewPrompt: string): Boolean;
begin
  Result := True;
  var errorchar: Char;
  if Trim(aNewFolderName) = '' then
  begin
    aNewPrompt := 'Error: You must enter a Group name:';
    Result := False;
  end
  else if not PAIsFilenameValid(aNewFolderName, errorchar) then
  begin
    aNewPrompt := 'Error: No illegal characters (' + errorchar + '):';
    Result := False;
  end;
  // Todo: else...
end;

Example screenshots:


问:
Accessing information - Array of pointers
```<code>int* a[2];
int x = 5;
int y = 7;
int *b = x;
int *c = y;
a[0] = b;
a[1] = c;
printf("%d", *a[1]);
</code>```

Why isn't this working?
This is an Array of pointers and I'm trying to get the value of y - a[1] is the address of y so I added a * to get the value of it..
Thanks everyone!

答:
```<code>int *b = x;
int *c = y;
</code>```

The problem here is that your are assigning the values of the objects x and y instead of their address.

You can get the address of an object using the address-of operator &.

Body:
int* a[2];
int x = 5;
int y = 7;
int *b = x;
int *c = y;
a[0] = b;
a[1] = c;
printf("%d", *a[1]);

Why isn't this working?
This is an Array of pointers and I'm trying to get the value of y - a[1] is the address of y so I added a * to get the value of it..
Thanks everyone!

Body:
int *b = x;
int *c = y;

The problem here is that your are assigning the values of the objects x and y instead of their address.

You can get the address of an object using the address-of operator &.