问:
Center a modal vertically with scroll for large content
I have the following CSS and HTML for a Modal:

div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
}

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Page main content</h1>

<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png"/>

<div class="backdrop">

  <div class="modal">

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

  </div>

</div></code>```

How to center the modal vertically, leaving a margin on top and bottom?

And when the content is to height the modal content should scroll and not the modal itself as it is now.

答:
First Question:

How to center the modal vertically, leaving a margin on top and bottom?

The easiest way to do this would be to make a Flexbox out of the modal's parent. This way you can center the modal vertically and horizontally for sure.

```<code>div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
  display: flex;  //Added this
  justify-content: center;  //Added this
  align-items: center;  //Added this
}
</code>```

To leave a margin at the top and bottom you will have to set a max-height for your modal.

```<code>div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px); //Added this so there will always be 20px free space on the top and bottom.
}
</code>```

div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
  display: flex;
  justify-content: center;
  align-items: center;
}

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Page main content</h1>

<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png" />

<div class="backdrop">

  <div class="modal">

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

  </div>

</div></code>```

But you can see a small problem. The text is overshooting at the bottom which leads us to your second question:

Second question:

And when the content is to height the modal content should scroll and not the modal itself as it is now.

To do this and to combat the problem described above let's add a scroll bar:

```<code>div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px); //Added this so there will always be 20px free space on the top and bottom.
  overflow-x: auto; //Added this to add the scroll bar
}
</code>```

This is the final (working) result:

div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
  display: flex;
  justify-content: center;
  align-items: center;
}

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Page main content</h1>

<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png" />

<div class="backdrop">

  <div class="modal">

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

  </div>

</div></code>```

Edit:

Actually you have some CSS attributes you don't need. I made a simple example of a modal.

.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Page main content</h1>
<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png" />

<div class="backdrop">
  <div class="modal">
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
  </div>
</div></code>```

The cleanest way I could think of is to also remove the overflow of the body. I also added some closing and opening mechanics:

function openmodal() {
  document.querySelector("body").classList.toggle("overflow-hidden");
  document.querySelector(".backdrop").style.display = "flex";
}

function closemodal() {
  if (event.target == document.querySelector(".backdrop")) {
    document.querySelector("body").classList.toggle("overflow-hidden");
    document.querySelector(".backdrop").style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: auto;
}

.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  display: none;
  justify-content: center;
  align-items: center;
}

.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
  overflow: auto;
}

.overflow-hidden {
  overflow: hidden;
}</code>```

Page main content

<button onclick="openmodal()">
Clik me
</button>

  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

```

Body:
I have the following CSS and HTML for a Modal:

div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
}

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
}

Page main content

  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

How to center the modal vertically, leaving a margin on top and bottom?

And when the content is to height the modal content should scroll and not the modal itself as it is now.

Body:
First Question:

How to center the modal vertically, leaving a margin on top and bottom?

The easiest way to do this would be to make a Flexbox out of the modal's parent. This way you can center the modal vertically and horizontally for sure.

div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
  display: flex;  //Added this
  justify-content: center;  //Added this
  align-items: center;  //Added this
}

To leave a margin at the top and bottom you will have to set a max-height for your modal.

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px); //Added this so there will always be 20px free space on the top and bottom.
}

div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
  display: flex;
  justify-content: center;
  align-items: center;
}

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
}

<h1>Page main content</h1>

<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png" />

<div class="backdrop">

  <div class="modal">

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

  </div>

</div>

But you can see a small problem. The text is overshooting at the bottom which leads us to your second question:

Second question:

And when the content is to height the modal content should scroll and not the modal itself as it is now.

To do this and to combat the problem described above let's add a scroll bar:

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px); //Added this so there will always be 20px free space on the top and bottom.
  overflow-x: auto; //Added this to add the scroll bar
}

This is the final (working) result:

div.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  height: 100%;
  left: 0;
  overflow: auto;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 2020;
  display: flex;
  justify-content: center;
  align-items: center;
}

div.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
  overflow: auto;
}

<h1>Page main content</h1>

<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png" />

<div class="backdrop">

  <div class="modal">

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>

    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>

  </div>

</div>

Edit:

Actually you have some CSS attributes you don't need. I made a simple example of a modal.

.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
  overflow: auto;
}

<h1>Page main content</h1>
<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png" />

<div class="backdrop">
  <div class="modal">
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
  </div>
</div>

The cleanest way I could think of is to also remove the overflow of the body. I also added some closing and opening mechanics:

function openmodal() {
  document.querySelector("body").classList.toggle("overflow-hidden");
  document.querySelector(".backdrop").style.display = "flex";
}

function closemodal() {
  if (event.target == document.querySelector(".backdrop")) {
    document.querySelector("body").classList.toggle("overflow-hidden");
    document.querySelector(".backdrop").style.display = "none";
  }
}

body {
  overflow: auto;
}

.backdrop {
  background-color: rgba(0, 0, 0, 0.4);
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  display: none;
  justify-content: center;
  align-items: center;
}

.modal {
  background-color: white;
  border: 1px solid red;
  margin: 10% auto;
  max-width: 800px;
  width: 80%;
  max-height: calc(100% - 40px);
  overflow: auto;
}

.overflow-hidden {
  overflow: hidden;
}

<h1>Page main content</h1>
<button onclick="openmodal()">
Clik me
</button>
<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>
<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<img src="https://via.placeholder.com/800x120.png" />

<div class="backdrop" onclick="closemodal()">
  <div class="modal">
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <p>
      It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    </p>
  </div>
</div>


来源: stackexchange

问:
How to parse variable length command line arguments with regex?
I have a large number of files that each contain a bash command with a variable amount of parameters. I need to replace these with a corresponding API call.

Example bash command in file (Note: number of '-p' arguments vary, some have none):

```<code>./some_script.sh http://some.server.com -p a=value -p b=value -p c=value
</code>```

Example corresponding API call

```<code>http://some.server.com/api/some/endpoint?a=value&b=value&c=value
</code>```

My issue is I can't seem to group each parameter, given that the number of parameters is variable.

Basic regex (this will match above example, but only group first parameter):

```<code>.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)
</code>```

And I tried:

```<code>.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)*
</code>```

However, this seems to only group the last parameter.
(tested with regex101)

Ideally, I would like this regex to be able to group an indefinite number of arguments in these files so that I can easily rebuild the command as an API call.

If more detail is required please let me know, any suggestions are welcome.

答:
You need to use the \G anchor

```<code>/(?|\.\/some_script\.sh\s([\w\/:.]*)|(?!^)\G())\s-(\w)\s([\w=]*)/
</code>```

https://regex101.com/r/0151qC/1

Expanded

```<code> (?|                           # Branch reset
      \. /some_script \. sh         # First, find the script name
      \s
      ( [\w/:.]* )                  # (1), url

   |                              # or,
      (?! ^ )
      \G                            # Start where last left off
      ( )                           # (1), blank url

 )

 \s -
 ( \w )                        # (2), - 'p'
 \s
 ( [\w=]* )                    # (3), 'a=value'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a large number of files that each contain a bash command with a variable amount of parameters. I need to replace these with a corresponding API call.

Example bash command in file (Note: number of '-p' arguments vary, some have none):

./some_script.sh http://some.server.com -p a=value -p b=value -p c=value

Example corresponding API call

http://some.server.com/api/some/endpoint?a=value&b=value&c=value

My issue is I can't seem to group each parameter, given that the number of parameters is variable.

Basic regex (this will match above example, but only group first parameter):

.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)

And I tried:

.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)*

However, this seems to only group the last parameter.
(tested with regex101)

Ideally, I would like this regex to be able to group an indefinite number of arguments in these files so that I can easily rebuild the command as an API call.

If more detail is required please let me know, any suggestions are welcome.

Body:
You need to use the \G anchor

/(?|\.\/some_script\.sh\s([\w\/:.]*)|(?!^)\G())\s-(\w)\s([\w=]*)/

https://regex101.com/r/0151qC/1

Expanded

 (?|                           # Branch reset
      \. /some_script \. sh         # First, find the script name
      \s
      ( [\w/:.]* )                  # (1), url

   |                              # or,
      (?! ^ )
      \G                            # Start where last left off
      ( )                           # (1), blank url

 )

 \s -
 ( \w )                        # (2), - 'p'
 \s
 ( [\w=]* )                    # (3), 'a=value'


问:
How to print qlist for below piece of code
I have QList < class > type . I want to print the Qlist how can i do it??

Declaration of QList:

QList < SidSafetyPacketIn > a_safetyPackets;
```

