问:
@AfterMapping mehod is not called in generated class
I'm trying to customize a mapping use a string to determine an object attribute so I wrote this:

```<code>@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ProductMapper {

public abstract ProductInput asProductInputFromIdentifier(String identifier);

@AfterMapping
protected void determineIdentifier(String identifier, @MappingTarget ProductInput out) {
    if (StringUtils.contains(identifier, '?')) {
        out.setExternalId(identifier);
    } else {
        out.setInernalId(identifier);
    }
}
}
</code>```

The generated class doesn't call the determineIdentifier method. I found another solution by using directly the Java expression on the asProductInputFromIdentifier method but I really want to write a clear code using the @AfterMapping.

```<code>@Mapping(target = "externalId", expression = "java( org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
@Mapping(target = "internalId", expression = "java( !org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
public abstract ProductInput asProductDetailInputFromIdentifier(String identifier);
</code>```

I didn't understand why it doesn't work Is it because I don't have an Object in method parameter?

答:
MapStruct doesn't know how to map from String to ProductInput in your case I would suggest that you implement the mapping method on your own.

e.g.

```<code>@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ProductMapper {

    public ProductInput asProductInputFromIdentifier(String identifier) {
        ProductInput out = new ProductInput();
        if (StringUtils.contains(identifier, '?')) {
            out.setExternalId(identifier);
        } else {
            out.setInernalId(identifier);
        }
        return out;
    }
}
</code>```

There is no point in using lifecycle callbacks nor special @Mapping annotations to perform a simple mapping like in this example.

Body:
I'm trying to customize a mapping use a string to determine an object attribute so I wrote this:

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ProductMapper {

public abstract ProductInput asProductInputFromIdentifier(String identifier);

@AfterMapping
protected void determineIdentifier(String identifier, @MappingTarget ProductInput out) {
    if (StringUtils.contains(identifier, '?')) {
        out.setExternalId(identifier);
    } else {
        out.setInernalId(identifier);
    }
}
}

The generated class doesn't call the determineIdentifier method. I found another solution by using directly the Java expression on the asProductInputFromIdentifier method but I really want to write a clear code using the @AfterMapping.

