问:
How to find products within the cateogry containing the most expensive product
I'm currently using the following code:

```<code>SELECT PROD_NO,
       PROD_NAME,
       PROD_TYPE
FROM PRODUCTS
WHERE PROD_SELL IN (SELECT MAX(PROD_SELL)
                    FROM PRODUCTS)
</code>```

Current output:

```<code>PROD_NO PROD_NAME                      PROD_TYPE
---------- ------------------------------ --------------------
     40103 StarDome                       Tents
</code>```

Desired Output:

```<code> PROD_NO PROD_NAME                      PROD_TYPE
---------- ------------------------------ --------------------
     40100 Star Lite                      Tents
     40101 Star Gazer-2                   Tents
     40102 Star Gazer-3                   Tents
     40103 StarDome                       Tents
</code>```

This is because the 'StarDome' Product has the highest prod_sell

My code returns the highest priced product type. However, there are 4 products within that type and I need to list all of the products within that type (which returned the highest sell price).

Can't figure it out for the life of me.

答:
As you commented, query of a subquery of another subquery ... sounds quite inefficient, querying the same table all over again (3 times, I guess).

Sample data:

```<code>SQL> select * From products;

   PROD_NO PROD_NAME    PROD_  PROD_SELL
---------- ------------ ----- ----------
     40100 Star Lite    Tents        200
     40101 Star Gazer-2 Tents        100
     40102 Star Gazer-3 Tents        150
     40103 StarDome     Tents        500  --> the most expensive, so - you want all "Tents" as a result
     10000 Whatever     Beds         400
     10001 Something    Bikes        450

6 rows selected.

SQL>
</code>```

This is your current query (if I guessed right; table products is referenced 3 times):

```<code>SQL> select prod_no, prod_name, prod_type
  2  from products                                                 --> first
  3  where prod_type in (select prod_type
  4                      from products                             --> second
  5                      where prod_sell = (select max(prod_sell)
  6                                         from products          --> third
  7                                        )
  8                     )
  9  order by prod_no;

   PROD_NO PROD_NAME    PROD_
---------- ------------ -----
     40100 Star Lite    Tents
     40101 Star Gazer-2 Tents
     40102 Star Gazer-3 Tents
     40103 StarDome     Tents

SQL>
</code>```

I'd suggest you to consider another approach: use analytic function to rank products by price, and then fetch those that ranked the highest.

```<code>SQL> select prod_type,
  2    max(prod_sell) max_prod_sell,
  3    rank() over (order by max(prod_sell) desc) rnk
  4  from products
  5  group by prod_type;

PROD_ MAX_PROD_SELL        RNK
----- ------------- ----------
Tents           500          1     --> Tents rank as "highest"
Bikes           450          2
Beds            400          3

SQL>
</code>```

Now, use that query as a subquery (or a CTE, as I did):

```<code>SQL> with temp as
  2    (select prod_type,
  3            rank() over (order by max(prod_sell) desc) rnk
  4     from products                                             --> first
  5     group by prod_type
  6    )
  7  select p.prod_no, p.prod_name, p.prod_type
  8  from products p join temp t on t.prod_type = p.prod_type     --> second
  9  where t.rnk = 1
 10  order by p.prod_no;

   PROD_NO PROD_NAME    PROD_
---------- ------------ -----
     40100 Star Lite    Tents
     40101 Star Gazer-2 Tents
     40102 Star Gazer-3 Tents
     40103 StarDome     Tents

SQL>
</code>```

That's the same result you got, but should be somewhat more efficient. Certainly, you won't notice any difference on small tables, but might as number of rows gets higher and higher.

Body:
I'm currently using the following code:

SELECT PROD_NO,
       PROD_NAME,
       PROD_TYPE
FROM PRODUCTS
WHERE PROD_SELL IN (SELECT MAX(PROD_SELL)
                    FROM PRODUCTS)

Current output:

PROD_NO PROD_NAME                      PROD_TYPE
---------- ------------------------------ --------------------
     40103 StarDome                       Tents

Desired Output:

 PROD_NO PROD_NAME                      PROD_TYPE
---------- ------------------------------ --------------------
     40100 Star Lite                      Tents
     40101 Star Gazer-2                   Tents
     40102 Star Gazer-3                   Tents
     40103 StarDome                       Tents

This is because the 'StarDome' Product has the highest prod_sell

My code returns the highest priced product type. However, there are 4 products within that type and I need to list all of the products within that type (which returned the highest sell price).

Can't figure it out for the life of me.

Body:
As you commented, query of a subquery of another subquery ... sounds quite inefficient, querying the same table all over again (3 times, I guess).

Sample data:

SQL> select * From products;

   PROD_NO PROD_NAME    PROD_  PROD_SELL
---------- ------------ ----- ----------
     40100 Star Lite    Tents        200
     40101 Star Gazer-2 Tents        100
     40102 Star Gazer-3 Tents        150
     40103 StarDome     Tents        500  --> the most expensive, so - you want all "Tents" as a result
     10000 Whatever     Beds         400
     10001 Something    Bikes        450

6 rows selected.

SQL>

This is your current query (if I guessed right; table products is referenced 3 times):

SQL> select prod_no, prod_name, prod_type
  2  from products                                                 --> first
  3  where prod_type in (select prod_type
  4                      from products                             --> second
  5                      where prod_sell = (select max(prod_sell)
  6                                         from products          --> third
  7                                        )
  8                     )
  9  order by prod_no;

   PROD_NO PROD_NAME    PROD_
---------- ------------ -----
     40100 Star Lite    Tents
     40101 Star Gazer-2 Tents
     40102 Star Gazer-3 Tents
     40103 StarDome     Tents

SQL>

I'd suggest you to consider another approach: use analytic function to rank products by price, and then fetch those that ranked the highest.

SQL> select prod_type,
  2    max(prod_sell) max_prod_sell,
  3    rank() over (order by max(prod_sell) desc) rnk
  4  from products
  5  group by prod_type;

PROD_ MAX_PROD_SELL        RNK
----- ------------- ----------
Tents           500          1     --> Tents rank as "highest"
Bikes           450          2
Beds            400          3

SQL>

Now, use that query as a subquery (or a CTE, as I did):

SQL> with temp as
  2    (select prod_type,
  3            rank() over (order by max(prod_sell) desc) rnk
  4     from products                                             --> first
  5     group by prod_type
  6    )
  7  select p.prod_no, p.prod_name, p.prod_type
  8  from products p join temp t on t.prod_type = p.prod_type     --> second
  9  where t.rnk = 1
 10  order by p.prod_no;

   PROD_NO PROD_NAME    PROD_
---------- ------------ -----
     40100 Star Lite    Tents
     40101 Star Gazer-2 Tents
     40102 Star Gazer-3 Tents
     40103 StarDome     Tents

SQL>

That's the same result you got, but should be somewhat more efficient. Certainly, you won't notice any difference on small tables, but might as number of rows gets higher and higher.


来源: stackexchange

问:
Accessing elements in Python dictionary
bit of a strange question, but I was trying to come up with different ways to get around this.

Let's say I have the following Dictionary:

```<code>dict={

    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'],
    'Fruit':['Apple', 'Orange', 'Banana']
}
</code>```

Is there a way to access just the third element of every key?
The output being 'Ocelot' 'Frank 'Banana'

I know that the notation for single key is Dictionary(KEY)[ITEM PLACE] but is there a way to do this without specifying the key?

Thanks

答:
Here's one approach.

```<code>d = {
    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'],
    'Fruit':['Apple', 'Orange', 'Banana']
}
print([d[k][2] for k in d])
</code>```

Result:

```<code>['Ocelot', 'Frank', 'Banana']
</code>```

ContentLicense: CC BY-SA 4.0

Title: Accessing elements in Python dictionary

Body:
bit of a strange question, but I was trying to come up with different ways to get around this.

Let's say I have the following Dictionary:

dict={

    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'],
    'Fruit':['Apple', 'Orange', 'Banana']
}

Is there a way to access just the third element of every key?
The output being 'Ocelot' 'Frank 'Banana'

I know that the notation for single key is Dictionary(KEY)[ITEM PLACE] but is there a way to do this without specifying the key?

Thanks

Body:
Here's one approach.

d = {
    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'],
    'Fruit':['Apple', 'Orange', 'Banana']
}
print([d[k][2] for k in d])

Result:

['Ocelot', 'Frank', 'Banana']


问:
C char* + char* concatenation
I have char* str1 and char* str2

I wanna concatenate like this res = str1 + str2

strcat(str1, str2) change value of str1, it is not what i need

How to get this result?

答:
You would have to first copy the first string, and then concatenate the second to that:

```<code>strcpy(res, str1);
strcat(res, str2);
</code>```

... making sure res has enough space allocated for the result, including the null terminator.