<p>Now Data appended for QList like below:</p>

<pre class="lang-cpp prettyprint-override"><code>a_safetyPackets.append(SidSafetyPacketIn(pSpdFrom1To4Model, expectedSids[i], i));
</code>```

Now if i want to print the above QList how to do it?

答:
If the SidSafetyPacketIn class is printable,you can print QList simply use foreach() function,a example like this:

```<code>QList<QString>lst;
lst.append("haha");
lst.append("bigg");
foreach(auto &x,lst)
    qDebug()<<x;
</code>```

and the output is:

```<code>"haha"
"bigg"
</code>```

Body:
I have QList < class > type . I want to print the Qlist how can i do it??

Declaration of QList:

QList < SidSafetyPacketIn > a_safetyPackets;

Now Data appended for QList like below:

a_safetyPackets.append(SidSafetyPacketIn(pSpdFrom1To4Model, expectedSids[i], i));

Now if i want to print the above QList how to do it?

Body:
If the SidSafetyPacketIn class is printable,you can print QList simply use foreach() function,a example like this:

QList<QString>lst;
lst.append("haha");
lst.append("bigg");
foreach(auto &x,lst)
    qDebug()<<x;

and the output is:

"haha"
"bigg"


问:
Get emails, not MS Teams messages from MS Graph
When I GET https://graph.microsoft.com/v1.0/me/messages, it returns messages I received in MS Teams.

How can I query for only emails using the MS Graph API?

答:
As AAvery said, I believe as well that Teams send you the messages to your Outlook after a while of inactivity. Try to remove those emails(notifications) from MS Teams and try to GET again.

Eventually, try this: https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/messages/delta


问:
Why wouldn't an S3 ACL "stick"?
We would like to set an ACL to allow access to one of our buckets with a partner account. We've tested the process on a test account and everything works fine. On our production account/buckets, however, we can set the ACL and see the update but as soon as we attempt to access the bucket from the other account we get a forbidden response. Afterwards, when we look at the ACL list for the bucket, the permission is gone.

We've tried using both Amazon's new S3 tool in the AWS Management Console and CloudBerry Explorer and both tools exhibit exactly the same behavior. Using the same process to update an ACL from our test account works as expected ( the ACL update "sticks" ).

What would cause the ACL to not "stick"? Does anyone have any ideas on how to fix/workaround the problem?

答:
It's been quite a while since I asked this question, and I've since worked around the issue.

As I remember it, it appeared to be that the format for some policies had changed, but the validator still accepted the old format. However, the old-format policy wouldn't be accepted, so the policy wouldn't "stick" properly.

ContentLicense: CC BY-SA 2.5

Title: Why wouldn't an S3 ACL "stick"?

ContentLicense: CC BY-SA 3.0


问:
Can I query for documents and filter some document fields out of the querySnapshot response using Firestore?
Imagine that I have a collection of documents:

collection:
'products'

And inside that collection I have documents, and each document has a really heavy field that I want filtered before it gets sent to my clients.

document product1:

```<code>{
  id: 'someUniqueKey',
  title: 'This is the title',
  price: 35.00,
  heavyField: [
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
</code>```

Can I query for those documents inside the products collection and leave this specific heavyField out of my response?

I would like to be able to get the documents with 1 of their fields filtered out. Maybe select the fields I want to receive on my client.

Is this possible? Or in this case it's best to structure my data different and leave the heavyField in a different collection?

答:
In SQL, this would be called a "projection" in a query.  Cloud Firestore doesn't support projections from web and mobile client SDKs.  You should instead put your "heavy" fields into documents in another collection, and query that only as needed.

If you're wondering why, it partly has to do with the way that the client local persistence layer works.  It would make caching much more complicated if only certain fields existed locally for a given document.  It's much more straightforward to simply fetch and store the entire document, so there is no question whether or not the document is locally available.

For the purpose of data modeling, it's best to think of documents as "atomic units", all or nothing, that can't be broken down.

Body:
Imagine that I have a collection of documents:

collection:
'products'

And inside that collection I have documents, and each document has a really heavy field that I want filtered before it gets sent to my clients.

document product1:

{
  id: 'someUniqueKey',
  title: 'This is the title',
  price: 35.00,
  heavyField: [
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'longStringxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}

Can I query for those documents inside the products collection and leave this specific heavyField out of my response?

I would like to be able to get the documents with 1 of their fields filtered out. Maybe select the fields I want to receive on my client.

Is this possible? Or in this case it's best to structure my data different and leave the heavyField in a different collection?


问:
How to apply a function to an input of integers in Golang
For example, if the input was this

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

all separated by a space, I want to apply the function of squaring each individual number then adding it.

I just don't know how to apply the function to each number. All I can figure is that I have to put the numbers into a slice then apply the function to each of the numbers. I have looked everywhere and can't find out how to do this.

in Python I just do it like this and I already put the values into a list called "n".

```<code>#The list is pasted from the initial puzzle
n=[10, 10, 9, 8, 10, 10, 10]

# The list is first squared
b = (list(map(lambda x:x**2,n)))
</code>```

b becomes the new list where the function is done to each number.

答:
You can do it like this if your integers are actually a string separated by spaces.

```<code>package main

import "fmt"
import "strings"
import "strconv"

func main() {
    numbers := "1 3 4 5"
    var n []int
    for _, v := range strings.Fields(numbers) {
        i, err := strconv.Atoi(v)
        if err != nil {
            fmt.Println(err.Error())
            break
        }
        n = append(n, i*i)
    }
    fmt.Println(n)
}
</code>```

https://play.golang.org/p/JcivNd29Gzg

Body:
For example, if the input was this

1 3 4 5

all separated by a space, I want to apply the function of squaring each individual number then adding it.

I just don't know how to apply the function to each number. All I can figure is that I have to put the numbers into a slice then apply the function to each of the numbers. I have looked everywhere and can't find out how to do this.

in Python I just do it like this and I already put the values into a list called "n".

#The list is pasted from the initial puzzle
n=[10, 10, 9, 8, 10, 10, 10]

# The list is first squared
b = (list(map(lambda x:x**2,n)))

b becomes the new list where the function is done to each number.

Body:
You can do it like this if your integers are actually a string separated by spaces.

package main

import "fmt"
import "strings"
import "strconv"

func main() {
    numbers := "1 3 4 5"
    var n []int
    for _, v := range strings.Fields(numbers) {
        i, err := strconv.Atoi(v)
        if err != nil {
            fmt.Println(err.Error())
            break
        }
        n = append(n, i*i)
    }
    fmt.Println(n)
}

https://play.golang.org/p/JcivNd29Gzg


问:
Transferring objects across service provider scopes
I have a CorrelationIdMiddleware that is inspecting incoming request headers and setting a scoped CorrelationId later propagated to all HttpClients.

```<code>public class CorrelationId {
    public string Value { get;set; }
}

public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddScoped<CorrelationId>();
    ...
}
</code>```

I have run into a use case where I need to create an isolated scope around a section of code, but would like the CorrelationId from the scope of the http request to propagate into the isolated scope (The isolated scope has an HttpClient which I would like to have the same header attached).

I would like to spawn off a background Task that is created from DI w/ any required dependencies and for any HttpClients to have headers injected via HttpClientFactory plugins.

```<code>public Controller {

    public Controller(IServiceProvider serviceProvider, CorrelationId correlationId) { ... }

    public IActionResult PostTask() {
        var isolatedScope = _serviceProvider.CreateScope();

        var action = () => {
            using(isolatedScope) {
                var backgroundJob = isolatedScope
                    .ServiceProvider
                    .GetRequiredService<IBackgroundJob>();
                backgroundJob.Execute();

                // scopedCorrelationId  =/= correlationId
                // how can i get correlationId to jump scopes?
            }
        };

        return Task.Factory.StartNew(
            action,
            CancellationToken.None,
            TaskCreationOptions.LongRunning,
            TaskScheduler.Default);
    }
}
</code>```

Is there a way to transfer certain objects into the isolated scope? Ideally without having to know the typeof(object) i need to transfer.

答:
It is not possible to transfer objects between the parent scope and the isolated scope.

Information like the CorrelationId arriving with the headers of a request better fits with the HttpContext or with an AsyncLocal variable if it needs to be propagated through an async execution flow.

Body:
I have a CorrelationIdMiddleware that is inspecting incoming request headers and setting a scoped CorrelationId later propagated to all HttpClients.

public class CorrelationId {
    public string Value { get;set; }
}

public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddScoped<CorrelationId>();
    ...
}

I have run into a use case where I need to create an isolated scope around a section of code, but would like the CorrelationId from the scope of the http request to propagate into the isolated scope (The isolated scope has an HttpClient which I would like to have the same header attached).

I would like to spawn off a background Task that is created from DI w/ any required dependencies and for any HttpClients to have headers injected via HttpClientFactory plugins.

public Controller {

    public Controller(IServiceProvider serviceProvider, CorrelationId correlationId) { ... }

    public IActionResult PostTask() {
        var isolatedScope = _serviceProvider.CreateScope();

        var action = () => {
            using(isolatedScope) {
                var backgroundJob = isolatedScope
                    .ServiceProvider
                    .GetRequiredService<IBackgroundJob>();
                backgroundJob.Execute();

                // scopedCorrelationId  =/= correlationId
                // how can i get correlationId to jump scopes?
            }
        };

        return Task.Factory.StartNew(
            action,
            CancellationToken.None,
            TaskCreationOptions.LongRunning,
            TaskScheduler.Default);
    }
}

Is there a way to transfer certain objects into the isolated scope? Ideally without having to know the typeof(object) i need to transfer.


问:
Why are word embeddings with linguistic features (e.g. Sense2Vec) not used?
Given that embedding systems such as Sense2Vec incorporate linguistic features such as part-of-speech, why are these embeddings not more commonly used?

Across popular work in NLP today, Word2Vec and GloVe are the most commonly used word embedding systems. Despite the fact that they only incorporate word information and does not have linguistic features of the words.

For example, in sentiment analysis, text classification or machine translation tasks, it makes logical sense that if the input incorporates linguistic features as well, performance could be improved. Particular when disambiguating words such as "duck" the verb and "duck" the noun.

Is this thinking flawed? Or is there some other practical reason why these embeddings are not more widely used.

答:
It's a very subjective question.  One reason is the pos-tagger itself. Pos-tagger is a probabilistic model which could add to the overall error/confusion.

For eg. say you have dense representations for duck-NP and duck-VB but during run/inference time your pos-tagger tags 'duck' as something else then you wont even find it. Moreover it also effectively reduces the total number of times your system sees the word duck hence one could argue that representations generated would be weak.

To top it off the main problem which sense2vec was addressing is contextualisation of word representations which has been solved by contextual representations like BERT and ElMo etc. without producing any of the above problems.


问:
Dotnet upgrade - 2.0 to 3.5 - performance
We have a number of winforms apps that are written in dotnet 2.0.  Are there any performance upgrades that we would expect when taking transistion to 3.5 runtime?  Any particular benefits we will get, besides the language features?</p>

答:
The actual 3.5 framework won't make much of a performance difference.  In many respects, it's just another library.

What will make a difference though is that the 3.5 framework requires CLR 2.0 SP1.  SP1 has a number of performance improvements that will impact your application.  Or 2.0 SP2 if you choose to use 3.5 SP1.

Here is a blog entry on some of the performance impromevents in CLR 2.0 SP2: http://blogs.msdn.com/clrcodegeneration/archive/2007/11/02/how-are-value-types-implemented-in-the-32-bit-clr-what-has-been-done-to-improve-their-performance.aspx

OwnerDisplayName: mek

OwnerDisplayName: JaredPar


问:
Right architecture for using HangFire
I'm about to start using hangfire in C# in a asp.net mvc web application, and wonder how to create the right architecture.

As we are going to use HangFire, we are using it as a messagequeue, so we can process(store in the database) the user data directly and then for instance notify other systems and send email later in a separate process.
So our code now looks like this

```<code>function Xy(Client newClient)
{
_repository.save(newClient);
_crmConnector.notify(newClient);
mailer.Send(repository.GetMailInfo(), newClient)
}
</code>```

And now we want to put the last two lines 'on the queue'

So following the example on the hangfire site we could do this

```<code>var client = new BackgroundJobClient();
client.Enqueue(() => _crmConnector.notify(newClient));
client.Enqueue(() => mailer.Send(repository.GetMailInfo(), newClient));
</code>```

but I was wondering whether that is the right solution.

I once read about putting items on a queue and those were called 'commands', and they were classes especially created to wrap a task/command/thing-to-do and put it on a queue.

So for the notify the crm connector this would then be

```<code>client.Enqueue(() => new CrmNotifyCommand(newClient).Execute();
</code>```

The CrmNotifyCommand would then receive the new client and have the knowledge to execute _crmConnector.notify(newClient).

In this case all items that are put on the queue (executed by HangFire) would be wrapped in a 'command'.
Such a command would then be a self containing class which knows how to execute a kind of business functionality. When the command itself uses more than 1 other class it could also be known as a facade I guess.

What do you think about such an architecture?

答:
I once read about putting items on a queue and those were called
  'commands', and they were classes especially created to wrap a
  task/command/thing-to-do and put it on a queue.

Yes, your intuition is correct.

You should encapsulate all dependencies and explicit functionality in a separate class, and tell Hangfire to simply execute a single method (or command).

Here is my example, that I derived from Blake Connally's Hangfire demo.

```<code>namespace HangfireDemo.Core.Demo
{
    public interface IDemoService
    {
        void RunDemoTask(PerformContext context);
    }

    public class DemoService : IDemoService
    {
        [DisplayName("Data Gathering Task <a href=\"jira.contoso.com\">Confluence Page</a>")]
        public void RunDemoTask(PerformContext context)
        {
            Console.WriteLine("This is a task that ran from the demo service.");
            BackgroundJob.ContinueJobWith(context.BackgroundJob.Id, () => NextJob());
        }

        public void NextJob()
        {
            Console.WriteLine("This is my next task.");
        }
    }
}
</code>```

And then separately, to schedule that command, you'd write something like the following:

```<code>BackgroundJob.Enqueue("demo-job", () => this._demoService.RunDemoTask(null));
</code>```

If you need further clarification, I encourage you to watch Blake Connally's Hangfire demo.

Title: Right architecture for using HangFire

Body:
I'm about to start using hangfire in C# in a asp.net mvc web application, and wonder how to create the right architecture.

As we are going to use HangFire, we are using it as a messagequeue, so we can process(store in the database) the user data directly and then for instance notify other systems and send email later in a separate process.
So our code now looks like this

function Xy(Client newClient)
{
_repository.save(newClient);
_crmConnector.notify(newClient);
mailer.Send(repository.GetMailInfo(), newClient)
}

And now we want to put the last two lines 'on the queue'

So following the example on the hangfire site we could do this

var client = new BackgroundJobClient();
client.Enqueue(() => _crmConnector.notify(newClient));
client.Enqueue(() => mailer.Send(repository.GetMailInfo(), newClient));

but I was wondering whether that is the right solution.

I once read about putting items on a queue and those were called 'commands', and they were classes especially created to wrap a task/command/thing-to-do and put it on a queue.

So for the notify the crm connector this would then be

client.Enqueue(() => new CrmNotifyCommand(newClient).Execute();

The CrmNotifyCommand would then receive the new client and have the knowledge to execute _crmConnector.notify(newClient).

In this case all items that are put on the queue (executed by HangFire) would be wrapped in a 'command'.
Such a command would then be a self containing class which knows how to execute a kind of business functionality. When the command itself uses more than 1 other class it could also be known as a facade I guess.

What do you think about such an architecture?

Body:
I once read about putting items on a queue and those were called
  'commands', and they were classes especially created to wrap a
  task/command/thing-to-do and put it on a queue.

Yes, your intuition is correct.

You should encapsulate all dependencies and explicit functionality in a separate class, and tell Hangfire to simply execute a single method (or command).

Here is my example, that I derived from Blake Connally's Hangfire demo.

namespace HangfireDemo.Core.Demo
{
    public interface IDemoService
    {
        void RunDemoTask(PerformContext context);
    }

    public class DemoService : IDemoService
    {
        [DisplayName("Data Gathering Task <a href=\"jira.contoso.com\">Confluence Page</a>")]
        public void RunDemoTask(PerformContext context)
        {
            Console.WriteLine("This is a task that ran from the demo service.");
            BackgroundJob.ContinueJobWith(context.BackgroundJob.Id, () => NextJob());
        }

        public void NextJob()
        {
            Console.WriteLine("This is my next task.");
        }
    }
}

And then separately, to schedule that command, you'd write something like the following:

BackgroundJob.Enqueue("demo-job", () => this._demoService.RunDemoTask(null));

If you need further clarification, I encourage you to watch Blake Connally's Hangfire demo.


问:
Oracle table column contain $
I'm currently migrating AIX to Linux. The Oracle script contains a $ in the column name. While fetching through the shell script, I set the escape character to $, but it does not work. The query is like below:

```<code>Set escape $

Select c.logoff$time from temp c;
</code>```

When run from shell script I'm getting "c.logoff invalid identifier".

How can I fix this?

答:
This isn't an SQL*Plus (I assume that's your client) problem, so the set escape isn't doing anything - that's for escaping things SQL*Plus tries to interpret - see the docs.

This is a shell issue/feature. the $time part is being treated as a shell variable, and that doesn't exist, so the final table name doesn't have it. You can escape that at shell level, referring to \$time; e.g. if you're using a heredoc:

```<code>sqlplus -s -l usr/pass@db <<EOF

select c.logoff\$time from temp c;

EOF
</code>```

Title: Oracle table column contain $

Body:
I'm currently migrating AIX to Linux. The Oracle script contains a $ in the column name. While fetching through the shell script, I set the escape character to $, but it does not work. The query is like below:

Set escape $

Select c.logoff$time from temp c;

When run from shell script I'm getting "c.logoff invalid identifier".

How can I fix this?

Body:
This isn't an SQL*Plus (I assume that's your client) problem, so the set escape isn't doing anything - that's for escaping things SQL*Plus tries to interpret - see the docs.

This is a shell issue/feature. the $time part is being treated as a shell variable, and that doesn't exist, so the final table name doesn't have it. You can escape that at shell level, referring to \$time; e.g. if you're using a heredoc:

sqlplus -s -l usr/pass@db <<EOF

select c.logoff\$time from temp c;

EOF


答:
Use zgrep not grep on .gz files.

zgrep - search possibly compressed files for a regular expression

Title: Using grep to extract reads from nanopore fastq files

Body:
I'm trying to extract the a specific sequence from a fastq file using grep to search the sequence ID

less all_barcode03.fastq.gz

@3cb04ae7-2c7b-4da8-8d09-59edb5b8f45c_t  runid=7204dc15205b93bfd6430ca0f3a0218f11ce0787 read=10 ch=120 start_time=2019-04-12T13:55:25Z
TCGGTAGCCACTTCGTTCAGTCAATTTGGGTTGTTTAACCGAGTCTTGTGTGTCCCAGTTACCAGGGTTTTCGCATTTATCGTGAAACGCTTTCGCGTTTTCGTGCGCCGCTTCAGTGATCAGTGAAGATGGGTTTGTGGTGGAATACTCTTGCTGCTCATGGCAAACTTTATGTTGGTTTTCTCATGCATTTGTTTCTCGTAATCCCATACGTCATCCAAAGTCATCTGAAAAAGAGGGAAGGGGTGGATTGTGGGTGAAATGTTGTGTACTCCTCTATAATGGGGCTCAGTTGACAAACAGGTGGAGGAGAGGATCATTTGCTTAAAGGGGTGAGTGAAGCGGAGTTTAAGGATAATTCAAGCTTTTAAAAGTGGCTTTAGAGGTAAAGGGTTAGCTCCCATGACCCACAGGATTTATAGGAGATGGCTCTGAACAAACCAGAGCCACACACACA
+
-%&&($$%%#%,-*),-5(&,$$%$%+).'-(+-4-(')%%$*+-,3...14,7/))/03.06-./-3:8.0(*,/7+*,966006.,(*(,-(&(*,./+--902/./),,,0,-/./,4(+0/,0).0-7048,(+*',*/.)*#(((.0--10764+('(%.3/+$&%&'./4'0.;:6.895778+0/*(28/),(+-/404/*'(),.16517&83+*/0/0.--033**$&'*,''*/,,,/..0.*0*0$##*((($/6&('-,.230/01/2+4,,::8719(*.4.'.26/0(*))0*+,(*+-,-+-.4765-$%&.'%.*/')(&''#-()*21,-.;+3).*,,'557686+(-7;-2:8))(&%%'*)**%&&).6&,*(.-'$'(*2+*0587:0+*+)/*/63--/*('#&)-68664&%534)/13.))'14*+**%%$$#
@69e7e435-a78c-4ec8-94cd-b0c1f3c40c11_t  runid=7204dc15205b93bfd6430ca0f3a0218f11ce0787 read=15 ch=465 start_time=2019-04-12T13:55:25Z
TCGGTACTTCGTTCGGTTGGAGAAGGTGGTGTTGCCGAGTCTTGTGTCCCAGTTACCAGGGTTTTCGCATTTATCGTGGCTTGCTGCGTTTTCGTGCGCCACCGCTTCATGTGTGTGTGTGTGTCTGGTGTTATTACTCACTTGGCAAGCGTGTCTGGACAGCAGCTGTTTGAGTGTTGAGAGCGCTTCTTCTCCAGGAGAAGCGGTTGAGCCTAAGCTGAATCCCCGTCCGTCTTTATCTTCGGACATGCTCTGGATATGCCTGAGGAGGACAATGGAGGAACAGAACAGATGGATGAAGAGCTCATAAAACTGGCACACATGCATCAAAGCCCACCTTCGTCACTCTGATGACCAGTGACTGCCGTTTATTACTGCGATTTACCATGAAGTTATCTGCTTTTTGGGTCAGTTAGTGTGTGTGTGTGTGTGTGTGTGTGTGCCTTTTCTGTCCTCCAGATACTCAGTACTACAGAGGAGCTATTAATACTTACTACATCGATATGTTATGTAATATCATTCTAGCCTGCTACTCCTGTCTTCTGTATACAACTGTCGTCTGTCCCGAATAGCTCCTGGGTGCCCTCTCCTCCATAGTAGCCACAGTTACAGGAATATTACTCTTTATCATAGAAGCGGTATCTAGTAGAACAGTCCTTAGTTAAAATAATAACGGGGTGTGGGCATGTACAGCCTCTGGTATTCCGTTGCTCAGCAGAGCCTCATAACTCTCCTAGTGGCTCAGGAAGGCTGAAACAGGCTGTGTGCACCCAGCCAGCTGGAACTGTGTTTGAGTGCCATCTTGGAATACTGTTTATAAGCGCTCTTAAGTTATATGTGAGGATGGTGGTATTAGATATGGAAGTGTGTAGGAGGAGAAAGAGGAAATAGTGTCATGTTGATATGAACAGTTTGGTCAGTAAAATGAGGGCAGTAAAAAAGTGTTTTAAGCGTTTTGTCGGTCGACAATATGATAATAAAATGCATTTGGTTCACGATAACAAGAAAACAGAAAAGACCAGCAATGAATATTTAGCATTTTTTGTTTGAAAGATGAAACAAATAATTGAAATAGCTGCCAAATATTTGTGAAATGTACTAAATGGTCAGAGTGAAGATGCAGCTTTGAAAAGAAGATTCGGA
+
+&$%)'./-0,*1(&&&%#%&$(&)'%&&%$"#$&+,'*-*1+++5-73+)*/+,32/46552:/-+2025/+-057,$#$$&)/01,)433/2732'&$#&$"$'$((+*+),+,,,*+,,-11)*'&((*"0#"&*((,*.--.&.+-*,)-17861+&%'%)),73:60-/-32:++(('.')+56894,4+)./'%')%$&-,('%#41.'$%&')$0))/2.*04632,20)(+'&&,+7.97825-++**166678950-))%*+,-26-.6,*/(4.$+'+-5/0/.-02/-+)'%+73//245+(&(%%'))(&$#&&(7.:2-0;7014354398')-83/00/04:*330))&#)))-5/(-*++5#./+50-(,0765/1,,8//05/0.:0/%#$&)--+4+)+5575312+1&-')).'+&*%)(,,,((%++/,.2486112'&#$&##$%'(*+,1/)/+...+-.1312/1+**-(-.8---,*+,-.5,1,(+%..1,)--.8;441019.1780000313658;99621-,,.++)#,-.011537%#&-2,',-,86)(.''%(.2+/24,.23/./+*$)4--.0.340/+())0..62019-7:+).2(/*%),&--30/32*)&)%)$%')+2;829%*)'4:;401/,-71%.,'(*+)2837653/0-&/63861'(*-6*()5:.3--'%')',)2977&(%(%'+-/**-0727112246..*1,-..3&/.4535-3+3.00,7*%'1+12311321.35567:93&)*))'-/,2-7-.6/,..-4;6/3/&(&%**03745+-.-.::95544467..--))'*)#('*+,..(%)&'(%%&-+'++)*/1&&'$%&+*&())$()(,%+'$&'&($&'2.44:0..++#%).78*(((/1'($$&-:;98.(*00;;2-''),053.//3+&))+14-8&**,..01.2:;743425:7(,*.((+*,,-+'&*'+057,*(.53-(+3703/210.06256;.+,01.5<<5,06;:+.7)')3,$(+'4;.,*'*'*-4--)+-*)+&--,*$(+&(-$*,''/2778:;9/.857+%%'()*((*11-,)+-5-+,31/#&%$%5)-#%#

Then try to show one of the sequences by searching for the sequence ID:

grep '@3cb04ae7-2c7b-4da8-8d09-59edb5b8f45c_t' all_barcode03.fastq.gz

grep '*@3cb04ae7-2c7b-4da8-8d09-59edb5b8f45c_t*' all_barcode03.fastq.gz

grep @3cb04ae7-2c7b-4da8-8d09-59edb5b8f45c_t all_barcode03.fastq.gz

grep *@3cb04ae7-2c7b-4da8-8d09-59edb5b8f45c_t* all_barcode03.fastq.gz

All the above grep commands return no results however there is a line in  the file staring with @3cb04ae7-2c7b-4da8-8d09-59edb5b8f45c_t


问:
How to get day month and year in integer from given string date in pattern dd-MMM-yyyy
I have a string date in format (dd-MMM-yyyy) like (23-SEP-2019). I want to seperate day month and year from above string in integer like day = 23, month = 09, year = 2019.

答:
There's a few ways to do this, but I would go with this:

```<code>//convert it to a char array.
char[] asChars = dateString.toCharArray();
//Parse the date and year and from new strings.
int dayVal = Interger.ParseInt(""+asChars[0]+asChars[1]);
int yearVal = Interger.ParseInt(""+asChars[7]+asChars[8]+asChars[9]+asChars[10]);
//use a switch for the month.
int monthVal = 0;
String monthString = ""+asChars[3]+asChars[5]+asChars[6];
switch (monthString) {
    case "JAN" :
        monthVal = 1;
        break;
    case "FEB" :
        monthVal = 2;
        break;
    case "MAR"  :
        monthVal = 3;
        break;
    case "APR" :
        monthVal = 4;
        break;
    case "MAY" :
        monthVal = 5;
        break;
    case "JUN" :
        monthVal = 6;
        break;
    case "JUL" :
        monthVal = 7;
        break;
    case "AUG" :
        monthVal = 8;
        break;
    case "SEP" :
        monthVal = 9;
        break;
    case "OCT" :
        monthVal = 10;
        break;
    case "NOV" :
        monthVal = 11;
        break;
    case "DEC" :
        monthVal = 12;
        break;
}
</code>```

You'll need to put that in a try block and you'll want a catch for NumberFormatException and IndexOutOfBounds, in both cases the string was formatted incorrectly.

You will also separately need to check that the month string matched a month, so either add a default case to the switch or have a check that monthVal>0 after all that.

If you really want to be sure the original string was formatted correctly (which is a separate issue but I think still relevant) then you could check the string is of length 11 before all of that.

Body:
There's a few ways to do this, but I would go with this:

//convert it to a char array.
char[] asChars = dateString.toCharArray();
//Parse the date and year and from new strings.
int dayVal = Interger.ParseInt(""+asChars[0]+asChars[1]);
int yearVal = Interger.ParseInt(""+asChars[7]+asChars[8]+asChars[9]+asChars[10]);
//use a switch for the month.
int monthVal = 0;
String monthString = ""+asChars[3]+asChars[5]+asChars[6];
switch (monthString) {
    case "JAN" :
        monthVal = 1;
        break;
    case "FEB" :
        monthVal = 2;
        break;
    case "MAR"  :
        monthVal = 3;
        break;
    case "APR" :
        monthVal = 4;
        break;
    case "MAY" :
        monthVal = 5;
        break;
    case "JUN" :
        monthVal = 6;
        break;
    case "JUL" :
        monthVal = 7;
        break;
    case "AUG" :
        monthVal = 8;
        break;
    case "SEP" :
        monthVal = 9;
        break;
    case "OCT" :
        monthVal = 10;
        break;
    case "NOV" :
        monthVal = 11;
        break;
    case "DEC" :
        monthVal = 12;
        break;
}

You'll need to put that in a try block and you'll want a catch for NumberFormatException and IndexOutOfBounds, in both cases the string was formatted incorrectly.

You will also separately need to check that the month string matched a month, so either add a default case to the switch or have a check that monthVal>0 after all that.

If you really want to be sure the original string was formatted correctly (which is a separate issue but I think still relevant) then you could check the string is of length 11 before all of that.


问:
manage api calls when using vuex
I am currently working on an asset manager for network/server infrastructure in vue.js.

I am also using vuetify for the look and feel since the goal is to create a progressive web app. Engineers can use their phone to scan tags on company assets to request details.

Currently all data is loaded into the app using a rest api. I am using vuex for state management in the application.

I would like some insights in to when to launch these api requests.

So there is some data i currently load at the start of the web app just after logging in when the main core view is loaded. This is impacting performance. Some examples of loaded data:
-> asset types,vendors,suppliers,...
This data is used in a lot of places in the application. (forms,filters,...)
I prefer not to call the vuex actions to perform the api request form inside a specific component since this could lead to unnecessary request when browsing the app.
The only exception to this being the assets them self since this is a lot of data to load at the start.

The problem i am facing is that on mobile platforms loading the data each time at the start of the app is a waste of data connection. It is possible that the engineer is using the app without actually needing the data.

I know this is kind of an abstract question, i am not looking for the one final awnser. Just some insight or recommendations from the community.

答:
Correct me if I misunderstood but it sounds like you are prefetching a lot of non critical information all at start up. You should really focus on when that data is actually needed and reach out and retrieve it only when its actually needed. A common case of this is on route change, so if you have multiple pages within your app an admin page is likely going to need data that your home screen doesn't need. Wait until you navigate to that page before you retrieve information specific to that page. This is commonly done within the beforeRouteEnter router hook or created life cycle hook. Now to build on this, it may take some time to download that new data after a route change - the page could render before all of its necessary data has been made available. You can use a library like Vue-Promised to handle that intermediate state for sections that require data that is still loading. This allows you to let the page render quickly without having to wait on all of its data.

A couple other tips to further optimize things:

If you data that doesn't change often, sometimes it doesn't hurt to persist that data within the browser, either using the Cache-Control http header when making your http calls or by using something like the browsers LocalStorage or one of the hard persistence methods available within the browser. Theres a number of Vuex plugins that make this really easy, ex. vuex-persist. On startup you can load this data from storage which is faster than making a network call, your app will be able to respond faster and you can even go and make that network request in the background to refresh that data after the page has rendered.

If retrieving large sets of data is an issue then you can page the data to retrieve it in smaller chunks and only retrieve additional "pages" fo data when the user needs it. In tables this is commonly done using pagination buttons or infinite scrolling. Theres a number of libraries that do both of these as well, pagination would likely be built into the vuetify libraries table component.

Title: manage api calls when using vuex


问:
Check if a particular NPM package is installed globally
I'm trying to check if a particular npm package is installed/available globally using Nodejs. I managed to list the global dependencies/packages through the npm command npm list -g --depth=0. So i tried out this piece of code.

```<code>const {exec} = require("child_process");

exec("npm list -g --depth=0",(err, stdout, stderr) => {
   if (err) {
     console.error(err);
     return;
    }
  console.log(stdout);
});
</code>```

Then it throws an error like this

PS: i also tried to use npm list -g --depth=0 | grep nodemon but i cannot use it on command prompt. So that is wrong in the above code? how can check whether if package installed globally in any OS using nodejs?

答:
The code in your npm.js file looks OK and should run successfully - that's assuming that:

when you run npm list -g --depth=0 directly in your CLI you do get the desired result.

The version of nodejs you're running does support ES6 features, such as Object Destructuring and Arrow functions.

The problem is the filenaming of the nodejs script - Don't name it npm.js.

You need to rename the file as something else, such as, e.g. get-global-pkgs.js.

Then cd to the directory where get-global-pkgs.js resides, and run either of the following commands:

node get-global-pkgs.js
```

<p>or </p>

<pre class="lang-none prettyprint-override"><code>node get-global-pkgs
</code>```

i.e without the .js suffix

Note: Naming the file npm.js only seems to be an issue when the files content utilizes exec() and/or spawn() methods, and the given command results in a http(s) GET request.

Body:
I'm trying to check if a particular npm package is installed/available globally using Nodejs. I managed to list the global dependencies/packages through the npm command npm list -g --depth=0. So i tried out this piece of code.

const {exec} = require("child_process");

exec("npm list -g --depth=0",(err, stdout, stderr) => {
   if (err) {
     console.error(err);
     return;
    }
  console.log(stdout);
});

Then it throws an error like this

PS: i also tried to use npm list -g --depth=0 | grep nodemon but i cannot use it on command prompt. So that is wrong in the above code? how can check whether if package installed globally in any OS using nodejs?

Body:
The code in your npm.js file looks OK and should run successfully - that's assuming that:

when you run npm list -g --depth=0 directly in your CLI you do get the desired result.

The version of nodejs you're running does support ES6 features, such as Object Destructuring and Arrow functions.

The problem is the filenaming of the nodejs script - Don't name it npm.js.

You need to rename the file as something else, such as, e.g. get-global-pkgs.js.

Then cd to the directory where get-global-pkgs.js resides, and run either of the following commands:

node get-global-pkgs.js

or

node get-global-pkgs

i.e without the .js suffix

Note: Naming the file npm.js only seems to be an issue when the files content utilizes exec() and/or spawn() methods, and the given command results in a http(s) GET request.


问:
Error: log4j-api-2.9.0.jar is a multi-release jar file but --multi-release option is not set
Exploring the maven-jdeps-plugin:3.1.0 with Java9 using the following minimal pom.xml:-

```<code><dependencies>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.9.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
               <source>1.9</source>
               <target>1.9</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jdeps-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>jdkinternals</goal> <!-- verify main classes -->
                        <goal>test-jdkinternals</goal> <!-- verify test classes -->
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

On executing

```<code>mvn install
</code>```

I end up getting a detailed error that reads the following:-

```<code>[INFO] Error: log4j-api-2.9.0.jar is a multi-release jar file but --multi-release option is not set
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.389 s
[INFO] Finished at: ...
[INFO] Final Memory: 12M/41M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-jdeps-plugin:3.1.0:jdkinternals (default) on project maven-jigsaw:
[ERROR] Exit code: 2
[ERROR] Command line was: /bin/sh -c '/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/jdeps' '-cp' '.../.m2/repository/org/apache/logging/log4j/log4j-api/2.9.0/log4j-api-2.9.0.jar' '../maven/target/classes'
</code>```

I couldn't find much relevance related to --multi-release flag in either jdeps:jdkinternals goal detailed on Maven's official site or even in the jdeps tool documented at Oracle help center.

Can someone throw some light on this implementation in maven-jdeps-plugin? Is there a way to fix this(set the --multi-release option)?

答:
Regarding the plugin itself, following configuration works.</p>

```<code>  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jdeps-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
      <execution>
        <goals>
          <goal>jdkinternals</goal> <!-- verify main classes -->
          <goal>test-jdkinternals</goal> <!-- verify test classes -->
        </goals>
      </execution>
    </executions>
    <configuration>
      <multiRelease>9</multiRelease> <!-- Check this out -->
    </configuration>
  </plugin>
</code>```

Body:
Exploring the maven-jdeps-plugin:3.1.0 with Java9 using the following minimal pom.xml:-

<dependencies>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.9.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
               <source>1.9</source>
               <target>1.9</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jdeps-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>jdkinternals</goal>
                        <goal>test-jdkinternals</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

On executing

mvn install

I end up getting a detailed error that reads the following:-

[INFO] Error: log4j-api-2.9.0.jar is a multi-release jar file but --multi-release option is not set
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.389 s
[INFO] Finished at: ...
[INFO] Final Memory: 12M/41M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-jdeps-plugin:3.1.0:jdkinternals (default) on project maven-jigsaw:
[ERROR] Exit code: 2
[ERROR] Command line was: /bin/sh -c '/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/jdeps' '-cp' '.../.m2/repository/org/apache/logging/log4j/log4j-api/2.9.0/log4j-api-2.9.0.jar' '../maven/target/classes'

I couldn't find much relevance related to --multi-release flag in either jdeps:jdkinternals goal detailed on Maven's official site or even in the jdeps tool documented at Oracle help center.

Can someone throw some light on this implementation in maven-jdeps-plugin? Is there a way to fix this(set the --multi-release option)?

Body:
Regarding the plugin itself, following configuration works.

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jdeps-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
      <execution>
        <goals>
          <goal>jdkinternals</goal> <!-- verify main classes -->
          <goal>test-jdkinternals</goal> <!-- verify test classes -->
        </goals>
      </execution>
    </executions>
    <configuration>
      <multiRelease>9</multiRelease> <!-- Check this out -->
    </configuration>
  </plugin>


问:
How to continue sequence / parallel actions from cachedActions Libgdx
I have a clicklistener extended class which aims to cached any current actions of the actor during touchDown, and assigns it back when touchUp is triggered. However, it does not works for sequence or parallel actions.

```<code>public class MyClickListener extends ClickListener {

    public Actor actor;
    private final Array<Action> cachedActions = new Array<Action>();

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);
        actor = event.getListenerActor();
        actor.addAction(btnScaleBackActions());
        for(Action action:cachedActions)
        {
            //action.reset(); // i wants the actor to continue at where it stop
            action.setTarget(actor);
            action.setActor(actor);
            actor.addAction(action);
        }
        cachedActions.clear();
    }

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        if(pointer==0)
        {
            actor = event.getListenerActor();
            actor.setScale(0.9f);
            cachedActions.addAll(actor.getActions());
            actor.clearActions();
            return super.touchDown(event, x, y, pointer, button);
        }
        else
        {
            return false;
        }
    }
</code>```

My buttons testing:

```<code>// button touchUp continue its previous action at where it stop
btn1.addAction(Actions.scaleBy(1,1,3));

// button touchUp not continue it previous actions and complete stop
btn2.addAction(sequence(Actions.scaleBy(1,1,3)));

// button touchUp give nullException error
btn3.addAction(forever(Actions.scaleBy(1,1,3)));

//error :
Exception in thread "LWJGL Application" java.lang.NullPointerException
        at com.badlogic.gdx.scenes.scene2d.actions.RepeatAction.delegate(RepeatAction.java:29)
        at com.badlogic.gdx.scenes.scene2d.actions.DelegateAction.act(DelegateAction.java:43)
</code>```

Is it possible to continue sequence/parallel actions at where it stop at myClickListener class?

答:
Here's an alternate idea. Rather than deal with removing and restoring actions, and subsequently dealing with the pools issue, you can wrap your actions in a new type of pausable action.

```<code>public class PausableAction extends DelegateAction {

    public static PausableAction pausable(Action wrappedAction){
        PausableAction action = Actions.action(PausableAction.class);
        action.setAction(wrappedAction);
        return action;
    }

    boolean paused = false;

    public void pause (){
        paused = true;
    }

    public void unpause (){
        paused = false;
    }

    protected boolean delegate (float delta){
        if (paused)
            return false;
        return action.act(delta);
    }

    public void restart () {
        super.restart();
        paused = false;
    }
}
</code>```

Now when getting your actions, wrap them in a pausable, for example:

```<code>btn1.addAction(PausableAction.pausable(Actions.scaleBy(1,1,3)));
</code>```

And pause/unpause actions when you need to, like:

```<code>//...
actor = event.getListenerActor();
actor.setScale(0.9f);
for (Action action : actor.getActions())
    if (action instanceof PausableAction)
        ((PausableAction)action).pause();
return super.touchDown(event, x, y, pointer, button);
</code>```

Body:
I have a clicklistener extended class which aims to cached any current actions of the actor during touchDown, and assigns it back when touchUp is triggered. However, it does not works for sequence or parallel actions.

public class MyClickListener extends ClickListener {

    public Actor actor;
    private final Array<Action> cachedActions = new Array<Action>();

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);
        actor = event.getListenerActor();
        actor.addAction(btnScaleBackActions());
        for(Action action:cachedActions)
        {
            //action.reset(); // i wants the actor to continue at where it stop
            action.setTarget(actor);
            action.setActor(actor);
            actor.addAction(action);
        }
        cachedActions.clear();
    }

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        if(pointer==0)
        {
            actor = event.getListenerActor();
            actor.setScale(0.9f);
            cachedActions.addAll(actor.getActions());
            actor.clearActions();
            return super.touchDown(event, x, y, pointer, button);
        }
        else
        {
            return false;
        }
    }