@Mapping(target = "externalId", expression = "java( org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
@Mapping(target = "internalId", expression = "java( !org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
public abstract ProductInput asProductDetailInputFromIdentifier(String identifier);

I didn't understand why it doesn't work Is it because I don't have an Object in method parameter?

Body:
MapStruct doesn't know how to map from String to ProductInput in your case I would suggest that you implement the mapping method on your own.

e.g.

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ProductMapper {

    public ProductInput asProductInputFromIdentifier(String identifier) {
        ProductInput out = new ProductInput();
        if (StringUtils.contains(identifier, '?')) {
            out.setExternalId(identifier);
        } else {
            out.setInernalId(identifier);
        }
        return out;
    }
}

There is no point in using lifecycle callbacks nor special @Mapping annotations to perform a simple mapping like in this example.


来源: stackexchange

问:
catplot() in seaborn doesn't work with subplot()
I cannot subplot catplot. Here is my code:

```<code>import seaborn as sns
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1,2)
sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
sns.catplot(x='species', y='sepal_width', data=df , kind='violin')
</code>```

And here is the output:
How can I fix it?
Thank you.

答:
Although this may be a promotion of my package, patchworklib allows you to handle catplot plots as matplotlib subplots.
Please see the following code.

import seaborn as sns
import matplotlib.pyplot as plt
import patchworklib as pw
pw.overwrite_axisgrid()

df = sns.load_dataset('iris')
g1 = sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
g1 = pw.load_seaborngrid(g1)

g2 = sns.catplot(x='species', y='sepal_width', data=df , kind='violin')
g2 = pw.load_seaborngrid(g2)

(g1|g2).savefig()
```
<p><img src="https://i.stack.imgur.com/zyEfx.png" alt="enter image description here" /></p>
<p>You can also align them vertically as follow.</p>
<pre class="lang-py prettyprint-override"><code>(g1/g2).savefig()
</code>```

The code above is executable in Google colab.

ContentLicense: CC BY-SA 4.0

Body:
I cannot subplot catplot. Here is my code:

import seaborn as sns
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1,2)
sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
sns.catplot(x='species', y='sepal_width', data=df , kind='violin')

And here is the output:
How can I fix it?
Thank you.

Body:
Although this may be a promotion of my package, patchworklib allows you to handle catplot plots as matplotlib subplots.
Please see the following code.

import seaborn as sns
import matplotlib.pyplot as plt
import patchworklib as pw
pw.overwrite_axisgrid()

df = sns.load_dataset('iris')
g1 = sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
g1 = pw.load_seaborngrid(g1)

g2 = sns.catplot(x='species', y='sepal_width', data=df , kind='violin')
g2 = pw.load_seaborngrid(g2)

(g1|g2).savefig()

You can also align them vertically as follow.

(g1/g2).savefig()

The code above is executable in Google colab.


问:
Why getting too many re-renders?
I have a Calculator component for calculating the exponent of a given base.
My code is as follows:

```<code>//Exponential Calculator (Power/Squre-Root/Cube-Root)
  const Exponents=()=>{
    const [result,setResult]=useState(null);
    const [choice,setChoice]=useState("Power");
    const [x,setX]=useState(null);
    const [n,setN]=useState(null);
    useEffect(()=>{

    },[choice,x,n,result]);
    const calcResult=()=>{
      let res=1;
      if(choice=="Power")
      {
        for(var i=1;i<=n;i++)
        res*=x;
      }
      else if(choice=="SquareRoot")
      res=Math.sqrt(x);
      else
      res=Math.cbrt(x);

      setResult(res);
    }
    const handleChange=(e)=>{
      reset();
      setChoice(e.target.value);
    }
    function reset(){
      setResult(null);
      setX(null);
      setN(null);
    }
    const choiceData=()=>{
      if(choice==="Power"){
        return {
          name:"Power",
          quantities:["Base","Exponent"],
          disabled:false
        }
      }
      else if(choice==="SquareRoot")
      {
        setN(0.50);
        return{
          name:"Square-Root",
          quantities:["Base","Exponent"],
          disabled:true
        }
      }
      else if(choice==="CubeRoot")
      {
        setN(0.34);
        return{
          name:"Cube-Root",
          quantities:["Base","Exponent"],
          disabled:true
        }
      }
    }
    return(
      <>
      <Form>
      <Form.Group className="mb-4" controlId="choice">
            <Form.Label>Select the type of calculation</Form.Label>
            <Form.Control
              as="select"
              className="select-custom-res"
              onChange={(e) => handleChange(e)}
            >
              <option value="Power">Power</option>
              <option value="SquareRoot">Square Root</option>
              <option value="CubeRoot">Cube Root</option>
            </Form.Control>
          </Form.Group>
          <Form.Group className="mb-4" controlId="text">
            <Form.Text className="text">
              <strong>
                To find the {choiceData().name}, Enter the following values
              </strong>
              <br />
            </Form.Text>
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>{choiceData().quantities[0]}</Form.Label>
            <Form.Control
              onChange={(e) => setX(e.target.value)}
              type="number"
              placeholder={"Enter the Base"}
              value={x === null ? "" : x}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>{choiceData().quantities[1]}</Form.Label>
            <Form.Control
              onChange={(e) => setN(e.target.value)}
              type="number"
              placeholder={"Enter the Exponent"}
              value={n === null ? "" : n}
              disabled={choiceData().disabled}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Control
              readOnly
              type="number"
              placeholder={result === null ? "Result" : result + " "}
            />
          </Form.Group>
      </Form>
        <div className="button-custom-grp">
          <Button variant="primary" onClick={calcResult}>
            Calculate
          </Button>

          <Button variant="dark" onClick={() => reset()} type="reset">
            Reset
          </Button>
        </div>
      </>
    )
  }
</code>```

On changing the choice from Power to SquareRoot I get an error:Too many rerenders. Interestingly,   when I remove the setState line in the choiceData function,the error vanishes. Although I have used useEffect to prevent re-renders, it's not working.

答:
Issue

You call choiceData in the render return, which should be free of side-effects, like enqueueing state updates. When you call setN in the choiceData function it triggers a rerender, which calls choiceData again, which triggers a rerender... repeat ad nauseam.

Solution

I suggest converting choiceData into a chunk of state, and use an useEffect hook to update it and the n state depending on the choice state. In the render return, instead of calling a function to get a value, i.e. choiceData().quantities[0], you instead just access a property of the new choiceData state, i.e. choiceData.quantities[0].

```<code>const Exponents = () => {
  const [result, setResult] = useState(null);
  const [choice, setChoice] = useState("Power");
  const [choiceData, setChoiceData] = useState({});
  const [x, setX] = useState(null);
  const [n, setN] = useState(null);

  useEffect(() => {
    if (choice === "Power") {
      setChoiceData({
        name: "Power",
        quantities: ["Base", "Exponent"],
        disabled: false
      });
    } else if (choice === "SquareRoot") {
      setN(0.5);
      setChoiceData({
        name: "Square-Root",
        quantities: ["Base", "Exponent"],
        disabled: true
      });
    } else if (choice === "CubeRoot") {
      setN(0.34);
      setChoiceData({
        name: "Cube-Root",
        quantities: ["Base", "Exponent"],
        disabled: true
      });
    }
  }, [choice]);

  useEffect(() => {
    // is this effect used for anything?
  }, [choice, x, n, result]);

  const calcResult = () => {
    let res = 1;
    if (choice == "Power") {
      for (var i = 1; i <= n; i++) res *= x;
    } else if (choice == "SquareRoot") res = Math.sqrt(x);
    else res = Math.cbrt(x);

    setResult(res);
  };

  const handleChange = (e) => {
    reset();
    setChoice(e.target.value);
  };

  function reset() {
    setResult(null);
    setX(null);
    setN(null);
  }

  return (
    <>
      <Form>
        <Form.Group className="mb-4" controlId="choice">
          <Form.Label>Select the type of calculation</Form.Label>
          <Form.Control
            as="select"
            className="select-custom-res"
            onChange={(e) => handleChange(e)}
          >
            <option value="Power">Power</option>
            <option value="SquareRoot">Square Root</option>
            <option value="CubeRoot">Cube Root</option>
          </Form.Control>
        </Form.Group>
        <Form.Group className="mb-4" controlId="text">
          <Form.Text className="text">
            <strong>
              To find the {choiceData.name}, Enter the following values
            </strong>
            <br />
          </Form.Text>
        </Form.Group>
        <Form.Group className="mb-4">
          <Form.Label>{choiceData.quantities[0]}</Form.Label>
          <Form.Control
            onChange={(e) => setX(e.target.value)}
            type="number"
            placeholder={"Enter the Base"}
            value={x === null ? "" : x}
          />
        </Form.Group>
        <Form.Group className="mb-4">
          <Form.Label>{choiceData.quantities[1]}</Form.Label>
          <Form.Control
            onChange={(e) => setN(e.target.value)}
            type="number"
            placeholder={"Enter the Exponent"}
            value={n === null ? "" : n}
            disabled={choiceData.disabled}
          />
        </Form.Group>
        <Form.Group className="mb-4">
          <Form.Control
            readOnly
            type="number"
            placeholder={result === null ? "Result" : result + " "}
          />
        </Form.Group>
      </Form>
      <div className="button-custom-grp">
        <Button variant="primary" onClick={calcResult}>
          Calculate
        </Button>

        <Button variant="dark" onClick={() => reset()} type="reset">
          Reset
        </Button>
      </div>
    </>
  );
};
</code>```

Title: Why getting too many re-renders?

Body:
I have a Calculator component for calculating the exponent of a given base.
My code is as follows:

//Exponential Calculator (Power/Squre-Root/Cube-Root)
  const Exponents=()=>{
    const [result,setResult]=useState(null);
    const [choice,setChoice]=useState("Power");
    const [x,setX]=useState(null);
    const [n,setN]=useState(null);
    useEffect(()=>{

    },[choice,x,n,result]);
    const calcResult=()=>{
      let res=1;
      if(choice=="Power")
      {
        for(var i=1;i<=n;i++)
        res*=x;
      }
      else if(choice=="SquareRoot")
      res=Math.sqrt(x);
      else
      res=Math.cbrt(x);

      setResult(res);
    }
    const handleChange=(e)=>{
      reset();
      setChoice(e.target.value);
    }
    function reset(){
      setResult(null);
      setX(null);
      setN(null);
    }
    const choiceData=()=>{
      if(choice==="Power"){
        return {
          name:"Power",
          quantities:["Base","Exponent"],
          disabled:false
        }
      }
      else if(choice==="SquareRoot")
      {
        setN(0.50);
        return{
          name:"Square-Root",
          quantities:["Base","Exponent"],
          disabled:true
        }
      }
      else if(choice==="CubeRoot")
      {
        setN(0.34);
        return{
          name:"Cube-Root",
          quantities:["Base","Exponent"],
          disabled:true
        }
      }
    }
    return(
      <>
      <Form>
      <Form.Group className="mb-4" controlId="choice">
            <Form.Label>Select the type of calculation</Form.Label>
            <Form.Control
              as="select"
              className="select-custom-res"
              onChange={(e) => handleChange(e)}
            >
              <option value="Power">Power</option>
              <option value="SquareRoot">Square Root</option>
              <option value="CubeRoot">Cube Root</option>
            </Form.Control>
          </Form.Group>
          <Form.Group className="mb-4" controlId="text">
            <Form.Text className="text">

                To find the {choiceData().name}, Enter the following values

            </Form.Text>
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>{choiceData().quantities[0]}</Form.Label>
            <Form.Control
              onChange={(e) => setX(e.target.value)}
              type="number"
              placeholder={"Enter the Base"}
              value={x === null ? "" : x}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>{choiceData().quantities[1]}</Form.Label>
            <Form.Control
              onChange={(e) => setN(e.target.value)}
              type="number"
              placeholder={"Enter the Exponent"}
              value={n === null ? "" : n}
              disabled={choiceData().disabled}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Control
              readOnly
              type="number"
              placeholder={result === null ? "Result" : result + " "}
            />
          </Form.Group>
      </Form>

          <Button variant="primary" onClick={calcResult}>
            Calculate
          </Button>

          <Button variant="dark" onClick={() => reset()} type="reset">
            Reset
          </Button>

      </>
    )
  }

On changing the choice from Power to SquareRoot I get an error:Too many rerenders. Interestingly,   when I remove the setState line in the choiceData function,the error vanishes. Although I have used useEffect to prevent re-renders, it's not working.

Body:
Issue

You call choiceData in the render return, which should be free of side-effects, like enqueueing state updates. When you call setN in the choiceData function it triggers a rerender, which calls choiceData again, which triggers a rerender... repeat ad nauseam.

Solution

I suggest converting choiceData into a chunk of state, and use an useEffect hook to update it and the n state depending on the choice state. In the render return, instead of calling a function to get a value, i.e. choiceData().quantities[0], you instead just access a property of the new choiceData state, i.e. choiceData.quantities[0].

const Exponents = () => {
  const [result, setResult] = useState(null);
  const [choice, setChoice] = useState("Power");
  const [choiceData, setChoiceData] = useState({});
  const [x, setX] = useState(null);
  const [n, setN] = useState(null);

  useEffect(() => {
    if (choice === "Power") {
      setChoiceData({
        name: "Power",
        quantities: ["Base", "Exponent"],
        disabled: false
      });
    } else if (choice === "SquareRoot") {
      setN(0.5);
      setChoiceData({
        name: "Square-Root",
        quantities: ["Base", "Exponent"],
        disabled: true
      });
    } else if (choice === "CubeRoot") {
      setN(0.34);
      setChoiceData({
        name: "Cube-Root",
        quantities: ["Base", "Exponent"],
        disabled: true
      });
    }
  }, [choice]);

  useEffect(() => {
    // is this effect used for anything?
  }, [choice, x, n, result]);

  const calcResult = () => {
    let res = 1;
    if (choice == "Power") {
      for (var i = 1; i <= n; i++) res *= x;
    } else if (choice == "SquareRoot") res = Math.sqrt(x);
    else res = Math.cbrt(x);

    setResult(res);
  };

  const handleChange = (e) => {
    reset();
    setChoice(e.target.value);
  };

  function reset() {
    setResult(null);
    setX(null);
    setN(null);
  }

  return (
    <>
      <Form>
        <Form.Group className="mb-4" controlId="choice">
          <Form.Label>Select the type of calculation</Form.Label>
          <Form.Control
            as="select"
            className="select-custom-res"
            onChange={(e) => handleChange(e)}
          >
            <option value="Power">Power</option>
            <option value="SquareRoot">Square Root</option>
            <option value="CubeRoot">Cube Root</option>
          </Form.Control>
        </Form.Group>
        <Form.Group className="mb-4" controlId="text">
          <Form.Text className="text">
            <strong>
              To find the {choiceData.name}, Enter the following values
            </strong>
            <br />
          </Form.Text>
        </Form.Group>
        <Form.Group className="mb-4">
          <Form.Label>{choiceData.quantities[0]}</Form.Label>
          <Form.Control
            onChange={(e) => setX(e.target.value)}
            type="number"
            placeholder={"Enter the Base"}
            value={x === null ? "" : x}
          />
        </Form.Group>
        <Form.Group className="mb-4">
          <Form.Label>{choiceData.quantities[1]}</Form.Label>
          <Form.Control
            onChange={(e) => setN(e.target.value)}
            type="number"
            placeholder={"Enter the Exponent"}
            value={n === null ? "" : n}
            disabled={choiceData.disabled}
          />
        </Form.Group>
        <Form.Group className="mb-4">
          <Form.Control
            readOnly
            type="number"
            placeholder={result === null ? "Result" : result + " "}
          />
        </Form.Group>
      </Form>
      <div className="button-custom-grp">
        <Button variant="primary" onClick={calcResult}>
          Calculate
        </Button>
        &nbsp;&nbsp;&nbsp;
        <Button variant="dark" onClick={() => reset()} type="reset">
          Reset
        </Button>
      </div>
    </>
  );
};


问:
Avoid ngOnChanges until ngOnInit is completed in Angular
Scenario : I have two components Parent and Child. Both components have some API calls being done in ngOnInit. Child component has ngOnChanges lifecycle hook.
On page load based on certain conditions I'm triggering child's ngOnChanges from Parent component by changing the @Input parameter being passed to Child.

Issue : Child component's ngOnChanges is being triggered from Parent component before the Child component's ngOnInit is completed.

How to avoid this ??

答:
Assuming from parent component once your ngOninit api call completes you will be updating the input variable for child component.

You can check a condition in child components ngOnchanges :

```<code>ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    //reLoad: Boolean type input parameter comming from parent component
    if (changes['reLoad'] && (changes['reLoad'].previousValue !== changes['reLoad'].currentValue)) {
      if (changes['reLoad'].currentValue) {
        //Call load method of child component
        this.childApiLoad();
      }
    }
  }
</code>```

It's a default behavior of Angular component, ngOnChanges lifecycle hook will invoke first and than ngOnInit.
https://angular.io/guide/lifecycle-hooks

Body:
Assuming from parent component once your ngOninit api call completes you will be updating the input variable for child component.

You can check a condition in child components ngOnchanges :

ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    //reLoad: Boolean type input parameter comming from parent component
    if (changes['reLoad'] && (changes['reLoad'].previousValue !== changes['reLoad'].currentValue)) {
      if (changes['reLoad'].currentValue) {
        //Call load method of child component
        this.childApiLoad();
      }
    }
  }

It's a default behavior of Angular component, ngOnChanges lifecycle hook will invoke first and than ngOnInit.
https://angular.io/guide/lifecycle-hooks


问:
How do I center a value surrounded by CardActions (material ui)
So I'm having this issue, this is an image of my site

And this is code.

```<code><CardActions>
   <Typography
     style={{
     fontWeight: 'bold',
     color: 'red',
    }}
    >
    {product.price}đ  ///// the price number /////
   </Typography>
</CardActions>

</code>```

I want my price tag to be at the center of the card (similar to the sold button underneath), at first I tried to wrap it in <Box> element then add textAlign to it, no success there.

This seems like a simple issue to solve but I think I'm misunderstanding something here, I've tried many ways but to no avail. Any help would be greatly appreciated.

答:
To align the price you try just add a in-line style like below

<CardActions>
  <Typography
    style={{
      fontWeight: "bold",
      color: "red",
      margin: "0px auto"
    }}
  >
    123 d
  </Typography>