Or as a one-liner, if you wish (thanks, Eugene Sh.):

```<code>strcat(strcpy(res,str1), str2)
</code>```

Another (and safer) option is to use snprintf(), which assures you will not overflow the destination buffer:

```<code>int count = snprintf(res, sizeof res, "%s%s", str1, str2);
</code>```

If count is less than the size of res minus one, the result was truncated to fit. Note that res must be an array (not decayed to a pointer) for sizeof res to work. If you have another source of the buffer length, you could use that instead.

(snprintf info adapted from user3386109's comment -- thank you!)

Title: C char* + char* concatenation

Body:
You would have to first copy the first string, and then concatenate the second to that:

strcpy(res, str1);
strcat(res, str2);

... making sure res has enough space allocated for the result, including the null terminator.

Or as a one-liner, if you wish (thanks, Eugene Sh.):

strcat(strcpy(res,str1), str2)

Another (and safer) option is to use snprintf(), which assures you will not overflow the destination buffer:

int count = snprintf(res, sizeof res, "%s%s", str1, str2);

If count is less than the size of res minus one, the result was truncated to fit. Note that res must be an array (not decayed to a pointer) for sizeof res to work. If you have another source of the buffer length, you could use that instead.

(snprintf info adapted from user3386109's comment -- thank you!)


问:
Analysis of algorithms
I am reading algorithm analysis topic. Here is the text snippet from the book

When n doubles, the running time goes up by a factor of 2 for linear
  programs, 4 for quadratic programs, and  8 for cubic programs.
  Programs that run in logarithmic time take only an additive constant
  longer when n doubles,  and programs that run in O(n log n) take
  slightly more than twice as long to run under the same circumstances.

These increases can be hard to spot if the lower-order terms have
  relatively large coefficients and n is not large enough.

My question is what does author mean lower-order terms have relatively large coefficients? Can any one explain with example

Thanks!

答:
For instance if you have an O(n) algorithm at lower scales you could have T(n) = 490239n + (insert ridiculous constant here) which means that the performance would look bad but as the scales increase you see that the increase is always linear.

Real world example is merge sort, O(n logn) problem is that recursion has a computational cost or overhead which is a factor of n which is a smaller order than nlogn so it gets discarded in the Big-O, problem is that that factor gets to be quite large as well and affects performance.

ContentLicense: CC BY-SA 3.0

Title: Analysis of algorithms


问:
Accessing props function outside of the component
React beginner here, i'm implementing zooming in/out functionality to my project using react-zoom-pan-pinch, i have my zooming buttons outside of 'TransformWrapper', all examples what i have seen have them inside 'TransformWrapper', so my question is how to have access to 'zoomIn','zoomOut','resetTransform'  outside of 'TransformWrapper'.

at the end i have tried it with useRef without success, is there a way ?

code:
https://codesandbox.io/s/react-zoom-pan-pinch-forked-j6yst?file=/src/index.js

code:

import React, { useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
import styled from "styled-components";

const Container = styled.div`
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
`;
const Box = styled.div`
  width: 50px;
  height: 50px;
  background-color: ${(props) => (props.backColor ? props.backColor : "blue")};
  margin: 5px;
`;
const Toolbox = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: calc(100vw - 60px);
  margin-bottom: 10px;
  button {
    margin-left: 10px;
    width: 2em;
  }
`;
function App() {
  const transformRef = useRef();

  const onClick = () => {
    alert("onClick : open popup");
  };
  const onContextMenu = (e) => {
    e.preventDefault();
    alert("onContextMenu : show info");
  };

  const renderBoxes = () => {
    let i;
    let arr = [];
    for (i = 0; i < 30; i++) {
      arr.push(
        <Box key={"b" + i} onClick={onClick} onContextMenu={onContextMenu} />
      );
      arr.push(
        <Box
          key={"r" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="red"
        />
      );
      arr.push(
        <Box
          key={"y" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="yellow"
        />
      );
      arr.push(
        <Box
          key={"g" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="gray"
        />
      );
    }
    return arr;
  };
  return (

      <TransformWrapper
        defaultScale={1}
        defaultPositionX={200}
        defaultPositionY={100}
        ref={transformRef}
      >
        {({
          zoomIn,
          zoomOut,
          resetTransform,
          positionX,
          positionY,
          ...rest
        }) => (
          <React.Fragment>
            <Toolbox>
              <button onClick={zoomIn}>+</button>
              <button onClick={zoomOut}>-</button>
              <button onClick={resetTransform}>x</button>
            </Toolbox>
            <TransformComponent>
              <Container>{renderBoxes()}</Container>
            </TransformComponent>
          </React.Fragment>
        )}
      </TransformWrapper>
      <Toolbox>
        <button onClick={() => transformRef?.current?.zoomIn()}>+</button>
      </Toolbox>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);```
</div>
</div>
</p>
<p>i have tried with useRef as you can see in the code
<button onClick={() => transformRef?.current?.zoomIn()}>+< / button>
which doesnt work</p>
<p>i want to have this</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><Toolbox>
            <button onClick={zoomIn}>+</button>
            <button onClick={zoomOut}>-</button>
            <button onClick={resetTransform}>x</button>
          </Toolbox></code>```

working outside of 'TransformWrapper' any idea ?

答:
I solved it, mainly the problem was with codesandbox it uses react-zoom-pan-pinch 1.1.2 which is very old, upgrading it to 2.1.3 and using  a React ref on the TransformWrapper to access the handlers.

import React, { useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
import styled from "styled-components";

const Container = styled.div`
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
`;
const Box = styled.div`
  width: 50px;
  height: 50px;
  background-color: ${(props) => (props.backColor ? props.backColor : "blue")};
  margin: 5px;
`;
const Toolbox = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: calc(100vw - 60px);
  margin-bottom: 10px;
  button {
    margin-left: 10px;
    width: 2em;
  };
`
function App() {
  const transformComponentRef = useRef();
  const onClick = () => {
    alert("onClick : open popup");
  };
  const onContextMenu = (e) => {
    e.preventDefault();
    alert("onContextMenu : show info");
  };

  const renderBoxes = () => {
    let i;
    let arr = [];
    for (i = 0; i < 30; i++) {
      arr.push(
        <Box key={"b" + i} onClick={onClick} onContextMenu={onContextMenu} />
      );
      arr.push(
        <Box
          key={"r" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="red"
        />
      );
      arr.push(
        <Box
          key={"y" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="yellow"
        />
      );
      arr.push(
        <Box
          key={"g" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="gray"
        />
      );
    }
    return arr;
  };

  return (

<button onClick={()=>transformComponentRef?.current?.zoomIn()}>+</button>

      <TransformWrapper
         ref={transformComponentRef}
        defaultScale={1}
        defaultPositionX={200}
        defaultPositionY={100}

      >
        {({
          zoomIn,
          zoomOut,
          resetTransform,
          positionX,
          positionY,
          ...rest
        }) => (

            <TransformComponent>
              <Container>{renderBoxes()}</Container>
            </TransformComponent>

        )}
      </TransformWrapper>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);```

Body:
React beginner here, i'm implementing zooming in/out functionality to my project using react-zoom-pan-pinch, i have my zooming buttons outside of 'TransformWrapper', all examples what i have seen have them inside 'TransformWrapper', so my question is how to have access to 'zoomIn','zoomOut','resetTransform'  outside of 'TransformWrapper'.

at the end i have tried it with useRef without success, is there a way ?

code:
https://codesandbox.io/s/react-zoom-pan-pinch-forked-j6yst?file=/src/index.js

code:

import React, { useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
import styled from "styled-components";

const Container = styled.div`
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
`;
const Box = styled.div`
  width: 50px;
  height: 50px;
  background-color: ${(props) => (props.backColor ? props.backColor : "blue")};
  margin: 5px;
`;
const Toolbox = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: calc(100vw - 60px);
  margin-bottom: 10px;
  button {
    margin-left: 10px;
    width: 2em;
  }
`;
function App() {
  const transformRef = useRef();

  const onClick = () => {
    alert("onClick : open popup");
  };
  const onContextMenu = (e) => {
    e.preventDefault();
    alert("onContextMenu : show info");
  };

  const renderBoxes = () => {
    let i;
    let arr = [];
    for (i = 0; i < 30; i++) {
      arr.push(
        <Box key={"b" + i} onClick={onClick} onContextMenu={onContextMenu} />
      );
      arr.push(
        <Box
          key={"r" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="red"
        />
      );
      arr.push(
        <Box
          key={"y" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="yellow"
        />
      );
      arr.push(
        <Box
          key={"g" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="gray"
        />
      );
    }
    return arr;
  };
  return (

      <TransformWrapper
        defaultScale={1}
        defaultPositionX={200}
        defaultPositionY={100}
        ref={transformRef}
      >
        {({
          zoomIn,
          zoomOut,
          resetTransform,
          positionX,
          positionY,
          ...rest
        }) => (
          <React.Fragment>
            <Toolbox>
              <button onClick={zoomIn}>+</button>
              <button onClick={zoomOut}>-</button>
              <button onClick={resetTransform}>x</button>
            </Toolbox>
            <TransformComponent>
              <Container>{renderBoxes()}</Container>
            </TransformComponent>
          </React.Fragment>
        )}
      </TransformWrapper>
      <Toolbox>
        <button onClick={() => transformRef?.current?.zoomIn()}>+</button>
      </Toolbox>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

i have tried with useRef as you can see in the code
<button onClick={() => transformRef?.current?.zoomIn()}>+< / button>
which doesnt work

i want to have this

<Toolbox>
            <button onClick={zoomIn}>+</button>
            <button onClick={zoomOut}>-</button>
            <button onClick={resetTransform}>x</button>
          </Toolbox>

working outside of 'TransformWrapper' any idea ?

Body:
I solved it, mainly the problem was with codesandbox it uses react-zoom-pan-pinch 1.1.2 which is very old, upgrading it to 2.1.3 and using  a React ref on the TransformWrapper to access the handlers.

import React, { useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
import styled from "styled-components";

const Container = styled.div`
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
`;
const Box = styled.div`
  width: 50px;
  height: 50px;
  background-color: ${(props) => (props.backColor ? props.backColor : "blue")};
  margin: 5px;
`;
const Toolbox = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: calc(100vw - 60px);
  margin-bottom: 10px;
  button {
    margin-left: 10px;
    width: 2em;
  };
`
function App() {
  const transformComponentRef = useRef();
  const onClick = () => {
    alert("onClick : open popup");
  };
  const onContextMenu = (e) => {
    e.preventDefault();
    alert("onContextMenu : show info");
  };

  const renderBoxes = () => {
    let i;
    let arr = [];
    for (i = 0; i < 30; i++) {
      arr.push(
        <Box key={"b" + i} onClick={onClick} onContextMenu={onContextMenu} />
      );
      arr.push(
        <Box
          key={"r" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="red"
        />
      );
      arr.push(
        <Box
          key={"y" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="yellow"
        />
      );
      arr.push(
        <Box
          key={"g" + i}
          onClick={onClick}
          onContextMenu={onContextMenu}
          backColor="gray"
        />
      );
    }
    return arr;
  };

  return (
    <div>
<button onClick={()=>transformComponentRef?.current?.zoomIn()}>+</button>

      <TransformWrapper
         ref={transformComponentRef}
        defaultScale={1}
        defaultPositionX={200}
        defaultPositionY={100}

      >
        {({
          zoomIn,
          zoomOut,
          resetTransform,
          positionX,
          positionY,
          ...rest
        }) => (

            <TransformComponent>
              <Container>{renderBoxes()}</Container>
            </TransformComponent>

        )}
      </TransformWrapper>

    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


问:
Snowflake match_recognize function to create step funnel
I've read several articles giving examples of what can MATCH_RECOGNIZE do. One of them is creating a step funnel. Let's say we want to track certain events and see after each of the event how many users left. For instance, arriving at the home page, then going to the search page, then putting something in the cart, and finally paying. Those are events, and we have records for each one of them. Now I would like to create funnel like this:

Arriving at home page - 1000 users

Going to search page - 980 users

Adding something to shopping cart - 90 users

Paying - 10 users

That's step funnel example, where we have fewer and fewer users after each step.
Now, back to match_recognize, we can use this function to tell us how many users matched this pattern (event1 + event2 + event3 + event4 +), but the problem I'm trying to solve, how can we use this function so we know how many users did not pass to next event/phase, not just the ones that matched whole pattern sequence?

答:
So using bits, and date limits per step you can build you own funnel logic, and decide what makes the cut or not:

```<code>WITH data(id, action_date, details) AS (
    SELECT * FROM VALUES
        (1,  '2022-03-02', 'home_page'),
        (1,  '2022-03-03', 'search'),
        (1,  '2022-03-04', 'add_cart'),
        (1,  '2022-03-05', 'pay'),

        (2,  '2022-03-02', 'home_page'),
        (2,  '2022-03-03', 'search'),
        (2,  '2022-03-04', 'add_cart'),

        (3,  '2022-03-02', 'home_page'),
        (3,  '2022-03-03', 'search'),

        (4,  '2022-03-02', 'home_page'),

        (5,  '2022-03-03', 'home_page'), -- missed the search step
        (5,  '2022-03-04', 'add_cart'),

        (6,  '2022-03-01', 'home_page'), -- gap between s1 & s2 too long
        (6,  '2022-03-05', 'search')
), prep_a AS (
    SELECT id
        ,action_date
        ,details
        ,lag(details)over (partition by id order by action_date) as prior_detail
        ,datediff('seconds',lag(action_date,1,action_date)over(partition by id order by action_date),action_date)/86400 as prior_action_days_gap
        ,iff(details = 'home_page', action_date, null) as chain_start_date
        ,case
            when details = 'home_page' then 1
            when details = 'search' and prior_detail = 'home_page' and prior_action_days_gap <= 2 then 2
            when details = 'add_cart' and prior_detail = 'search' and prior_action_days_gap <= 1 then 4
            when details = 'pay' and prior_detail = 'add_cart' and prior_action_days_gap <= 1 then 8
            else 0
         end chain_bits
    FROM data
    --ORDER BY 1,2;
)
SELECT
    chain_date
    ,count_if(funnel_home_page) as c_home_pages_step
    ,count_if(funnel_search) as c_search_step
    ,c_home_pages_step - c_search_step as c_search_step_drop
    ,count_if(funnel_cart) as c_cart_step
    ,c_search_step - c_cart_step as c_cart_step_drop
    ,count_if(funnel_pay) as c_pay_step
    ,c_cart_step_drop - c_pay_step as c_pay_step_drop
FROM (
    SELECT *
        ,sum(chain_bits)over(partition by id, chain_date order by action_date) as chain_state
        ,chain_bits=1 as funnel_home_page
        ,chain_bits=2 and chain_state = 3 as funnel_search
        ,chain_bits=4 and chain_state = 7 as funnel_cart
        ,chain_bits=8 and chain_state = 15 as funnel_pay
    FROM (
        SELECT *
            ,nvl(chain_start_date, lag(chain_start_date) ignore nulls over (partition by id order by action_date)) as chain_date
        FROM prep_a
    )
)
GROUP BY 1
</code>```

gives:

CHAIN_DATE
C_HOME_PAGES_STEP
C_SEARCH_STEP
C_SEARCH_STEP_DROP
C_CART_STEP
C_CART_STEP_DROP
C_PAY_STEP
C_PAY_STEP_DROP

2022-03-02
4
3
1
2
1
1
0

2022-03-03
1
0
1
0
0
0
0

2022-03-01
1
0
1
0
0
0
0

Body:
So using bits, and date limits per step you can build you own funnel logic, and decide what makes the cut or not:

WITH data(id, action_date, details) AS (
    SELECT * FROM VALUES
        (1,  '2022-03-02', 'home_page'),
        (1,  '2022-03-03', 'search'),
        (1,  '2022-03-04', 'add_cart'),
        (1,  '2022-03-05', 'pay'),

        (2,  '2022-03-02', 'home_page'),
        (2,  '2022-03-03', 'search'),
        (2,  '2022-03-04', 'add_cart'),

        (3,  '2022-03-02', 'home_page'),
        (3,  '2022-03-03', 'search'),

        (4,  '2022-03-02', 'home_page'),

        (5,  '2022-03-03', 'home_page'), -- missed the search step
        (5,  '2022-03-04', 'add_cart'),

        (6,  '2022-03-01', 'home_page'), -- gap between s1 & s2 too long
        (6,  '2022-03-05', 'search')
), prep_a AS (
    SELECT id
        ,action_date
        ,details
        ,lag(details)over (partition by id order by action_date) as prior_detail
        ,datediff('seconds',lag(action_date,1,action_date)over(partition by id order by action_date),action_date)/86400 as prior_action_days_gap
        ,iff(details = 'home_page', action_date, null) as chain_start_date
        ,case
            when details = 'home_page' then 1
            when details = 'search' and prior_detail = 'home_page' and prior_action_days_gap <= 2 then 2
            when details = 'add_cart' and prior_detail = 'search' and prior_action_days_gap <= 1 then 4
            when details = 'pay' and prior_detail = 'add_cart' and prior_action_days_gap <= 1 then 8
            else 0
         end chain_bits
    FROM data
    --ORDER BY 1,2;
)
SELECT
    chain_date
    ,count_if(funnel_home_page) as c_home_pages_step
    ,count_if(funnel_search) as c_search_step
    ,c_home_pages_step - c_search_step as c_search_step_drop
    ,count_if(funnel_cart) as c_cart_step
    ,c_search_step - c_cart_step as c_cart_step_drop
    ,count_if(funnel_pay) as c_pay_step
    ,c_cart_step_drop - c_pay_step as c_pay_step_drop
FROM (
    SELECT *
        ,sum(chain_bits)over(partition by id, chain_date order by action_date) as chain_state
        ,chain_bits=1 as funnel_home_page
        ,chain_bits=2 and chain_state = 3 as funnel_search
        ,chain_bits=4 and chain_state = 7 as funnel_cart
        ,chain_bits=8 and chain_state = 15 as funnel_pay
    FROM (
        SELECT *
            ,nvl(chain_start_date, lag(chain_start_date) ignore nulls over (partition by id order by action_date)) as chain_date
        FROM prep_a
    )
)
GROUP BY 1

gives:

CHAIN_DATE
C_HOME_PAGES_STEP
C_SEARCH_STEP
C_SEARCH_STEP_DROP
C_CART_STEP
C_CART_STEP_DROP
C_PAY_STEP
C_PAY_STEP_DROP

2022-03-02
4
3
1
2
1
1
0

2022-03-03
1
0
1
0
0
0
0

2022-03-01
1
0
1
0
0
0
0


问:
SetupProxy file not being read in Create React App Typescript
I have this code using CRA --template typescript in setupProxy.js file

```<code>const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    '/user/try',
    createProxyMiddleware({
      target: 'http://localhost:8002',
      changeOrigin: true,
    })
  );
};
</code>```

but the problem is that setupProxy.js file is completely ignored causing my request to fail.

I know I can use the "proxy": "http://localhost:8002" in package.json but it will not accept multiple proxies.

To further test, I also created a new CRA but without typescript and suddenly it's working with the same code above.

Is there a way to make setupProxy.js work in CRA typescript?

答:
Should be able to just add this to your tsconfig.json. Hope it works for you.</p>
```<code>"exclude": ["src/setupProxy.js"]
</code>```

Body:
I have this code using CRA --template typescript in setupProxy.js file

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    '/user/try',
    createProxyMiddleware({
      target: 'http://localhost:8002',
      changeOrigin: true,
    })
  );
};

but the problem is that setupProxy.js file is completely ignored causing my request to fail.

I know I can use the "proxy": "http://localhost:8002" in package.json but it will not accept multiple proxies.

To further test, I also created a new CRA but without typescript and suddenly it's working with the same code above.

Is there a way to make setupProxy.js work in CRA typescript?

Body:
Should be able to just add this to your tsconfig.json. Hope it works for you.

"exclude": ["src/setupProxy.js"]


问:
Validate Date entered into cell
I have a workbook with a field for a user to enter a date.  In testing, I entered 11/31/21 which is not a valid date.  I thought I would test for valid date entry and can't seem to make it work.  I am trying to use IsDate to check and must being doing something wrong.  I tried setting my cell value as both date and string with no luck.</p>
```<code>Public Sub Worksheet_Change(ByVal Target As Range)
    Dim PCell As Range
    Dim Edate As Date

    Set PCell = Range("S2")
        Edate = Range("S2")

If Not Application.Intersect(PCell, Range(Target.Address)) _
           Is Nothing Then
    If IsDate(Edate) = 1 Then
    ActiveWorkbook.Connections("Query - SelectedDataByDate").Refresh
Else
MsgBox ("You have entered an invalide date.")
End If

End If

End Sub
</code>```

答:
I think that

```<code>Edate = Range("S2")
</code>```

Should be

```<code>Edate = Range("S2").value
</code>```

Title: Validate Date entered into cell

Body:
I have a workbook with a field for a user to enter a date.  In testing, I entered 11/31/21 which is not a valid date.  I thought I would test for valid date entry and can't seem to make it work.  I am trying to use IsDate to check and must being doing something wrong.  I tried setting my cell value as both date and string with no luck.

Public Sub Worksheet_Change(ByVal Target As Range)
    Dim PCell As Range
    Dim Edate As Date

    Set PCell = Range("S2")
        Edate = Range("S2")

If Not Application.Intersect(PCell, Range(Target.Address)) _
           Is Nothing Then
    If IsDate(Edate) = 1 Then
    ActiveWorkbook.Connections("Query - SelectedDataByDate").Refresh
Else
MsgBox ("You have entered an invalide date.")
End If

End If

End Sub

Body:
I think that

Edate = Range("S2")

Should be

Edate = Range("S2").value


问:
Single WCF project will not create build artifact under YAML Azure DevOps Build Pipeline
Our build pipeline includes a YML template that is used to build all of our WCF services and Web applications. For all of the WCF services but one, it works like a charm. For this one WCF service, however, the following output is generated in the build logs during the Publish Artifact stage:

##[warning]Directory 'D:\azagent\A2_work\1381\a' is empty. Nothing will be added to build artifact 'drop'.

Our Build stage invokes a separate YML file which includes the following to build and publish the project:

```<code>  - task: VSBuild@1
    displayName: "Build ${{ parameters.solution}}"
    inputs:
      solution: ${{ parameters.solution }}
      msbuildArgs: >
        /p:DeployOnBuild=true
        /p:WebPublishMethod=Package
        /p:PackageAsSingleFile=true
        /p:SkipInvalidConfigurations=true
        /p:IgnoreDeployManagedRuntimeVersion=true
        /p:PackageLocation="$(build.ArtifactStagingDirectory)"
      platform: ${{ parameters.buildPlatform }}
      configuration: ${{ parameters.buildConfiguration }}

  - task: PublishBuildArtifacts@1
    displayName: "Publish Build Artifact"
    inputs:
      PathtoPublish: "$(Build.ArtifactStagingDirectory)"
      ArtifactName: "drop"
      publishLocation: "Container"
</code>```

As stated earlier, this works perfectly for all other WCF projects, and generates a build artifact. However, for the problematic WCF Service, no build artifact is generated. What we've observed is that no ZIP file is created in the D:\azagent\A2_work\1381\a folder (theoretically, Build.ArtifactStagingDirectory).

I have tried numerous recommended solutions to resolve this issue, all to no effect.

Adding a CopyFiles@2 task between the VSBuild@1 task and the PublishBuildArtifacts@1 task did place the files in the Build.ArtifactStagingDirectory, but they were not in a ZIP file. Further, the deployment task (later in the pipeline) failed because no ZIP file was present in the drop folder.

Adding /p:OutDir=$(Build.ArtfactStagingDirectory) did seem to produce some sort of artifact, but the deployment task still failed, claiming it could not find the ZIP file in the drop folder.

I created a test repo that contained only the WCF project (as it's normally contained in a solution containing it and a Web application) and ran the pipeline against that repo. No build artifact was created.

Ultimately, nothing I do seems to be able to get this project to generate a build artifact.

What am I missing here? What further information can I provide that will help you to help me resolve this issue?

答:
According to Microsoft's Developer Community, this has been a known issue since August of 2019. WCF services built using a YAML pipeline do not produce build artifacts. Consequently, they cannot be deployed via YAML pipelines.

As of this date, there is neither a fix nor a workaround available from Microsoft.

Body:
Our build pipeline includes a YML template that is used to build all of our WCF services and Web applications. For all of the WCF services but one, it works like a charm. For this one WCF service, however, the following output is generated in the build logs during the Publish Artifact stage:

##[warning]Directory 'D:\azagent\A2_work\1381\a' is empty. Nothing will be added to build artifact 'drop'.

Our Build stage invokes a separate YML file which includes the following to build and publish the project:

  - task: VSBuild@1
    displayName: "Build ${{ parameters.solution}}"
    inputs:
      solution: ${{ parameters.solution }}
      msbuildArgs: >
        /p:DeployOnBuild=true
        /p:WebPublishMethod=Package
        /p:PackageAsSingleFile=true
        /p:SkipInvalidConfigurations=true
        /p:IgnoreDeployManagedRuntimeVersion=true
        /p:PackageLocation="$(build.ArtifactStagingDirectory)"
      platform: ${{ parameters.buildPlatform }}
      configuration: ${{ parameters.buildConfiguration }}

  - task: PublishBuildArtifacts@1
    displayName: "Publish Build Artifact"
    inputs:
      PathtoPublish: "$(Build.ArtifactStagingDirectory)"
      ArtifactName: "drop"
      publishLocation: "Container"

As stated earlier, this works perfectly for all other WCF projects, and generates a build artifact. However, for the problematic WCF Service, no build artifact is generated. What we've observed is that no ZIP file is created in the D:\azagent\A2_work\1381\a folder (theoretically, Build.ArtifactStagingDirectory).

I have tried numerous recommended solutions to resolve this issue, all to no effect.

Adding a CopyFiles@2 task between the VSBuild@1 task and the PublishBuildArtifacts@1 task did place the files in the Build.ArtifactStagingDirectory, but they were not in a ZIP file. Further, the deployment task (later in the pipeline) failed because no ZIP file was present in the drop folder.

Adding /p:OutDir=$(Build.ArtfactStagingDirectory) did seem to produce some sort of artifact, but the deployment task still failed, claiming it could not find the ZIP file in the drop folder.

I created a test repo that contained only the WCF project (as it's normally contained in a solution containing it and a Web application) and ran the pipeline against that repo. No build artifact was created.

Ultimately, nothing I do seems to be able to get this project to generate a build artifact.

What am I missing here? What further information can I provide that will help you to help me resolve this issue?


问:
How to load the glyph for a character, that Google Fonts is not passing by default?
I'm using "Noto Serif" font for normal text, and it is working fine. The Google Fonts URL is https://fonts.googleapis.com/css?family=Noto+Serif

However, that font face request does not return references for all the characters actually supported by "Noto Serif". It returns only latin, cyrillic, greek, and vietnamese subsets.

If I add the infinity symbol ("∞", U+221E) to the text, it gets displayed by a fallback font, even though "Noto Serif" does have a glyph for that character.

I tried to enforce a subset. I'm not sure what is the subset that would include "∞", maybe "math", if Google Fonts have such. However, the public API does not seem to support "subset" parameter (anymore?), and it seems to have no effect on the font request.

I see that a JSON API call with some access key supposedly supports parameter "subset". Is that the only way, if it even works for such case?

There is also an API parameter "text". https://fonts.googleapis.com/css?family=Noto+Serif&text=∞ does in fact return the "∞" glyph, however it returns nothing else. Is there a way to still return all the default characters and, in addition, also this "text" character?

I cannot just do both font requests, because the text one does not have unicode-range parameter, so they would override each other.

I could add manual @font-face CSS definition, but that would void the Google Fonts dynamic benefits of serving different replies to different browsers in a way they would understand best.

I could list all the characters in the text parameter... Resulting in a big query to get the font, and maybe miss some characters.

I could download the TTF font and host it locally, but that would void the benefits of not loading all the font files, containing a lot of glyphs that will never be used.

What is the best way to do this?

答:
It turned out that loading the same font a second time doesn't actually override the first one, the browsers seem to be smart and merge them all right.

So, the solution I used is:

```<code><link href="https://fonts.googleapis.com/css2?family=Noto+Serif:ital,wght@0,400;0,700;1,400;1,700&display=block" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif:ital,wght@0,400;0,700;1,400;1,700&display=block&text=%E2%88%9E" rel="stylesheet">
</code>```

At first, load all the usual characters Google Fonts give you by default, and then load the font a second time and request specific characters in text parameter.

Of course, this works nicely only if you don't have too many of those extra characters that are needed...

Body:
It turned out that loading the same font a second time doesn't actually override the first one, the browsers seem to be smart and merge them all right.

So, the solution I used is:

<link href="https://fonts.googleapis.com/css2?family=Noto+Serif:ital,wght@0,400;0,700;1,400;1,700&display=block" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif:ital,wght@0,400;0,700;1,400;1,700&display=block&text=%E2%88%9E" rel="stylesheet">

At first, load all the usual characters Google Fonts give you by default, and then load the font a second time and request specific characters in text parameter.

Of course, this works nicely only if you don't have too many of those extra characters that are needed...


问:
Gzip writer not writing gzip data to S3 in Golang
I've got a (hopefully) simple problem. I'm trying to write the results of a HTTP request to a Gzip file in S3. However when downloading the resultant file from S3, it's just in plain text and not compressed. Below is a snippet of the code (sans bootstrapping). The code builds, lints and runs without error, so I'm not sure where I'm going wrong...any pointers would be greatly appreciated!</p>
```<code>r, w := io.Pipe()
gw := gzip.NewWriter(w)
go func() {
    defer w.Close()
    defer gw.Close()
    _, err := gw.Write(httpResponse)
    if err != nil {
        fmt.Println(“error”)
    }
}()
cfg, _ := config.LoadDefaultConfig(context.TODO())
s3Client := s3.NewFromConfig(cfg)
ul := manager.NewUploader(s3Client)
_, err := ul.Upload(context.TODO(), &s3.PutObjectInput{
    Bucket:          aws.String(bucket),
    ContentEncoding: aws.String("gzip"),
    Key:             aws.String(fileName),
    Body:            r,
})
if err != nil {
    fmt.Println(“error”)
}
</code>```

答:
This is a side effect of downloading via the browser, it'll decode the gzip but leave the .gz extension (which is frankly confusing). If you use the AWS cli or API to download the file, it will remain as GZIP.

See: https://superuser.com/questions/940605/chromium-prevent-unpacking-tar-gz?noredirect=1&lq=1

Body:
I've got a (hopefully) simple problem. I'm trying to write the results of a HTTP request to a Gzip file in S3. However when downloading the resultant file from S3, it's just in plain text and not compressed. Below is a snippet of the code (sans bootstrapping). The code builds, lints and runs without error, so I'm not sure where I'm going wrong...any pointers would be greatly appreciated!

r, w := io.Pipe()
gw := gzip.NewWriter(w)
go func() {
    defer w.Close()
    defer gw.Close()
    _, err := gw.Write(httpResponse)
    if err != nil {
        fmt.Println(“error”)
    }
}()
cfg, _ := config.LoadDefaultConfig(context.TODO())
s3Client := s3.NewFromConfig(cfg)
ul := manager.NewUploader(s3Client)
_, err := ul.Upload(context.TODO(), &s3.PutObjectInput{
    Bucket:          aws.String(bucket),
    ContentEncoding: aws.String("gzip"),
    Key:             aws.String(fileName),
    Body:            r,
})
if err != nil {
    fmt.Println(“error”)
}


问:
Spring boot: java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getHttpServletMapping()Ljavax/servlet/http/HttpServletMapping;
When I run this application on built-in server or other tomcat server it
 gives me following error message. I am using jdk8, STS V-3.9.7. Can someone help me resolve it

Simple Springboot application with following content:

application.properties file for view mapping

```<code>    spring.mvc.view.prefix=/WEB-INF/jspViews/
    spring.mvc.view.suffix=.jsp
</code>```

index.jsp

```<code>    <body>
       <h3>Application is working</h3>
     </body>
</code>```

Controller class

```<code>    @Controller
    public class AppController {
       @RequestMapping("/")
       public String indexPage() {
           return "index";
       }
    }
</code>```

pom.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ehospitalsso</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

web.xml file

```<code> <?xml version="1.0" encoding="UTF-8"?>
    <web-app
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">

      <display-name>demo</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
</code>```

Error StackTrace ::

```<code>java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getHttpServletMapping()Ljavax/servlet/http/HttpServletMapping;
    at org.apache.catalina.core.ApplicationHttpRequest.setRequest(ApplicationHttpRequest.java:690) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationHttpRequest.<init>(ApplicationHttpRequest.java:114) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.wrapRequest(ApplicationDispatcher.java:917) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:358) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312) ~[catalina.jar:na]
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[servlet-api.jar:na]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[servlet-api.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-websocket.jar:9.0.13-dev]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:130) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:105) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:123) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [catalina.jar:na]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:na]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [catalina.jar:na]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [catalina.jar:na]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:na]
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668) [catalina.jar:na]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [catalina.jar:na]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:na]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.13-dev]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_161]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_161]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.13-dev]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_161]
</code>```

Screen Sort:

Kind attend Mr.Avijit for update pox.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>Demo_App</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Demo_App</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

ServletInitializer  Class

```<code>import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoAppApplication.class);
    }

}
</code>```

DemoAppApplication class

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoAppApplication.class, args);
    }

}
</code>```