My buttons testing:

// button touchUp continue its previous action at where it stop
btn1.addAction(Actions.scaleBy(1,1,3));

// button touchUp not continue it previous actions and complete stop
btn2.addAction(sequence(Actions.scaleBy(1,1,3)));

// button touchUp give nullException error
btn3.addAction(forever(Actions.scaleBy(1,1,3)));

//error :
Exception in thread "LWJGL Application" java.lang.NullPointerException
        at com.badlogic.gdx.scenes.scene2d.actions.RepeatAction.delegate(RepeatAction.java:29)
        at com.badlogic.gdx.scenes.scene2d.actions.DelegateAction.act(DelegateAction.java:43)

Is it possible to continue sequence/parallel actions at where it stop at myClickListener class?

Body:
Here's an alternate idea. Rather than deal with removing and restoring actions, and subsequently dealing with the pools issue, you can wrap your actions in a new type of pausable action.

public class PausableAction extends DelegateAction {

    public static PausableAction pausable(Action wrappedAction){
        PausableAction action = Actions.action(PausableAction.class);
        action.setAction(wrappedAction);
        return action;
    }

    boolean paused = false;

    public void pause (){
        paused = true;
    }

    public void unpause (){
        paused = false;
    }

    protected boolean delegate (float delta){
        if (paused)
            return false;
        return action.act(delta);
    }