</CardActions>```

encourage me with a up-vote when it works.

Body:
So I'm having this issue, this is an image of my site

And this is code.

<CardActions>
   <Typography
     style={{
     fontWeight: 'bold',
     color: 'red',
    }}
    >
    {product.price}đ  ///// the price number /////
   </Typography>
</CardActions>

I want my price tag to be at the center of the card (similar to the sold button underneath), at first I tried to wrap it in <Box> element then add textAlign to it, no success there.

This seems like a simple issue to solve but I think I'm misunderstanding something here, I've tried many ways but to no avail. Any help would be greatly appreciated.

Body:
To align the price you try just add a in-line style like below

<CardActions>
  <Typography
    style={{
      fontWeight: "bold",
      color: "red",
      margin: "0px auto"
    }}
  >
    123 d
  </Typography>
</CardActions>

encourage me with a up-vote when it works.


问:
Display second prompt if the first prompt is not TRUE
I have a problem when i try to display new prompt, i use loop but it will display both my prompt. Here is my code and i really need help</p>
```<code><body>
<p id="age" style="font-weight: bold"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
var age = document.getElementById("age").value;
var age = prompt("Enter Your birth year:");// This is the first prompt
const year = new Date().getFullYear();
if (age != null) {
          document.getElementById("age").innerHTML =
            "Your " + age + " is so beautiful"; // If user enter birth year < current year will display this
        }
  do {
     age = prompt("Re-enter your birth year:"); // Ortherwise, this will display and they need to enter until birth year < current year
    } while (age > year && age != null);
        var tuoi = year - age;// This is just calculate user'age, for example if the user enter 2000 will display user'age is 22
        document.getElementById("age").innerHTML =
          "Tuổi " + tuoi + " này đẹp đó";
}
</script>
</body>

</code>```

答:
your code has several issues and does some things which do not make total sense to me, but I think you want something like this:</p>
```<code><body>
  <p id="age" style="font-weight: bold"></p>
  <button onclick=" notify()">Try it</button>
  <script>
    function notify() {
      const year = new Date().getFullYear();
      var birth_year = parseInt(prompt("Enter Your birth year:")); // This is the first prompt

      if (!isNaN(birth_year) && birth_year < year) {
        document.getElementById("age").innerHTML =
          "Your " + birth_year + " is so beautiful"; // If user enter birth year < current year will display this
      } else {
        do {
          birth_year = parseInt(prompt("Enter Your birth year:")); // Ortherwise, this will display and they need to enter until birth year < current year
        } while (isNaN(parseInt(birth_year)) || birth_year >= year);
        var tuoi = year - age; // This is just calculate user'age, for example if the user enter 2000 will display user'age is 22
        document.getElementById("age").innerHTML =
          "Tuổi " + birth_year + " này đẹp đó";
      }
    }

  </script>
</body>
</code>```

Body:
I have a problem when i try to display new prompt, i use loop but it will display both my prompt. Here is my code and i really need help

<button onclick=" notify()">Try it</button>

Body:
your code has several issues and does some things which do not make total sense to me, but I think you want something like this:

<body>
  <p id="age" style="font-weight: bold"></p>
  <button onclick=" notify()">Try it</button>
  <script>
    function notify() {
      const year = new Date().getFullYear();
      var birth_year = parseInt(prompt("Enter Your birth year:")); // This is the first prompt

      if (!isNaN(birth_year) && birth_year < year) {
        document.getElementById("age").innerHTML =
          "Your " + birth_year + " is so beautiful"; // If user enter birth year < current year will display this
      } else {
        do {
          birth_year = parseInt(prompt("Enter Your birth year:")); // Ortherwise, this will display and they need to enter until birth year < current year
        } while (isNaN(parseInt(birth_year)) || birth_year >= year);
        var tuoi = year - age; // This is just calculate user'age, for example if the user enter 2000 will display user'age is 22
        document.getElementById("age").innerHTML =
          "Tuổi " + birth_year + " này đẹp đó";
      }
    }

  </script>
</body>


问:
Perform MessageActions on Messages for .Net 6 Isolated Worker ServiceBusTriggers
I want to be able to perform flexible actions on Service Bus Messages through a .Net 6 out-of-process ServiceBusTrigger. Actions include abandoning, completing, deferring, as well as dead-letter-queuing messages. I.e. the same actions that are available through the ServiceBusReceivedMessage and ServiceBusMessageActions bindings of the in-process ServiceBusTrigger.

However, out-of-process triggers seem only to be able to bind the message body as a string, as well as the FunctionContext. Are the described actions available for out-of-process triggers in some other way? If not, do you know if it's on the roadmap for near future releases?

Example of how the actions are available for in-process triggers:

[FunctionName(nameof(InProcessReceiver))]
public async Task RunAsync(
   [ServiceBusTrigger("%TOPIC_NAME%", "%SUB_NAME%", Connection="CONNECTION_NAME")]
   ServiceBusReceivedMessage message,
   ServiceBusMessageActions messageActions
)
{
   await messageActions.DeadLetterMessageAsync(message);
   //await messageActions.AbandonMessageAsync(message);
   //await messageActions.CompleteMessageAsync(message);
   //await messageActions.DeferMessageAsync(message);
}
```
<p>Example of out-of-process trigger, for which I want to do the same things as above</p>
<pre class="lang-cs prettyprint-override"><code>[Function(nameof(OutOfProcessReceiver))]
public async Task RunAsync(
   [ServiceBusTrigger("%TOPIC_NAME%", "%SUB_NAME%", Connection="CONNECTION_NAME")]
   string mySbMsg
)
{
   //How to access message actions and bind them to the current message here?
}
</code>```

As mentioned by the Microsoft team in this roadmap blog post, the future is isolated. Therefore I'm trying to avoid in-process, but I realize that it might be the only solution for now.

Thanks in advance!

答:
Are the described actions available for out-of-process triggers in some other way? If not, do you know if it's on the roadmap for near future releases?

At the moment it's not possible. Out of process/isolated worker SDK cannot pass to the Function native SDK types. There are a few related issues you can track for updates.

IMessageReceiver on ServiceBusTrigger

With a ServiceBusTrigger, how to go from string/byte[] to Message?

Body:
I want to be able to perform flexible actions on Service Bus Messages through a .Net 6 out-of-process ServiceBusTrigger. Actions include abandoning, completing, deferring, as well as dead-letter-queuing messages. I.e. the same actions that are available through the ServiceBusReceivedMessage and ServiceBusMessageActions bindings of the in-process ServiceBusTrigger.

However, out-of-process triggers seem only to be able to bind the message body as a string, as well as the FunctionContext. Are the described actions available for out-of-process triggers in some other way? If not, do you know if it's on the roadmap for near future releases?

Example of how the actions are available for in-process triggers:

[FunctionName(nameof(InProcessReceiver))]
public async Task RunAsync(
   [ServiceBusTrigger("%TOPIC_NAME%", "%SUB_NAME%", Connection="CONNECTION_NAME")]
   ServiceBusReceivedMessage message,
   ServiceBusMessageActions messageActions
)
{
   await messageActions.DeadLetterMessageAsync(message);
   //await messageActions.AbandonMessageAsync(message);
   //await messageActions.CompleteMessageAsync(message);
   //await messageActions.DeferMessageAsync(message);
}

Example of out-of-process trigger, for which I want to do the same things as above

[Function(nameof(OutOfProcessReceiver))]
public async Task RunAsync(
   [ServiceBusTrigger("%TOPIC_NAME%", "%SUB_NAME%", Connection="CONNECTION_NAME")]
   string mySbMsg
)
{
   //How to access message actions and bind them to the current message here?
}

As mentioned by the Microsoft team in this roadmap blog post, the future is isolated. Therefore I'm trying to avoid in-process, but I realize that it might be the only solution for now.

Thanks in advance!


问:
How to draw on Jetpack Compose Canvas using touch events?
This is Q&A-style question since i was looking for a drawing sample with Jetpack Canvas but questions on stackoverflow, this one or another one, i found use pointerInteropFilter for drawing like View's onTouchEvent MotionEvents which is not advised according to docs as

A special PointerInputModifier that provides access to the underlying
MotionEvents originally dispatched to Compose. Prefer pointerInput
and use this only for interoperation with existing code that consumes
MotionEvents.

While the main intent of this Modifier is to allow arbitrary code to
access the original MotionEvent dispatched to Compose, for
completeness, analogs are provided to allow arbitrary code to interact
with the system as if it were an Android View.

答:
Edit

It's been a while since i posted this answer and as i got feedback from this question that previous answer was a little bit confusing for beginners, so i simplify it, library for this gesture and more is available in github repo.

We need motion states as we have with View's first

```<code>enum class MotionEvent {
    Idle, Down, Move, Up
}
</code>```

Idle state is needed to not leave state on Up because if any recomposition happens your Canvas gets recomposed with Up state which leads to unwanted drawings or even crashes.

Path, current touch position and touch states

```<code>var motionEvent by remember { mutableStateOf(MotionEvent.Idle) }
// This is our motion event we get from touch motion
var currentPosition by remember { mutableStateOf(Offset.Unspecified) }
// This is previous motion event before next touch is saved into this current position
var previousPosition by remember { mutableStateOf(Offset.Unspecified) }
</code>```

previousPosition is optional i use it because i want to draw smooth lines with  path.quadraticBezierTo, instead of path.lineTo while moving with pointer

Modifier for creating touch events. Modifier.clipToBounds() is to prevent drawing outside of Canvas.

```<code>val drawModifier = Modifier
    .fillMaxWidth()
    .height(300.dp)
    .clipToBounds()
    .background(Color.White)
    .pointerMotionEvents(
        onDown = { pointerInputChange: PointerInputChange ->
            currentPosition = pointerInputChange.position
            motionEvent = MotionEvent.Down
            pointerInputChange.consume()
        },
        onMove = { pointerInputChange: PointerInputChange ->
            currentPosition = pointerInputChange.position
            motionEvent = MotionEvent.Move
            pointerInputChange.consume()
        },
        onUp = { pointerInputChange: PointerInputChange ->
            motionEvent = MotionEvent.Up
            pointerInputChange.consume()
        },
        delayAfterDownInMillis = 25L
    )
