问:
MySQL order by before group by
There are plenty of similar questions to be found on here but I don't think that any answer the question adequately.

I'll continue from the current most popular question and use their example if that's alright.

The task in this instance is to get the latest post for each author in the database.

The example query produces unusable results as its not always the latest post that is returned.

```<code>SELECT wp_posts.* FROM wp_posts
    WHERE wp_posts.post_status='publish'
    AND wp_posts.post_type='post'
    GROUP BY wp_posts.post_author
    ORDER BY wp_posts.post_date DESC
</code>```

The current accepted answer is

```<code>SELECT
    wp_posts.*
FROM wp_posts
WHERE
    wp_posts.post_status='publish'
    AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author
HAVING wp_posts.post_date = MAX(wp_posts.post_date) <- ONLY THE LAST POST FOR EACH AUTHOR
ORDER BY wp_posts.post_date DESC
</code>```

Unfortunately this answer is plain and simple wrong and in many cases produces less stable results than the orginal query.

My best solution is to use a subquery of the form

```<code>SELECT wp_posts.* FROM
(
    SELECT *
    FROM wp_posts
    ORDER BY wp_posts.post_date DESC
) AS wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author
</code>```

My question is a simple one then:
Is there anyway to order rows before grouping without resorting to a subquery?

Edit: This question was a continuation from another question and the specifics of my situation are slightly different. You can (and should) assume that there is also a wp_posts.id that is a unique identifier for that particular post.

答:
Here is my solution with User-Defined Variable to get consistent results and even without GROUP BY. The goal was to get the whole row, not just the maximum value of one cell in a row. See example below:

```<code>SET @product_id := 0;

SELECT
    products.order_code,
    purchases.`date`,
    purchases.price
FROM products
LEFT JOIN (
    SELECT
        purchases.`date`,
        purchases.price,
        IF(@product_id = purchases.product_id, 0, 1) AS is_last,
        @product_id := purchases.product_id AS product_id
    FROM purchases
    ORDER BY purchases.product_id ASC, purchases.id DESC
) purchases ON products.id = purchases.product_id
WHERE purchases.is_last = 1
ORDER BY products.order_code ASC;
</code>```

I am not sure about the performance, but it was 0.1 sec on 50000 rows of purchases table. Please let me know if i can make any performance improvements.

Title: MySQL order by before group by

Body:
There are plenty of similar questions to be found on here but I don't think that any answer the question adequately.

I'll continue from the current most popular question and use their example if that's alright.

The task in this instance is to get the latest post for each author in the database.

The example query produces unusable results as its not always the latest post that is returned.

SELECT wp_posts.* FROM wp_posts
    WHERE wp_posts.post_status='publish'
    AND wp_posts.post_type='post'
    GROUP BY wp_posts.post_author
    ORDER BY wp_posts.post_date DESC

The current accepted answer is

SELECT
    wp_posts.*
FROM wp_posts
WHERE
    wp_posts.post_status='publish'
    AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author
HAVING wp_posts.post_date = MAX(wp_posts.post_date) <- ONLY THE LAST POST FOR EACH AUTHOR
ORDER BY wp_posts.post_date DESC

Unfortunately this answer is plain and simple wrong and in many cases produces less stable results than the orginal query.

My best solution is to use a subquery of the form

SELECT wp_posts.* FROM
(
    SELECT *
    FROM wp_posts
    ORDER BY wp_posts.post_date DESC
) AS wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author

My question is a simple one then:
Is there anyway to order rows before grouping without resorting to a subquery?

Edit: This question was a continuation from another question and the specifics of my situation are slightly different. You can (and should) assume that there is also a wp_posts.id that is a unique identifier for that particular post.

Body:
Here is my solution with User-Defined Variable to get consistent results and even without GROUP BY. The goal was to get the whole row, not just the maximum value of one cell in a row. See example below:

SET @product_id := 0;

SELECT
    products.order_code,
    purchases.`date`,
    purchases.price
FROM products
LEFT JOIN (
    SELECT
        purchases.`date`,
        purchases.price,
        IF(@product_id = purchases.product_id, 0, 1) AS is_last,
        @product_id := purchases.product_id AS product_id
    FROM purchases
    ORDER BY purchases.product_id ASC, purchases.id DESC
) purchases ON products.id = purchases.product_id
WHERE purchases.is_last = 1
ORDER BY products.order_code ASC;

I am not sure about the performance, but it was 0.1 sec on 50000 rows of purchases table. Please let me know if i can make any performance improvements.


来源: stackexchange

问:
Environment variables for React Application at runtime
I have a React Application to be deployed to Cloud Foundry. I want to segregate dev, stage and prod. The issue is React provides .env.development for react-scripts start and .env.production for react-scripts build.

I want a solution to have 3 separate environments at runtime (with npm build)

I have added app-config.js:

const SPACE_NAME_JSON = process.env.VCAP_APPLICATION
const SPACE_NAME = JSON.parse(SPACE_NAME_JSON).space_name

if (SPACE_NAME.match(/development/)) {
    process.env.NODE_ENV = 'development'
} else if (SPACE_NAME.match(/stage/)) {
    process.env.NODE_ENV = 'stage'
}
} else if (SPACE_NAME.match(/production/)) {
    process.env.NODE_ENV = 'production'
}

console.log(`${process.env.NODE_ENV}`)

```
<p><code>package.json</code>: <code>build": " react-scripts build && cp app-config.js ./build"</code></p>
<p>And injecting the script at runtime in <code>public/index</code></p>
```
```

But after running the application, process.env.NODE_ENV gives production instead of development for development environment. This means it defaults to CRA's environment.

Is there a way to do this without ejecting webpack. (Since webpack is happening build time, but the application fetches detail at runtime.

答:
You can either write scripts to alter your files before serving follow - https://dev.to/akdevcraft/react-runtime-variables-49dc, or use a package which does that https://github.com/andrewmclagan/react-env

Sample code would be in lines of

```<code>// .env file
# .env
REACT_APP_NEXT="Next.js"
REACT_APP_CRA="Create React App"
REACT_APP_NOT_SECRET_CODE="1234"

// Your code
import env from "@beam-australia/react-env";

export default (props) => (
  <div>
    <small>
      Works in the browser: <b>{env("CRA")}</b>.
    </small>
    <small>
      Also works for server side rendering: <b>{env("NEXT")}</b>.
    </small>
    <form>
      <input type="hidden" defaultValue={env("NOT_SECRET_CODE")} />
    </form>
    <small>
      Entire safe environment:
      ```
        {{JSON.stringify(env())}}
      ```
    </small>
  </div>
);

// package.json
{
  ...
  "scripts": {
    "start": "react-env --env APP_ENV -- next start" // where .env.${APP_ENV}
  }
  ...
}
</code>```

Few other configuration steps are needed, which you could find in the package help

ContentLicense: CC BY-SA 4.0

Body:
I have a React Application to be deployed to Cloud Foundry. I want to segregate dev, stage and prod. The issue is React provides .env.development for react-scripts start and .env.production for react-scripts build.

I want a solution to have 3 separate environments at runtime (with npm build)

I have added app-config.js:

const SPACE_NAME_JSON = process.env.VCAP_APPLICATION
const SPACE_NAME = JSON.parse(SPACE_NAME_JSON).space_name

if (SPACE_NAME.match(/development/)) {
    process.env.NODE_ENV = 'development'
} else if (SPACE_NAME.match(/stage/)) {
    process.env.NODE_ENV = 'stage'
}
} else if (SPACE_NAME.match(/production/)) {
    process.env.NODE_ENV = 'production'
}

console.log(`${process.env.NODE_ENV}`)

package.json: build": " react-scripts build && cp app-config.js ./build"

And injecting the script at runtime in public/index

But after running the application, process.env.NODE_ENV gives production instead of development for development environment. This means it defaults to CRA's environment.

Is there a way to do this without ejecting webpack. (Since webpack is happening build time, but the application fetches detail at runtime.

Body:
You can either write scripts to alter your files before serving follow - https://dev.to/akdevcraft/react-runtime-variables-49dc, or use a package which does that https://github.com/andrewmclagan/react-env

Sample code would be in lines of

// .env file
# .env
REACT_APP_NEXT="Next.js"
REACT_APP_CRA="Create React App"
REACT_APP_NOT_SECRET_CODE="1234"

// Your code
import env from "@beam-australia/react-env";

export default (props) => (
  <div>
    <small>
      Works in the browser: <b>{env("CRA")}</b>.
    </small>
    <small>
      Also works for server side rendering: <b>{env("NEXT")}</b>.
    </small>
    <form>
      <input type="hidden" defaultValue={env("NOT_SECRET_CODE")} />
    </form>
    <small>
      Entire safe environment:
      <pre>
        <code>{{JSON.stringify(env())}}</code>
      </pre>
    </small>
  </div>
);

// package.json
{
  ...
  "scripts": {
    "start": "react-env --env APP_ENV -- next start" // where .env.${APP_ENV}
  }
  ...
}

Few other configuration steps are needed, which you could find in the package help


问:
Which of these SQL UPDATE statements would be faster?
Which would be faster?

Method A:

```<code>UPDATE table1
SET table1.column1 = table2.column1
FROM table2
WHERE table1.column2 = table2.column2
</code>```

Method B:

```<code>UPDATE table1
SET table1.column1 = table2.column1
FROM table1
JOIN table2 on table1.column2 = table2.column2
</code>```

Will they generate the same execution plan?

Is there any case where I should avoid one of them?

Some tests I did took them almost the same time to execute, but always good to hear a second opnion.

答:
They are equivalent. You can verify this by checking the execution plan yourself. The second option:

```<code>UPDATE table1
SET table1.column1 = table2.column1
FROM table1 JOIN
     table2 on table1.column2 = table2.column2