    public void restart () {
        super.restart();
        paused = false;
    }
}

Now when getting your actions, wrap them in a pausable, for example:

btn1.addAction(PausableAction.pausable(Actions.scaleBy(1,1,3)));

And pause/unpause actions when you need to, like:

//...
actor = event.getListenerActor();
actor.setScale(0.9f);
for (Action action : actor.getActions())
    if (action instanceof PausableAction)
        ((PausableAction)action).pause();
return super.touchDown(event, x, y, pointer, button);


问:
Uses of Java Native Interface(JNI)
Could you please help me understanding under what scenario JNI (or Java Native Interface) could be useful from web application development perspective?

I did read some articles that promises that JNI can give you access to native application like menu bar/scroll bar etc, so the user interface can be more catchy... however these things can be done in other technologies rather than Java.

I'm still not able to find practical uses of JNI. Have you used the JNI in your projects/apps ever? and for what?

答:
It shouldn't be necessary for web development since just about anything you need is already written in Java--and it would also be a terrible idea because it will make your app platform dependent.

It is sometimes used to access a system API an old DLL that you must use without rewriting for some awful management-related reason.

Title: Uses of Java Native Interface(JNI)


问:
NavMeshAgent face same direction as destination point in Unity
I have a NavMeshAgent NPC that walks correctly to its destination position. However, when it stops, it faces the walking direction, while I would like to have it turn to the same direction as the destination point, in the most natural way as my NPC is a human.