</code>```

Modifier.pointerMotionEvents custom gesture library i wrote for it be counterpart of onTouchEvent, it's available on github repo above, and here is a detailed explanation about gestures, you can easily build your own gesture if you don't want to. Delay after first touch occurs on onTouchEvent of View has, it's about 16ms on my devices, this is the fastest i measured, i added to gestures on Compose too because Canvas can't process down events when user has a very swift pointer movement initially.

And apply this modifier to canvas and move or draw based on current state and position

```<code>Canvas(modifier = drawModifier) {

    when (motionEvent) {
        MotionEvent.Down -> {
            path.moveTo(currentPosition.x, currentPosition.y)
            previousPosition = currentPosition
        }

        MotionEvent.Move -> {
            path.quadraticBezierTo(
                previousPosition.x,
                previousPosition.y,
                (previousPosition.x + currentPosition.x) / 2,
                (previousPosition.y + currentPosition.y) / 2

            )
            previousPosition = currentPosition
        }

        MotionEvent.Up -> {
            path.lineTo(currentPosition.x, currentPosition.y)
            currentPosition = Offset.Unspecified
            previousPosition = currentPosition
            motionEvent = MotionEvent.Idle
        }

        else -> Unit
    }

    drawPath(
        color = Color.Red,
        path = path,
        style = Stroke(width = 4.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round)
    )
}
</code>```

Github repo for a full drawing app also available here.

Body:
Edit

It's been a while since i posted this answer and as i got feedback from this question that previous answer was a little bit confusing for beginners, so i simplify it, library for this gesture and more is available in github repo.

We need motion states as we have with View's first

enum class MotionEvent {
    Idle, Down, Move, Up
}

Idle state is needed to not leave state on Up because if any recomposition happens your Canvas gets recomposed with Up state which leads to unwanted drawings or even crashes.

Path, current touch position and touch states

var motionEvent by remember { mutableStateOf(MotionEvent.Idle) }
// This is our motion event we get from touch motion
var currentPosition by remember { mutableStateOf(Offset.Unspecified) }
// This is previous motion event before next touch is saved into this current position
var previousPosition by remember { mutableStateOf(Offset.Unspecified) }

previousPosition is optional i use it because i want to draw smooth lines with  path.quadraticBezierTo, instead of path.lineTo while moving with pointer

Modifier for creating touch events. Modifier.clipToBounds() is to prevent drawing outside of Canvas.

val drawModifier = Modifier
    .fillMaxWidth()
    .height(300.dp)
    .clipToBounds()
    .background(Color.White)
    .pointerMotionEvents(
        onDown = { pointerInputChange: PointerInputChange ->
            currentPosition = pointerInputChange.position
            motionEvent = MotionEvent.Down
            pointerInputChange.consume()
        },
        onMove = { pointerInputChange: PointerInputChange ->
            currentPosition = pointerInputChange.position
            motionEvent = MotionEvent.Move
            pointerInputChange.consume()
        },
        onUp = { pointerInputChange: PointerInputChange ->
            motionEvent = MotionEvent.Up
            pointerInputChange.consume()
        },
        delayAfterDownInMillis = 25L
    )

Modifier.pointerMotionEvents custom gesture library i wrote for it be counterpart of onTouchEvent, it's available on github repo above, and here is a detailed explanation about gestures, you can easily build your own gesture if you don't want to. Delay after first touch occurs on onTouchEvent of View has, it's about 16ms on my devices, this is the fastest i measured, i added to gestures on Compose too because Canvas can't process down events when user has a very swift pointer movement initially.

And apply this modifier to canvas and move or draw based on current state and position

Canvas(modifier = drawModifier) {

    when (motionEvent) {
        MotionEvent.Down -> {
            path.moveTo(currentPosition.x, currentPosition.y)
            previousPosition = currentPosition
        }

        MotionEvent.Move -> {
            path.quadraticBezierTo(
                previousPosition.x,
                previousPosition.y,
                (previousPosition.x + currentPosition.x) / 2,
                (previousPosition.y + currentPosition.y) / 2

            )
            previousPosition = currentPosition
        }

        MotionEvent.Up -> {
            path.lineTo(currentPosition.x, currentPosition.y)
            currentPosition = Offset.Unspecified
            previousPosition = currentPosition
            motionEvent = MotionEvent.Idle
        }

        else -> Unit
    }

    drawPath(
        color = Color.Red,
        path = path,
        style = Stroke(width = 4.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round)
    )
}

Github repo for a full drawing app also available here.


问:
How do I select from IF(....) as 'A'
Sorry I Don't know what to say it.
It was like</p>
```<code>SELECT

(IF(ISNULL(fieldA),'it is null','fieldA')) AS 'I_want_this',

'I_want_this' as 'Show'

from table
</code>```

答:
You can use COALESCE(). It will print the value of first parameter if it's not null other will print second parameter.

Schema and insert statements:

```<code> create table tableA(fieldA varchar(10));
 insert into tableA values(null);
 insert into tableA values('a');
 insert into tableA values('b');
 insert into tableA values(null);
 insert into tableA values('c');
</code>```

Query:

```<code> SELECT COALESCE(fieldA,'it is null') AS 'I_want_this'
 from tableA
</code>```

Output:

I_want_this

it is null

a

b

it is null

c

db<>fiddle here

Title: How do I select from IF(....) as 'A'

Body:
Sorry I Don't know what to say it.
It was like

SELECT

(IF(ISNULL(fieldA),'it is null','fieldA')) AS 'I_want_this',

'I_want_this' as 'Show'

from table

Body:
You can use COALESCE(). It will print the value of first parameter if it's not null other will print second parameter.

Schema and insert statements:

 create table tableA(fieldA varchar(10));
 insert into tableA values(null);
 insert into tableA values('a');
 insert into tableA values('b');
 insert into tableA values(null);
 insert into tableA values('c');

Query:

 SELECT COALESCE(fieldA,'it is null') AS 'I_want_this'
 from tableA

Output:

I_want_this

it is null

a

b

it is null

c

db<>fiddle here


问:
Where is the global git config data stored?
When using git config --global to set things up, to which file will it write?

Example:

```<code>git config --global core.editor "blah"
</code>```

I can't find it at these places:

```<code>C:\Program Files\Git\etc\gitconfig

C:\myapp\.git\config
</code>```

I have not set an ENV?

My Git version: 1.6.5.1.1367.gcd48 –
on Windows 7

答:
Just completely agree with @cameron-mckenzie's answer here on this page, above about When is the global .gitconfig file created? (this clearly applies in case of every OS). Rest of his answer deals with Win7 systems.

In Win10 systems too, the .gitconfig global file would create for the very first time only when you tend to set user.name & user.email system variables via windows command-prompt.
As soon as it's set, the .gitconfig file would get created  in %USERPROFILE% dir.

Below command works for Win & MacOS, both

So, let's suppose if .gitconfig file already exists. You can know its location via Command-prompt/Gitbash/Terminal by :

```<code>git config --global --list --show-origin
</code>```

Body:
When using git config --global to set things up, to which file will it write?

Example:

git config --global core.editor "blah"

I can't find it at these places:

C:\Program Files\Git\etc\gitconfig

C:\myapp\.git\config

I have not set an ENV?

My Git version: 1.6.5.1.1367.gcd48 –
on Windows 7

Body:
Just completely agree with @cameron-mckenzie's answer here on this page, above about When is the global .gitconfig file created? (this clearly applies in case of every OS). Rest of his answer deals with Win7 systems.

In Win10 systems too, the .gitconfig global file would create for the very first time only when you tend to set user.name & user.email system variables via windows command-prompt.
As soon as it's set, the .gitconfig file would get created  in %USERPROFILE% dir.

Below command works for Win & MacOS, both

So, let's suppose if .gitconfig file already exists. You can know its location via Command-prompt/Gitbash/Terminal by :

git config --global --list --show-origin


问:
How to initialize list of custom object with no constructor [Dart/Flutter]
I've been facing this issue, I have a mock class with static values for testing.
but I am unable to create a list for custom Object class which has no constructor as following.

```<code>class Video {

  Video();  //this is default constructor

  late int id;
  late String name;
}
</code>```

Problem:
Now I want to initialize a static list.

```<code>final List<Video> videos = [
  new Video({id = 1, name = ""}) //but this gives an error.
];
</code>```

I don't want to change class constructor.

Is there any way to initialize list of custom class without constructor?

答:
Technically, this would work:

```<code>final List<Video> videos = [
  Video()..id = 1..name = '',
  Video()..id = 2..name = 'another',
];
</code>```

You basically assign the late properties after creating the Video instance, but before it's in the list.

However, it's likely that you don't need those properties to be late-initizalized and rather use a constructor for it

```<code>class Video {

  Video({required this.id, required this.name});

  int id;
  String name;
}

final List<Video> videos = [
  Video(id: 1, name: ''),
  Video(id: 2, name: 'another'),
];
</code>```

But that depends on your use case, of course

Body:
I've been facing this issue, I have a mock class with static values for testing.
but I am unable to create a list for custom Object class which has no constructor as following.

class Video {

  Video();  //this is default constructor

  late int id;
  late String name;
}

Problem:
Now I want to initialize a static list.

final List<Video> videos = [
  new Video({id = 1, name = ""}) //but this gives an error.
];

I don't want to change class constructor.

Is there any way to initialize list of custom class without constructor?

Body:
Technically, this would work:

final List<Video> videos = [
  Video()..id = 1..name = '',
  Video()..id = 2..name = 'another',
];

You basically assign the late properties after creating the Video instance, but before it's in the list.

However, it's likely that you don't need those properties to be late-initizalized and rather use a constructor for it

class Video {

  Video({required this.id, required this.name});

  int id;
  String name;
}

final List<Video> videos = [
  Video(id: 1, name: ''),
  Video(id: 2, name: 'another'),
];

But that depends on your use case, of course


问:
Deleting localStorage data
What vulnerabilities do i face, when coding a web app utilising localStorage, of a user inadvertently or deliberately delete localStorage data?

I'm happy to put a button saying "Delete my data", this is under my control, but are there ways beyond my control that localStorage data may be deleted? Or not used (ie. Incognito mode/private browsing mode)?

Thanks

答:
localStorage is editable by the user , it's similar to the cookies .

User can delete / edit it if he wants , so you should make ur tests on server sides ...

here's an example of how angry birds got hacked ...

http://thenextweb.com/apps/2011/05/11/angry-birds-for-chrome-already-hacked-unlocking-all-levels/

```<code>     var i = 0;
     while (i<=69) {
       localStorage.setItem('level_star_'+i,'3');
       i++;
      }
     window.location.reload();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Deleting localStorage data

Body:
localStorage is editable by the user , it's similar to the cookies .

User can delete / edit it if he wants , so you should make ur tests on server sides ...

here's an example of how angry birds got hacked ...

http://thenextweb.com/apps/2011/05/11/angry-birds-for-chrome-already-hacked-unlocking-all-levels/

     var i = 0;
     while (i<=69) {
       localStorage.setItem('level_star_'+i,'3');
       i++;
      }
     window.location.reload();


问:
Copying elements of an array in C having unexpected results
I am trying to copy elements of an array using a simple copy function outside of main.
My code is as follows:

```<code>int* copy(int* nums){
    int size = sizeof(nums) / sizeof(nums[0]); // len of array
    int *arr = (int*)malloc(size * sizeof(int)); // dynamic allocation of array mem
    *arr = *nums; // copy operation
    return arr; // return copied arr
}

int main(){
    int nums[] = {1,2};
    int array[2];
    *array = *copy(nums); // operation in question
    printf("[%d, %d]", array[0], array[1]);
}

</code>```

My output:

```<code>[1, 0]
</code>```

It seems like the copy function is returning only the first element in my array. Can someone explain to me why this is happening?

答:
*nums returns the first element of nums

*arr = whatever; assigns whatever to the first element of arr

Thus, *arr = *nums; is a "copy one element operation". Same thing with *array = *copy(nums);, by the way.

Body:
I am trying to copy elements of an array using a simple copy function outside of main.
My code is as follows:

int* copy(int* nums){
    int size = sizeof(nums) / sizeof(nums[0]); // len of array
    int *arr = (int*)malloc(size * sizeof(int)); // dynamic allocation of array mem
    *arr = *nums; // copy operation
    return arr; // return copied arr
}

int main(){
    int nums[] = {1,2};
    int array[2];
    *array = *copy(nums); // operation in question
    printf("[%d, %d]", array[0], array[1]);
}

My output:

[1, 0]

It seems like the copy function is returning only the first element in my array. Can someone explain to me why this is happening?


问:
How do i split list using 2 different method in for LOOP?
I am sorry if I am unable to put out the question properly. But here is my CODE

```<code>data1 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG']
data2 = ['TOOK2231515100HG','BOGGOK2221643200GH']

for i in data1:
  splt_1 = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
  print('data1:', splt_1)

for I in data2:
  splt_2 = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print('data2:', splt_2)

</code>```

Output result

```<code>data1: ['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
data1: ['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']

data2: ['', 'TOOK', '22315', '15100', 'HG', '']
data2: ['', 'BOGGOK', '22216', '43200', 'GH', '']
</code>```

What I want to do?

if

```<code>data = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG', 'TOOK2231515100HG','BOGGOK2221643200GH']
</code>```

I want to be able to loop and split data list using the 2 method

```<code>re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i) or
re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]
</code>```

P.S: Output result can be in same or similar format

I tried this Code

```<code>data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print(dk)
</code>```

Result

```<code>['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', None, None, None, None, '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', None, None, None, None, '']
['', None, None, None, None, None, None, 'TOOK', '22315', '15100', 'HG', '']
['', None, None, None, None, None, None, 'BOGGOK', '22216', '43200', 'GH', '']
</code>```

Result I want

```<code>['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']
['', 'TOOK', '22315', '15100', 'HG', '']
['', 'BOGGOK', '22216', '43200', 'GH', '']

or

['TOOK', '22', 'JAN', '15', '15100', 'HG']
['BOGGOK', '22', 'MAR', '17', '42200', 'HG']
['TOOK', '22315', '15100', 'HG']
['BOGGOK', '22216', '43200', 'GH']
</code>```

Thank you for taking your time to answer my question..
really appreciate it.

答:
First Solution:

```<code>data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']
for i in range(len(data5)):
    data5[i] = [item for item in (re.split(r'(TOOK|BOGGOK)([0-9]{2})([A-Z]{3})([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', data5[i])) if (item is not None) and len(item)>0]
print(data5)
</code>```

Second Solution:

```<code>def resultant_string_list(data5):
    return [([item for item in (re.split(r'(TOOK|BOGGOK)([0-9]{2})([A-Z]{3})([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', data5[i])) if (item is not None) and len(item)>0]) for i in range(len(data5))]

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']
print(resultant_string_list(data5))
</code>```

output for both the above code:

```<code>[['TOOK', '22', 'JAN', '15', '15100', 'HG'], ['BOGGOK', '22', 'MAR', '17', '42200', 'HG'], ['TOOK', '22315', '15100', 'HG'], ['BOGGOK', '22216', '43200', 'GH']]
</code>```

I have written the code keeping in mind the space used, so your current variable get replaced with the resultant list.
Example:

```<code>Before: data5[0] = "TOOK22JAN1515100HG"
After: data5[0] = ['TOOK', '22', 'JAN', '15', '15100', 'HG']
</code>```

Body:
I am sorry if I am unable to put out the question properly. But here is my CODE

data1 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG']
data2 = ['TOOK2231515100HG','BOGGOK2221643200GH']

for i in data1:
  splt_1 = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
  print('data1:', splt_1)

for I in data2:
  splt_2 = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print('data2:', splt_2)

Output result

data1: ['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
data1: ['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']

data2: ['', 'TOOK', '22315', '15100', 'HG', '']
data2: ['', 'BOGGOK', '22216', '43200', 'GH', '']

What I want to do?

if

data = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG', 'TOOK2231515100HG','BOGGOK2221643200GH']

I want to be able to loop and split data list using the 2 method

re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i) or
re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]

P.S: Output result can be in same or similar format

I tried this Code

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print(dk)

Result

['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', None, None, None, None, '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', None, None, None, None, '']
['', None, None, None, None, None, None, 'TOOK', '22315', '15100', 'HG', '']
['', None, None, None, None, None, None, 'BOGGOK', '22216', '43200', 'GH', '']

Result I want

['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']
['', 'TOOK', '22315', '15100', 'HG', '']
['', 'BOGGOK', '22216', '43200', 'GH', '']

or

['TOOK', '22', 'JAN', '15', '15100', 'HG']
['BOGGOK', '22', 'MAR', '17', '42200', 'HG']
['TOOK', '22315', '15100', 'HG']
['BOGGOK', '22216', '43200', 'GH']

Thank you for taking your time to answer my question..
really appreciate it.

Body:
First Solution:

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']
for i in range(len(data5)):
    data5[i] = [item for item in (re.split(r'(TOOK|BOGGOK)([0-9]{2})([A-Z]{3})([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', data5[i])) if (item is not None) and len(item)>0]
print(data5)

Second Solution:

def resultant_string_list(data5):
    return [([item for item in (re.split(r'(TOOK|BOGGOK)([0-9]{2})([A-Z]{3})([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', data5[i])) if (item is not None) and len(item)>0]) for i in range(len(data5))]

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']
print(resultant_string_list(data5))

output for both the above code:

[['TOOK', '22', 'JAN', '15', '15100', 'HG'], ['BOGGOK', '22', 'MAR', '17', '42200', 'HG'], ['TOOK', '22315', '15100', 'HG'], ['BOGGOK', '22216', '43200', 'GH']]

I have written the code keeping in mind the space used, so your current variable get replaced with the resultant list.
Example:

Before: data5[0] = "TOOK22JAN1515100HG"
After: data5[0] = ['TOOK', '22', 'JAN', '15', '15100', 'HG']


问:
From a component in a v-for loop, get both loop index and an emitted value
I have a component which is created by a v-for loop. The index of the for loop is important to me, and I also have to pass data with the emit method of the component to the parent. How can I get both these values, namely a value from the component child which is emitted, and also the index of the loop from the parent?

My template:

```<code><div
v-for="(presc, index) in editedPrescription"
:key="index"
>
    <autocomplete-input
    placeholder="Brand name"
    arialabel="BrandName"
    :searcheventresults="brandformattedsearchresults"
    :defaultterm="editedPrescription[index].brand"
    minimum-letters-to-trigger="4"
    @changed="BrandSearch"
    @selected="SelectedBrand(index)"
    />
</div>
</code>```

In the child component, in a method:

```<code>Select(vindex) {
    console.log(`In Autocomplete widget, Selected vindex: ${vindex}`);
    this.searchterm = this.searcheventresults[index]
    this.$emit("selected", vindex);
},
</code>```

When I try to get the emitted value in the parent method:

```<code>SelectedBrand(i, j) {
  console.log(`In SelectedBrand, i:`, i);
  console.log(`j:`, j);
},
</code>```

In console,

```<code>In SelectedBrand, i: 0
PrescriptionBlock.vue ? c2fe : 1155 j: undefined
</code>```

How can I get both these values? With my current implementation, I can get only the index of the loop. If I change to @selected="SelectedBrand", then I can get the emitted value from child component. But I lose the index of the loop. I need both.

答:
You can use an anonymous function like this :</p>
```<code>@selected="(arg) => {SelectedBrand(arg, index)}"
</code>```

Body:
I have a component which is created by a v-for loop. The index of the for loop is important to me, and I also have to pass data with the emit method of the component to the parent. How can I get both these values, namely a value from the component child which is emitted, and also the index of the loop from the parent?

My template:

    <autocomplete-input
    placeholder="Brand name"
    arialabel="BrandName"
    :searcheventresults="brandformattedsearchresults"
    :defaultterm="editedPrescription[index].brand"
    minimum-letters-to-trigger="4"
    @changed="BrandSearch"
    @selected="SelectedBrand(index)"
    />

In the child component, in a method:

Select(vindex) {
    console.log(`In Autocomplete widget, Selected vindex: ${vindex}`);
    this.searchterm = this.searcheventresults[index]
    this.$emit("selected", vindex);
},

When I try to get the emitted value in the parent method:

SelectedBrand(i, j) {
  console.log(`In SelectedBrand, i:`, i);
  console.log(`j:`, j);
},

In console,

In SelectedBrand, i: 0
PrescriptionBlock.vue ? c2fe : 1155 j: undefined

How can I get both these values? With my current implementation, I can get only the index of the loop. If I change to @selected="SelectedBrand", then I can get the emitted value from child component. But I lose the index of the loop. I need both.

Body:
You can use an anonymous function like this :

@selected="(arg) => {SelectedBrand(arg, index)}"


问:
JPQL Query to select row with minimum value
Similar to SQL query to select distinct row with minimum value and Select rows with minimum date but I am asking specifically for JPQL because the examples provided return * but I would want it to be the same object.

Say I have the query like this.

```<code>from BillingTargetDiscountAmount g
  where g.billingTarget = :billingTarget
   and g.discountSource = :discountSource
   and g.startDate <= :date
</code>```

I also have a composite key of

```<code>@Data
public class BillingTargetDiscountAmountPK implements Serializable {
    @ToString.Exclude
    private BillingTarget billingTarget;

    private String discountSource;

    private LocalDate startDate;

    @ToString.Include
    private Integer billingTargetID() {

        return billingTarget.getId();

    }

}
</code>```

My guess would be something like though I am not sure what to do with the specific synax

```<code>select * [??? BillingTargetDiscountAmount ] from (
  select g.billingTarget, g.discountSource, min(g.startDate), other fields
  from BillingTargetDiscountAmount g
    where g.billingTarget = :billingTarget
     and g.discountSource = :discountSource
     and g.startDate <= :date
)
</code>```

答:
Since I only needed to do one column for the min value.  I did a subselect and just repeated the parameters</p>
```<code>from BillingTargetDiscountAmount btda
where btda.billingTarget = :billingTarget and
      btda.discountSource = :discountSource and
      btda.startDate = (
        select min(g.startDate)
          from BillingTargetDiscountAmount g
          where g.billingTarget = :billingTarget
            and g.discountSource = :discountSource
            and g.startDate <= :date
      )

</code>```

Body:
Similar to SQL query to select distinct row with minimum value and Select rows with minimum date but I am asking specifically for JPQL because the examples provided return * but I would want it to be the same object.

Say I have the query like this.

from BillingTargetDiscountAmount g
  where g.billingTarget = :billingTarget
   and g.discountSource = :discountSource
   and g.startDate <= :date

I also have a composite key of