</code>```

Is currently the preferred method for writing queries, as it's more clear why the criteria is being specified.

ContentLicense: CC BY-SA 3.0

Body:
Which would be faster?

Method A:

UPDATE table1
SET table1.column1 = table2.column1
FROM table2
WHERE table1.column2 = table2.column2

Method B:

UPDATE table1
SET table1.column1 = table2.column1
FROM table1
JOIN table2 on table1.column2 = table2.column2

Will they generate the same execution plan?

Is there any case where I should avoid one of them?

Some tests I did took them almost the same time to execute, but always good to hear a second opnion.

Body:
They are equivalent. You can verify this by checking the execution plan yourself. The second option:

UPDATE table1
SET table1.column1 = table2.column1
FROM table1 JOIN
     table2 on table1.column2 = table2.column2

Is currently the preferred method for writing queries, as it's more clear why the criteria is being specified.


问:
Shimmer effect with vannila js
Here is my code and I'm trying to implement the Shimmer Loading Effect on it.
I made the effect and you can see it on the initial render. The thing is I don't know how to use it.
the first text content is from my html file and doesnt need an ajax call.
But when the button is clicked the request is sent to api and the effect should displays as long as the data from ajax call returns. then it shoud be disappeard again.
I got confused totally.

const btn = document.getElementById('jokeBtn');
const text = document.getElementById('text');

const loading = document.getElementById('shimmer');

const url = 'https://icanhazdadjoke.com/';

async function getter() {
  const initialPromise = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  const myPromise = await initialPromise.json();
  text.innerHTML = myPromise.joke;
  loading.style.display = 'none';
}

btn.addEventListener('click', getter);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100;300&display=swap');
* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}
html {
  box-sizing: border-box;
  font-size: 62.5%;
  font-family: 'Georama', sans-serif;
}
body {
  height: 100vh;
  justify-content: center;
  align-items: center;
  display: flex;
  color: #fff;
  -webkit-font-smoothing: antialiased;
  background-color: #000;
  display: flex;
  flex-direction: column;
}
.sec1 {
  height: 500px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sec2 {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

p {
  font-size: 2rem;
  color: #222;
  text-align: left;
  margin-left: 0.7rem;
  margin-top: 1rem;
  margin-right: 0.7rem;
}

.jokebtn {
  padding: 1rem 1.5rem;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
  background-color: #ea526f;
  border-radius: 20px;
  border: 1px solid #e42549;
  cursor: pointer;
  color: #ffffff;
  font-size: 2rem;
  text-decoration: none;
  text-shadow: 0px 1px 0px #e42549;
}

.text-container {
  height: auto;
  width: 30vw;
  text-align: center;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
}

#text {
  margin: 2rem;
}

h2 {
  background-color: #555;
  font-size: 2rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  color: #fff;
}

.jokebtn:active {
  transform: scale(0.98);
}

.jokebtn:hover {
  background-color: #e42549;
}

.text-cont {
  height: auto;
  width: 100%;
}
.btn-cont {
  height: 35%;
  width: 100%;
}

.animated-bg {
  opacity: 0.3;
  background-image: linear-gradient(
    to right,
    #c6c8ca 0%,
    #dbdbdd 10%,
    #bebebe 20%,
    #f3f3f3 1000%
  );
  background-size: 200% 100%;
  animation: bgPos 1s linear infinite;
}

.animated-bg-text {
  border-radius: 10px;
  display: block;
  margin: 0.7rem;
  height: 20px;
  width: 100px;
}

@keyframes bgPos {
  0% {
    background-position: 50% 0;
  }
  100% {
    background-position: -150% 0;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

Test

          When you walked through the door. It was clear to me (Clear to me).
          You’re the one they adore. Who they came to see (Who they came to

      <button type="submit" id="jokeBtn" class="jokebtn">One more!</button>

```

答:
I try to fix, what you mean?

const btn = document.getElementById('jokeBtn');
const text = document.getElementById('text');

const loading = document.getElementById('shimmer');

const url = 'https://icanhazdadjoke.com/';