答:
For anyone still stuck after the above suggestions:

My issue was due to including javax.servlet:javax.servlet-api:3.1.0 in my build.gradle file dependencies (although the same issue could occur with maven).

If you're using embedded Tomcat, the javax library is included in the tomcat-embed-core jar which is found in the maven library spring-boot-starter-tomcat.  Remove the reference to javax.servlet:javax.servlet-api:3.1.0.

Body:
When I run this application on built-in server or other tomcat server it
 gives me following error message. I am using jdk8, STS V-3.9.7. Can someone help me resolve it

Simple Springboot application with following content:

application.properties file for view mapping

    spring.mvc.view.prefix=/WEB-INF/jspViews/
    spring.mvc.view.suffix=.jsp

index.jsp

Application is working

Controller class

    @Controller
    public class AppController {
       @RequestMapping("/")
       public String indexPage() {
           return "index";
       }
    }

pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ehospitalsso</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

web.xml file

 <?xml version="1.0" encoding="UTF-8"?>
    <web-app
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">

      <display-name>demo</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

Error StackTrace ::

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getHttpServletMapping()Ljavax/servlet/http/HttpServletMapping;
    at org.apache.catalina.core.ApplicationHttpRequest.setRequest(ApplicationHttpRequest.java:690) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationHttpRequest.<init>(ApplicationHttpRequest.java:114) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.wrapRequest(ApplicationDispatcher.java:917) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:358) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312) ~[catalina.jar:na]
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[servlet-api.jar:na]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[servlet-api.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-websocket.jar:9.0.13-dev]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:130) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:105) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:123) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [catalina.jar:na]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:na]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [catalina.jar:na]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [catalina.jar:na]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:na]
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668) [catalina.jar:na]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [catalina.jar:na]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:na]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.13-dev]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_161]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_161]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.13-dev]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_161]