Is there a way to have the NPC, while walking to the destination point, also to set a destination rotation?

答:
You can set and idle animation.
Then you can trigger a look at function with this animation

https://docs.unity3d.com/Manual/animeditor-AnimationEvents.html


问:
ROC_AUC_SCORE is different while calculating using predict() vs predict_proba() in Random Forest
Both predict() vs predict_proba() gives different roc_auc_score in Random Forest.

I understand that predict_proba() gives probabilities such as in case of Binary Classification it will gives two probabilities corresponding both classes.
predict() gives class it predicted.

```<code>    #Using predict_proba()
    rf = RandomForestClassifier(n_estimators=200, random_state=39)
    rf.fit(X_train[['Cabin_mapped', 'Sex']], y_train)

    #make predictions on train and test set
    pred_train = rf.predict_proba(X_train[['Cabin_mapped', 'Sex']])
    pred_test = rf.predict_proba(X_test[['Cabin_mapped', 'Sex']].fillna(0))

    print('Train set')
    print('Random Forests using predict roc-auc: {}'.format(roc_auc_score (y_train, pred_train)))

    print('Test set')
    print('Random Forests using predict roc-auc: {}'.format(roc_auc_score(y_test, pred_test)))

   #using predict()

   pred_train = rf.predict(X_train[['Cabin_reduced', 'Sex']])
   pred_test = rf.predict(X_test[['Cabin_reduced', 'Sex']])

   print('Train set')
   print('Random Forests using predict roc-auc: {}'.format(roc_auc_score(y_train, pred_train)))
   print('Test set')
   print('Random Forests using predict roc-auc: {}'.format(roc_auc_score(y_test, pred_test)))
</code>```