async function getter() {
  text.style.display = 'none';
  loading.style.display = 'block';
  const initialPromise = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  const myPromise = await initialPromise.json();
  text.innerHTML = myPromise.joke;
  loading.style.display = 'none';
  text.style.display = 'block';
}
loading.style.display = 'none';
btn.addEventListener('click', getter);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100;300&display=swap');
* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}
html {
  box-sizing: border-box;
  font-size: 62.5%;
  font-family: 'Georama', sans-serif;
}
body {
  height: 100vh;
  justify-content: center;
  align-items: center;
  display: flex;
  color: #fff;
  -webkit-font-smoothing: antialiased;
  background-color: #000;
  display: flex;
  flex-direction: column;
}
.sec1 {
  height: 500px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sec2 {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

p {
  font-size: 2rem;
  color: #222;
  text-align: left;
  margin-left: 0.7rem;
  margin-top: 1rem;
  margin-right: 0.7rem;
}

.jokebtn {
  padding: 1rem 1.5rem;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
  background-color: #ea526f;
  border-radius: 20px;
  border: 1px solid #e42549;
  cursor: pointer;
  color: #ffffff;
  font-size: 2rem;
  text-decoration: none;
  text-shadow: 0px 1px 0px #e42549;
}

.text-container {
  height: auto;
  width: 30vw;
  text-align: center;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
}

#text {
  margin: 2rem;
}

h2 {
  background-color: #555;
  font-size: 2rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  color: #fff;
}

.jokebtn:active {
  transform: scale(0.98);
}

.jokebtn:hover {
  background-color: #e42549;
}

.text-cont {
  height: auto;
  width: 100%;
}
.btn-cont {
  height: 35%;
  width: 100%;
}

.animated-bg {
  opacity: 0.3;
  background-image: linear-gradient(
    to right,
    #c6c8ca 0%,
    #dbdbdd 10%,
    #bebebe 20%,
    #f3f3f3 1000%
  );
  background-size: 200% 100%;
  animation: bgPos 1s linear infinite;
}

.animated-bg-text {
  border-radius: 10px;
  display: block;
  margin: 0.7rem;
  height: 20px;
  width: 100px;
}

@keyframes bgPos {
  0% {
    background-position: 50% 0;
  }
  100% {
    background-position: -150% 0;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

Test

          When you walked through the door. It was clear to me (Clear to me).
          You’re the one they adore. Who they came to see (Who they came to

      <button type="submit" id="jokeBtn" class="jokebtn">One more!</button>

```

Title: Shimmer effect with vannila js

Body:
Here is my code and I'm trying to implement the Shimmer Loading Effect on it.
I made the effect and you can see it on the initial render. The thing is I don't know how to use it.
the first text content is from my html file and doesnt need an ajax call.
But when the button is clicked the request is sent to api and the effect should displays as long as the data from ajax call returns. then it shoud be disappeard again.
I got confused totally.

const btn = document.getElementById('jokeBtn');
const text = document.getElementById('text');

const loading = document.getElementById('shimmer');

const url = 'https://icanhazdadjoke.com/';

async function getter() {
  const initialPromise = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  const myPromise = await initialPromise.json();
  text.innerHTML = myPromise.joke;
  loading.style.display = 'none';
}

btn.addEventListener('click', getter);

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100;300&display=swap');
* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}
html {
  box-sizing: border-box;
  font-size: 62.5%;
  font-family: 'Georama', sans-serif;
}
body {
  height: 100vh;
  justify-content: center;
  align-items: center;
  display: flex;
  color: #fff;
  -webkit-font-smoothing: antialiased;
  background-color: #000;
  display: flex;
  flex-direction: column;
}
.sec1 {
  height: 500px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sec2 {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

p {
  font-size: 2rem;
  color: #222;
  text-align: left;
  margin-left: 0.7rem;
  margin-top: 1rem;
  margin-right: 0.7rem;
}

.jokebtn {
  padding: 1rem 1.5rem;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
  background-color: #ea526f;
  border-radius: 20px;
  border: 1px solid #e42549;
  cursor: pointer;
  color: #ffffff;
  font-size: 2rem;
  text-decoration: none;
  text-shadow: 0px 1px 0px #e42549;
}

.text-container {
  height: auto;
  width: 30vw;
  text-align: center;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
}

#text {
  margin: 2rem;
}

h2 {
  background-color: #555;
  font-size: 2rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  color: #fff;
}

.jokebtn:active {
  transform: scale(0.98);
}

.jokebtn:hover {
  background-color: #e42549;
}

.text-cont {
  height: auto;
  width: 100%;
}
.btn-cont {
  height: 35%;
  width: 100%;
}

.animated-bg {
  opacity: 0.3;
  background-image: linear-gradient(
    to right,
    #c6c8ca 0%,
    #dbdbdd 10%,
    #bebebe 20%,
    #f3f3f3 1000%
  );
  background-size: 200% 100%;
  animation: bgPos 1s linear infinite;
}

.animated-bg-text {
  border-radius: 10px;
  display: block;
  margin: 0.7rem;
  height: 20px;
  width: 100px;
}

@keyframes bgPos {
  0% {
    background-position: 50% 0;
  }
  100% {
    background-position: -150% 0;
  }
}

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

Test

          When you walked through the door. It was clear to me (Clear to me).
          You’re the one they adore. Who they came to see (Who they came to

      <button type="submit" id="jokeBtn" class="jokebtn">One more!</button>

Body:
I try to fix, what you mean?

const btn = document.getElementById('jokeBtn');
const text = document.getElementById('text');

const loading = document.getElementById('shimmer');

const url = 'https://icanhazdadjoke.com/';

async function getter() {
  text.style.display = 'none';
  loading.style.display = 'block';
  const initialPromise = await fetch(url, {
    headers: {
      Accept: 'application/json',
    },
  });
  const myPromise = await initialPromise.json();
  text.innerHTML = myPromise.joke;
  loading.style.display = 'none';
  text.style.display = 'block';
}
loading.style.display = 'none';
btn.addEventListener('click', getter);

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100;300&display=swap');
* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}
html {
  box-sizing: border-box;
  font-size: 62.5%;
  font-family: 'Georama', sans-serif;
}
body {
  height: 100vh;
  justify-content: center;
  align-items: center;
  display: flex;
  color: #fff;
  -webkit-font-smoothing: antialiased;
  background-color: #000;
  display: flex;
  flex-direction: column;
}
.sec1 {
  height: 500px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sec2 {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

p {
  font-size: 2rem;
  color: #222;
  text-align: left;
  margin-left: 0.7rem;
  margin-top: 1rem;
  margin-right: 0.7rem;
}

.jokebtn {
  padding: 1rem 1.5rem;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
  background-color: #ea526f;
  border-radius: 20px;
  border: 1px solid #e42549;
  cursor: pointer;
  color: #ffffff;
  font-size: 2rem;
  text-decoration: none;
  text-shadow: 0px 1px 0px #e42549;
}

.text-container {
  height: auto;
  width: 30vw;
  text-align: center;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 2px 4px 17px -5px rgba(0, 0, 0, 0.71);
}

#text {
  margin: 2rem;
}

h2 {
  background-color: #555;
  font-size: 2rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  color: #fff;
}

.jokebtn:active {
  transform: scale(0.98);
}

.jokebtn:hover {
  background-color: #e42549;
}

.text-cont {
  height: auto;
  width: 100%;
}
.btn-cont {
  height: 35%;
  width: 100%;
}

.animated-bg {
  opacity: 0.3;
  background-image: linear-gradient(
    to right,
    #c6c8ca 0%,
    #dbdbdd 10%,
    #bebebe 20%,
    #f3f3f3 1000%
  );
  background-size: 200% 100%;
  animation: bgPos 1s linear infinite;
}

.animated-bg-text {
  border-radius: 10px;
  display: block;
  margin: 0.7rem;
  height: 20px;
  width: 100px;
}

@keyframes bgPos {
  0% {
    background-position: 50% 0;
  }
  100% {
    background-position: -150% 0;
  }
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
  </head>
  <body>
    <section class="sec1">
      <div class="text-container">
        <div class="title-cont">
          <h2>Test</h2>
        </div>
        <p id="text">
          When you walked through the door. It was clear to me (Clear to me).
          You’re the one they adore. Who they came to see (Who they came to

        </p>
        <div id="shimmer">
          <span class="animated-bg-text animated-bg" style="width: 100%"
            >&nbsp;</span
          >
          <span class="animated-bg-text animated-bg" style="width: 100%"
            >&nbsp;</span
          >
          <span class="animated-bg-text animated-bg" style="width: 100%"
            >&nbsp;</span
          >
          <span class="animated-bg-text animated-bg" style="width: 50%"
            >&nbsp;</span
          >
        </div>
      </div>
    </section>
    <section class="sec2">
      <button type="submit" id="jokeBtn" class="jokebtn">One more!</button>
    </section>
    <script src="main.js"></script>
  </body>
</html>


问:
Regex to find the first capital letter in a string
I have looked all over for an answer to this, but no one has had quite the same question as I do.

The problem I am trying to solve is to find the first capital letter in a string and no other capital letters. I have been able to narrow my search to each instance of a capital letter, but no amount of quantifiers I could find can make it only the first one.

For example, in this String abcDefgH. I only want to match the D and not the H.

答:
Use a simple
([A-Z])I maybe missunderstood your question, but this will select only the first Capitalized letter in string.


问:
Adb daemon doesn't start automatically
Since upgrading to Android Studio Bumblebee, the adb demon doesn't start automatically when launching AS. I have to manually start it with adb start-server every time I launch AS in order to run/debug projects. That wasn't the case before the upgrade.

The setting is set to automatically start:

Is there a way to start it automatically when launching Android Studio?

答:
Thanks to this answer. Resolved by disabling adb mDNS for wireless debugging:

Android Studio > Settings > Build, Execution, Deployment > Debugger > Untick "Enable adb mDNS for wireless debugging"

Title: Adb daemon doesn't start automatically


问:
Report error "eaddrinuse" but there is no port occupied in "netstat" or "lsof -i:port"
{error_logger,{{2013,10,14},{12,31,31}},"Protocol: ~p: register/listen error: ~p~n",["inet_tcp",eaddrinuse]}

Can anyone give some advice. Thank you.

答:
For people who tries to run 2 rabbitmq on same server, don't uncomment two tcp port with same port in /etc/rabbitmq/rabbitmq.conf. It should be like:

```<code>listeners.tcp.default = 5700

## To listen on a specific interface, provide an IP address with port.
## For example, to listen only on localhost for both IPv4 and IPv6:
##
# IPv4
#listeners.tcp.local    = 127.0.0.1:5700
# IPv6
# listeners.tcp.local_v6 = ::1:5700
</code>```

For ipv4 and ipv6 change the port, otherwise you'll face with eaddrinuse error.

Body:
For people who tries to run 2 rabbitmq on same server, don't uncomment two tcp port with same port in /etc/rabbitmq/rabbitmq.conf. It should be like:

listeners.tcp.default = 5700

## To listen on a specific interface, provide an IP address with port.
## For example, to listen only on localhost for both IPv4 and IPv6:
##
# IPv4
#listeners.tcp.local    = 127.0.0.1:5700
# IPv6
# listeners.tcp.local_v6 = ::1:5700

For ipv4 and ipv6 change the port, otherwise you'll face with eaddrinuse error.


问:
Terraform - data resource access in AWS cross account
I writing a terraform script and I want to use data resource to get Kafka MSK related resources, such as Kafka cluster ARN, Kafka Topic ARN.

for example -

```<code>data "aws_s3_bucket" "content_bucket" {
  bucket = "nameof-bucket-from-another-account"
}
</code>```

and I'm wondering if terraform supports getting such resources cross AWS accounts?

I searched but could not find anything about it.

答:
I don't know if can be helpful, i never tried something like that, but i think you can use Assume Role for access from your AWS account to another account.

In this way you can set another provider in Terraform with an alias and use it in the data source.

```<code>provider "aws" {
  region     = var.aws_default_region
  access_key = var.aws_access_key_id
  secret_key = var.aws_secret_access_key

}

provider "aws" {
  alias      = "second_account"
  region     = var.aws_default_region
  access_key = var.aws_access_key_id
  secret_key = var.aws_secret_access_key

  assume_role {
    role_arn = var.account_role_arn
  }
}

data "aws_s3_bucket" "content_bucket" {
  provider = aws.second_account
  bucket = "nameof-bucket-from-another-account"
}
</code>```

I am not sure if is possible to use provider aliases also in the Data Source, if you try please keep me updated, I will edit the response.

Body:
I writing a terraform script and I want to use data resource to get Kafka MSK related resources, such as Kafka cluster ARN, Kafka Topic ARN.

for example -

data "aws_s3_bucket" "content_bucket" {
  bucket = "nameof-bucket-from-another-account"
}

and I'm wondering if terraform supports getting such resources cross AWS accounts?

I searched but could not find anything about it.

Body:
I don't know if can be helpful, i never tried something like that, but i think you can use Assume Role for access from your AWS account to another account.

In this way you can set another provider in Terraform with an alias and use it in the data source.

provider "aws" {
  region     = var.aws_default_region
  access_key = var.aws_access_key_id
  secret_key = var.aws_secret_access_key

}

provider "aws" {
  alias      = "second_account"
  region     = var.aws_default_region
  access_key = var.aws_access_key_id
  secret_key = var.aws_secret_access_key

  assume_role {
    role_arn = var.account_role_arn
  }
}

data "aws_s3_bucket" "content_bucket" {
  provider = aws.second_account
  bucket = "nameof-bucket-from-another-account"
}

I am not sure if is possible to use provider aliases also in the Data Source, if you try please keep me updated, I will edit the response.


问:
Extension Methods - Changing the Namespace
I'm using a third party library which contains a bunch of extension methods on top of IQueryable. To use these extension methods i don't wish to have my application littered with using statements to the third party namespace in which the extension method resides in.

This is so that i can switch it out the library sometime in the near future as easily as possible. However i'm not sure what's the best way of doing this. One option i did contemplate was to create my own set of extension methods within the project (then i can control the namespace). The problem with this is i can't see how i can maintain the name of the existing extension method. For example:

```<code>namespace MyProject.Extensions {
    public static class IQueryableExtension {
        public static IQueryable<T> Fetch<T, K>(this IQueryable<T> queryable, Expression<Func<T, K>> selector) {
            return queryable.Fetch(selector);
        }
    }
}
</code>```

You may see the problem here. Where i am trying to call the third party extension method within mine it actually calls itself creating an infinite loop.

I'd appreciate the help. Thanks

答:
You don't have to use extension methods as extension methods, you can use them like static methods... so you could call the 3rd party Fetch method:</p>

```<code>ThirdPartyNamespace.Fetch(queryable, selector)
</code>```

Body:
I'm using a third party library which contains a bunch of extension methods on top of IQueryable. To use these extension methods i don't wish to have my application littered with using statements to the third party namespace in which the extension method resides in.

This is so that i can switch it out the library sometime in the near future as easily as possible. However i'm not sure what's the best way of doing this. One option i did contemplate was to create my own set of extension methods within the project (then i can control the namespace). The problem with this is i can't see how i can maintain the name of the existing extension method. For example:

namespace MyProject.Extensions {
    public static class IQueryableExtension {
        public static IQueryable<T> Fetch<T, K>(this IQueryable<T> queryable, Expression<Func<T, K>> selector) {
            return queryable.Fetch(selector);
        }
    }
}

You may see the problem here. Where i am trying to call the third party extension method within mine it actually calls itself creating an infinite loop.

I'd appreciate the help. Thanks

Body:
You don't have to use extension methods as extension methods, you can use them like static methods... so you could call the 3rd party Fetch method:

ThirdPartyNamespace.Fetch(queryable, selector)


问:
Eslint not showing warnings - React
On my new project, ESLint is not outputting warnings like before, I'm using VSCode. If I have an unsed var somewhere in my code, it doesn't show the warning in the  terminal output anymore. Only in the problem tab.

Here's my eslint config file:

.eslintrc.json

```<code>{
  "env": {
      "browser": true,
      "es6": true
  },
  "extends": [
      "plugin:react/recommended",
      "airbnb-typescript",
      "plugin:@typescript-eslint/recommended",
      "plugin:@typescript-eslint/eslint-recommended",
      "prettier/@typescript-eslint",
      "plugin:prettier/recommended"
  ],
  "globals": {
      "Atomics": "readonly",
      "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaFeatures": {
          "jsx": true
      },
      "ecmaVersion": 2018,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "react",
      "react-hooks",
      "@typescript-eslint",
      "prettier"
  ],
  "rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks":"error",
    "react-hooks/exhaustive-deps": "warn",
    "camelcase": "off",
    "@typescript-eslint/camelcase": "off",
    "react/jsx-filename-extension": [1, {"extensions": [".tsx"]}],
    "import/prefer-default-export": "off",
    "react/jsx-one-expression-per-line": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "no-unused-expressions": "off",
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      {
        "allowExpressions": true
      }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never",
        "tsx": "never"
      }
    ],
    "semi":"off"
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    }
  }
}

</code>```

and Here is my package.json devDependencies:

package.json

```<code>  "dependencies": {
    ...,
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "^4.0.2"
  }
  "devDependencies": {
    "@types/react-router-dom": "^5.1.7",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.14.2",
    "@typescript-eslint/parser": "^4.14.2",
    "eslint": "^7.19.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^7.2.0",
    "eslint-import-resolver-typescript": "^2.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "husky": "^5.0.8",
    "prettier": "^2.2.1",
    "prettier-eslint-cli": "^5.0.0",
    "typescript": "^4.1.3"
  }