Screen Sort:

Kind attend Mr.Avijit for update pox.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>Demo_App</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Demo_App</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

ServletInitializer  Class

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoAppApplication.class);
    }

}

DemoAppApplication class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoAppApplication.class, args);
    }

}


问:
AWS ECS fails to start windows on Fargate
According to the new AWS feature https://aws.amazon.com/about-aws/whats-new/2021/10/aws-fargate-amazon-ecs-windows-containers/. Trying to launch my windows fails with the following:  CannotCreateVolumeError: unsupported: Dockerfile contains VOLUME instruction. Volumes are not configured in task definiuton, nor Dockerfile. Any ideas why this may happen?</p>

答:
If anyone is reading this, the solution was to NOT use the default Windows images at https://hub.docker.com/r/jenkins/inbound-agent. These images are actually built from https://github.com/jenkinsci/docker-inbound-agent/tree/master/11/windows/windowsservercore-ltsc2019 (this image does not have Volume instructions), which was built from https://github.com/jenkinsci/docker-agent/blob/master/11/windows/windowsservercore-ltsc2019/Dockerfile (this one does have Volume instruction). There are variations of it including "nanoserver" and "jdk8/jdk11" versions but they all have Volume instructions which I think these will work on EC2 but not Fargate.

If you want it to work on Fargate, you will need to build a custom image based off of these two Dockerfiles above. I use a multi-stage Dockerfile and commented out the Volume instructions on the first Dockerfile and concatenate the second Dockerfile contents to it.