Train set Random Forests using predict_proba roc-auc: 0.8199550985878832

Test set Random Forests using preditc_proba roc-auc: 0.8332142857142857

Train set Random Forests using predict roc-auc: 0.7779440793041364

Test set Random Forests using predict roc-auc: 0.7686904761904761

答:
As you said, the predict function returns the prediction as True/False value, whereas proba function returns probabilities, values between one and zero
and this is the reason for the difference.

AUC means "area under the curve" which is indeed different if the curve is a 0/1 step function or a curve made of continuous values.

Let's imagine you have only one example, it should be classified as False. If your classifier yields the probability of 0.7, the ROC-AUC value is 1.0-0.7=0.3. If you used predict, the prediction will be True = 1.0, so the ROC-AUC will be 1.0-1.0=0.0.

Body:
Both predict() vs predict_proba() gives different roc_auc_score in Random Forest.

I understand that predict_proba() gives probabilities such as in case of Binary Classification it will gives two probabilities corresponding both classes.
predict() gives class it predicted.

    #Using predict_proba()
    rf = RandomForestClassifier(n_estimators=200, random_state=39)
    rf.fit(X_train[['Cabin_mapped', 'Sex']], y_train)

    #make predictions on train and test set
    pred_train = rf.predict_proba(X_train[['Cabin_mapped', 'Sex']])
    pred_test = rf.predict_proba(X_test[['Cabin_mapped', 'Sex']].fillna(0))

    print('Train set')
    print('Random Forests using predict roc-auc: {}'.format(roc_auc_score (y_train, pred_train)))

    print('Test set')
    print('Random Forests using predict roc-auc: {}'.format(roc_auc_score(y_test, pred_test)))

   #using predict()

   pred_train = rf.predict(X_train[['Cabin_reduced', 'Sex']])
   pred_test = rf.predict(X_test[['Cabin_reduced', 'Sex']])

   print('Train set')
   print('Random Forests using predict roc-auc: {}'.format(roc_auc_score(y_train, pred_train)))
   print('Test set')
   print('Random Forests using predict roc-auc: {}'.format(roc_auc_score(y_test, pred_test)))