@Data
public class BillingTargetDiscountAmountPK implements Serializable {
    @ToString.Exclude
    private BillingTarget billingTarget;

    private String discountSource;

    private LocalDate startDate;

    @ToString.Include
    private Integer billingTargetID() {

        return billingTarget.getId();

    }

}

My guess would be something like though I am not sure what to do with the specific synax

select * [??? BillingTargetDiscountAmount ] from (
  select g.billingTarget, g.discountSource, min(g.startDate), other fields
  from BillingTargetDiscountAmount g
    where g.billingTarget = :billingTarget
     and g.discountSource = :discountSource
     and g.startDate <= :date
)

Body:
Since I only needed to do one column for the min value.  I did a subselect and just repeated the parameters

from BillingTargetDiscountAmount btda
where btda.billingTarget = :billingTarget and
      btda.discountSource = :discountSource and
      btda.startDate = (
        select min(g.startDate)
          from BillingTargetDiscountAmount g
          where g.billingTarget = :billingTarget
            and g.discountSource = :discountSource
            and g.startDate <= :date
      )


问:
ElasticSearch: compare dotted version strings
I'm looking for a way to save a dotted version as string (e.g "1.2.23") in elastic and then use range query on this field.
e.g

```<code>{
 "query": {
   "range": {
    "version": {"gte": "1.2.3", "lt": "1.3"}
   }
  }
}
</code>```

I have only 3 components (major, minor, build). I need to be able to determine that

1.20.3 > 1.2.3

1.02.4 > 1.2.3

1.3    > 1.2.3

I thought about the following approaches:

Pad with zeros (e.g "1.2.3" -> "000001.000002.000003"). This assumes I know the max length of each component

Split into 3 different integer fields (i.e "major", "minor", "build"). Writing queries for this seems to be a pain, but I'd be happy to get suggestions for this.

Perhaps some sort of a custom analyser? I saw this: Elasticsearch analysis plugin for natural sort which might be a good start.

Any other ideas or recommendations?

答:
Elasticsearch has added support for version comparison and sort starting from version 7.10.
https://www.elastic.co/guide/en/elasticsearch/reference/current/version.html</p>

Body:
I'm looking for a way to save a dotted version as string (e.g "1.2.23") in elastic and then use range query on this field.
e.g

{
 "query": {
   "range": {
    "version": {"gte": "1.2.3", "lt": "1.3"}
   }
  }
}

I have only 3 components (major, minor, build). I need to be able to determine that

1.20.3 > 1.2.3

1.02.4 > 1.2.3

1.3    > 1.2.3

I thought about the following approaches:

Pad with zeros (e.g "1.2.3" -> "000001.000002.000003"). This assumes I know the max length of each component

Split into 3 different integer fields (i.e "major", "minor", "build"). Writing queries for this seems to be a pain, but I'd be happy to get suggestions for this.

Perhaps some sort of a custom analyser? I saw this: Elasticsearch analysis plugin for natural sort which might be a good start.

Any other ideas or recommendations?


问:
Fingerprint of a Java WAR file
I'm writing a JAR library that can be included inside any WAR, sending log data to a server (EDIT: it's an appender for Log4j). In order to later group logs that originated from the same application version, but came from different servers, I want to generate a fingerprint/checksum for the WAR.

I thought about using classpath items and file sizes - but just can't seem to figure out the best way.

How would you do it?

答:
I'm afraid the only acceptable answer is:
it can't be done without irresponsible, nasty hacks.

Title: Fingerprint of a Java WAR file


问:
ClassLoader#getResourceAsStream() behaving differently in IDE and jar file
I have written following piece of code to get the list of names of files in metadata folder.

```<code>  public class Demo {
    public static void main(String[] args) throws IOException {
    InputStream is=Demo.class.getClassLoader().getResourceAsStream("metadata");
    System.out.println(is.available());
    InputStreamReader isr=new InputStreamReader(is,StandardCharsets.UTF_8.name());
    BufferedReader br = new BufferedReader(isr);

    List<String> list=new ArrayList<>();
    String line;
    while((line = br.readLine()) != null) {
        list.add(line);
    }

    System.out.println(list);

} }
</code>```

Here is the project structure in Intellij IDE

This program runs as expected in IDE and prints following output:

```<code>22
[test1.json, test2.json]
</code>```

However, when I build an executable jar of this program:

and run it using java -jar, the output is:

```<code>0
[]
</code>```

Why does jar file behave differently?

答:
Real filesystems traditionally have (or simulate) directories that can be enumerated although the OS API and thus the implementation of File(with isDirectory true).list() varies by platform, and FileURLConnection (which is used for a resource in the filesystem) returns that list as the 'contents' of a directory.

JAR files are really ZIP files, and ZIP files were designed to store files not directories as such, although the files can have slash-separated names to organize them into directories. (Always slash, even though when it was created MSDOS and Windows already used backslash in the API.) Java jar creates a dummy 'file' entry for each directory, to contain the modtime and (I think) permissions to be used when extracting/restoring, but this entry contains no data, and that's what JarURLConnection reads for a resource 'directory' in a JAR.