</code>```

答:
You can check if ESLint works correctly by directly invoking the command ./node_modules/.bin/eslint .. This way you'll get more helpful error messages if there are any. Also, make sure to check if you have multiple configuration files. Have a look at this ESLint Documentation page to make sure, your configuration is the only (or the one with the highest priority).

If there are multiple configuration files in the same directory, ESLint will only use one. The priority order is as follows:

.eslintrc.js

.eslintrc.cjs

.eslintrc.yaml

.eslintrc.yml

.eslintrc.json

package.json

Title: Eslint not showing warnings - React

Body:
On my new project, ESLint is not outputting warnings like before, I'm using VSCode. If I have an unsed var somewhere in my code, it doesn't show the warning in the  terminal output anymore. Only in the problem tab.

Here's my eslint config file:

.eslintrc.json

{
  "env": {
      "browser": true,
      "es6": true
  },
  "extends": [
      "plugin:react/recommended",
      "airbnb-typescript",
      "plugin:@typescript-eslint/recommended",
      "plugin:@typescript-eslint/eslint-recommended",
      "prettier/@typescript-eslint",
      "plugin:prettier/recommended"
  ],
  "globals": {
      "Atomics": "readonly",
      "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaFeatures": {
          "jsx": true
      },
      "ecmaVersion": 2018,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "react",
      "react-hooks",
      "@typescript-eslint",
      "prettier"
  ],
  "rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks":"error",
    "react-hooks/exhaustive-deps": "warn",
    "camelcase": "off",
    "@typescript-eslint/camelcase": "off",
    "react/jsx-filename-extension": [1, {"extensions": [".tsx"]}],
    "import/prefer-default-export": "off",
    "react/jsx-one-expression-per-line": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "no-unused-expressions": "off",
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      {
        "allowExpressions": true
      }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never",
        "tsx": "never"
      }
    ],
    "semi":"off"
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    }
  }
}

and Here is my package.json devDependencies:

package.json

  "dependencies": {
    ...,
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "^4.0.2"
  }
  "devDependencies": {
    "@types/react-router-dom": "^5.1.7",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.14.2",
    "@typescript-eslint/parser": "^4.14.2",
    "eslint": "^7.19.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^7.2.0",
    "eslint-import-resolver-typescript": "^2.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "husky": "^5.0.8",
    "prettier": "^2.2.1",
    "prettier-eslint-cli": "^5.0.0",
    "typescript": "^4.1.3"
  }


问:
Get all product categories in WooCommerce
I am trying to get product categories in WooCommerce, but get_terms() function doesn't work for me. I am getting an empty array.

What I am doing wrong? How to get all Woocommerce product category terms?

答:
I got mine out of all product categories, also exclude categories that I don't want to display</p>
```<code>$taxonomy = "product_cat";
$terms = get_terms($taxonomy, array('orderby' => 'slug', 'hide_empty' => false, 'exclude' => array( 19 ))); //Exclude Specific Category by ID