Train set Random Forests using predict_proba roc-auc: 0.8199550985878832

Test set Random Forests using preditc_proba roc-auc: 0.8332142857142857

Train set Random Forests using predict roc-auc: 0.7779440793041364

Test set Random Forests using predict roc-auc: 0.7686904761904761


问:
How to use the value of a variable as key when constructing a dictionary
In Python , I want to make a dictionary using a formula in a loop.

My problem is that this code:

```<code>i = 1
A = {}
A.update(i=12)
print(A)
</code>```

gives me {'i': 12}， while I want to get {1: 12}, with the value of i as key instead of its name.
How can I achieve that?

答:
As stated in the documentation for dict.update:

update() accepts either another dictionary object or an iterable of
  key/value pairs (as tuples or other iterables of length two). If
  keyword arguments are specified, the dictionary is then updated with
  those key/value pairs: d.update(red=1, blue=2).

If you use the syntax with keyword arguments, the names of the arguments will be used as keys.

In your case, as you want the value of i to be used, you want to use a dict as argument to update:

```<code>i=1
A={}
A.update({i:12})
print(A)

#{1: 12}
</code>```

Body:
In Python , I want to make a dictionary using a formula in a loop.

My problem is that this code:

i = 1
A = {}
A.update(i=12)
print(A)

gives me {'i': 12}， while I want to get {1: 12}, with the value of i as key instead of its name.
How can I achieve that?

Body:
As stated in the documentation for dict.update:

update() accepts either another dictionary object or an iterable of
  key/value pairs (as tuples or other iterables of length two). If
  keyword arguments are specified, the dictionary is then updated with
  those key/value pairs: d.update(red=1, blue=2).

If you use the syntax with keyword arguments, the names of the arguments will be used as keys.

In your case, as you want the value of i to be used, you want to use a dict as argument to update:

i=1
A={}
A.update({i:12})
print(A)

#{1: 12}


问:
SQL query to get max of a column and display with every row
Here's my scenario...
Multiple Items with multiple item types which have multiple prices.
Want to select Items with all types showing the MAX price. Can't figure out how to get the max?

Input:

```<code>ProductId   ProductType Description     Price
</code>```

1           A           BAKED BEANS     1.29

1           B           BAKED BEANS     1.98

Output:

```<code>ProductId   ProductType Description     Price
</code>```