You can list entries under a given directory pathname in a ZIP, including a JAR, using the (j7+) NIO ZipFileSystemProvider; see my answer at Reading .cer files from jar file failing . (And for real files such as unpacked jars you can of course use the NIO default=OS filesystem the same way; that's equivalent to the 'legacy' java.io.File class.)

Body:
I have written following piece of code to get the list of names of files in metadata folder.

  public class Demo {
    public static void main(String[] args) throws IOException {
    InputStream is=Demo.class.getClassLoader().getResourceAsStream("metadata");
    System.out.println(is.available());
    InputStreamReader isr=new InputStreamReader(is,StandardCharsets.UTF_8.name());
    BufferedReader br = new BufferedReader(isr);

    List<String> list=new ArrayList<>();
    String line;
    while((line = br.readLine()) != null) {
        list.add(line);
    }

    System.out.println(list);

} }

Here is the project structure in Intellij IDE

This program runs as expected in IDE and prints following output:

22
[test1.json, test2.json]

However, when I build an executable jar of this program:

and run it using java -jar, the output is:

0
[]

Why does jar file behave differently?


答:
You simply forgot a part of your if condition.

Change if (age != null) to if (age != null && age < year) and it will work as you expect it. Don't forget the case if age == year.

Title: Display second prompt if the first prompt is not TRUE

Body:
I have a problem when i try to display new prompt, i use loop but it will display both my prompt. Here is my code and i really need help

<button onclick=" notify()">Try it</button>


问:
Creating a list of existing dictionaries in python
I need to get a list of some dictionaries that I defined before.The dictionaries look like these:
dic1={"D":1.4,"SD":1.4} dic2={"D":1.2,"SD":1.2,"L":1.6,"LR":1.6,"LR0.5":1.6,"LP":1.6,"LRF":0.5} dic3={"D":1.2,"SD":1.2,"L":1,"LR":1,"LR0.5":1,"LP":1,"LRF":1.6}
And I expect a list like this:

```<code>list=[{"D":1.4,"SD":1.4},{"D":1.2,"SD":1.2,"L":1.6,"LR":1.6,"LR0.5":1.6,"LP":1.6,"LRF":0.5},                                                                               {"D":1.2,"SD":1.2,"L":1,"LR":1,"LR0.5":1,"LP":1,"LRF":1.6}]
</code>```

How can I create it using a loop in python?

答:
```<code>list(filter(lambda a: type(a) == dict, locals().values()))
</code>```

Will return all local variables with dict type as a list

Body:
I need to get a list of some dictionaries that I defined before.The dictionaries look like these:
dic1={"D":1.4,"SD":1.4} dic2={"D":1.2,"SD":1.2,"L":1.6,"LR":1.6,"LR0.5":1.6,"LP":1.6,"LRF":0.5} dic3={"D":1.2,"SD":1.2,"L":1,"LR":1,"LR0.5":1,"LP":1,"LRF":1.6}
And I expect a list like this:

list=[{"D":1.4,"SD":1.4},{"D":1.2,"SD":1.2,"L":1.6,"LR":1.6,"LR0.5":1.6,"LP":1.6,"LRF":0.5},                                                                               {"D":1.2,"SD":1.2,"L":1,"LR":1,"LR0.5":1,"LP":1,"LRF":1.6}]

How can I create it using a loop in python?

Body:
list(filter(lambda a: type(a) == dict, locals().values()))

Will return all local variables with dict type as a list


问:
How to left rows with the same values in columns using dplyr package in R?
I wonder how can we filter rows with the same values in columns using dplyr package? I tried doing something in opposite to what was asked and proposed in this question but nothing worked.

I used the approach with apply function but received the following error:

```<code>same_vals <- apply(mydata, 1, function(x) all(x == x[1]))

final <- mydata %>%
  filter(same_vals)

Error: Can't subset elements that don't exist.
x Location 1 doesn't exist.
i There are only 0 elements.
</code>```

apply drives me crazy every time I try to use it. Neither it worked on my sample data:

```<code>set.seed(2022)
test <- tibble(id = floor(runif(10, min = 0, max = 111)),
       var1 = ceiling(runif(10, min = 5, max = 10)),
       var2 = c(6, 5, 4, 8, 12, 1223, 14, 1, 90, 1),
       var3 = c(6, 3, 4, 8, 11, 45, 56, 78, 0, 9))

# A tibble: 10 x 4
      id  var1  var2  var3
   <dbl> <dbl> <dbl> <dbl>
 1    90     6     6     6
 2    71     6     5     3
 3    13     6     4     4
 4    60     8     8     8
 5    20     9    12    11
 6    70     6  1223    45
 7     8     9    14    56
 8     4     8     1    78
 9    41     8    90     0
10    84    10     1     9

test1 <- apply(test, 1, function(x) all(x == x[1]))

test %>%
  filter(test1)

# A tibble: 0 x 4
# ... with 4 variables: id <dbl>, var1 <dbl>, var2 <dbl>, var3 <dbl>
</code>```

Desirable output

```<code># A tibble: 10 x 4
      id  var1  var2  var3
   <dbl> <dbl> <dbl> <dbl>
 1    90     6     6     6
 4    60     8     8     8
</code>```

答:
Also found for myself another solution which looks almost like Ronak's suggestion. data.table, a little bit of dplyr and matrixStats packages are needed:

```<code>setDT(test)

test[, sd_var := matrixStats::rowSds(as.matrix(.SD)),
     .SDcols = c("var1", "var2", "var3"), by = 1:nrow(test)] %>%
  .[sd_var == 0, , ]

   id var1 var2 var3 sd_var
1: 90    6    6    6      0
2: 60    8    8    8      0
</code>```

Body:
I wonder how can we filter rows with the same values in columns using dplyr package? I tried doing something in opposite to what was asked and proposed in this question but nothing worked.

I used the approach with apply function but received the following error:

same_vals <- apply(mydata, 1, function(x) all(x == x[1]))

final <- mydata %>%
  filter(same_vals)

Error: Can't subset elements that don't exist.
x Location 1 doesn't exist.
i There are only 0 elements.

apply drives me crazy every time I try to use it. Neither it worked on my sample data:

set.seed(2022)
test <- tibble(id = floor(runif(10, min = 0, max = 111)),
       var1 = ceiling(runif(10, min = 5, max = 10)),
       var2 = c(6, 5, 4, 8, 12, 1223, 14, 1, 90, 1),
       var3 = c(6, 3, 4, 8, 11, 45, 56, 78, 0, 9))

# A tibble: 10 x 4
      id  var1  var2  var3
   <dbl> <dbl> <dbl> <dbl>
 1    90     6     6     6
 2    71     6     5     3
 3    13     6     4     4
 4    60     8     8     8
 5    20     9    12    11
 6    70     6  1223    45
 7     8     9    14    56
 8     4     8     1    78
 9    41     8    90     0
10    84    10     1     9

test1 <- apply(test, 1, function(x) all(x == x[1]))

test %>%
  filter(test1)

# A tibble: 0 x 4
# ... with 4 variables: id <dbl>, var1 <dbl>, var2 <dbl>, var3 <dbl>

Desirable output

# A tibble: 10 x 4
      id  var1  var2  var3
   <dbl> <dbl> <dbl> <dbl>
 1    90     6     6     6
 4    60     8     8     8

Body:
Also found for myself another solution which looks almost like Ronak's suggestion. data.table, a little bit of dplyr and matrixStats packages are needed:

setDT(test)

test[, sd_var := matrixStats::rowSds(as.matrix(.SD)),
     .SDcols = c("var1", "var2", "var3"), by = 1:nrow(test)] %>%
  .[sd_var == 0, , ]

   id var1 var2 var3 sd_var
1: 90    6    6    6      0
2: 60    8    8    8      0


问:
issues with GetColumnIndex
so here's my case: while trying to make a database, i encountered a serious issue that is killing me! so here's the code:

```<code>}public ArrayList<String> ListProduits() {
        ArrayList<String> productList= new ArrayList<>(  );
        SQLiteDatabase ProductDatabase = this.getReadableDatabase();
        try {
            String querySelector = "SELECT * FROM " + TABLENAME;
            Cursor queryCursor = ProductDatabase.rawQuery(querySelector, null);
            if (queryCursor.getCount()>0) {
                while (queryCursor.moveToNext()) {
                    String product = queryCursor.getString(queryCursor.getColumnIndex("products"));
                    productList.add(product);
                }
            }ProductDatabase.setTransactionSuccessful();
        } catch ( Exception e) {
            e.printStackTrace();
        }
return productList;
    }
</code>```

and it returned me this:

`Value must be ≥ 0

can anyone explain this?

btw everything else works fine

答:
Use getColumnIndexOrThrow instead of getColumnIndex

getColumnIndex Returns the zero-based index for the given column name, or -1 if the column doesn't exist. If you expect the column to exist use getColumnIndexOrThrow(java.lang.String) instead, which will make the error more clear.

reference : https://developer.android.com/reference/android/database/Cursor#getColumnIndex(java.lang.String)

Title: issues with GetColumnIndex

Body:
so here's my case: while trying to make a database, i encountered a serious issue that is killing me! so here's the code:

}public ArrayList<String> ListProduits() {
        ArrayList<String> productList= new ArrayList<>(  );
        SQLiteDatabase ProductDatabase = this.getReadableDatabase();
        try {
            String querySelector = "SELECT * FROM " + TABLENAME;
            Cursor queryCursor = ProductDatabase.rawQuery(querySelector, null);
            if (queryCursor.getCount()>0) {
                while (queryCursor.moveToNext()) {
                    String product = queryCursor.getString(queryCursor.getColumnIndex("products"));
                    productList.add(product);
                }
            }ProductDatabase.setTransactionSuccessful();
        } catch ( Exception e) {
            e.printStackTrace();
        }
return productList;
    }

and it returned me this:

`Value must be ≥ 0

can anyone explain this?

btw everything else works fine


问:
Handling Multiple Events from a Single Listener
I want to have a single event listener for multiple events and depending on the

type of event i want to handle them separately.

Something similar to Swiz framework see: 'Handling Multiple Events from a Single Method'

i have a piece of code like

```<code>     var toolOptions:UIComponent=ToolOptions.createToolOptions(type);
            if (options != null)
            {
                options.addEventListener(Event.SELECT,toolOptionSelectedHandler);
                someViewComponent.addOptions(toolOptions);
            }

   // handle depending on event type
    private function toolOptionSelectedHandler(event:*):void
    {
        //handle depending on type of event fired
        // type cast  event depending on type and  retrieve VO from event
        //and send handle it..

        //SomeToolObj.handle(event.VO);

    }
</code>```

In above toolOptions is a mxml component which get dynamically created based on

'type'.

Also which type of event should be dispatch the event from the component? eg: Event.SELECT

To be more precise the above is basically required for a toolbar.

When user selects a tool,he is shown options for a tool and when he selects options,

tool should apply them to object on the view.

Is there a better way to do the same?

答:
You may also want to try something like this:
http://blog.iconara.net/2008/03/30/separating-event-handling-from-event-filtering/

and I've done a solution I'm a bit more comfortable with by using a Chain of Responsibility with links that have separate determineResponsibility and meetResponsibility methods, where the specific event data is stored when the link is created.  If we find a match between that and the event that gets passed into the chain, then we call meetResponsibility.  Otherwise, we call the next link in the chain.

For more on COR, check out http://www.as3dp.com/2008/01/14/actionscript-30-chain-of-responsibility-design-pattern-decoupling-request-and-request-handler/

Body:
I want to have a single event listener for multiple events and depending on the

type of event i want to handle them separately.

Something similar to Swiz framework see: 'Handling Multiple Events from a Single Method'

i have a piece of code like

     var toolOptions:UIComponent=ToolOptions.createToolOptions(type);
            if (options != null)
            {
                options.addEventListener(Event.SELECT,toolOptionSelectedHandler);
                someViewComponent.addOptions(toolOptions);
            }

   // handle depending on event type
    private function toolOptionSelectedHandler(event:*):void
    {
        //handle depending on type of event fired
        // type cast  event depending on type and  retrieve VO from event
        //and send handle it..

        //SomeToolObj.handle(event.VO);

    }

In above toolOptions is a mxml component which get dynamically created based on

'type'.

Also which type of event should be dispatch the event from the component? eg: Event.SELECT

To be more precise the above is basically required for a toolbar.

When user selects a tool,he is shown options for a tool and when he selects options,

tool should apply them to object on the view.

Is there a better way to do the same?


问:
MapStruct dependency scope in a Maven project
MapStruct generates code at compile-time and it should not require any runtime dependencies:

How is MapStruct different from other bean mapping tools?

Unlike most other bean mapping tools, MapStruct doesn’t work at runtime but is a compile-time code generator.

Generating mapping code at build time has many advantages:

Excellent performance, as no reflection or byte code generation at runtime is needed; the generated code contains plain method invocations, just as if the mapper was hand-written

No runtime dependencies, making MapStruct a great solution for Android applications

Which dependency scope should be used in a Maven project? Should MapStruct be included as a provided dependency?

```<code><dependencies>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
</code>```

答:
The org.mapstruct:mapstruct dependency contains the needed annotations to signal the org.mapstruct:mapstruct-processor what to do.

It also contains the Mappers factory that is used when using the default component model. Therefore, the scope of org.mapstruct:mapstruct depends on the component model that you are using:

Default component model

If you are using this component model then you need org.mapstruct:mapstruct during runtime if you are using Mappers or if you have dependencies between different mappers.

In theory you can use the default component model and instantiate your own mappers. However, dependencies between mappers are still going to use Mappers, unless you have instantiated your mapper in MyMapper.INSTANCE somehow already, then MapStruct will use MyMapper.INSTANCE to get the instance of the MyMapper. This would mean that you can still use the same scope as the other component models (see below for more information)

Other component model (spring, jsr330, cdi, etc.)

In this case you do not need org.mapstruct:mapstruct during runtime and you can use <optional>true</optional> with <scope>provided</scope>.

With Gradle this would be compileOnly dependency.

Note: Be careful when using Spring Boot and <scope>provided</scope> the Spring Boot maven plugin will still include the org.mapstruct:mapstruct dependency in the final provided jar. You'll need to ignore it by configuring the Spring Boot Maven plugin.

Body:
MapStruct generates code at compile-time and it should not require any runtime dependencies:

How is MapStruct different from other bean mapping tools?

Unlike most other bean mapping tools, MapStruct doesn’t work at runtime but is a compile-time code generator.

Generating mapping code at build time has many advantages:

Excellent performance, as no reflection or byte code generation at runtime is needed; the generated code contains plain method invocations, just as if the mapper was hand-written

No runtime dependencies, making MapStruct a great solution for Android applications

Which dependency scope should be used in a Maven project? Should MapStruct be included as a provided dependency?

<dependencies>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>


问:
labels on tops and bottoms
please help me to plot labels on tops and bottoms based on this short indicator I hope the result will be like this pic lables.
I tried but it plots labels on all candles not on pivots tops and bottoms only.</p>
```<code>//@version=5
indicator('piv lbl', overlay=true, max_lines_count=500)

period   = input.int(200, title="Period")

hh = ta.highest(high, period)
ll = ta.lowest(low,   period)

hsrc =  input.source(high , title="High source")
lsrc =  input.source(low  , title="Low  source")

newhh   = high > hh[1]
newll   = low  < ll[1]

hhb = ta.barssince(hh)
plot(hhb)

if hh
    label.new(bar_index, na, yloc=yloc.abovebar)
if ll
    label.new(bar_index, na, yloc=yloc.belowbar)
</code>```

答:
You can use the ta.pivothigh() and ta.pivotlow() functions to find the pivots.

```<code>//@version=5
indicator("PivotHigh", overlay=true)
leftBars = input(10)
rightBars=input(10)
ph = ta.pivothigh(leftBars, rightBars)
pl = ta.pivotlow(leftBars, rightBars)
plotshape(ph, "Pivot High", shape.triangledown, location.abovebar, color.green, -rightBars, "Pivot\nHigh", size=size.small)
plotshape(pl, "Pivot Low", shape.triangleup, location.belowbar, color.red, -rightBars, "Pivot\nLow", size=size.small)
</code>```

Title: labels on tops and bottoms

Body:
please help me to plot labels on tops and bottoms based on this short indicator I hope the result will be like this pic lables.
I tried but it plots labels on all candles not on pivots tops and bottoms only.

//@version=5
indicator('piv lbl', overlay=true, max_lines_count=500)

period   = input.int(200, title="Period")

hh = ta.highest(high, period)
ll = ta.lowest(low,   period)

hsrc =  input.source(high , title="High source")
lsrc =  input.source(low  , title="Low  source")

newhh   = high > hh[1]
newll   = low  < ll[1]

hhb = ta.barssince(hh)
plot(hhb)

if hh
    label.new(bar_index, na, yloc=yloc.abovebar)
if ll
    label.new(bar_index, na, yloc=yloc.belowbar)

Body:
You can use the ta.pivothigh() and ta.pivotlow() functions to find the pivots.

//@version=5
indicator("PivotHigh", overlay=true)
leftBars = input(10)
rightBars=input(10)
ph = ta.pivothigh(leftBars, rightBars)
pl = ta.pivotlow(leftBars, rightBars)
plotshape(ph, "Pivot High", shape.triangledown, location.abovebar, color.green, -rightBars, "Pivot\nHigh", size=size.small)
plotshape(pl, "Pivot Low", shape.triangleup, location.belowbar, color.red, -rightBars, "Pivot\nLow", size=size.small)


问:
Writing a function that returns a list with the name and content of subfolders in r
I'm trying to write a function that displays the subfolder names and contents. I have the following written code. However when I call the function, only the names of the subfolders are returned.

```<code>My_file <- function (Folder_name){

  My_list <- list.files(path =  "/Users/user/Desktop/task/Data/Data")

return(My_list)

}

</code>```

The folder "Data" contains 2 subfolders "House" and "Cars". I want the function to return the name of the subfolder and the contents of each subfolder.

For example output should be:

```<code>$House

Bungalow.extension

$Car

Porsche.extension
</code>```

Thank you!

答:
You can use recursive = TRUE in list.files -

```<code>My_file <- function (Folder_name) {
  My_list <- list.files(path = "/Users/user/Desktop/task/Data/Data", recursive = TRUE)
  return(My_list)
}
</code>```

Body:
I'm trying to write a function that displays the subfolder names and contents. I have the following written code. However when I call the function, only the names of the subfolders are returned.

My_file <- function (Folder_name){

  My_list <- list.files(path =  "/Users/user/Desktop/task/Data/Data")

return(My_list)

}

The folder "Data" contains 2 subfolders "House" and "Cars". I want the function to return the name of the subfolder and the contents of each subfolder.

For example output should be:

$House

Bungalow.extension

$Car

Porsche.extension

Thank you!

Body:
You can use recursive = TRUE in list.files -

My_file <- function (Folder_name) {
  My_list <- list.files(path = "/Users/user/Desktop/task/Data/Data", recursive = TRUE)
  return(My_list)
}


问:
JPA excesive querys for mapping an entity
I have the following entity:

```<code>    @Name("estructuraOrganica")
    @Entity
    @Table(name = "srht_estructuras_organicas")
    public class EstructuraOrganica extends EntidadBasica implements Auditable,
    Desplegable<EstructuraOrganica> {

private static final long serialVersionUID = 1L;

@NotNull
@Length(max = 50)
@Column(name = "codigo", nullable = false, length = 50)
private String codigo;

@Length(max = 300)
@Column(name = "nombre", nullable = true, length = 160)
private String nombre;

@Column(name = "institucion_id")
private Long institucionId;

@NotNull
@Length(max = 1)
@Column(name = "es_uarh", nullable = false, length = 1)
private String esUARH;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "catalogo_jerarquia_proceso_unidad_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Catalogo catalogoJerarquiaProcesoUnidad;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estatuto_id", nullable = false)
private Estatuto estatuto;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "estructura_organica_padre_id", nullable = true)
private EstructuraOrganica estructuraOrganicaPadre;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "padre_auxiliar_estructura_id", nullable = true)
private EstructuraOrganica estructuraOrganicaJerarquia;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estado_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Estado estado;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY,                             mappedBy                    =                           "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
private List<EstructuraOrganica> estructurasOrganicas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
private List<OrganigramaPosicion> organigramasPosiciones;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
@Where(clause = "estado_id=1")
private List<OrganigramaPosicion> organigramasPosicionesActivas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
@Where(clause = "estado_id=1")
private List<EstructuraOrganica> estructurasOrganicasActivas;

@Column(name = "estado_plan_vacaciones")
private Integer estadoPlanVacaciones;

@Column(name = "tipo")
private Integer tipo;

@Column(name = "puesto_jefe_inmediato")
private Long puestoJefeInmediato;

@Length(max = 10)
@Column(name = "codigo_mef", nullable = true, length = 10)
private String codigoMef;

@Transient
private Boolean puedeEliminarse;

@Transient
private Boolean uarh;

@Transient
private Boolean puedeGrabarse;

@Transient
private RegimenDePersonal regimenDePersonal;

@Column(name="institucion_desconcentrada_id")
private Long institucionDesconcentradaId;

... Getters and Setters omitted...

   }
</code>```

Now the JPQL query to find a certain instance of this entity is the following:

```<code>   SELECT o FROM EstructuraOrganica o WHERE o.estatuto.institucion.id=:institucionId and        o.estructuraOrganicaPadre is null AND o.estado.id=1 ORDER BY o.codigo ASC")
</code>```

However, the problem is that this simple query is generating an excesive count of calls to the database... doing selects basically. A native sql for doing the same could be:

```<code>    SELECT * from sch_senres.srht_estructuras_organicas,
          sch_senres.srht_estatutos,
          sch_senres.srht_instituciones,
          sch_senres.srht_estados
    WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id
    AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id
    AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id
    AND   sch_senres.srht_instituciones.id=91122
    AND   sch_senres.srht_estados.id=1
    AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL
    ORDER BY sch_senres.srht_estructuras_organicas.codigo
</code>```

So the idea was to create a NativeQuery like this:

```<code>    Query query=entityManager.createNativeQuery("SELECT * from  sch_senres.srht_estructuras_organicas,"+                                                    "sch_senres.srht_estatutos,sch_senres.srht_instituciones,"+
                                                "sch_senres.srht_estados "+
                                                "WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id "+
                                                "AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id "+
                                                "AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id "+
                                                "AND   sch_senres.srht_instituciones.id= :institucionId "+
                                                "AND   sch_senres.srht_estados.id=1 "+
                                                "AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL "+
                                                "ORDER BY sch_senres.srht_estructuras_organicas.codigo", EstructuraOrganica.class);
    query.setParameter("institucionId", institucionId);
</code>```

However I got no result... hibernate continues doing like 50 calls to the database. Does anybody know why is this happening, and how could I avoid so many calls?. Thanks a lot.

答: Yes, you all were right, the problem was that the @PostLoad method was referencing the relationship of the same entity, in other words, it was calling the estructurasOrganicas property. This was causing a recursive fetch from the database. I didn't see the PostLoad method at first time, this was the problem. Thanks a lot.</p>

Body:
I have the following entity:

    @Name("estructuraOrganica")
    @Entity
    @Table(name = "srht_estructuras_organicas")
    public class EstructuraOrganica extends EntidadBasica implements Auditable,
    Desplegable<EstructuraOrganica> {

private static final long serialVersionUID = 1L;

@NotNull
@Length(max = 50)
@Column(name = "codigo", nullable = false, length = 50)
private String codigo;

@Length(max = 300)
@Column(name = "nombre", nullable = true, length = 160)
private String nombre;

@Column(name = "institucion_id")
private Long institucionId;

@NotNull
@Length(max = 1)
@Column(name = "es_uarh", nullable = false, length = 1)
private String esUARH;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "catalogo_jerarquia_proceso_unidad_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Catalogo catalogoJerarquiaProcesoUnidad;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estatuto_id", nullable = false)
private Estatuto estatuto;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "estructura_organica_padre_id", nullable = true)
private EstructuraOrganica estructuraOrganicaPadre;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "padre_auxiliar_estructura_id", nullable = true)
private EstructuraOrganica estructuraOrganicaJerarquia;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estado_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Estado estado;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY,                             mappedBy                    =                           "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
private List<EstructuraOrganica> estructurasOrganicas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
private List<OrganigramaPosicion> organigramasPosiciones;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
@Where(clause = "estado_id=1")
private List<OrganigramaPosicion> organigramasPosicionesActivas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
@Where(clause = "estado_id=1")
private List<EstructuraOrganica> estructurasOrganicasActivas;