foreach ($terms as $term) {
    $thumbnail_id = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
    $image = wp_get_attachment_url($thumbnail_id); ?>

    <div class="col-12 col-md-3">
        <div class="cat-item drop-shadow white-b padding-20 align-center margin-bottom-30">
            <?php
                echo '<h3 class="uppercase strong blue-2-c margin-bototm-20 equal-height">' . $term->name . '</h3>';
                echo '<div class="item-thumbnail" style="background: url('.$image.');height:150px"></div>';
                echo '<a href="' . get_term_link($term->name, $taxonomy) . '" class="button color-blue-2-radial">View Range</a>';
            ?>
        </div>
    </div>
</code>```

Body:
I got mine out of all product categories, also exclude categories that I don't want to display

$taxonomy = "product_cat";
$terms = get_terms($taxonomy, array('orderby' => 'slug', 'hide_empty' => false, 'exclude' => array( 19 ))); //Exclude Specific Category by ID

foreach ($terms as $term) {
    $thumbnail_id = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
    $image = wp_get_attachment_url($thumbnail_id); ?>

    <div class="col-12 col-md-3">
        <div class="cat-item drop-shadow white-b padding-20 align-center margin-bottom-30">
            <?php
                echo '<h3 class="uppercase strong blue-2-c margin-bototm-20 equal-height">' . $term->name . '</h3>';
                echo '<div class="item-thumbnail" style="background: url('.$image.');height:150px"></div>';
                echo '<a href="' . get_term_link($term->name, $taxonomy) . '" class="button color-blue-2-radial">View Range</a>';
            ?>
        </div>
    </div>


问:
React native: Error "Unexpected identifier '_classCallCheck'.import call expects exactly one argument"
I'm using React-Native on my android program, after open my porject with react-native run-android ,the error occurred.The same error message occurred twice.

```<code>Unexpected identifier '_classCallCheck'.import call expects exactly one argument

Unexpected identifier '_classCallCheck'.import call expects exactly one argument

no stack

no stack
</code>```

I googled this and try some solutions, but still can't resolve.
Here is a similar problem that I have found:
https://github.com/facebook/react-native/issues/23669

What I have been tried for this error:

cd to /andorid, use gradlew clean

use react-native start --reset-cache

use npm install -g react-native-cli

Here is my develop environment:

```<code>Android:
AVD version: Android 7.0 with Play Store
System:
OS: Windows 10 10.0.19043
CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Memory: 2.11 GB / 15.71 GB
Binaries:
Node: 10.16.0 - D:\nodejs\node.EXE
Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD
npm: 6.9.0 - D:\nodejs\npm.CMD
Watchman: Not Found
SDKs:
Android SDK:
  API Levels: 28, 32
  Build Tools: 28.0.3, 32.0.0
  System Images: android-24 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom
  Android NDK: Not Found
Windows SDK: Not Found
IDEs:
Android Studio: Version     2020.3.0.0 AI-203.7717.56.2031.7935034
Visual Studio: Not Found
Languages:
Java: 1.8.0_232
npmPackages:
@react-native-community/cli: Not Found
react: 16.9.0 => 16.9.0
react-native: ^0.64.0 => 0.64.3
react-native-windows: Not Found
npmGlobalPackages:
*react-native*: Not Found
</code>```

Guys,I just solved this problem.Here's the link.
https://github.com/babel/babel/issues/14139

from:

```<code>module.exports = {
   presets: ['module:metro-react-native-babel-preset'],
};
</code>```

to:

```<code>module.exports = {
   presets: [['module:metro-react-native-babel-preset', {
        unstable_disableES6Transforms: true
    }]],
};
</code>```

答: I had the same problem and the steps above didn't work, so i update metro-react-native-babel-preset from 0.56.0 to 0.59.0 and it worked.</p>

Body:
I'm using React-Native on my android program, after open my porject with react-native run-android ,the error occurred.The same error message occurred twice.

Unexpected identifier '_classCallCheck'.import call expects exactly one argument

Unexpected identifier '_classCallCheck'.import call expects exactly one argument

no stack

no stack

I googled this and try some solutions, but still can't resolve.
Here is a similar problem that I have found:
https://github.com/facebook/react-native/issues/23669

What I have been tried for this error:

cd to /andorid, use gradlew clean

use react-native start --reset-cache

use npm install -g react-native-cli

Here is my develop environment:

Android:
AVD version: Android 7.0 with Play Store
System:
OS: Windows 10 10.0.19043
CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Memory: 2.11 GB / 15.71 GB
Binaries:
Node: 10.16.0 - D:\nodejs\node.EXE
Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD
npm: 6.9.0 - D:\nodejs\npm.CMD
Watchman: Not Found
SDKs:
Android SDK:
  API Levels: 28, 32
  Build Tools: 28.0.3, 32.0.0
  System Images: android-24 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom
  Android NDK: Not Found
Windows SDK: Not Found
IDEs:
Android Studio: Version     2020.3.0.0 AI-203.7717.56.2031.7935034
Visual Studio: Not Found
Languages:
Java: 1.8.0_232
npmPackages:
@react-native-community/cli: Not Found
react: 16.9.0 => 16.9.0
react-native: ^0.64.0 => 0.64.3
react-native-windows: Not Found
npmGlobalPackages:
*react-native*: Not Found

Guys,I just solved this problem.Here's the link.
https://github.com/babel/babel/issues/14139

from:

module.exports = {
   presets: ['module:metro-react-native-babel-preset'],
};

to:

module.exports = {
   presets: [['module:metro-react-native-babel-preset', {
        unstable_disableES6Transforms: true
    }]],
};


问:
infinite loop in assembly 8086
So I have a bit of a problem here with a loop.I want an array to be of size n inputed by the user which can be no smaller than 5 and which elements are given by the user then give me the smallest value in the array.The problem is that the loop works for far more than n and then for min value it just prints all the elements of the array.</p>
```<code>data segment
    value_n    db  13,10,'Entrer n : $'
    text        db  13,10,' Entrer un chiffre : $'
    mini        db  13,10,' Min : $'
    n           dw  ?              ;taille du tableau
    tab1        db  n dup(0)
    k           dw  4
    j           dw  11
ends

stack segment
    db 128 dup(0)
ends

code segment
    lea dx,n
    mov ah,09h
    int 21h

    mov ah,01
    int 21h

    k equ 4
    j equ 11

    cmp dx,4
    jle instruction

    instruction :
    mov ax,data
    mov ds,ax
    mov ax,stack
    mov ss,ax

    mov ax,00h
    mov si,00h
    mov cx,dx
    mov [200h],3Ah  ;min

    i:
    mov  ah,09h
    mov  dl,offset text
    int  21h
    mov  ah,01h
    int  21h
    mov  tab1[si],al
    cmp  al,[200h]
    jl   min
    x:
    cmp  al,[201h]
    jmp  v
    min:
    mov  [200h],al
    jmp  x
    v:
    inc  si
    loop i

    mov  ah,02h
    mov  dl,0Ah
    int  21h

    mov  ah,09h
    mov  dl,offset mini
    int  21h
    mov  ah,02h
    mov  dl,[200h]
    int  21h
    mov  ah,09h
    int  21h
    mov  ah,02h
    mov  dl,[201h]
    int  21h

    mov  ax,4C00h
    int  21h
ends
</code>```

答:
The handling of dx at the beginning seems wrong.

lea dx, n loads dx with the address of n (by the way, mov dx, offset n is equivalent and saves 1 byte).  There are no further writes to dx, and the int 21h calls would preserve it, so the subsequent cmp dx, 4 is comparing the address of n with the number 4, which doesn't make much sense.  If it's less than or equal (signed compare, also seems odd) then you jump to instruction.  If it isn't... then you fall through into instruction anyway, so the whole cmp/jle sequence was just pointless.

So you end up in instruction with dx still equal to the address of n.  You move that into cx and use it as your loop count.  That surely doesn't seem right.

So: what is it that you are trying to compare against 4?  Whatever it is, it isn't in dx at that point.  And when you do make the compare, if the jle is not taken, you need to write some code after that to say what should happen instead.

By the way, your assumption that the memory at ds:[200h] is free and safe to overwrite also seems really sketchy.

Title: infinite loop in assembly 8086

Body:
So I have a bit of a problem here with a loop.I want an array to be of size n inputed by the user which can be no smaller than 5 and which elements are given by the user then give me the smallest value in the array.The problem is that the loop works for far more than n and then for min value it just prints all the elements of the array.

data segment
    value_n    db  13,10,'Entrer n : $'
    text        db  13,10,' Entrer un chiffre : $'
    mini        db  13,10,' Min : $'
    n           dw  ?              ;taille du tableau
    tab1        db  n dup(0)
    k           dw  4
    j           dw  11
ends

stack segment
    db 128 dup(0)
ends

code segment
    lea dx,n
    mov ah,09h
    int 21h

    mov ah,01
    int 21h

    k equ 4
    j equ 11

    cmp dx,4
    jle instruction

    instruction :
    mov ax,data
    mov ds,ax
    mov ax,stack
    mov ss,ax

    mov ax,00h
    mov si,00h
    mov cx,dx
    mov [200h],3Ah  ;min

    i:
    mov  ah,09h
    mov  dl,offset text
    int  21h
    mov  ah,01h
    int  21h
    mov  tab1[si],al
    cmp  al,[200h]
    jl   min
    x:
    cmp  al,[201h]
    jmp  v
    min:
    mov  [200h],al
    jmp  x
    v:
    inc  si
    loop i

    mov  ah,02h
    mov  dl,0Ah
    int  21h

    mov  ah,09h
    mov  dl,offset mini
    int  21h
    mov  ah,02h
    mov  dl,[200h]
    int  21h
    mov  ah,09h
    int  21h
    mov  ah,02h
    mov  dl,[201h]
    int  21h

    mov  ax,4C00h
    int  21h
ends


问:
React hooks one checkbox checked to uncheck other checkbox
Hi I have a parent component which contains a bunch child components which are checkboxes.
parent component is something like this inside:

```<code>const [items, setItems] = useState([
{
    id:1,
    selected: false,
},
{
    id:2,
    selected: false,
}
]);
const changeSelected = (id) =>
  {
    items.forEach((item)=>
    {
      if (item.id === id)
      {
        item.selected = !item.selected;
      }
      else{
        item.selected = false;
      }
    })
  }
return(
    <div>
        {items.map((item)=>{
            <Child item={item} changeSelected={changeSelected}/>
        })}
    </div>
)
</code>```

and in the child component, it has something like this inside:

```<code>return(
    <div>
        <input type="checkbox" checked={props.item.selected} onChange={()=>{props.changeSelected(props.item.id)}} />
    </div>
)
</code>```

I know partially this isnt working is because useState is async but I dont know what to do to make it work, or if I should try a different approach? Thank you

答:
You can refactor your function to this:</p>
```<code>const changeSelected = (id) => {
  setItems(prev => ([...prev, {id, selected: !prev.filter(x => x.id === id)[0].selected}]))
  }
</code>```

Body:
Hi I have a parent component which contains a bunch child components which are checkboxes.
parent component is something like this inside:

const [items, setItems] = useState([
{
    id:1,
    selected: false,
},
{
    id:2,
    selected: false,
}
]);
const changeSelected = (id) =>
  {
    items.forEach((item)=>
    {
      if (item.id === id)
      {
        item.selected = !item.selected;
      }
      else{
        item.selected = false;
      }
    })
  }
return(

        {items.map((item)=>{
            <Child item={item} changeSelected={changeSelected}/>
        })}

)

and in the child component, it has something like this inside:

return(

        <input type="checkbox" checked={props.item.selected} onChange={()=>{props.changeSelected(props.item.id)}} />

)

I know partially this isnt working is because useState is async but I dont know what to do to make it work, or if I should try a different approach? Thank you

Body:
You can refactor your function to this:

const changeSelected = (id) => {
  setItems(prev => ([...prev, {id, selected: !prev.filter(x => x.id === id)[0].selected}]))
  }


问:
How do you parse a poorly formatted HTML file?
I have to parse a series of web pages in order to import data into an application. Each type of web page provides the same kind of data. The problem is that the HTML of each page is different, so the location of the data varies. Another problem is that the HTML code is poorly formatted, making it impossible to use a XML-like parser.

So far, the best strategy I can think of, is to define a template for each kind of page, like:

Template A:

```<code><html>
...
  <tr><td>Table column that is missing a td
      <td> Another table column</td></tr>
  <tr><td>$data_item_1$</td>
...
</html>
</code>```

Template B:

```<code><html>
...
  <ul><li>Yet another poorly formatted page <li>$data_item_1$</td></tr>
...
</html>
</code>```

This way I would only need one single parser for all the pages, that would compare each page with its template and retrieving the $data_item_1$, $data_item_2$, etc.  Still, it is going to be a lot of work.  Can you think of any simpler solution? Any library that can help?

Thanks

答: I'd recommend Html Agility Pack. It has the ability to work with poorly structured HTML while giving you Xml like selection using Xpath. You would still have to template items or select using different selections and analyze but it will get you past the poor structure hump.</p>

OwnerDisplayName: ivo

ContentLicense: CC BY-SA 2.5

Body:
I have to parse a series of web pages in order to import data into an application. Each type of web page provides the same kind of data. The problem is that the HTML of each page is different, so the location of the data varies. Another problem is that the HTML code is poorly formatted, making it impossible to use a XML-like parser.

So far, the best strategy I can think of, is to define a template for each kind of page, like:

Template A:

...

Table column that is missing a td
       Another table column

$data_item_1$
...

Template B:

...

Yet another poorly formatted page
$data_item_1$

...

This way I would only need one single parser for all the pages, that would compare each page with its template and retrieving the $data_item_1$, $data_item_2$, etc.  Still, it is going to be a lot of work.  Can you think of any simpler solution? Any library that can help?

Thanks

LastEditorDisplayName: Eddie

OwnerDisplayName: Pat


问:
Any free XLSX ( Excel 2007 or above) reader and writer Helper Class or Library
Now I am in need of a Excel Library.
Any free XLSX ( Excel 2007 or above) reader and writer Helper Class or Library</p>

答:
See OpenXML 2.0 from MS...

It is a free library that does NOT require office to be installed... you can read + write Office files including Excel and Word (Version 2007 and up...).

IF you need more features (like rendering to PDF etc.) then you would need some 3rd-party library...


问:
Java Optional with multiple commands and return object
Attempting to execute multiple commands and return an Object (ResponseEntity) using Optional.ifPresentOrElse

More complex does not work:

```<code>return ifPresentOrElse(
           repoService.findById(inId),
           i -> {
               i.setStatus(inStatus);
               repoService.save(i);
               ResponseEntity.ok().body(i);
           },
           () -> {
               LOG.error("Object not available");
               ResponseEntity.notFound().build();
           });
</code>```

Simpler works but doesn't execute all the commands required:

```<code>Optional<I> iOptional = repoService.findById(inId);

return iOptional.map(i -> ResponseEntity.ok().body(i))
                .orElse(ResponseEntity.notFound().build());
</code>```

Is there away to achieve this using Optional functions?

答:
Firstly, the signature of ifPresentOrElse is:

public void ifPresentOrElse(Consumer<T> action, Runnable emptyAction)

means that you can't return the value of this function.

So you are not retuning anything when you call ResponseEntity.ok().body(i) or ResponseEntity.notFound().build(),
they are just rvalues.

On the other side, the signiture of map function is:

public  Optional map(Function<? super T,? extends U> mapper)

means that you can return the invocation of the mapper function.

Body:
Attempting to execute multiple commands and return an Object (ResponseEntity) using Optional.ifPresentOrElse

More complex does not work:

return ifPresentOrElse(
           repoService.findById(inId),
           i -> {
               i.setStatus(inStatus);
               repoService.save(i);
               ResponseEntity.ok().body(i);
           },
           () -> {
               LOG.error("Object not available");
               ResponseEntity.notFound().build();
           });

Simpler works but doesn't execute all the commands required:

Optional iOptional = repoService.findById(inId);

return iOptional.map(i -> ResponseEntity.ok().body(i))
                .orElse(ResponseEntity.notFound().build());

Is there away to achieve this using Optional functions?

Body:
Firstly, the signature of ifPresentOrElse is:

public void ifPresentOrElse(Consumer<T> action, Runnable emptyAction)

means that you can't return the value of this function.

So you are not retuning anything when you call ResponseEntity.ok().body(i) or ResponseEntity.notFound().build(),
they are just rvalues.

On the other side, the signiture of map function is:

public <U> Optional<U> map(Function<? super T,? extends U> mapper)

means that you can return the invocation of the mapper function.


问:
How to check when/whether an offer on the XRP Ledger's DEX has been accepted/fully consumed? [XRP] [XRPL]
I've been testing out interacting with the XRP Ledger, coding in Python. I started coding some basic queries regarding the status of the XRP Ledger from scratch based on the XRPL documentation (available here) but then discovered XRPL-PY (I've reviewed the GitHub repo here and the documentation here) and have since been predominately using XRPL-PY to interact with the XRP Ledger given its general ease of use. I've been able to accomplish most of the basic types of interactions with the XRP Ledger one might want to do, including creating a wallet and submitting an offer to exchange one currency for another on the XRP Ledger (what I'll call an "Offer"). However, one point that I have been unable to figure out, whether by using XRPL-PY or interacting with the XRP Ledger directly, is how to determine when/whether a previously submitted Offer has been fully consumed (i.e., another transaction, or transactions, were submitted to the XRP Ledger that accepted my Offer such that it is no longer outstanding and the offered currencies were exchanged at the offered rate). This seems like a basic query that most people interacting with the XRP Ledger would want to be able to establish, but I haven't seen anything in the XRPL or XRPL-PY documentation explaining how to do it. My preference would be to be able to subscribe to updates from the XRPL Ledger such that it lets me know once my Offer has been partially or fully consumed, but if that's not possible I would like to at least be able to repeatedly query the status of my Offer from the XRP Ledger and know what will change in the response once my Offer has been partially or fully consumed. Any suggestions would be greatly appreciated.</p>

答:
It looks like you had your question answered on another channel so I will include this here just in case people will find this useful later. Cheers!

You have 3 options:

POLLING account_offers. You can use the sequence number to identify the offer
POLLING book_offer. You can use the "Account" and "Sequence" fields to identify the offer.
WS subscribing to "accounts" using the account you want to track. This is the most "complex" because you need to parse all the metadata for all validated transactions that involve the particular account but it's the best because it's asynchronous and via websocket.


问:
NLRX Package: Include boolean parameter as variable
Can I include boolean parameters in the variables for a simdesign? An if so, how would that look like? Right now I only have metric variables like that:

```<code>variables = list(
    'navigation-system-rate' = list(min = 0, max = 1, qfun="qunif"),
    "expected-weight" = list(min = 0, max = 1, qfun="qunif")
  )
</code>```

but I want them to take the value "true" or "false" randomly for a certain parameter. Is that possible somehow?

答:
Yes you can define boolean and categorical variable values, but only for certain simdesigns (simple, distinct, full factorial) as explained here:
https://docs.ropensci.org/nlrx/articles/furthernotes.html#variables-and-constants-definitions

For example you can use,

```<code>variables = list(
    "bool1" = list(values = c("true", "false")),
    "bool2" = list(values = c("true", "false"))
  )
</code>```

and then for example apply a simdesign_ff() to run all combinations of your boolean variables.

All other simdesigns expect a numeric range/distribution and will not work with any categorical/boolean values.
As a simple workaround you could just apply some transformation to your parameter matrix after it has been generated.

E.g., if you are doing a latin hypercube, you can just define your boolean variable as uniformly distributed variable within the range 0 to 1. Then after applying the simdesign_lhs, just overwrite the nl@simdesign@siminput tibble and update the values of your variable by setting all cells with a value < 0.5 to false, and all other values to true.

```<code>
# Define variable as numeric in range 0 .. 1
nl@experiment <- experiment(
  # ...
  variables = list("bool1" = list(min = 0, max = 1, qfun="qunif"))
  # ...
)

# apply simdesign_lhs to generate parameter matrix
nl@simdesign <- simdesign_lhs(nl=nl,
                               samples=100,
                               nseeds=3,
                               precision=3)

# apply transformation to boolean (netlogo needs booleans as strings)
nl@simdesign@siminput <- nl@simdesign@siminput %>%
  dplyr::mutate(bool1 = dplyr::if_else(bool1 < 0.5, "false", "true"))

</code>```

Body:
Can I include boolean parameters in the variables for a simdesign? An if so, how would that look like? Right now I only have metric variables like that:

variables = list(
    'navigation-system-rate' = list(min = 0, max = 1, qfun="qunif"),
    "expected-weight" = list(min = 0, max = 1, qfun="qunif")
  )

but I want them to take the value "true" or "false" randomly for a certain parameter. Is that possible somehow?

Body:
Yes you can define boolean and categorical variable values, but only for certain simdesigns (simple, distinct, full factorial) as explained here:
https://docs.ropensci.org/nlrx/articles/furthernotes.html#variables-and-constants-definitions

For example you can use,

variables = list(
    "bool1" = list(values = c("true", "false")),
    "bool2" = list(values = c("true", "false"))
  )

and then for example apply a simdesign_ff() to run all combinations of your boolean variables.

All other simdesigns expect a numeric range/distribution and will not work with any categorical/boolean values.
As a simple workaround you could just apply some transformation to your parameter matrix after it has been generated.

E.g., if you are doing a latin hypercube, you can just define your boolean variable as uniformly distributed variable within the range 0 to 1. Then after applying the simdesign_lhs, just overwrite the nl@simdesign@siminput tibble and update the values of your variable by setting all cells with a value < 0.5 to false, and all other values to true.

# Define variable as numeric in range 0 .. 1
nl@experiment <- experiment(
  # ...
  variables = list("bool1" = list(min = 0, max = 1, qfun="qunif"))
  # ...
)

# apply simdesign_lhs to generate parameter matrix
nl@simdesign <- simdesign_lhs(nl=nl,
                               samples=100,
                               nseeds=3,
                               precision=3)

# apply transformation to boolean (netlogo needs booleans as strings)
nl@simdesign@siminput <- nl@simdesign@siminput %>%
  dplyr::mutate(bool1 = dplyr::if_else(bool1 < 0.5, "false", "true"))


问:
Error: "'node' not recognized as..." when I try to run the file with package.json script
I am learning Node, and I get the error "node is not recognized as an internal or external command" when I try to run my project with npm start or npm run start. It works if I use node index.js. I have checked the Node Environment Variables, my Node version is v16.13.2 and npm is 8.4.1.
My package.json:

```<code>{
  "name": "node-express-practica",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.17.0",
    "@babel/core": "^7.17.2",
    "@babel/preset-env": "^7.16.11",
    "@babel/register": "^7.17.0",
    "nodemon": "^2.0.15"
  }
}
</code>```

答: Running command as administrator should work for you.</p>

Body:
I am learning Node, and I get the error "node is not recognized as an internal or external command" when I try to run my project with npm start or npm run start. It works if I use node index.js. I have checked the Node Environment Variables, my Node version is v16.13.2 and npm is 8.4.1.
My package.json:

{
  "name": "node-express-practica",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.17.0",
    "@babel/core": "^7.17.2",
    "@babel/preset-env": "^7.16.11",
    "@babel/register": "^7.17.0",
    "nodemon": "^2.0.15"
  }
}


问:
Automatic Ordinal Number in django queryset ? How to sort this thing in Django?
I have problem to sort such thing as 'Ordinal Number'.

For example, I have my Parent Model (Order) and child (Item). I don't know how make Items ID field starting from 1 to N where N is number of items in this particullar Order.
It's hard to explain for me , so I put some img with things I want to make and try to explain it by example.

My problem on screen

And those are my models.py:

```<code>class Order(models.Model):
    PENDING = 0
    DURING = 1
    DONE = 2
    STATUS = (
        (PENDING, 'Oczekuję'),
        (DURING, 'W trakcie'),
        (DONE, 'Zakończone'),
    )
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_user')
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    slug = RandomSlugField(length=7, exclude_lower=True, exclude_upper=True, exclude_vowels=True)
    status = models.SmallIntegerField(choices=STATUS, default=PENDING)

    class Meta:
        verbose_name = "zamówienie"
        verbose_name_plural = "zamówienia"

    def __str__(self):
        return "Zamówienie ID#{} z dnia {}".format(self.slug, self.date_created.strftime('%d/%m/%y'))

    def get_absolute_url(self):
        return reverse('detail', kwargs={'slug': self.slug})