1           A           BAKED BEANS     1.98

1           B           BAKED BEANS     1.98

Any suggestions?

答:
```<code>Select ProductId, ProductType, Description, MaxByDesc.MaxPrice
From Product
    Join    (
            Select Description, Max(Price) As MaxPrice
            From Product
            Group By Description
            ) As MaxByDesc
        On MaxByDesc.Description = Product.Description
</code>```

If you are using SQL Server 2005 or later:

```<code>Select ProductId, ProductType, Description
    , Max( Price ) Over ( Partition By Description ) As MaxPrice
From Product
</code>```

Body:
Here's my scenario...
Multiple Items with multiple item types which have multiple prices.
Want to select Items with all types showing the MAX price. Can't figure out how to get the max?

Input:

ProductId   ProductType Description     Price

1           A           BAKED BEANS     1.29

1           B           BAKED BEANS     1.98

Output:

ProductId   ProductType Description     Price

1           A           BAKED BEANS     1.98

1           B           BAKED BEANS     1.98

Any suggestions?

Body:
Select ProductId, ProductType, Description, MaxByDesc.MaxPrice
From Product
    Join    (
            Select Description, Max(Price) As MaxPrice
            From Product
            Group By Description
            ) As MaxByDesc
        On MaxByDesc.Description = Product.Description

If you are using SQL Server 2005 or later:

Select ProductId, ProductType, Description
    , Max( Price ) Over ( Partition By Description ) As MaxPrice
From Product


问:
How to fix : "FActorSpawnParameters is not defined" error in C++ in UE4?
I'm following a tutorial to make a game with UE4 and C++ and a error appear when I type the following line

FActorSpawnParameters params;

It says that the identifier FActorSpawnParameters is not defined.

I've tried to modify some of my code but it didn't change...
So I replace all the things in order.

void AUltimatePawn::Shoot()
{
    if (BulletClass)
    {
        FActorSpawnParameters params;
        params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
        params.bNoFail = true;
        params.Owner = this;
        params.Instigator = this;

        FTransform BulletSpawnTransform;
        BulletSpawnTransform.SetLocation(GetActorForwardVector() * 500.f + GetActorLocation());
        BulletSpawnTransform.SetRotation(GetActorRotation().Quaternion());
        BulletSpawnTransform.SetScale3D(FVector(1.f));

        GetWorld()->SpawnActor<ABullet>(BulletClass, BulletSpawnTransform, params);
    }

}
```

I just want you to tell me how to fix this error,
Thank's

答:
Make sure that you include Runtime/Engine/Classes/Engine/World.h.

I extracted this information from the official API reference.

Body:
I'm following a tutorial to make a game with UE4 and C++ and a error appear when I type the following line

FActorSpawnParameters params;

It says that the identifier FActorSpawnParameters is not defined.

I've tried to modify some of my code but it didn't change...
So I replace all the things in order.

void AUltimatePawn::Shoot()
{
    if (BulletClass)
    {
        FActorSpawnParameters params;
        params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
        params.bNoFail = true;
        params.Owner = this;
        params.Instigator = this;

        FTransform BulletSpawnTransform;
        BulletSpawnTransform.SetLocation(GetActorForwardVector() * 500.f + GetActorLocation());
        BulletSpawnTransform.SetRotation(GetActorRotation().Quaternion());
        BulletSpawnTransform.SetScale3D(FVector(1.f));

        GetWorld()->SpawnActor<ABullet>(BulletClass, BulletSpawnTransform, params);
    }

}

I just want you to tell me how to fix this error,
Thank's


问:
how to insert media files in cassandra using nodejs?
How we insert an image into a Cassandra database using node js
I have tried with following.

I have used base64(image) to store the image, but I need store base64 in blob datatype of Cassandra. I know the blob datatype in Cassandra is equivalent to Buffer datatype in node js.

```<code>
var cassandra=require('cassandra-driver');
var client=new cassandra.Client({contactPoints:['localhost'],localDataCenter:"datacenter1",keyspace:"employee"});
var path=require('path');
var fs=require('fs');
var base64 = fs.readFileSync(path.resolve(__dirname + '/download.jpeg'), 'base64');

var imageBuffer = new Buffer(base64, 'base64');

var query="INSERT INTO photo(id,image) VALUES ('ranjith',imageBuffer)";

client.execute(query,function(err){
   if(err) {
      console.log(err);
   } else {
      console.log('success');
   }
});
</code>```

Here is the error message:

```<code>> { ResponseError: line 1:57 no viable alternative at input ')'
> (...id,image) VALUES ('ranjith',[imageBuffer]))
>     at FrameReader.readError (/home/innvoot/Desktop/cassandra_and_node_trails/node_modules/cassandra-driver/lib/readers.js:326:15)
>     at Parser.parseBody (/home/innvoot/Desktop/cassandra_and_node_trails/node_modules/cassandra-driver/lib/streams.js:194:66)
>     at Parser._transform (/home/innvoot/Desktop/cassandra_and_node_trails/node_modules/cassandra-driver/lib/streams.js:137:10)
>     at Parser.Transform._read (_stream_transform.js:186:10)
>     at Parser.Transform._write (_stream_transform.js:174:12)
>     at doWrite (_stream_writable.js:396:12)
>     at writeOrBuffer (_stream_writable.js:382:5)
>     at Parser.Writable.write (_stream_writable.js:290:11)
>     at Protocol.ondata (_stream_readable.js:639:20)
>     at emitOne (events.js:116:13)   name: 'ResponseError',   info: 'Represents an error message from the server',   message: 'line 1:57
> no viable alternative at input \')\' (...id,image) VALUES
> (\'ranjith\',[imageBuffer]))',   code: 8192,   coordinator:
> '127.0.0.1:9042',   query: 'INSERT INTO photo(id,image) VALUES
> (\'ranjith\',imageBuffer)' }
</code>```

I expect to get "SUCCESS" as the result.

答:
I'm no javascript expert, but seeing your error;

no viable alternative at input \')\' (...id,image) VALUES (\'ranjith\',[imageBuffer]))'

I feel that the query syntax could be wrong, could try

const query = 'INSERT INTO photo (id, image) VALUES (?, ?)';

client.execute(query, [ 'ranjith', imageBuffer ], { prepare: true }, function(err, result) {
  assert.ifError(err);
  console.log('Success');
});
```

Body:
How we insert an image into a Cassandra database using node js
I have tried with following.

I have used base64(image) to store the image, but I need store base64 in blob datatype of Cassandra. I know the blob datatype in Cassandra is equivalent to Buffer datatype in node js.

var cassandra=require('cassandra-driver');
var client=new cassandra.Client({contactPoints:['localhost'],localDataCenter:"datacenter1",keyspace:"employee"});
var path=require('path');
var fs=require('fs');
var base64 = fs.readFileSync(path.resolve(__dirname + '/download.jpeg'), 'base64');

var imageBuffer = new Buffer(base64, 'base64');

var query="INSERT INTO photo(id,image) VALUES ('ranjith',imageBuffer)";

client.execute(query,function(err){
   if(err) {
      console.log(err);
   } else {
      console.log('success');
   }
});

Here is the error message:

> { ResponseError: line 1:57 no viable alternative at input ')'
> (...id,image) VALUES ('ranjith',[imageBuffer]))
>     at FrameReader.readError (/home/innvoot/Desktop/cassandra_and_node_trails/node_modules/cassandra-driver/lib/readers.js:326:15)
>     at Parser.parseBody (/home/innvoot/Desktop/cassandra_and_node_trails/node_modules/cassandra-driver/lib/streams.js:194:66)
>     at Parser._transform (/home/innvoot/Desktop/cassandra_and_node_trails/node_modules/cassandra-driver/lib/streams.js:137:10)
>     at Parser.Transform._read (_stream_transform.js:186:10)
>     at Parser.Transform._write (_stream_transform.js:174:12)
>     at doWrite (_stream_writable.js:396:12)
>     at writeOrBuffer (_stream_writable.js:382:5)
>     at Parser.Writable.write (_stream_writable.js:290:11)
>     at Protocol.ondata (_stream_readable.js:639:20)
>     at emitOne (events.js:116:13)   name: 'ResponseError',   info: 'Represents an error message from the server',   message: 'line 1:57
> no viable alternative at input \')\' (...id,image) VALUES
> (\'ranjith\',[imageBuffer]))',   code: 8192,   coordinator:
> '127.0.0.1:9042',   query: 'INSERT INTO photo(id,image) VALUES
> (\'ranjith\',imageBuffer)' }

I expect to get "SUCCESS" as the result.