```<code>FROM eclipse-temurin:11.0.13_8-jdk-windowsservercore-1809 AS jenkins-agent-windows-builder

...

#VOLUME ${AGENT_ROOT}/.jenkins
#VOLUME ${AGENT_WORKDIR}

...

FROM jenkins-agent-windows-builder

</code>```

Body:
If anyone is reading this, the solution was to NOT use the default Windows images at https://hub.docker.com/r/jenkins/inbound-agent. These images are actually built from https://github.com/jenkinsci/docker-inbound-agent/tree/master/11/windows/windowsservercore-ltsc2019 (this image does not have Volume instructions), which was built from https://github.com/jenkinsci/docker-agent/blob/master/11/windows/windowsservercore-ltsc2019/Dockerfile (this one does have Volume instruction). There are variations of it including "nanoserver" and "jdk8/jdk11" versions but they all have Volume instructions which I think these will work on EC2 but not Fargate.

If you want it to work on Fargate, you will need to build a custom image based off of these two Dockerfiles above. I use a multi-stage Dockerfile and commented out the Volume instructions on the first Dockerfile and concatenate the second Dockerfile contents to it.

FROM eclipse-temurin:11.0.13_8-jdk-windowsservercore-1809 AS jenkins-agent-windows-builder

...

#VOLUME ${AGENT_ROOT}/.jenkins
#VOLUME ${AGENT_WORKDIR}