class Item(models.Model):

    order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL)
    lenght = models.DecimalField(max_digits=4, decimal_places=0)
    width = models.DecimalField(max_digits=4, decimal_places=0)
    lenght = models.PositiveSmallIntegerField(blank=False)
    quantity = models.SmallIntegerField(default=1, blank=False, null=False)
    description = models.CharField(max_length=255, blank=True, null=True)
    lenght1 = models.BooleanField(default=False)
    lenght2 = models.BooleanField(default=False)
    width1 = models.BooleanField(default=False)
    width2 = models.BooleanField(default=False)

    class Meta:

        verbose_name = "formatka"
        verbose_name_plural = "formatki"

    def __str__(self):
        return "{} x {}".format(self.width, self.lenght)
</code>```

答:
```<code>#Make items ID count from 1 for each Order
for index, i in enumerate(item):
    i.id = index + 1
    i.save()
</code>```

The solution is to use enumarte(), example for my code above. Where index is a number off element in list, as usually counting from 0. So we need do index + 1, to start counting from 1. And finally we do i.save(), to save it updated to db.

Body:
I have problem to sort such thing as 'Ordinal Number'.

For example, I have my Parent Model (Order) and child (Item). I don't know how make Items ID field starting from 1 to N where N is number of items in this particullar Order.
It's hard to explain for me , so I put some img with things I want to make and try to explain it by example.

My problem on screen

And those are my models.py:

class Order(models.Model):
    PENDING = 0
    DURING = 1
    DONE = 2
    STATUS = (
        (PENDING, 'Oczekuję'),
        (DURING, 'W trakcie'),
        (DONE, 'Zakończone'),
    )
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_user')
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    slug = RandomSlugField(length=7, exclude_lower=True, exclude_upper=True, exclude_vowels=True)
    status = models.SmallIntegerField(choices=STATUS, default=PENDING)

    class Meta:
        verbose_name = "zamówienie"
        verbose_name_plural = "zamówienia"

    def __str__(self):
        return "Zamówienie ID#{} z dnia {}".format(self.slug, self.date_created.strftime('%d/%m/%y'))

    def get_absolute_url(self):
        return reverse('detail', kwargs={'slug': self.slug})

class Item(models.Model):

    order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL)
    lenght = models.DecimalField(max_digits=4, decimal_places=0)
    width = models.DecimalField(max_digits=4, decimal_places=0)
    lenght = models.PositiveSmallIntegerField(blank=False)
    quantity = models.SmallIntegerField(default=1, blank=False, null=False)
    description = models.CharField(max_length=255, blank=True, null=True)
    lenght1 = models.BooleanField(default=False)
    lenght2 = models.BooleanField(default=False)
    width1 = models.BooleanField(default=False)
    width2 = models.BooleanField(default=False)

    class Meta:

        verbose_name = "formatka"
        verbose_name_plural = "formatki"

    def __str__(self):
        return "{} x {}".format(self.width, self.lenght)

Body:
#Make items ID count from 1 for each Order
for index, i in enumerate(item):
    i.id = index + 1
    i.save()

The solution is to use enumarte(), example for my code above. Where index is a number off element in list, as usually counting from 0. So we need do index + 1, to start counting from 1. And finally we do i.save(), to save it updated to db.


问:
How to select columns from different tables in 1 query when I don't have a foreign key
I have the following tables in my database:

As you can see my matches table contains 2 columns named: team_id_1 and team_id_2, what I want is to select all column from the matches table and also get the team_name_en and team_name_ar from the teams table for team_id_1 and team_id_2.

Note that my matches table has 1 foreign key: group_id

答:
You can join all tables , teams twice, to get all colums.

```<code>SELECT
    m.*, g.*, t1.*, t2.*
FROM
    matches m
        INNER JOIN
    `groups` g ON g.group_id = m.group_id
        INNER JOIN
    teams t1 ON t1.team_id = m.team_id_1
        INNER JOIN
    teams t2 ON t2.team_id = m.team_id_2