@Column(name = "estado_plan_vacaciones")
private Integer estadoPlanVacaciones;

@Column(name = "tipo")
private Integer tipo;

@Column(name = "puesto_jefe_inmediato")
private Long puestoJefeInmediato;

@Length(max = 10)
@Column(name = "codigo_mef", nullable = true, length = 10)
private String codigoMef;

@Transient
private Boolean puedeEliminarse;

@Transient
private Boolean uarh;

@Transient
private Boolean puedeGrabarse;

@Transient
private RegimenDePersonal regimenDePersonal;

@Column(name="institucion_desconcentrada_id")
private Long institucionDesconcentradaId;

... Getters and Setters omitted...

   }

Now the JPQL query to find a certain instance of this entity is the following:

   SELECT o FROM EstructuraOrganica o WHERE o.estatuto.institucion.id=:institucionId and        o.estructuraOrganicaPadre is null AND o.estado.id=1 ORDER BY o.codigo ASC")

However, the problem is that this simple query is generating an excesive count of calls to the database... doing selects basically. A native sql for doing the same could be:

    SELECT * from sch_senres.srht_estructuras_organicas,
          sch_senres.srht_estatutos,
          sch_senres.srht_instituciones,
          sch_senres.srht_estados
    WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id
    AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id
    AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id
    AND   sch_senres.srht_instituciones.id=91122
    AND   sch_senres.srht_estados.id=1
    AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL
    ORDER BY sch_senres.srht_estructuras_organicas.codigo

So the idea was to create a NativeQuery like this:

    Query query=entityManager.createNativeQuery("SELECT * from  sch_senres.srht_estructuras_organicas,"+                                                    "sch_senres.srht_estatutos,sch_senres.srht_instituciones,"+
                                                "sch_senres.srht_estados "+
                                                "WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id "+
                                                "AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id "+
                                                "AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id "+
                                                "AND   sch_senres.srht_instituciones.id= :institucionId "+
                                                "AND   sch_senres.srht_estados.id=1 "+
                                                "AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL "+
                                                "ORDER BY sch_senres.srht_estructuras_organicas.codigo", EstructuraOrganica.class);
    query.setParameter("institucionId", institucionId);

However I got no result... hibernate continues doing like 50 calls to the database. Does anybody know why is this happening, and how could I avoid so many calls?. Thanks a lot.