...

FROM jenkins-agent-windows-builder


问:
Setting incoming Json data as Unix Timestamp to nullable
I have to convert the data I get through the API and that's why I couldn't set it to nullable.

```<code>var releaseDateTime =
        DateTime.fromMillisecondsSinceEpoch(_data.releaseDate! * 1000);
String releaseDate = DateFormat('yyyy-MM-dd').format(releaseDateTime);

Text(releaseDate),
</code>```

But the incoming data may come as null or "0". So,

How can I print "N/A" in case of null or "0" depending on the condition.

答:
You should check value before pass data in DateTime.fromMillisecondsSinceEpoch()

check below sample :

String releaseDate = "N/A"

if(_data.releaseDate != null && _data.releaseDate != "0"){
var releaseDateTime =
        DateTime.fromMillisecondsSinceEpoch(_data.releaseDate! * 1000);
 releaseDate = DateFormat('yyyy-MM-dd').format(releaseDateTime);
}

Text(releaseDate),

```

Body:
I have to convert the data I get through the API and that's why I couldn't set it to nullable.

var releaseDateTime =
        DateTime.fromMillisecondsSinceEpoch(_data.releaseDate! * 1000);
String releaseDate = DateFormat('yyyy-MM-dd').format(releaseDateTime);

Text(releaseDate),

But the incoming data may come as null or "0". So,

How can I print "N/A" in case of null or "0" depending on the condition.


问:
Need a better understanding of installing AWS-Nuke for Mac
Im sure this this just a lack of knowledge on my end but im having a hard time understand how to install aws-nuke following there documentation. I have downloaded the latest release but install instructions are not so clear for me https://github.com/rebuy-de/aws-nuke#:~:text=Use%20Released%20Binaries,Run%20%24%20aws%2Dnuke%2Dv2.16.0%2Dlinux%2Damd64

Any suggestions would be appreciated.

答:
On a Mac you can run aws-nuke using the following steps:

Open a terminal (Command + Space and write terminal)

Grab the latest version of the aws-nuke. Currently the latest version is 2.17.0 but obviously this will change in the future. In order to download aws-nuke, we can run the following command:

For M1 Mac:

```<code>wget https://github.com/rebuy-de/aws-nuke/releases/download/v2.17.0/aws-nuke-v2.17.0-darwin-arm64.tar.gz
</code>```

For intel Mac:

```<code>wget https://github.com/rebuy-de/aws-nuke/releases/download/v2.17.0/aws-nuke-v2.17.0-darwin-amd64.tar.gz
</code>```

Extract the package using the following command (note: use amd64 instead of arm64 if you are on an intel Mac):

```<code>tar -xvf aws-nuke-v2.17.0-darwin-arm64.tar.gz
</code>```

Create a config.yml file with the following content and place it nearby the extracted executable:

```<code>regions:
- global

account-blocklist:
- "999999999999" # leave it as it is, since the current version wont work if you don't provide a blocklist

accounts:
  "000000000000": {} # fill in your own AWS account number
</code>```

Run the following command:

```<code>./aws-nuke-v2.17.0-darwin-arm64 -c config.yml
</code>```

This should list the resources which might be deleted. If you are ok with the list, append --no-dry-run to the previous command.

Body:
On a Mac you can run aws-nuke using the following steps:

Open a terminal (Command + Space and write terminal)

Grab the latest version of the aws-nuke. Currently the latest version is 2.17.0 but obviously this will change in the future. In order to download aws-nuke, we can run the following command:

For M1 Mac:

wget https://github.com/rebuy-de/aws-nuke/releases/download/v2.17.0/aws-nuke-v2.17.0-darwin-arm64.tar.gz

For intel Mac:

wget https://github.com/rebuy-de/aws-nuke/releases/download/v2.17.0/aws-nuke-v2.17.0-darwin-amd64.tar.gz

Extract the package using the following command (note: use amd64 instead of arm64 if you are on an intel Mac):

tar -xvf aws-nuke-v2.17.0-darwin-arm64.tar.gz

Create a config.yml file with the following content and place it nearby the extracted executable:

regions:
- global

account-blocklist:
- "999999999999" # leave it as it is, since the current version wont work if you don't provide a blocklist

accounts:
  "000000000000": {} # fill in your own AWS account number

Run the following command:

./aws-nuke-v2.17.0-darwin-arm64 -c config.yml

This should list the resources which might be deleted. If you are ok with the list, append --no-dry-run to the previous command.


问:
How to return static HTML pages within a directory using web.py?
I have a web app built with web.py that generates some HTML files and serves them up to the front end. Just by going through the web.py tutorial, it seems I need to explicitly create a class for each static HTML page I serve, but that won't work for my purposes if my web app is generating these HTML files on the fly. Ideally, I'd have one directory cache/ where I put all of my HTML files, and sending a GET request to <IP_address_of_server>:8080/cache/<any_number>.html will return the one I want. Is this possible?

答:
Use a regular expression in your urls(), for example:

```<code>urls = (
    '/foobar/(.*)\.html', 'MyHandler',
    )
</code>```

Then, your handler will get one parameter as input, which can by your file name to serve.

```<code>class MyHandler:
    def GET(self, filenumber):
        with open('cache/' + filenumber + '.html') as fp:
            return fp.read()