</code>```

But you should only join tables, if you need the columns.

also you should only get the columns that are needed. but when you run the query you at least can see how it works

Body:
You can join all tables , teams twice, to get all colums.

SELECT
    m.*, g.*, t1.*, t2.*
FROM
    matches m
        INNER JOIN
    `groups` g ON g.group_id = m.group_id
        INNER JOIN
    teams t1 ON t1.team_id = m.team_id_1
        INNER JOIN
    teams t2 ON t2.team_id = m.team_id_2

But you should only join tables, if you need the columns.

also you should only get the columns that are needed. but when you run the query you at least can see how it works


问:
Find the lowest and highest NUMBERS in a collection
I have a List<BigDecimal> collection which contains (for the sake of simplicity) BigDecimal prices. I would like to process the collection and get:

All of the highest prices.

All of the lowest prices.

My initial thoughts are to approach this using look-behind in order to decide if the numbers are moving in an up or down trend. When the trend changes - determine which of the previous numbers are "highest" or "lowest" prices and then add them to the respectful List<BigDecimal> lowestPrices and List<BigDecimal highestPrices collections. For example, the first 3 dots are in an up-trend, but the 4th changes the trend to a down-trend. So can now determine the min/max of the numbers before the change (0,1,2) and get the prices.

I am not entirely sure if this isn't a naive approach so I was wondering if there would be the best approach to solving this issue in java?
Maybe a library that can already do this? (probably better not to re-invent the wheel)

答:
You are looking for local maxima (/minima).

Just look at whether the current point is greater (/less) than the point preceding and following it:

For a local maximum:

```<code>list.get(i) > list.get(i - 1) && list.get(i) > list.get(i + 1)
</code>```

For a local minimum:

```<code>list.get(i) < list.get(i - 1) && list.get(i) < list.get(i + 1)
</code>```

Pseudocode:

```<code>for (int i = 1; i < list.size()-1; ++i) {
  if (local maximum) {
    // Add to list of local maxima
  } else if (local minimum) {
    // Add to list of local minima
  }
}
</code>```

and handle the two endpoints as you desire.

(You can also do this in ways that are more efficient for non-random access lists, e.g. LinkedList, using (List)Iterators; but the principle is the same).

Body:
You are looking for local maxima (/minima).

Just look at whether the current point is greater (/less) than the point preceding and following it:

For a local maximum:

list.get(i) > list.get(i - 1) && list.get(i) > list.get(i + 1)

For a local minimum:

list.get(i) < list.get(i - 1) && list.get(i) < list.get(i + 1)

Pseudocode:

for (int i = 1; i < list.size()-1; ++i) {
  if (local maximum) {
    // Add to list of local maxima
  } else if (local minimum) {
    // Add to list of local minima
  }
}

and handle the two endpoints as you desire.

(You can also do this in ways that are more efficient for non-random access lists, e.g. LinkedList, using (List)Iterators; but the principle is the same).


问:
regex for matching phrases even if its within a bracket
I want to match 'marks' 'marks-for-days' 'reactions(98%)' 'fun-for me'

All of those even if its without the brackets like:

marksman - no match

marksreaction - no match

but

marks (98%) - match

reactions 98% - match

fun for me - match

there are no fun only marks - match

I tried the basic word matching but it doesnt work  \w*(marks|reactions|fun for me)\w*.

答:
You are not matching the - in marks-for-days only the spaces.

Using a character class can match either a space or hyphen [- ] and use word boundaries to prevent partial matches.

```<code>\b(?:marks|reactions|fun[- ]for[- ]me)\b
</code>```

Regex demo

If you want to match the whole line you can add .* before and after the pattern:

```<code>.*\b(?:marks|reactions|fun[- ]for[- ]me)\b.*
</code>```

Regex demo

Body:
You are not matching the - in marks-for-days only the spaces.

Using a character class can match either a space or hyphen [- ] and use word boundaries to prevent partial matches.

\b(?:marks|reactions|fun[- ]for[- ]me)\b

Regex demo

If you want to match the whole line you can add .* before and after the pattern:

.*\b(?:marks|reactions|fun[- ]for[- ]me)\b.*

Regex demo


问:
Error saving e-mail from outlook via Python win32com.client: Unable to write to file
I am trying to save mail via Python and get this error

-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Unable to write to file: C:\...\ docs. Right-click the folder containing the file you want to write to, and then select 'Properties' from the menu and check your permissions for this folder.'

Account has all the permissions and access to the folder.

答: The system drive C:\ requires admin privileges for writing. Try choosing another drive or folder.


问:
range slider html css javascript
I'm planning to make a 'range slider' type in registration form and the JavaScript validation 'must be 16 years and above'.

Example if I'm plan make a JavaScript valuation "must be minimum 0 years and maximum 50 years", these are the html

```<code><input type="range" id="vol" name="vol" min="0" max="50">
</code>```

But if I'm assuming 'must be 16 years and above' the minimum is 16 years old and the maximum is infinite, what would the html code be? is infinite possible or the maximum is always 100?

答:
 giphy animated gif link

I have developed a range slider but it uses html css and angular (typescript).  You may have to modify code slightly but it works by using a CSS circle, placing the number value at a position in that circle, and placing that over the input range.

html section

```<code><div class="row small-margin"><div class="col-lg-8 small-padding">
<div class="form-group has-success">
  <label>Credit Score</label>
  <br />
  <div class="ui medium-padding">
    <div class="slidecontainer">
      <input #creditSlider (input)="updateCreditSlider()"  (change)="updateCreditSlider()" type="range" min="300" max="850" value="{{ creditSliderValue }}" class="slider" id="myRange">
    </div>
  </div>
  <div #creditSliderSpan class="sliderValue circle" >
    <span class="noselect">{{ creditSliderValue }}</span>
  </div>
  <div #creditSliderTrack class="sliderTrack" ></div>
</div>
</code>```

typescript section   (In the angular component class)

```<code>creditSliderValue : any;
@ViewChild('creditSlider') creditSlider;
@ViewChild('creditSliderSpan') creditSliderSpan;
.
.
.
updateCreditSlider() {
      let horizontalOffset:number = 0;
      //values from 300 to 850 - Next value needs to be adjusted based on your placement of slider object
      horizontalOffset =  ( (Number.parseInt(this.creditSlider.nativeElement.value )- 280)/2.45);
      this.creditSliderSpan.nativeElement.style.left = ( horizontalOffset )+ 'px';
      this.creditSliderSpan.nativeElement.style.top = this.creditSliderSpan.nativeElement.style.top  + 'px';
      this.creditSliderValue = this.creditSlider.nativeElement.value;
    }
</code>```

css section

```<code>.smallPadding {
  margin-bottom: 0px;
  padding: 4px;
}

.slidecontainer {
    width: 100%; /* Width of the outside container */
}

/* The slider itself */
.slider {
    position: relative;
    -webkit-appearance: none;  /* Override default CSS styles */
    appearance: none;
    width:275px;
    //width: 100%; /* Full-width */
    height: 15px;
    border-radius: 5px;
    //background: #d3d3d3; /* Grey background */
    background: rgba(211,211,211, 0.00);

    outline: none; /* Remove outline */
    opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
    -webkit-transition: .2s; /* 0.2 seconds transition on hover */
    transition: opacity .2s;
    z-index: 20;
}

/* Mouse-over effects */
.slider:hover {
    //opacity: 1; /* Fully shown on mouse-over */
}

/* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */
.slider::-webkit-slider-thumb {
    position: relative;
    -webkit-appearance: none; /* Override default look */
    appearance: none;
    width: 50px; /* Set a specific slider handle width */
    height: 50px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.slider::-moz-range-thumb {
    width: 25px; /* Set a specific slider handle width */
    height: 25px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.sliderValue {
    position: absolute;
    top: 25px;
    left: 0px;
    width: 100%; /* Width of the outside container */
    z-index: 15;

}
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}

@media screen and (max-width: 992px) {

}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  font-size: 14pt;
  color: black;
  line-height: 46px;
  text-align: center;
  background: white;
  vertical-align: center;
  //display: table-cell;
  border-style: solid;
  border-color: #7E7E7E;
}

.medium-padding {
  padding-top: 14px;
  padding-bottom: 14px;
}
.sliderTrack {
  position: relative;
  width: 220px;
  height: 10px;
  background-color: #E0E1E2;
  vertical-align: center;
  border-radius: 5px;
  top: -35px;
  left: 25px;
  //display: table-cell;
  //border-style: solid;
  //border-color: #7E7E7E;
}
.left-padding {
  padding-left: 14px;

}