</code>```

Calling /foobar/15567.html will result in MyHandler.GET() with filename="15567". which allows you to find and read and return the contents of that file.

Note do not do it this simply: Queries for, for example, /foobar/../root/passwd.txt  will result in users being able to "look outside" of your cache subdirectory, possibly doing things you do not want to do -- you should check your input (the value of filenumber), for example, make sure it is all numeric, or a simple file name (no / or ..) or the resulting normalized path starts with your expected path.):

```<code>os.path.normpath('cache/' + filenumber + '.html).startswith('cache/')
</code>```

Body:
Use a regular expression in your urls(), for example:

urls = (
    '/foobar/(.*)\.html', 'MyHandler',
    )

Then, your handler will get one parameter as input, which can by your file name to serve.

class MyHandler:
    def GET(self, filenumber):
        with open('cache/' + filenumber + '.html') as fp:
            return fp.read()

Calling /foobar/15567.html will result in MyHandler.GET() with filename="15567". which allows you to find and read and return the contents of that file.

Note do not do it this simply: Queries for, for example, /foobar/../root/passwd.txt  will result in users being able to "look outside" of your cache subdirectory, possibly doing things you do not want to do -- you should check your input (the value of filenumber), for example, make sure it is all numeric, or a simple file name (no / or ..) or the resulting normalized path starts with your expected path.):

os.path.normpath('cache/' + filenumber + '.html).startswith('cache/')


问:
Installed AirFLow 2.2.3 but getting error AttributeError: task decorator 'docker' not found
Just trying to run the example in:
https://github.com/apache/airflow/blob/main/airflow/example_dags/tutorial_etl_dag.py

But basically getting this (removed the try/except at the and and some comments, so line numbers might not match).

Is there something special I need to install?

```<code>Traceback (most recent call last):
  File "/usr/local/airflow/d/dags/tc70_test_script.py", line 27, in <module>
    tc70_test_script = tc70_test_script()
  File "/usr/local/lib/python3.6/site-packages/airflow/models/dag.py", line 2984, in factory
    f(**f_kwargs)
  File "/usr/local/airflow/d/dags/tc70_test_script.py", line 9, in tc70_test_script
    @task.docker()
  File "/usr/local/lib/python3.6/site-packages/airflow/decorators/__init__.py", line 33, in __getattr__
    raise AttributeError(f"task decorator {name!r} not found")
AttributeError: task decorator 'docker' not found
</code>```

答:
You asked about tutorial_etl_dag.py but your traceback shows tc70_test_script.py which you didn't share the code of that script. The tutorial DAG you shared doesn't use docker.

Docker decorator is part of the docker provider and works only for Airflow >= 2.2.0 & docker provider >=2.2.0 (It's just a coincidence that both has the same version)
If you don't have the provider installed you can get it with:

```<code>pip install apache-airflow-providers-docker>=2.2.0
</code>```

Then you can use @task.docker as shown in this example dag.

Body:
Just trying to run the example in:
https://github.com/apache/airflow/blob/main/airflow/example_dags/tutorial_etl_dag.py

But basically getting this (removed the try/except at the and and some comments, so line numbers might not match).

Is there something special I need to install?

Traceback (most recent call last):
  File "/usr/local/airflow/d/dags/tc70_test_script.py", line 27, in <module>
    tc70_test_script = tc70_test_script()
  File "/usr/local/lib/python3.6/site-packages/airflow/models/dag.py", line 2984, in factory
    f(**f_kwargs)
  File "/usr/local/airflow/d/dags/tc70_test_script.py", line 9, in tc70_test_script
    @task.docker()
  File "/usr/local/lib/python3.6/site-packages/airflow/decorators/__init__.py", line 33, in __getattr__
    raise AttributeError(f"task decorator {name!r} not found")
AttributeError: task decorator 'docker' not found

Body:
You asked about tutorial_etl_dag.py but your traceback shows tc70_test_script.py which you didn't share the code of that script. The tutorial DAG you shared doesn't use docker.

Docker decorator is part of the docker provider and works only for Airflow >= 2.2.0 & docker provider >=2.2.0 (It's just a coincidence that both has the same version)
If you don't have the provider installed you can get it with:

pip install apache-airflow-providers-docker>=2.2.0

Then you can use @task.docker as shown in this example dag.


答:
You can access the values without using a key;

```<code>>>> d = {'Animal': ['Cat', 'Dog', 'Ocelot'],
...  'Humans': ['Jack', 'Jill', 'Frank'],
...  'Fruit': ['Apple', 'Orange', 'Banana']}
>>>
>>> d.values()
dict_values([['Cat', 'Dog', 'Ocelot'], ['Jack', 'Jill', 'Frank'], ['Apple', 'Orange', 'Banana']])
>>> [i[2] for i in d.values()]
['Ocelot', 'Frank', 'Banana']
</code>```

Often it is more useful to iterate over the items:

```<code>>>> for k, v in d.items():
...     print(k, v[2])
...
Animal Ocelot
Humans Frank
Fruit Banana
</code>```

Title: Accessing elements in Python dictionary

Body:
bit of a strange question, but I was trying to come up with different ways to get around this.

Let's say I have the following Dictionary:

dict={

    'Animal':['Cat', 'Dog', 'Ocelot'],
    'Humans':['Jack', 'Jill', 'Frank'],
    'Fruit':['Apple', 'Orange', 'Banana']
}

Is there a way to access just the third element of every key?
The output being 'Ocelot' 'Frank 'Banana'

I know that the notation for single key is Dictionary(KEY)[ITEM PLACE] but is there a way to do this without specifying the key?

Thanks

Body:
You can access the values without using a key;

>>> d = {'Animal': ['Cat', 'Dog', 'Ocelot'],
...  'Humans': ['Jack', 'Jill', 'Frank'],
...  'Fruit': ['Apple', 'Orange', 'Banana']}
>>>
>>> d.values()
dict_values([['Cat', 'Dog', 'Ocelot'], ['Jack', 'Jill', 'Frank'], ['Apple', 'Orange', 'Banana']])
>>> [i[2] for i in d.values()]
['Ocelot', 'Frank', 'Banana']

Often it is more useful to iterate over the items:

>>> for k, v in d.items():
...     print(k, v[2])
...
Animal Ocelot
Humans Frank
Fruit Banana


问:
How to extract and compare the libc versions at runtime?
How to extract and compare the libc versions at runtime with the following restrictions?

stable solution (commands output parsing is discarded as this may vary)

should not rely on executing external tools like ldd, gcc or others

must work on a statically linked binary (AppRun)

will be implemented in C

Context:

In the AppImage project have been working on a feature to allow creating backward compatible bundles. To achieve this we created a program named AppRun. Things program compares the system glibc version with the one shipped in the bundle and configures the bundle to use the newer at runtime. This program is statically linked and should not depend on external tools.

Right now we scan the libc.so file for occurrences of GLIBC_X.XX and store the greater. But this is no longer working in the latest binary include in Ubuntu 20.04. The binary is 2.31 but there are no GLIBC_2.31 strings in the file therefore the method fails.

Related issues:

https://github.com/AppImageCrafters/AppRun/issues/35

https://github.com/AppImageCrafters/appimage-builder/issues/145

答:
the libc versions

There are alternatives to glibc.

Right now we scan the libc.so file for occurrences of GLIBC_X.XX

Search for the string that glibc prints - GNU C Library <pkg+release_name> release version <version>[,.]..., and version has format [0-9]+\.[0-9]+(\.[0-9]+)?.

Just find libc.so.6 in /etc/ld.so.cache.

Do this in C:

```<code>libcfile="$(grep -azm1 '/libc.so.6$' /etc/ld.so.cache | tr -d '\0')"
grep -aoP 'GNU C Library [^\n]* release version \K[0-9]*.[0-9]*' "$libcfile"
</code>```

Looking at commits, this should work since forever:

https://github.com/bminor/glibc/blame/b7eb84454020c59d528e826ae1889f411ed69e26/version.c#L28

https://github.com/bminor/glibc/blame/9f70e81bcaa12b0673cd0879d6f4a21ad6dddce5/version.c#L28

https://github.com/bminor/glibc/blame/92e4b6a92716f8b2457376291171a6330d072b0d/csu/version.c#L27

https://github.com/bminor/glibc/blame/50c66c7acd90f257b295e58bf938ed120cbc27c7/csu/version.c#L27

https://github.com/bminor/glibc/blame/b92a49359f33a461db080a33940d73f47c756126/csu/version.c#L27

Seems to work on the oldest ubuntu in docker I can find:

```<code>$ cmd='grep -aoP "GNU C Library [^\n]* release version \K[0-9]*.[0-9]*" "$(grep -azm1 "/libc.so.6$" /etc/ld.so.cache | tr -d "\0")"'
$ echo -n 'local: '; sh -c "$cmd"; for i in 13.04 16.04 14.04 22.04 21.10 20.04 18.04; do echo -n "ubuntu:$i "; docker run -ti --rm ubuntu:$i sh -c "$cmd"; done
local: 2.33
ubuntu:13.04 2.17
ubuntu:16.04 2.23
ubuntu:14.04 2.19
ubuntu:22.04 2.34
ubuntu:21.10 2.34
ubuntu:20.04 2.31
ubuntu:18.04 2.27
</code>```

I also tested opensuse12.2 with glibc2.15, libc.so.6 prints GNU C Library stable release version 2.15 (20120628), by Roland McGrath et al. there.

Body:
the libc versions

There are alternatives to glibc.

Right now we scan the libc.so file for occurrences of GLIBC_X.XX

Search for the string that glibc prints - GNU C Library <pkg+release_name> release version <version>[,.]..., and version has format [0-9]+\.[0-9]+(\.[0-9]+)?.

Just find libc.so.6 in /etc/ld.so.cache.

Do this in C:

libcfile="$(grep -azm1 '/libc.so.6$' /etc/ld.so.cache | tr -d '\0')"
grep -aoP 'GNU C Library [^\n]* release version \K[0-9]*.[0-9]*' "$libcfile"

Looking at commits, this should work since forever:

https://github.com/bminor/glibc/blame/b7eb84454020c59d528e826ae1889f411ed69e26/version.c#L28

https://github.com/bminor/glibc/blame/9f70e81bcaa12b0673cd0879d6f4a21ad6dddce5/version.c#L28

https://github.com/bminor/glibc/blame/92e4b6a92716f8b2457376291171a6330d072b0d/csu/version.c#L27

https://github.com/bminor/glibc/blame/50c66c7acd90f257b295e58bf938ed120cbc27c7/csu/version.c#L27

https://github.com/bminor/glibc/blame/b92a49359f33a461db080a33940d73f47c756126/csu/version.c#L27

Seems to work on the oldest ubuntu in docker I can find:

$ cmd='grep -aoP "GNU C Library [^\n]* release version \K[0-9]*.[0-9]*" "$(grep -azm1 "/libc.so.6$" /etc/ld.so.cache | tr -d "\0")"'
$ echo -n 'local: '; sh -c "$cmd"; for i in 13.04 16.04 14.04 22.04 21.10 20.04 18.04; do echo -n "ubuntu:$i "; docker run -ti --rm ubuntu:$i sh -c "$cmd"; done
local: 2.33
ubuntu:13.04 2.17
ubuntu:16.04 2.23
ubuntu:14.04 2.19
ubuntu:22.04 2.34
ubuntu:21.10 2.34
ubuntu:20.04 2.31
ubuntu:18.04 2.27

I also tested opensuse12.2 with glibc2.15, libc.so.6 prints GNU C Library stable release version 2.15 (20120628), by Roland McGrath et al. there.


问:
HtmlAgilityPack close form tag automatically
I am tring to parse an html file with this code:

```<code><div><form>...</div>...</form>
</code>```

the problem is that the HtmlAgilityPack automatically close the form tag before the div ending tag:

<form>...</form>
...</form>  so when I parse the form some of the form elements are missing. (I get only the elements befor the automatically added  tag)

I already tried:

```<code>htmlDoc.OptionFixNestedTags = false;
htmlDoc.OptionAutoCloseOnEnd = false;
htmlDoc.OptionCheckSyntax = false;
HtmlNode.ElementsFlags.Remove("form");
HtmlNode.ElementsFlags.Add("form", HtmlElementFlag.CanOverlap);
HtmlNode.ElementsFlags.Add("div", HtmlElementFlag.CanOverlap);
</code>```

But nothing helps!

thanks for you help!

答:
It depends on what you want to do programmatically after the text has been parsed. If you don't want to do anything special with it, the following code:

```<code>    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml("<div><form>form and div</div>form</form>");

    doc.Save(Console.Out);
</code>```

will display exactly the same string, that is:

```<code><div><form>form and div</div>form</form>
</code>```

Because the library was designed from the grounds up to try to keep the original Html as much as possible.

But in terms on how this is represented in the DOM, and in terms of errors, this is another story. You can't have at the same time 1) overlapping elements 2) XML-like DOM (which does not support overlaps) and 3) no errors.

So it depends on what you want to do after parsing.

Body:
I am tring to parse an html file with this code:

<form>...
...</form>

the problem is that the HtmlAgilityPack automatically close the form tag before the div ending tag:

<form>...</form>
...</form>  so when I parse the form some of the form elements are missing. (I get only the elements befor the automatically added  tag)

I already tried:

htmlDoc.OptionFixNestedTags = false;
htmlDoc.OptionAutoCloseOnEnd = false;
htmlDoc.OptionCheckSyntax = false;
HtmlNode.ElementsFlags.Remove("form");
HtmlNode.ElementsFlags.Add("form", HtmlElementFlag.CanOverlap);
HtmlNode.ElementsFlags.Add("div", HtmlElementFlag.CanOverlap);

But nothing helps!

thanks for you help!

Body:
It depends on what you want to do programmatically after the text has been parsed. If you don't want to do anything special with it, the following code:

    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml("<div><form>form and div</div>form</form>");

    doc.Save(Console.Out);

will display exactly the same string, that is:

<div><form>form and div</div>form</form>

Because the library was designed from the grounds up to try to keep the original Html as much as possible.

But in terms on how this is represented in the DOM, and in terms of errors, this is another story. You can't have at the same time 1) overlapping elements 2) XML-like DOM (which does not support overlaps) and 3) no errors.

So it depends on what you want to do after parsing.


问:
Java: What is the difference between subroutine and methods?
What is the difference?

```<code>public write(){
// dostuff
}
</code>```

Is the code above a subroutine, a method, or a program block?

I don't understand these terms because the meaning of them are all so similar?

So, if I was being very strict and pedantic, then which one would it be? I prefer calling them subroutines, is this STRICTLY correct?

Programming language: JAVA

EDIT:
Thanks, I understand now but what would be the safest way to call it? Block?
I use multiple programming languages, would the term "block" suffice?

Can I call a function a block?

So can I refer everything as a block? It will be easier for me, right?

I won't call a block a function or subroutine, but I will call a function, methods and whatever as a block. Would that be fine, calling them as a block?

So, does this mean this is somewhat ACCURATE?
A local variable is not accessed outside of the program block (yes, there are a few circumstances that this is not true).

答:
They are just terms to identify different types of callable structures.  Subroutine was not really a term that was "Ported" to Java, in fact it's rarely used any more.  In older languages it was often used to say "execute a reusable piece of code and return here".  This is a bit general, it doesn't specify where parameters are passed or returned.  This term is mostly used in systems with shared memory (public variables in Basic, system memory in assembly, ...), but I think it can really apply to any reusable code.

A more specific term that is often used is "Function".  Technically a (pure) function must always return the same result for a given set of parameters.  This was good for non-oo languages as a replacement for "Subroutine", it is a clearer term than subroutine because it specifies how values are passed and implies you aren't just accessing arbitrary memory, technically it's probably still a subroutine too.

The term Function isn't always accurate for OO languages though--In Object Oriented Languages we add in the idea of "Objects" to encapsulate data and do work on that data for you.  When you call a method like atomicInteger.incrementAndGet(), it might (will!) return a different value each time by mutating something inside the object.  This no longer fits the definition of a Function (Returns different results for the same parameters), so they call it a method.  It could still fall under the general term "Subroutine", but it would be confusing and less specific to do so in OO languages, so we just don't.

So Java can have both Functions and Methods.  Every routine on "String" is a function because none of them modify the state of the underlying object (and therefore a given function called on a string always returns the same value.  A Method can modify the state of the object.

These differences become pretty important when you are trying to make objects safe for multi-threading and sharing--You shouldn't call a method from multiple threads at once, but functions are fine.. Note that this makes any use of String safe for threading use because it's all Functions (An object that only has functions is also called Immutable).

Body:
What is the difference?

public write(){
// dostuff
}

Is the code above a subroutine, a method, or a program block?

I don't understand these terms because the meaning of them are all so similar?

So, if I was being very strict and pedantic, then which one would it be? I prefer calling them subroutines, is this STRICTLY correct?

Programming language: JAVA

EDIT:
Thanks, I understand now but what would be the safest way to call it? Block?
I use multiple programming languages, would the term "block" suffice?

Can I call a function a block?

So can I refer everything as a block? It will be easier for me, right?

I won't call a block a function or subroutine, but I will call a function, methods and whatever as a block. Would that be fine, calling them as a block?

So, does this mean this is somewhat ACCURATE?
A local variable is not accessed outside of the program block (yes, there are a few circumstances that this is not true).