.small-margin {
  margin-left: 4px;
}
.medium-margin {
  margin-left: 10px;
}
.small-padding{
  padding: 4px;
}
</code>```

Title: range slider html css javascript

Body:
I'm planning to make a 'range slider' type in registration form and the JavaScript validation 'must be 16 years and above'.

Example if I'm plan make a JavaScript valuation "must be minimum 0 years and maximum 50 years", these are the html

<input type="range" id="vol" name="vol" min="0" max="50">

But if I'm assuming 'must be 16 years and above' the minimum is 16 years old and the maximum is infinite, what would the html code be? is infinite possible or the maximum is always 100?

Body:
 giphy animated gif link

I have developed a range slider but it uses html css and angular (typescript).  You may have to modify code slightly but it works by using a CSS circle, placing the number value at a position in that circle, and placing that over the input range.

html section

<div class="row small-margin"><div class="col-lg-8 small-padding">
<div class="form-group has-success">
  <label>Credit Score</label>
  <br />
  <div class="ui medium-padding">
    <div class="slidecontainer">
      <input #creditSlider (input)="updateCreditSlider()"  (change)="updateCreditSlider()" type="range" min="300" max="850" value="{{ creditSliderValue }}" class="slider" id="myRange">
    </div>
  </div>
  <div #creditSliderSpan class="sliderValue circle" >
    <span class="noselect">{{ creditSliderValue }}</span>
  </div>
  <div #creditSliderTrack class="sliderTrack" ></div>
</div>

typescript section   (In the angular component class)

creditSliderValue : any;
@ViewChild('creditSlider') creditSlider;
@ViewChild('creditSliderSpan') creditSliderSpan;
.
.
.
updateCreditSlider() {
      let horizontalOffset:number = 0;
      //values from 300 to 850 - Next value needs to be adjusted based on your placement of slider object
      horizontalOffset =  ( (Number.parseInt(this.creditSlider.nativeElement.value )- 280)/2.45);
      this.creditSliderSpan.nativeElement.style.left = ( horizontalOffset )+ 'px';
      this.creditSliderSpan.nativeElement.style.top = this.creditSliderSpan.nativeElement.style.top  + 'px';
      this.creditSliderValue = this.creditSlider.nativeElement.value;
    }

css section

.smallPadding {
  margin-bottom: 0px;
  padding: 4px;
}

.slidecontainer {
    width: 100%; /* Width of the outside container */
}

/* The slider itself */
.slider {
    position: relative;
    -webkit-appearance: none;  /* Override default CSS styles */
    appearance: none;
    width:275px;
    //width: 100%; /* Full-width */
    height: 15px;
    border-radius: 5px;
    //background: #d3d3d3; /* Grey background */
    background: rgba(211,211,211, 0.00);

    outline: none; /* Remove outline */
    opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
    -webkit-transition: .2s; /* 0.2 seconds transition on hover */
    transition: opacity .2s;
    z-index: 20;
}

/* Mouse-over effects */
.slider:hover {
    //opacity: 1; /* Fully shown on mouse-over */
}

/* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */
.slider::-webkit-slider-thumb {
    position: relative;
    -webkit-appearance: none; /* Override default look */
    appearance: none;
    width: 50px; /* Set a specific slider handle width */
    height: 50px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.slider::-moz-range-thumb {
    width: 25px; /* Set a specific slider handle width */
    height: 25px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.sliderValue {
    position: absolute;
    top: 25px;
    left: 0px;
    width: 100%; /* Width of the outside container */
    z-index: 15;

}
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}

@media screen and (max-width: 992px) {

}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  font-size: 14pt;
  color: black;
  line-height: 46px;
  text-align: center;
  background: white;
  vertical-align: center;
  //display: table-cell;
  border-style: solid;
  border-color: #7E7E7E;
}

.medium-padding {
  padding-top: 14px;
  padding-bottom: 14px;
}
.sliderTrack {
  position: relative;
  width: 220px;
  height: 10px;
  background-color: #E0E1E2;
  vertical-align: center;
  border-radius: 5px;
  top: -35px;
  left: 25px;
  //display: table-cell;
  //border-style: solid;
  //border-color: #7E7E7E;
}
.left-padding {
  padding-left: 14px;

}

.small-margin {
  margin-left: 4px;
}
.medium-margin {
  margin-left: 10px;
}
.small-padding{
  padding: 4px;
}


问:
Can we customize mapping file names in Wiremock?
I am recording the application through Wiremock using JAVA DSL, Do we have the option to customize the mapping file names? instead of getting the filename which is generated from wiremock..

Example:  searchpanel_arrivalairport_th-72f9b8b7-076f-4102-b6a8-aa38710fde1b.json (Generated form wiremock using java )
I am expecting the above file name with my desired naming convention like

seacrpanel_airport_LGW.json

答:
There's no easy way to do this at the moment. It is however possible. As @santhiya-ps says you need to write your own implementation of RequestListener, probably using StubMappingJsonRecorder as a template.

You can't extend it and override writeToMappingAndBodyFile as that method is private, but that is the method you probably want to change.

import com.github.tomakehurst.wiremock.common.*;
import com.github.tomakehurst.wiremock.core.*;
import com.github.tomakehurst.wiremock.http.*;
import java.util.List;
import static com.github.tomakehurst.wiremock.core.WireMockApp.*;

class NameTemplateStubMappingJsonRecorder implements RequestListener {

  private final FileSource mappingsFileSource;
  private final FileSource filesFileSource;
  private final Admin admin;
  private final List<CaseInsensitiveKey> headersToMatch;
  private final IdGenerator idGenerator = new VeryShortIdGenerator();

  public NameTemplateStubMappingJsonRecorder(Admin admin) {
    this.mappingsFileSource = admin.getOptions().filesRoot().child(MAPPINGS_ROOT);
    this.filesFileSource = admin.getOptions().filesRoot().child(FILES_ROOT);
    this.admin = admin;
    this.headersToMatch = admin.getOptions().matchingHeaders();
  }

  @Override
  public void requestReceived(Request request, Response response) {
    // TODO copy StubMappingJsonRecorder changing as required...
  }
}

```
<p>You can then register your <code>RequestListener</code> as so:</p>
<pre class="lang-java prettyprint-override"><code>WireMockServer wireMockServer = new WireMockServer();

wireMockServer.addMockServiceRequestListener(
  new NameTemplateStubMappingJsonRecorder(wireMockServer)
);

wireMockServer.start();
</code>```

So long as you still store the mapping files in the expected directory (stored in FileSource mappingsFileSource above, which will be ${rootDir}/mappings, where rootDir is configured as explained in Configuration - File Locations) they should be loaded successfully as all files with extension json in that dir are loaded as mappings.

It would be much easier if StubMappingJsonRecorder took a strategy for generating these names - it might be worth creating an issue on the WireMock repo asking for an easier way to do this. I'd suggest getting an agreement on a basic design before raising a PR though.

Body:
There's no easy way to do this at the moment. It is however possible. As @santhiya-ps says you need to write your own implementation of RequestListener, probably using StubMappingJsonRecorder as a template.

You can't extend it and override writeToMappingAndBodyFile as that method is private, but that is the method you probably want to change.

import com.github.tomakehurst.wiremock.common.*;
import com.github.tomakehurst.wiremock.core.*;
import com.github.tomakehurst.wiremock.http.*;
import java.util.List;
import static com.github.tomakehurst.wiremock.core.WireMockApp.*;

class NameTemplateStubMappingJsonRecorder implements RequestListener {

  private final FileSource mappingsFileSource;
  private final FileSource filesFileSource;
  private final Admin admin;
  private final List<CaseInsensitiveKey> headersToMatch;
  private final IdGenerator idGenerator = new VeryShortIdGenerator();

  public NameTemplateStubMappingJsonRecorder(Admin admin) {
    this.mappingsFileSource = admin.getOptions().filesRoot().child(MAPPINGS_ROOT);
    this.filesFileSource = admin.getOptions().filesRoot().child(FILES_ROOT);
    this.admin = admin;
    this.headersToMatch = admin.getOptions().matchingHeaders();
  }

  @Override
  public void requestReceived(Request request, Response response) {
    // TODO copy StubMappingJsonRecorder changing as required...
  }
}

You can then register your RequestListener as so:

WireMockServer wireMockServer = new WireMockServer();

wireMockServer.addMockServiceRequestListener(
  new NameTemplateStubMappingJsonRecorder(wireMockServer)
);

wireMockServer.start();

So long as you still store the mapping files in the expected directory (stored in FileSource mappingsFileSource above, which will be ${rootDir}/mappings, where rootDir is configured as explained in Configuration - File Locations) they should be loaded successfully as all files with extension json in that dir are loaded as mappings.

It would be much easier if StubMappingJsonRecorder took a strategy for generating these names - it might be worth creating an issue on the WireMock repo asking for an easier way to do this. I'd suggest getting an agreement on a basic design before raising a PR though.


问:
dotnet publish only one project from the solution in VSTS
We are trying to build one project from a Visual Studio solution in VSTS with .NET Core task. We are able to "dotnet build" that project. But when we try to "dotnet publish" it tries to publish all projects from the solution. Even if we use "dotnet custom", it tries to publish all projects.

Is there a way to use .NET Core task to publish only one project or projects that were built? Or should we run a custom command line task?

Reason for this is that we have a project that won't build and we don't need/want to publish it. So we would like to build and publish one project and not all projects.

答: If you un-check the 'Publish Web Projects' you will see a field appear that allows you to enter the project (csproj) you want to target.</p>


问:
Best way to transfer struct from one process to another?
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

```<code>typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;
</code>```

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.

答: Are the server and clients on different hosts? If so, why don't you take UDP and to methods to serialize your structure to send via network and the second one to get it back to structure? ...</p>

Body:
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.


问:
Connection refused to wiremock when doing native test Quarkus : Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1]
I am facing a problem when using Wiremock with Quarkus. when launching integration test (native mode).

```<code>Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connexion refusée (Connection refused)
org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connexion refusée (Connection refused)
    at app//org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:156)
    at app//org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
    at app//org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
    at app//org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at app//org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at app//org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at app//org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at app//org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at app//com.github.tomakehurst.wiremock.client.HttpAdminClient.safelyExecuteRequest(HttpAdminClient.java:473)
    at app//com.github.tomakehurst.wiremock.client.HttpAdminClient.executeRequest(HttpAdminClient.java:454)
    at app//com.github.tomakehurst.wiremock.client.HttpAdminClient.addStubMapping(HttpAdminClient.java:131)
    at app//com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:298)
    at app//com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:293)
    at app//com.github.tomakehurst.wiremock.client.WireMock.givenThat(WireMock.java:104)
    at app//com.api.lambda.adapter.LambdaHandlerTest.initWiremock(LambdaHandlerTest.java:44)
</code>```
```<code>package com.api.lambda.adapter;

import io.quarkus.test.junit.QuarkusIntegrationTest;

@QuarkusIntegrationTest
public class LambdaHandlerNativeTest extends LambdaHandlerTest {

    // Execute the same tests but in native mode.
}
</code>```

Any idea?

答:
After investigation don't forget like me to add @QuarkusTestResource to native test class where MockStackExtension is your QuarkusTestResourceLifecycleManager implementation.

```<code>@QuarkusIntegrationTest
@QuarkusTestResource(MockStackExtension.class)
public class LambdaHandlerNativeTest extends LambdaHandlerTest {

    // Execute the same tests but in native mode.
}
</code>```

Body:
I am facing a problem when using Wiremock with Quarkus. when launching integration test (native mode).

Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connexion refusée (Connection refused)
org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connexion refusée (Connection refused)
    at app//org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:156)
    at app//org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
    at app//org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
    at app//org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at app//org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at app//org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at app//org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at app//org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at app//com.github.tomakehurst.wiremock.client.HttpAdminClient.safelyExecuteRequest(HttpAdminClient.java:473)
    at app//com.github.tomakehurst.wiremock.client.HttpAdminClient.executeRequest(HttpAdminClient.java:454)
    at app//com.github.tomakehurst.wiremock.client.HttpAdminClient.addStubMapping(HttpAdminClient.java:131)
    at app//com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:298)
    at app//com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:293)
    at app//com.github.tomakehurst.wiremock.client.WireMock.givenThat(WireMock.java:104)
    at app//com.api.lambda.adapter.LambdaHandlerTest.initWiremock(LambdaHandlerTest.java:44)

package com.api.lambda.adapter;

import io.quarkus.test.junit.QuarkusIntegrationTest;

@QuarkusIntegrationTest
public class LambdaHandlerNativeTest extends LambdaHandlerTest {

    // Execute the same tests but in native mode.
}

Any idea?

Body:
After investigation don't forget like me to add @QuarkusTestResource to native test class where MockStackExtension is your QuarkusTestResourceLifecycleManager implementation.

@QuarkusIntegrationTest
@QuarkusTestResource(MockStackExtension.class)
public class LambdaHandlerNativeTest extends LambdaHandlerTest {

    // Execute the same tests but in native mode.
}