问:
Iterate through array of objects using javascript
I am trying to iterate through the array of objects but somehow not getting it right. Can somone please let me know where i am going wrong.

Here is the data

```<code>const response = {
    "pass": 1,
    "fail": 2,
    "projects_all": [
        {
            "projects": [
                {
                    "name": "Project1",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        },
        {
            "projects": [
                {
                    "name": "Project2",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "FAIL",
                    }
                },
                {
                    "name": "Project3",
                    "status": "LIVE",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        }
    ]
}
</code>```

And here is the code i tried

```<code>if(response) {
  response?.projects_all?.forEach((projects) => {
     projects.forEach(project) => {
       if(project.previous !== null) {
         //do something here
       }
    });
 });
}
</code>```

I am trying to iterate through this array of objects but it says projects not iterable. Any help is appreciated to make me understand where i am going wrong.

答:
You were missing iterating over an array properly. A good idea is to format the JSON object that you plan to iterate over. So that you can see what are the arrays and objects, and at what hierarchy.</p>
```<code>if (response) {
  response?.projects_all?.forEach((project) => {
    project?.projects?.forEach((project) => {
      console.log(project?.name);
    });
  }
  );
}
</code>```

Body:
I am trying to iterate through the array of objects but somehow not getting it right. Can somone please let me know where i am going wrong.

Here is the data

const response = {
    "pass": 1,
    "fail": 2,
    "projects_all": [
        {
            "projects": [
                {
                    "name": "Project1",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        },
        {
            "projects": [
                {
                    "name": "Project2",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "FAIL",
                    }
                },
                {
                    "name": "Project3",
                    "status": "LIVE",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        }
    ]
}

And here is the code i tried

if(response) {
  response?.projects_all?.forEach((projects) => {
     projects.forEach(project) => {
       if(project.previous !== null) {
         //do something here
       }
    });
 });
}

I am trying to iterate through this array of objects but it says projects not iterable. Any help is appreciated to make me understand where i am going wrong.

Body:
You were missing iterating over an array properly. A good idea is to format the JSON object that you plan to iterate over. So that you can see what are the arrays and objects, and at what hierarchy.

if (response) {
  response?.projects_all?.forEach((project) => {
    project?.projects?.forEach((project) => {
      console.log(project?.name);
    });
  }
  );
}


来源: stackexchange

问:
How to Multiply a value to the next value in a list in scheme?
Is there a way to multiply each value in a list,
however instead of getting another list (2 4 6) like so,
you get the multiplication of all values together.

```<code>(define (multi x y)
  (if (null? y)
     '()
     (* x (car y))))
(multi 2 '(1 2 3))
2 * 1 * 2 * 3
==> 6
</code>```

This may be very simple to some people, but I am having a coding block here, so please don't be rude in the comments. thank you.

答:
```<code>(define (mult x lst)
  (if (null? lst)
      x
      (mult (* x (car lst))(cdr lst))))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to multiply each value in a list,
however instead of getting another list (2 4 6) like so,
you get the multiplication of all values together.

(define (multi x y)
  (if (null? y)
     '()
     (* x (car y))))
(multi 2 '(1 2 3))
2 * 1 * 2 * 3
==> 6

This may be very simple to some people, but I am having a coding block here, so please don't be rude in the comments. thank you.


问:
Mock specific graphql request in cypress when running e2e tests
When running e2e tests with Cypress, my goal is to mock a specific graphql query.

Currently, I can mock all requests like this:

cy.server();
cy.route('POST', '/graphql', {
    data: {
        foo: 'bar'
    },
});
```

<p>The problem is that this mocks <em>all</em> <code>/graphql</code> queries. It would be awesome if I somehow could say:</p>

<pre class="lang-js prettyprint-override"><code>cy.route('POST', '/graphql', 'fooQuery', {
    data: {
        foo: 'bar'
    },
});
</code>```

In our application, we are using Apollo Graphql - and thus all queries are named.

答:
You can try this if want to use fixture for graphql response:</p>
```<code>cy.intercept('POST', '/test_api/graphql', (req) => {
      req.continue((res) => {
        if (req.body.operationName === 'op_name') {
          res.send({ fixture: 'MyFixture/xyz.json' }),
            req.alias = 'graphql'
        }
      })
})
</code>```

Body:
When running e2e tests with Cypress, my goal is to mock a specific graphql query.

Currently, I can mock all requests like this:

cy.server();
cy.route('POST', '/graphql', {
    data: {
        foo: 'bar'
    },
});

The problem is that this mocks all /graphql queries. It would be awesome if I somehow could say:

cy.route('POST', '/graphql', 'fooQuery', {
    data: {
        foo: 'bar'
    },
});

In our application, we are using Apollo Graphql - and thus all queries are named.

Body:
You can try this if want to use fixture for graphql response:

cy.intercept('POST', '/test_api/graphql', (req) => {
      req.continue((res) => {
        if (req.body.operationName === 'op_name') {
          res.send({ fixture: 'MyFixture/xyz.json' }),
            req.alias = 'graphql'
        }
      })
})


问:
Passing parameter Array to powershell.exe
I have a script that require 2 arrays as input, and optional logname :

#file:test.ps1
Param(
    [string[]]$array1,
    [string[]]$array2,
    [string]$logName = "log{0}.csv" -f (get-date -format "yyyyMMdd")
)

"array1: {0}" -f ($array1 -join " ")
"array2: {0}({1})" -f ($array2 -join " ") ,$array2.count
"logName: {0}" -f $logName
```

<p>When run from a PowerShell console, everything is fine:</p>

```
PS D:\temp> .\test.ps1 -array1 one,two -array2 1,2,3
array1: one two
array2: 1 2 3(3)
logName: log20190723.csv
```

<p>But when run by calling <code>powershell.exe</code> (for scheduled task), only first element from array is grabbed, the rest is passed to the logname parameter.</p>

```
PS D:\temp> powershell.exe -F D:\temp\test.ps1 -array1 one,two -array2 1,2,3
array1: one
array2: 1(1)
logName: two
```

How should I define params to grab all params into the array?

(BTW: I'm using PS4.0, with same result on Windows 2008 and 2012)

答:
From the PowerShell.exe docs:

-File - | <filePath> <args>

[...] Parameters [i.e. the <args>] passed to the script are passed as literal strings, after interpretation by the current shell.

So complex types like arrays cannot be directly provided this way. And be aware that "interpretation by the current shell" and/or command line arguments parsing can do unexpected things to your values: Double quotes may get mangled, arguments are split at non-quoted whitespace, single quotes have no special meaning (always end up in the value as-is), etc. You can use EchoArgs.exe to check what happens.

If you cannot use PowerShell.exe -Command instead (as suggested by other answers) – e.g. because you are facilitating the Group Policy Logon/Startup/etc. script feature (where gpscript.exe [/logon|/startup|...] is calling PowerShell.exe with -File) – you can work around this limitation by processing the parameter's value inside your script:

```<code>$array1 = $array1 -split ','
# You can only have (intended!) whitespace within and between the
# parameter values *if* there are double quotes around them:
# powershell.exe -F test.ps1 -array1 "one, two two"
# And they will remain: $array1 = @("one"," two two")
</code>```

or

```<code>$array1 = Invoke-Expression $array1
# Call like this: powershell.exe -F test.ps1 -array1 "'one',' two two'"
# This way, values can quite safely contain whitespace, and the result will be more clear.
# And you could also pass other complex types like hashtables.
# (Though Invoke-Expression usage is discouraged, but should be ok if you have control over the parameters.)
</code>```

Body:
I have a script that require 2 arrays as input, and optional logname :

#file:test.ps1
Param(
    [string[]]$array1,
    [string[]]$array2,
    [string]$logName = "log{0}.csv" -f (get-date -format "yyyyMMdd")
)

"array1: {0}" -f ($array1 -join " ")
"array2: {0}({1})" -f ($array2 -join " ") ,$array2.count
"logName: {0}" -f $logName

When run from a PowerShell console, everything is fine:

PS D:\temp> .\test.ps1 -array1 one,two -array2 1,2,3
array1: one two
array2: 1 2 3(3)
logName: log20190723.csv

But when run by calling powershell.exe (for scheduled task), only first element from array is grabbed, the rest is passed to the logname parameter.

PS D:\temp> powershell.exe -F D:\temp\test.ps1 -array1 one,two -array2 1,2,3
array1: one
array2: 1(1)
logName: two

How should I define params to grab all params into the array?

(BTW: I'm using PS4.0, with same result on Windows 2008 and 2012)

Body:
From the PowerShell.exe docs:

-File - | <filePath> <args>

[...] Parameters [i.e. the <args>] passed to the script are passed as literal strings, after interpretation by the current shell.

So complex types like arrays cannot be directly provided this way. And be aware that "interpretation by the current shell" and/or command line arguments parsing can do unexpected things to your values: Double quotes may get mangled, arguments are split at non-quoted whitespace, single quotes have no special meaning (always end up in the value as-is), etc. You can use EchoArgs.exe to check what happens.

If you cannot use PowerShell.exe -Command instead (as suggested by other answers) – e.g. because you are facilitating the Group Policy Logon/Startup/etc. script feature (where gpscript.exe [/logon|/startup|...] is calling PowerShell.exe with -File) – you can work around this limitation by processing the parameter's value inside your script:

$array1 = $array1 -split ','
# You can only have (intended!) whitespace within and between the
# parameter values *if* there are double quotes around them:
# powershell.exe -F test.ps1 -array1 "one, two two"
# And they will remain: $array1 = @("one"," two two")

or

$array1 = Invoke-Expression $array1
# Call like this: powershell.exe -F test.ps1 -array1 "'one',' two two'"
# This way, values can quite safely contain whitespace, and the result will be more clear.
# And you could also pass other complex types like hashtables.
# (Though Invoke-Expression usage is discouraged, but should be ok if you have control over the parameters.)


问:
Filter rows on the condition that at least two distinct key words must be present
I have a dataframe with speech data, like this:

```<code>df <- data.frame(
  id = 1:12,
  partcl = c("yeah yeah yeah absolutely", "well you know it 's", "oh well yeah that's right",
             "yeah I mean well oh", "well erm well Peter will be there", "well yeah well",
             "yes yes yes totally", "yeah yeah yeah yeah", "well well I did n't do it",
             "er well yeah that 's true", "oh hey where 's he gone?", "er"
))
</code>```

and a vector with key words called parts:

```<code>parts <- c("yeah", "oh", "no", "well", "mm", "yes", "so", "right", "er", "like")
</code>```

What I need to do is filter those rows with at least two distinct parts values. What I can do is filter those rows with at least two parts values, regardless of whether they're distinct or the same:

```<code>library(dplyr)
df %>%
  filter(
    str_count(partcl, paste0("\\b(", paste0(parts, collapse = "|"), ")\\b")) > 1
  )
  id                            partcl
1  1         yeah yeah yeah absolutely
2  3         oh well yeah that's right
3  4               yeah I mean well oh
4  5 well erm well Peter will be there
5  6                    well yeah well
6  7               yes yes yes totally
7  8               yeah yeah yeah yeah
8  9         well well I did n't do it
9 10         er well yeah that 's true
</code>```

How can I assert that the matched partsbe distinct so that the result is this:

```<code>  id                            partcl
1  3         oh well yeah that's right
2  4               yeah I mean well oh
3  6                    well yeah well
4 10         er well yeah that 's true
</code>```

答:
May be this helps - extract the key words with str_extract_all, and then do the check with n_distinct to filter rows having more than one unique keyword

```<code>library(dplyr)
library(stringr)
library(purrr)
df %>%
  filter(map_lgl(str_extract_all(partcl,
    paste0("\\b(", paste0(parts, collapse = "|"), ")\\b")),
    ~  n_distinct(.x) > 1))
</code>```

-output

```<code> id                    partcl
1  3 oh well yeah that's right
2  4       yeah I mean well oh
3  6            well yeah well
4 10 er well yeah that 's true
</code>```

Body:
I have a dataframe with speech data, like this:

df <- data.frame(
  id = 1:12,
  partcl = c("yeah yeah yeah absolutely", "well you know it 's", "oh well yeah that's right",
             "yeah I mean well oh", "well erm well Peter will be there", "well yeah well",
             "yes yes yes totally", "yeah yeah yeah yeah", "well well I did n't do it",
             "er well yeah that 's true", "oh hey where 's he gone?", "er"
))

and a vector with key words called parts:

parts <- c("yeah", "oh", "no", "well", "mm", "yes", "so", "right", "er", "like")

What I need to do is filter those rows with at least two distinct parts values. What I can do is filter those rows with at least two parts values, regardless of whether they're distinct or the same:

library(dplyr)
df %>%
  filter(
    str_count(partcl, paste0("\\b(", paste0(parts, collapse = "|"), ")\\b")) > 1
  )
  id                            partcl
1  1         yeah yeah yeah absolutely
2  3         oh well yeah that's right
3  4               yeah I mean well oh
4  5 well erm well Peter will be there
5  6                    well yeah well
6  7               yes yes yes totally
7  8               yeah yeah yeah yeah
8  9         well well I did n't do it
9 10         er well yeah that 's true

How can I assert that the matched partsbe distinct so that the result is this:

  id                            partcl
1  3         oh well yeah that's right
2  4               yeah I mean well oh
3  6                    well yeah well
4 10         er well yeah that 's true

Body:
May be this helps - extract the key words with str_extract_all, and then do the check with n_distinct to filter rows having more than one unique keyword

library(dplyr)
library(stringr)
library(purrr)
df %>%
  filter(map_lgl(str_extract_all(partcl,
    paste0("\\b(", paste0(parts, collapse = "|"), ")\\b")),
    ~  n_distinct(.x) > 1))

-output

 id                    partcl
1  3 oh well yeah that's right
2  4       yeah I mean well oh
3  6            well yeah well
4 10 er well yeah that 's true


问:
apidata.map is not a function : ReactJS
Can someone please tell me why i am getting this error . I tried fixing it all day, but I could not fix it. So at last i had to come at stackoverflow

This is my code : App.js

```<code>import "./App.css";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key":
            "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108",
        },
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setApidata(data);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue);
  };

  return (
    <div className="App">
      <div className="main">
        <h2>Welcome To weather App </h2>
      </div>

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.map((data, i) => {
        return <h1>{data.current.feelslike_c}</h1>;
      })}
    </div>
    //Map
  );
}

export default App;
</code>```

This is the error I am getting :
enter image description here

答:
What I'm seeing is the api is initially returning an error object.  Also, when the proper data is returned, it comes back as an object. When setting your state, you will have to set data inside of an array (if you want to use the map method). You will also have to handle the error by doing something like this:

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

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key": "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108"
        }
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data)
        if (data.error) return null;
        setApidata([data]);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue);
  };

  console.log("test", apidata);

  return (
    <div className="App">
      <div className="main">
        <h2>Welcome To weather App </h2>
      </div>

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.length
        ? apidata.map((data, i) => {
            return <h1 key={i}>{data.current.feelslike_c}</h1>;
          })
        : null}
    </div>
    //Map
  );
}
</code>```

see working example: https://codesandbox.io/s/eager-wind-06ywo?file=/src/App.js

Title: apidata.map is not a function : ReactJS

Body:
Can someone please tell me why i am getting this error . I tried fixing it all day, but I could not fix it. So at last i had to come at stackoverflow

This is my code : App.js

import "./App.css";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key":
            "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108",
        },
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setApidata(data);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue);
  };

  return (

Welcome To weather App

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.map((data, i) => {
        return
{data.current.feelslike_c}
;
      })}

    //Map
  );
}

export default App;

This is the error I am getting :
enter image description here

Body:
What I'm seeing is the api is initially returning an error object.  Also, when the proper data is returned, it comes back as an object. When setting your state, you will have to set data inside of an array (if you want to use the map method). You will also have to handle the error by doing something like this:

import { useState, useEffect } from "react";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key": "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108"
        }
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data)
        if (data.error) return null;
        setApidata([data]);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue);
  };

  console.log("test", apidata);

  return (
    <div className="App">
      <div className="main">
        <h2>Welcome To weather App </h2>
      </div>

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.length
        ? apidata.map((data, i) => {
            return <h1 key={i}>{data.current.feelslike_c}</h1>;
          })
        : null}
    </div>
    //Map
  );
}

see working example: https://codesandbox.io/s/eager-wind-06ywo?file=/src/App.js


问:
WooCommerce checkout message based for a variable product and a specific variable?
I have added a custom message that now appears below woocommerce_after_order_notes, But I just want it to be displayed for one of the variables of a product.
The following code shows it only for the main product
Please tell me how to change it for a variable.

add_action( 'woocommerce_after_order_notes', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
    // set your products IDs here:
    $product_ids = array( 91);
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) )
            $bool = true;
    }
    // If the special cat is detected in one items of the cart
    // It displays the message
    if ($bool)
        echo '
This is Your custom message displayed.
';
}```

答:
You can check if there is any variation_id in cart like this $cart_item['variation_id']. try the below code.

```<code>add_action( 'woocommerce_after_order_notes', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {

    // set your products IDs here:
    $product_ids = array( 82, 94 ); // add your both product and variation id.

    $parent_ids_in_cart = false;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) ){
            $parent_ids_in_cart = true;
        }
    }

    $variation_ids_in_cart = false;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // Collecting product variation IDs if they are in cart for this variable product
        if ( $cart_item['variation_id'] > 0 && in_array( $cart_item['variation_id'], $product_ids ) ){
            $variation_ids_in_cart = true;
        }
    }

    // It displays the message
    if ( $parent_ids_in_cart || $variation_ids_in_cart ){
        echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
    }

}
</code>```

Body:
You can check if there is any variation_id in cart like this $cart_item['variation_id']. try the below code.

add_action( 'woocommerce_after_order_notes', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {

    // set your products IDs here:
    $product_ids = array( 82, 94 ); // add your both product and variation id.

    $parent_ids_in_cart = false;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) ){
            $parent_ids_in_cart = true;
        }
    }

    $variation_ids_in_cart = false;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // Collecting product variation IDs if they are in cart for this variable product
        if ( $cart_item['variation_id'] > 0 && in_array( $cart_item['variation_id'], $product_ids ) ){
            $variation_ids_in_cart = true;
        }
    }

    // It displays the message
    if ( $parent_ids_in_cart || $variation_ids_in_cart ){
        echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
    }

}


问:
What features are people looking forward to in .Net 4.0 - 4.1
I am very interested in learning what features people are interested in in the forthcoming .net framework(s)?

Whether these be new classes or new controls I am curious to know people views.

答:
I'm looking forward to new WPF controls. I believe the now WPF Toolkit will be incorporated as controls in the framework. It'll be a lot nicer having them as stock controls in Visual Studio and having them patched with the .NET framework rather than having to download a new set every time bugfixes have to go out.

Also, i'm looking forward to Visual Studio 2010 in all it's WPF glory!

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jirwin


答:
response?.projects_all?.forEach((projects) => {

This is the exact correct way to start the code. The problem that happens next is you apparently misunderstand what projects means in the following context

You do projects.forEach(project) as if you think projects is as array. projects is not an array at this point, it is an object that looks like this:

```<code>        {
            "projects": [
                {
                    "name": "Project1",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        }
</code>```

So I would actually want to do projects.projects.forEach(project => { ... }), or you could change the variable name from projects so it makes more sense to read.

Title: Iterate through array of objects using javascript

Body:
response?.projects_all?.forEach((projects) => {

This is the exact correct way to start the code. The problem that happens next is you apparently misunderstand what projects means in the following context

You do projects.forEach(project) as if you think projects is as array. projects is not an array at this point, it is an object that looks like this:

        {
            "projects": [
                {
                    "name": "Project1",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        }

So I would actually want to do projects.projects.forEach(project => { ... }), or you could change the variable name from projects so it makes more sense to read.


问:
Can I configure Django runserver to reload when static or non-python files are changed?
By default, Django's runserver command auto reloads the server when python or template files are changed.

Is it possible to configure Django to extend its file monitoring for this purpose to other directories or sets of files, such as JavaScript or CSS files being served statically (during development)?

This would be useful in this scenario: the Django app reads a set of static text files on startup and I would like the server to re-read them when they change, without having to add this specific feature - simply restarting would be fine.

Do I need to start meddling with (or extending) django/utils/autoreload.py ?

答: The answer to this is YES, all you need to do is touch your settings file which will trigger a runserver reload.  If all you need to do is source new static files, you don't need this, but if you need to trigger a reload for another reason, it is possible with a simple touch.

ContentLicense: CC BY-SA 3.0


问:
parse stringified object into row in oracle sql
We have a custom stringified object format that I'd like to explode into an object (or row?) inside of Oracle - with the goal of inserting it into a corresponding table.

The format looks like..
{key=value}:{key1=value1"}:{key2=value2}

e.g. {street=123 Main St}:{city=Somewhere}:{state=MI}:{zip=12345}

The approach I've taken in other languages generally looks like..

```<code>function packed2obj(packed_s) {
    packed_s = packed_s.match(/^\{(.+)\}$/);
    var packed_o = new Object();
    var pieces = packed_s[1].split("}:{");

    for (var i = 0; pieces != null && i < pieces.length; i++) {
        match = pieces[i].match(/([^=]*)=(.*)/);
        var key = new String(match[1]);
        var value = new String(match[2]);
        packed_o[key] = value;
    }
    return packed_o;
}
</code>```

I found this post: pl-sql-split-string-into-an-associative-array, which was somewhat helpful, but it returns each key value pair as a separate row.  I was hoping for something that might more easily inserted into a table with (mostly) matching columns (a record maybe?)

Parsing JSON into oracle sql also looks interesting, but the text isn't JSON format.   It might be possible to convert it to JSON before it hits the database, but it would be more convenient to the upstream systems if we could stick with the native format.

答:
Group extraction with regular expressions to the rescue (regexp_substr)!</p>
```<code>SELECT regexp_substr(line, '{street=([^}]+)', 1, 1, NULL, 1) as street,
       regexp_substr(line, '{city=([^}]+)', 1, 1, NULL, 1) as city,
       regexp_substr(line, '{state=([^}]+)', 1, 1, NULL, 1) as state,
       regexp_substr(line, '{zip=([^}]+)', 1, 1, NULL, 1) as zip
  FROM (SELECT '{street=123 Main St}:{city=Somewhere}:{state=MI}:{zip=12345}' line FROM dual);

STREET      | CITY      | STATE | ZIP
------------+-----------+-------+------
123 Main St | Somewhere | MI    | 12345
</code>```

Body:
We have a custom stringified object format that I'd like to explode into an object (or row?) inside of Oracle - with the goal of inserting it into a corresponding table.

The format looks like..
{key=value}:{key1=value1"}:{key2=value2}

e.g. {street=123 Main St}:{city=Somewhere}:{state=MI}:{zip=12345}

The approach I've taken in other languages generally looks like..

function packed2obj(packed_s) {
    packed_s = packed_s.match(/^\{(.+)\}$/);
    var packed_o = new Object();
    var pieces = packed_s[1].split("}:{");

    for (var i = 0; pieces != null && i < pieces.length; i++) {
        match = pieces[i].match(/([^=]*)=(.*)/);
        var key = new String(match[1]);
        var value = new String(match[2]);
        packed_o[key] = value;
    }
    return packed_o;
}

I found this post: pl-sql-split-string-into-an-associative-array, which was somewhat helpful, but it returns each key value pair as a separate row.  I was hoping for something that might more easily inserted into a table with (mostly) matching columns (a record maybe?)

Parsing JSON into oracle sql also looks interesting, but the text isn't JSON format.   It might be possible to convert it to JSON before it hits the database, but it would be more convenient to the upstream systems if we could stick with the native format.

Body:
Group extraction with regular expressions to the rescue (regexp_substr)!

SELECT regexp_substr(line, '{street=([^}]+)', 1, 1, NULL, 1) as street,
       regexp_substr(line, '{city=([^}]+)', 1, 1, NULL, 1) as city,
       regexp_substr(line, '{state=([^}]+)', 1, 1, NULL, 1) as state,
       regexp_substr(line, '{zip=([^}]+)', 1, 1, NULL, 1) as zip
  FROM (SELECT '{street=123 Main St}:{city=Somewhere}:{state=MI}:{zip=12345}' line FROM dual);

STREET      | CITY      | STATE | ZIP
------------+-----------+-------+------
123 Main St | Somewhere | MI    | 12345


问:
How do I add 1 to a variable each time it replaces a specific string
What I am trying to do is add 1 to $b each time it replaces the word hello with modal$b so it should look like modal1, modal2 etc.

```<code> $a=1
$b=1
$original_file = 'C:\Users\me\Desktop\2.txt'
$destination_file =  'C:\Users\me\Desktop\4.txt'
do {
(Get-Content $original_file)  | ForEach-Object  {
  $_  -replace "hello", "modal$b"`

    } | add-Content $destination_file

    $a++
}
until ($a -gt 1)
</code>```

Any help would be greatly appreciated!
thanks,
Sarash

答:
You could do it with just a ForEach-Object loop, there doesn't seem to be a need for the Do loop. Following what you already have, you can increase your variable like below.

```<code>$original_file = 'C:\Users\me\Desktop\2.txt'
$destination_file = 'C:\Users\me\Desktop\4.txt'
$b = 0
Get-Content $original_file | ForEach-Object {
    $_ -replace 'hello', "modal$(($b++))"
} | Out-File $destination_file
</code>```

The following would work too, using a Regex.Replace with a Script Block, this example would require to use the -Raw switch on Get-Content. It's important to note that using this method, the pattern is case sensitive (i.e.: 'Hello' will not match 'hello'), if you want it to be case-insensitive you could use the (?i) flag: '(?i)hello'.

```<code>[ref]$ref = 0
[regex]::Replace((Get-Content $original_file -Raw), 'hello', {
    "modal$(($ref.Value++))"
}) | Out-File $destination_file
</code>```

Replacement with a script block was implemented in PowerShell 6 (Core), thanks Mathias R. Jessen for the hard work :)

Above example, if you have PS Core, would be replaced by:

```<code>[ref]$ref = 0
(Get-Content $original_file -Raw) -replace 'hello', {
    "modal$(($ref.Value++))"
} | Out-File $destination_file
</code>```

And there wouldn't be a need for the (?i) flag since -replace is already case-insensitive.

Body:
What I am trying to do is add 1 to $b each time it replaces the word hello with modal$b so it should look like modal1, modal2 etc.

 $a=1
$b=1
$original_file = 'C:\Users\me\Desktop\2.txt'
$destination_file =  'C:\Users\me\Desktop\4.txt'
do {
(Get-Content $original_file)  | ForEach-Object  {
  $_  -replace "hello", "modal$b"`

    } | add-Content $destination_file

    $a++
}
until ($a -gt 1)

Any help would be greatly appreciated!
thanks,
Sarash

Body:
You could do it with just a ForEach-Object loop, there doesn't seem to be a need for the Do loop. Following what you already have, you can increase your variable like below.

$original_file = 'C:\Users\me\Desktop\2.txt'
$destination_file = 'C:\Users\me\Desktop\4.txt'
$b = 0
Get-Content $original_file | ForEach-Object {
    $_ -replace 'hello', "modal$(($b++))"
} | Out-File $destination_file

The following would work too, using a Regex.Replace with a Script Block, this example would require to use the -Raw switch on Get-Content. It's important to note that using this method, the pattern is case sensitive (i.e.: 'Hello' will not match 'hello'), if you want it to be case-insensitive you could use the (?i) flag: '(?i)hello'.

[ref]$ref = 0
[regex]::Replace((Get-Content $original_file -Raw), 'hello', {
    "modal$(($ref.Value++))"
}) | Out-File $destination_file

Replacement with a script block was implemented in PowerShell 6 (Core), thanks Mathias R. Jessen for the hard work :)

Above example, if you have PS Core, would be replaced by:

[ref]$ref = 0
(Get-Content $original_file -Raw) -replace 'hello', {
    "modal$(($ref.Value++))"
} | Out-File $destination_file

And there wouldn't be a need for the (?i) flag since -replace is already case-insensitive.


问:
ColdFusion : String : Get Price From Inside 2 Points
I'm playing with the NOMICS API and get data in a string.  But I'm having trouble getting just the Price:

This is part of the string from the METHOD=GET - which works fine..

"currency":"SHIB","platform_currency":"ETH","price":"0.000026199726","price_date":"2022-02-06T00:00:00Z","price_timestamp":"

I know that ,"price":" is the lead and then "," is the end...
But I can't seem to get just the 0.000026199726 from the middle- which is what I need.

```<code><CFHTTP METHOD="Get"
     URL="https://api.nomics.com/v1/currencies/ticker?key=#apikey#&ids=SHIB">

<cfset feedData = cfhttp.filecontent>

<cfset startpos = findNoCase(',"price":"', feedData)>
<cfset endpos = findNoCase('",', feedData)>
<cfset getdata = mid(feeddata,startpos,endpos-startpos)

<b>#getdata#</b> Errors as neg number.
</code>```

The value of parameter 3 of the function Mid, which is now -191, must be a non-negative integer

This has to be an easy task.  I must be using the wrong string function?

EDIT: Figured out - it was finding the "," but they are so many of them it found first one, which put things negative - so fix was to find the structure after. ","price_date" is after.

```<code>      <cfset string = cfhttp.filecontent>
      <cfset startpos = findNoCase('price":"', string)>
      <cfset endpos = findNoCase('","price_date"', string)>
      <cfset detdata = mid(string,startpos,endpos-startpos)>

      <cfoutput>
          start: #startpos#<br>
          end: #endpos#<br>
          data: #detdata#<br>
          trimmed data: #trim(detdata)#<br>
          trimmed data:
          <br><b>#removechars(detdata,1,8)#</b><br><br>
      </cfoutput>
</code>```

I'll look at the JSON examples as well. Perhaps that will help with multiple pulls.

Excellent Folks : Thank you so much

```<code>      <CFHTTP METHOD="Get"
URL="https://api.nomics.com/v1/currencies/ticker?key=#apikey#&ids=SHIB,BTC">

      <cfset output = cfhttp.filecontent>
      <cfoutput>
      <cfset arrayOfStructs = deserializeJson(output)>
      <cfloop array="#arrayOfStructs#" index="getpr">
            <cfset Price = getpr.price />
            <cfset TKID = getpr.id />
            #tkid#: #price#<br>
      </cfloop>
      </cfoutput>
</code>```

Spits out:

BTC: 43963.45841296

SHIB: 0.000033272664

答:
Credit to Andrea/SOS</p>
```<code>  <CFHTTP METHOD="Get"
      URL="https://api.nomics.com/v1/currencies/ticker?key=#apikey#&ids=SHIB,BTC">

  <cfset output = cfhttp.filecontent>
  <cfoutput>
  <cfset arrayOfStructs = deserializeJson(output)>
  <cfloop array="#arrayOfStructs#" index="getpr">
        <cfset Price = getpr.price />
        <cfset TKID = getpr.id />
        #tkid#: #price#<br>
  </cfloop>
  </cfoutput>
</code>```

Body:
I'm playing with the NOMICS API and get data in a string.  But I'm having trouble getting just the Price:

This is part of the string from the METHOD=GET - which works fine..

"currency":"SHIB","platform_currency":"ETH","price":"0.000026199726","price_date":"2022-02-06T00:00:00Z","price_timestamp":"

I know that ,"price":" is the lead and then "," is the end...
But I can't seem to get just the 0.000026199726 from the middle- which is what I need.

<CFHTTP METHOD="Get"
     URL="https://api.nomics.com/v1/currencies/ticker?key=#apikey#&ids=SHIB">

<cfset feedData = cfhttp.filecontent>

<cfset startpos = findNoCase(',"price":"', feedData)>
<cfset endpos = findNoCase('",', feedData)>
<cfset getdata = mid(feeddata,startpos,endpos-startpos)

#getdata# Errors as neg number.

The value of parameter 3 of the function Mid, which is now -191, must be a non-negative integer

This has to be an easy task.  I must be using the wrong string function?

EDIT: Figured out - it was finding the "," but they are so many of them it found first one, which put things negative - so fix was to find the structure after. ","price_date" is after.

      <cfset string = cfhttp.filecontent>
      <cfset startpos = findNoCase('price":"', string)>
      <cfset endpos = findNoCase('","price_date"', string)>
      <cfset detdata = mid(string,startpos,endpos-startpos)>

      <cfoutput>
          start: #startpos#

          end: #endpos#

          data: #detdata#

          trimmed data: #trim(detdata)#

          trimmed data:

#removechars(detdata,1,8)#

      </cfoutput>

I'll look at the JSON examples as well. Perhaps that will help with multiple pulls.

Excellent Folks : Thank you so much

      <CFHTTP METHOD="Get"
URL="https://api.nomics.com/v1/currencies/ticker?key=#apikey#&ids=SHIB,BTC">

      <cfset output = cfhttp.filecontent>
      <cfoutput>
      <cfset arrayOfStructs = deserializeJson(output)>
      <cfloop array="#arrayOfStructs#" index="getpr">
            <cfset Price = getpr.price />
            <cfset TKID = getpr.id />
            #tkid#: #price#

      </cfloop>
      </cfoutput>

Spits out:

BTC: 43963.45841296

SHIB: 0.000033272664

Body:
Credit to Andrea/SOS

  <CFHTTP METHOD="Get"
      URL="https://api.nomics.com/v1/currencies/ticker?key=#apikey#&ids=SHIB,BTC">

  <cfset output = cfhttp.filecontent>
  <cfoutput>
  <cfset arrayOfStructs = deserializeJson(output)>
  <cfloop array="#arrayOfStructs#" index="getpr">
        <cfset Price = getpr.price />
        <cfset TKID = getpr.id />
        #tkid#: #price#<br>
  </cfloop>
  </cfoutput>


问:
How to track how longer user is on app for react native
I am trying to count in minutes and hours how longer a user is on the app for and display it. I have got the app counting minutes I just cant seem to work out how to track when the app is active or not. Theres documentation on appState but I cannot figure out how to incorporate this into counting. Here is my code:

```<code>function Overview() {
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
const [count, setCount] = useState(0);
const [active, setActive] = useState(false);

useEffect(() => {
    const subscription = AppState.addEventListener("change", nextAppState => {
        if (appState.current.match(/inactive|background/) && nextAppState === "active") {
            setActive(true);
        }

        appState.current = nextAppState;
        setAppStateVisible(appState.current);
        console.log("AppState", appState.current);
    });

    return () => {
        subscription.remove();
    };
}, []);

useEffect(() => {
    const id = setInterval(() => setCount((oldCount) => oldCount + 1), 1000);

    return () => {
        clearInterval(id);
    };
}, []);

return (
    <View style={{margin: 32}}>
        <View style={{marginBottom: 32}}>
            <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
            <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
        </View>
        <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
            <OverviewContainer title="Weather" value="14 C" />
            <OverviewContainer title="Time on app" value={`${(count/60).toFixed(0).toString()} mins`} />
        </View>
    </View>
);
}
</code>```

Any help on putting the two together be great, thanks :)

答:
You can access the current appstate as well. How about something like</p>
```<code>setCount(if AppState.currentState is active then add one)
</code>```

Body:
I am trying to count in minutes and hours how longer a user is on the app for and display it. I have got the app counting minutes I just cant seem to work out how to track when the app is active or not. Theres documentation on appState but I cannot figure out how to incorporate this into counting. Here is my code:

function Overview() {
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
const [count, setCount] = useState(0);
const [active, setActive] = useState(false);

useEffect(() => {
    const subscription = AppState.addEventListener("change", nextAppState => {
        if (appState.current.match(/inactive|background/) && nextAppState === "active") {
            setActive(true);
        }

        appState.current = nextAppState;
        setAppStateVisible(appState.current);
        console.log("AppState", appState.current);
    });

    return () => {
        subscription.remove();
    };
}, []);

useEffect(() => {
    const id = setInterval(() => setCount((oldCount) => oldCount + 1), 1000);

    return () => {
        clearInterval(id);
    };
}, []);

return (
    <View style={{margin: 32}}>
        <View style={{marginBottom: 32}}>
            <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
            <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
        </View>
        <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
            <OverviewContainer title="Weather" value="14 C" />
            <OverviewContainer title="Time on app" value={`${(count/60).toFixed(0).toString()} mins`} />
        </View>
    </View>
);
}

Any help on putting the two together be great, thanks :)

Body:
You can access the current appstate as well. How about something like

setCount(if AppState.currentState is active then add one)


问:
How to keep user logged in using Firebase in Swift?
I'm kinda new to Swift programming and I can't find any tutorial on how to keep users logged in after closing the app.

I already did log in and sign up functionality in my app, but what are my steps to keep users logged after closing the app?

答:
By default, users are already kept logged into the Firebase after closing the app.

You can add an auth state listener to see this in action. If at app startup (after Firebase is configured), you listen for the authorization state, you'll see that the app gets notified that the user is logged in already, assuming they had a valid authorization state at the time the app was last closed.

```<code>handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}
</code>```

See documentation: https://firebase.google.com/docs/auth/ios/start#listen_for_authentication_state

Body:
By default, users are already kept logged into the Firebase after closing the app.

You can add an auth state listener to see this in action. If at app startup (after Firebase is configured), you listen for the authorization state, you'll see that the app gets notified that the user is logged in already, assuming they had a valid authorization state at the time the app was last closed.

handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}

See documentation: https://firebase.google.com/docs/auth/ios/start#listen_for_authentication_state


问:
get previous and next id using mysql
I am trying to create a function in PHP that returns "next_id" and "prev_id", from an sql table.

However, the id is not simply 1,2,3,etc which means if one record id is 50, the previous id might be 22 while the next id might be 81.

I tried, in this way...

```<code>public function prevNext($id)
    {
        "SELECT
            IFNULL(SELECT min(id)
                from table
                where id > t.id ) as next_id
            , IFNULL(SELECT max(id)
                from table
                where id < t.id) as prev_id
        from table as t
        where id = $id";
    }
</code>```

答:
finally reached on a solution to solve my problem</p>
```<code>public function prevNext($id)
    {
        "SELECT
            IFNULL(( SELECT min(id)
                from table
                where id > t.id ), (SELECT min(id)
                from table)) as next_id
            , IFNULL(( SELECT max(id)
                from table
                where id < t.id ), (SELECT max(id)
                from table)) as prev_id
        from table as t
        where id = $id";
     }
</code>```

Title: get previous and next id using mysql

Body:
I am trying to create a function in PHP that returns "next_id" and "prev_id", from an sql table.

However, the id is not simply 1,2,3,etc which means if one record id is 50, the previous id might be 22 while the next id might be 81.

I tried, in this way...

public function prevNext($id)
    {
        "SELECT
            IFNULL(SELECT min(id)
                from table
                where id > t.id ) as next_id
            , IFNULL(SELECT max(id)
                from table
                where id < t.id) as prev_id
        from table as t
        where id = $id";
    }

Body:
finally reached on a solution to solve my problem

public function prevNext($id)
    {
        "SELECT
            IFNULL(( SELECT min(id)
                from table
                where id > t.id ), (SELECT min(id)
                from table)) as next_id
            , IFNULL(( SELECT max(id)
                from table
                where id < t.id ), (SELECT max(id)
                from table)) as prev_id
        from table as t
        where id = $id";
     }


问:
Issue implementing StateNotifierProvider from Riverpod
I am trying to implement a Cart System using Riverpod to manage the state of the Cart.

This is the part where the user clicks on a product to add it to the cart:

```<code>   GestureDetector(
                      child: Icon(Icons.shopping_cart),
                      onTap: () async {
                        print("cart test");
                        //create new cart item
                        Cart cartItem = new Cart(
                          id: product.id,
                          name: product.name,
                          oldPrice: product.oldPrice,
                          price: product.price,
                          imageUrl: product.imageUrl,
                          category: product.category,
                          quantity: 1
                        );
                        var cartInstance = context.read(cartListProvider);
                        if(isExistsInCart(cartInstance.state,cartItem))
                          context.read(cartListProvider).edit(cartItem,1);
                        else
                          {
                            context.read(cartListProvider).add(cartItem);//if already available in cart, just increase quantity
                            var string = json.encode(context.read(cartListProvider).state);
                            await storage.write(key: cartKey, value: string);

                          }

                      },
                    )
</code>```

Here you have the  provider class:

```<code>import 'package:cart_system_riverpod/models/cart.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final cartListProvider = StateNotifierProvider((ref){

  return CartList([]); //init empty cart

});
</code>```

I have also added ProviderScope to the top of the Widgets tree.

My issue is that I am getting errors implementing:

```<code>cartInstance = context.read(cartListProvider)
</code>```

and

```<code>context.read(cartListProvider).edit(cartItem,1);
</code>```

always at the read(...) part

The editor shows the hint The method 'read' isn't defined for the type 'BuildContext'.

答:
From Riverpod 1.0.0 context.read was removed in favour of ref.read

So replace context.read with ref.read

Try this:

```<code>    Consumer(
      builder: (context, ref, _) {
        return GestureDetector(
          child: Icon(Icons.shopping_cart),
          onTap: () async {
            print("cart test");
            //create new cart item
            Cart cartItem = new Cart(
                id: product.id,
                name: product.name,
                oldPrice: product.oldPrice,
                price: product.price,
                imageUrl: product.imageUrl,
                category: product.category,
                quantity: 1);
            var cartInstance = ref.read(cartListProvider);
            if (isExistsInCart(cartInstance.state, cartItem))
              ref.read(cartListProvider).edit(cartItem, 1);
            else {
              ref.read(cartListProvider).add(
                  cartItem); //if already available in cart, just increase quantity
              var string = json.encode(ref.read(cartListProvider).state);
              await storage.write(key: cartKey, value: string);
            }
          },
        );
      },
    );
</code>```

Check here to read more.

Body:
I am trying to implement a Cart System using Riverpod to manage the state of the Cart.

This is the part where the user clicks on a product to add it to the cart:

   GestureDetector(
                      child: Icon(Icons.shopping_cart),
                      onTap: () async {
                        print("cart test");
                        //create new cart item
                        Cart cartItem = new Cart(
                          id: product.id,
                          name: product.name,
                          oldPrice: product.oldPrice,
                          price: product.price,
                          imageUrl: product.imageUrl,
                          category: product.category,
                          quantity: 1
                        );
                        var cartInstance = context.read(cartListProvider);
                        if(isExistsInCart(cartInstance.state,cartItem))
                          context.read(cartListProvider).edit(cartItem,1);
                        else
                          {
                            context.read(cartListProvider).add(cartItem);//if already available in cart, just increase quantity
                            var string = json.encode(context.read(cartListProvider).state);
                            await storage.write(key: cartKey, value: string);

                          }

                      },
                    )

Here you have the  provider class:

import 'package:cart_system_riverpod/models/cart.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final cartListProvider = StateNotifierProvider((ref){

  return CartList([]); //init empty cart

});

I have also added ProviderScope to the top of the Widgets tree.

My issue is that I am getting errors implementing:

cartInstance = context.read(cartListProvider)

and

context.read(cartListProvider).edit(cartItem,1);

always at the read(...) part

The editor shows the hint The method 'read' isn't defined for the type 'BuildContext'.

Body:
From Riverpod 1.0.0 context.read was removed in favour of ref.read

So replace context.read with ref.read

Try this:

    Consumer(
      builder: (context, ref, _) {
        return GestureDetector(
          child: Icon(Icons.shopping_cart),
          onTap: () async {
            print("cart test");
            //create new cart item
            Cart cartItem = new Cart(
                id: product.id,
                name: product.name,
                oldPrice: product.oldPrice,
                price: product.price,
                imageUrl: product.imageUrl,
                category: product.category,
                quantity: 1);
            var cartInstance = ref.read(cartListProvider);
            if (isExistsInCart(cartInstance.state, cartItem))
              ref.read(cartListProvider).edit(cartItem, 1);
            else {
              ref.read(cartListProvider).add(
                  cartItem); //if already available in cart, just increase quantity
              var string = json.encode(ref.read(cartListProvider).state);
              await storage.write(key: cartKey, value: string);
            }
          },
        );
      },
    );

Check here to read more.


问:
Excel - average on condition whilst changing values

I am trying to calculate the average of values based on various conditions: e.g. "a", but I want the value to be capped at a set value. E.g. say we cap the value column at 1500, it would look like this:

I can do the formula for this quite easily, e.g. using

```<code>=AVERAGE(IF($B$5:$B$8>=1500,1500,$B$5:$B$8))
</code>```

which works. However, I want to repeat this average formula but for the data filtered for subset "a" and subset "b"

so the average on filtered "a" should be (1000+1500)/2 = 1250, and for "b" it will be 1500. Is there any way to do this for a formula?

答:
To do this in one relatively simple-to-understand formula with no helper columns, you can use a (SUMIFS(<cap) + cap*COUNTIFS(>=cap) / COUNTIFS to calculate an average over a capped subset:

```<code>=(SUMIFS(B:B,A:A,"a",B:B,"<1500")+1500*COUNTIFS(A:A,"a",B:B,">=1500"))/COUNTIFS(A:A,"a")
</code>```

This:

sums all B if A = "a" and B < 1500

counts all B if A = "a" and B >= 1500, then multiplies by 1500

adds these together to get the capped totals for B where A = "a"

divides by count of A = "a"

Or to put the threshold in a separate cell, you have to combine it with the condition using &:

```<code>=(SUMIFS(B:B,A:A,"a",B:B,"<"&D5)+D5*COUNTIFS(A:A,"a",B:B,">="&D5))/COUNTIFS(A:A,"a")
</code>```

Excel is gaining LAMBDA and MAP functions - as of Feb 2022 it's in the Office Insiders program - which will probably give a much neater solution when it becomes generally available.

Something like:

```<code>=AVERAGEIF(MAP(B:B,LAMBDA(x, MIN(x,1500)),A:A,"a")
</code>```

If helper columns are an option you can take a simpler approach:

In another column X, put the formula =MIN(@B:B,1500)

Then you can make averages by category:

```<code>=SUMIFS(X:X, A:A, "a") / COUNTIFS(A:A, "a")
=SUMIFS(X:X, A:A, "b") / COUNTIFS(A:A, "b")
</code>```

This column X could be the next free column on your main sheet i.e. column C, another column on that sheet, or a column on a different (maybe hidden) sheet.

Body:
I am trying to calculate the average of values based on various conditions: e.g. "a", but I want the value to be capped at a set value. E.g. say we cap the value column at 1500, it would look like this:

I can do the formula for this quite easily, e.g. using

=AVERAGE(IF($B$5:$B$8>=1500,1500,$B$5:$B$8))

which works. However, I want to repeat this average formula but for the data filtered for subset "a" and subset "b"

so the average on filtered "a" should be (1000+1500)/2 = 1250, and for "b" it will be 1500. Is there any way to do this for a formula?

Body:
To do this in one relatively simple-to-understand formula with no helper columns, you can use a (SUMIFS(<cap) + cap*COUNTIFS(>=cap) / COUNTIFS to calculate an average over a capped subset:

=(SUMIFS(B:B,A:A,"a",B:B,"<1500")+1500*COUNTIFS(A:A,"a",B:B,">=1500"))/COUNTIFS(A:A,"a")

This:

sums all B if A = "a" and B < 1500

counts all B if A = "a" and B >= 1500, then multiplies by 1500

adds these together to get the capped totals for B where A = "a"

divides by count of A = "a"

Or to put the threshold in a separate cell, you have to combine it with the condition using &:

=(SUMIFS(B:B,A:A,"a",B:B,"<"&D5)+D5*COUNTIFS(A:A,"a",B:B,">="&D5))/COUNTIFS(A:A,"a")

Excel is gaining LAMBDA and MAP functions - as of Feb 2022 it's in the Office Insiders program - which will probably give a much neater solution when it becomes generally available.

Something like:

=AVERAGEIF(MAP(B:B,LAMBDA(x, MIN(x,1500)),A:A,"a")

If helper columns are an option you can take a simpler approach:

In another column X, put the formula =MIN(@B:B,1500)

Then you can make averages by category:

=SUMIFS(X:X, A:A, "a") / COUNTIFS(A:A, "a")
=SUMIFS(X:X, A:A, "b") / COUNTIFS(A:A, "b")

This column X could be the next free column on your main sheet i.e. column C, another column on that sheet, or a column on a different (maybe hidden) sheet.


问:
Add data in listbox in multiple columns
recently i came across a userfrom which have list box which shows the sheets name in first column and there property like are they visible or hidden in second columns. but when i tried to access the codes its lock i googled and did every thing to understand how it is done but i didnt found it hope i get my answer here below is mycode which i did i am noob please help me

my code:-

```<code>Private Sub UserForm_Initialize()

Dim ws As Worksheet

ListBox1.ColumnCount = 2
For Each ws In ThisWorkbook.Worksheets

    Me.ListBox1.AddItem ws.Name

Next ws

End Sub
</code>```

答:
There are several possibilities. One of them is:

```<code>Sub ListBoxMitArrayAusTabelleFuellen()
 Dim VarDat As Variant
 Dim lngRowMax As Long

 With Tabelle1

  lngRowMax = .Range("A" & .Rows.Count).End(xlUp).Row
  VarDat = .Range("A2:B" & lngRowMax ).Value

  .ListBox1.ColumnCount = UBound(VarDat, 2)
  .ListBox1.Clear
  .ListBox1.List = VarDat

 End With

End Sub
</code>```

BG
Bernd

Title: Add data in listbox in multiple columns

Body:
recently i came across a userfrom which have list box which shows the sheets name in first column and there property like are they visible or hidden in second columns. but when i tried to access the codes its lock i googled and did every thing to understand how it is done but i didnt found it hope i get my answer here below is mycode which i did i am noob please help me

my code:-

Private Sub UserForm_Initialize()

Dim ws As Worksheet

ListBox1.ColumnCount = 2
For Each ws In ThisWorkbook.Worksheets

    Me.ListBox1.AddItem ws.Name

Next ws

End Sub

Body:
There are several possibilities. One of them is:

Sub ListBoxMitArrayAusTabelleFuellen()
 Dim VarDat As Variant
 Dim lngRowMax As Long

 With Tabelle1

  lngRowMax = .Range("A" & .Rows.Count).End(xlUp).Row
  VarDat = .Range("A2:B" & lngRowMax ).Value

  .ListBox1.ColumnCount = UBound(VarDat, 2)
  .ListBox1.Clear
  .ListBox1.List = VarDat

 End With

End Sub

BG
Bernd


问:
member variable in rails model not set as expected
I have a simple model entity, called "entry" with one field "content" and on save or update I want to process that content.

But in the models' method the member variable @content is nil, in the controller function it's still set.

entries_controller.rb

```<code>   def create
    @entry = Entry.new(params[:entry])

    respond_to do |format|

      if @entry.save
         #@entry.process
         @entry.splitwords
</code>```

entry.rb

```<code>class Entry < ActiveRecord::Base

  def splitwords
    logger.debug "content: #{@content.inspect} "

    words = @content.split(" ")
    ...
</code>```

and that's from the log

```<code>entry: #<Entry id: 6, content: "Air-Berlin-Vorstandschef Joachim Hunold legt sein A...", created_at: "2011-08-18 09:30:52", updated_at: "2011-08-18 09:30:52">
content: nil
</code>```

So why is @content not set inside an entry ??

答:
Your problem is @content, which is indeed not defined in your model. What you want is to call "content" or "self.content" if you want. So your code would be:</p>

```<code>  def splitwords
    logger.debug "content: #{content.inspect} "

    words = content.split(" ")
    ...
</code>```

Body:
I have a simple model entity, called "entry" with one field "content" and on save or update I want to process that content.

But in the models' method the member variable @content is nil, in the controller function it's still set.

entries_controller.rb

   def create
    @entry = Entry.new(params[:entry])

    respond_to do |format|

      if @entry.save
         #@entry.process
         @entry.splitwords

entry.rb

class Entry < ActiveRecord::Base

  def splitwords
    logger.debug "content: #{@content.inspect} "

    words = @content.split(" ")
    ...

and that's from the log

entry: #<Entry id: 6, content: "Air-Berlin-Vorstandschef Joachim Hunold legt sein A...", created_at: "2011-08-18 09:30:52", updated_at: "2011-08-18 09:30:52">
content: nil

So why is @content not set inside an entry ??

Body:
Your problem is @content, which is indeed not defined in your model. What you want is to call "content" or "self.content" if you want. So your code would be:

  def splitwords
    logger.debug "content: #{content.inspect} "

    words = content.split(" ")
    ...


问:
Spring batch job is running automatically on project startup
I've developed spring batch job which gets the data from JDBC. The problem I'm facing, it's executing on project startup regardless of enabled_property. The value of the property is FALSE. I've tried to create a conditional bean on property but it didn't also worked and job is being executed on project startup.

Following the my code snippet.

```<code>@Bean
@ConditionalOnProperty(value = "wallet-manager.djeezyConfig.enableJob" , havingValue = "false")
public Job createJob() {
    return jobBuilderFactory.get("DJeezy wallet cleaner job")
            .incrementer(new RunIdIncrementer())
            .flow(Step1())
            .end()
            .build();
}

@Bean
@ConditionalOnProperty(value = "wallet-manager.djeezyConfig.enableJob" , havingValue = "false")
public Step Step1() {
    return stepBuilderFactory.get("DJeezy wallet cleaner job - step1")
            .<ResellerWallet,ResellerWallet> chunk(wConfig.getDjeezyConfig().getChunkSize())
            .reader(resellerWalletItemReader)
            //.processor(resellerWalletProcessor)
            .writer(resellerWalletItemWriter)
            .faultTolerant()
            .skip(EmptyResultDataAccessException.class)
            .build();
}
</code>```

I've also tried to commented the @Scheduled annotation but it stills executing the job and steps.

//@Scheduled(fixedDelay = 15000)
public void scheduleByFixedRate() throws Exception {

```<code>if(config.getDjeezyConfig().isEnableJob()) {

    System.out.println("Batch job starting");
    JobParameters jobParameters = new JobParametersBuilder()
            .addString("time", format.format(Calendar.getInstance().getTime())).toJobParameters();
    jobLauncher.run(job, jobParameters);
    System.out.println("Batch job executed successfully\n");
}
</code>```

}

Can someone please guide me what I'm missing here? and how can I prevent my job and step being executed on startup.

答:
```<code>spring.batch.job.enabled=false
</code>```

hope you are using this property in your properties file
this should work

Body:
I've developed spring batch job which gets the data from JDBC. The problem I'm facing, it's executing on project startup regardless of enabled_property. The value of the property is FALSE. I've tried to create a conditional bean on property but it didn't also worked and job is being executed on project startup.

Following the my code snippet.

@Bean
@ConditionalOnProperty(value = "wallet-manager.djeezyConfig.enableJob" , havingValue = "false")
public Job createJob() {
    return jobBuilderFactory.get("DJeezy wallet cleaner job")
            .incrementer(new RunIdIncrementer())
            .flow(Step1())
            .end()
            .build();
}

@Bean
@ConditionalOnProperty(value = "wallet-manager.djeezyConfig.enableJob" , havingValue = "false")
public Step Step1() {
    return stepBuilderFactory.get("DJeezy wallet cleaner job - step1")
            .<ResellerWallet,ResellerWallet> chunk(wConfig.getDjeezyConfig().getChunkSize())
            .reader(resellerWalletItemReader)
            //.processor(resellerWalletProcessor)
            .writer(resellerWalletItemWriter)
            .faultTolerant()
            .skip(EmptyResultDataAccessException.class)
            .build();
}

I've also tried to commented the @Scheduled annotation but it stills executing the job and steps.

//@Scheduled(fixedDelay = 15000)
public void scheduleByFixedRate() throws Exception {

if(config.getDjeezyConfig().isEnableJob()) {

    System.out.println("Batch job starting");
    JobParameters jobParameters = new JobParametersBuilder()
            .addString("time", format.format(Calendar.getInstance().getTime())).toJobParameters();
    jobLauncher.run(job, jobParameters);
    System.out.println("Batch job executed successfully\n");
}

}

Can someone please guide me what I'm missing here? and how can I prevent my job and step being executed on startup.

Body:
spring.batch.job.enabled=false

hope you are using this property in your properties file
this should work


问:
Java i18n too much lines
I have a Java program and I'm using i18n

```<code>
public class ListNames extends ListResourceBundle implements ListNamesInterface {

    @Override
    protected Object[][] getContents() {
        return new Object[][] {
               {"ALPHA", "Alpha"},
               [...
           }
}
</code>```

but Eclipse says me this:
The code of method getContents() is exceeding the 65535 bytes limit.

I have understood that the method is too much long, but I cannot know how to split it.

The row number of Object[][] is 100.000 lines.

Have you an idea to do it?

答:
The limit size of a method is 65535 byte, but you can define as many methods as you need to join as a large array. Obviously you could use ArrayList / addAll / toArray in place of System.arraycopy here to build longer arrays:

```<code>protected Object[][] getContents() {
    Object[][] contents1 = getContents1();
    Object[][] contents2 = getContents2();
    // You will need to repeat above many times to make 100,000 rows...

    // Then join up the arrays:
    Object[][] merged = new Object[contents1.length+contents2.length][]; // add more
    System.arraycopy(contents1, 0,merged, 0, contents1.length);
    System.arraycopy(contents2, 0,merged, contents1.length, contents2.length);
    // etc

    return merged;
}
</code>```

Having said that, the above is a terrible way to implement this when property resource bundle files are available to you.

I cannot recall using any JDK or OS combination on which Property bundle did not work effectively, so you have probably not investigated the alternative and much easier solution.

Title: Java i18n too much lines

Body:
I have a Java program and I'm using i18n

public class ListNames extends ListResourceBundle implements ListNamesInterface {

    @Override
    protected Object[][] getContents() {
        return new Object[][] {
               {"ALPHA", "Alpha"},
               [...
           }
}

but Eclipse says me this:
The code of method getContents() is exceeding the 65535 bytes limit.

I have understood that the method is too much long, but I cannot know how to split it.

The row number of Object[][] is 100.000 lines.

Have you an idea to do it?

Body:
The limit size of a method is 65535 byte, but you can define as many methods as you need to join as a large array. Obviously you could use ArrayList / addAll / toArray in place of System.arraycopy here to build longer arrays:

protected Object[][] getContents() {
    Object[][] contents1 = getContents1();
    Object[][] contents2 = getContents2();
    // You will need to repeat above many times to make 100,000 rows...

    // Then join up the arrays:
    Object[][] merged = new Object[contents1.length+contents2.length][]; // add more
    System.arraycopy(contents1, 0,merged, 0, contents1.length);
    System.arraycopy(contents2, 0,merged, contents1.length, contents2.length);
    // etc

    return merged;
}

Having said that, the above is a terrible way to implement this when property resource bundle files are available to you.

I cannot recall using any JDK or OS combination on which Property bundle did not work effectively, so you have probably not investigated the alternative and much easier solution.


问:
How to print complete row from excel Sheet using python pandas from user input?
I asked the same question but it is closed and I am not clear with that answer so I am asking again.

I have an excel file similar to this:

Above is the attached picture to see what the excel sheet looks like.

I am learning to write a program if the user input "Martin" it should displays the entire row.

Still learning the basics. Can someone help me how to display the entire row using user input?

below is the code which is not giving output or error.

```<code>import pandas as pd
import os

student = pd.read_excel("student.xlsx",sheet_name="Sheet1")

i = input("enter store number: ")

found = []

for letter in i:
    if letter in student:
        if letter not in found:
            found.append(letter)
for student in found:
    print(student)
</code>```

答:
Obviously you are trying to a select the rows where your column value = input. This is the best way to do that :)</p>
```<code>import pandas as pd
import os

student = pd.read_excel("student.xlsx",sheet_name="Sheet1")

i = input("enter store number: ")
print(student[student['Name'] == i])
</code>```

Body:
I asked the same question but it is closed and I am not clear with that answer so I am asking again.

I have an excel file similar to this:

Above is the attached picture to see what the excel sheet looks like.

I am learning to write a program if the user input "Martin" it should displays the entire row.

Still learning the basics. Can someone help me how to display the entire row using user input?

below is the code which is not giving output or error.

import pandas as pd
import os

student = pd.read_excel("student.xlsx",sheet_name="Sheet1")

i = input("enter store number: ")

found = []

for letter in i:
    if letter in student:
        if letter not in found:
            found.append(letter)
for student in found:
    print(student)

Body:
Obviously you are trying to a select the rows where your column value = input. This is the best way to do that :)

import pandas as pd
import os

student = pd.read_excel("student.xlsx",sheet_name="Sheet1")

i = input("enter store number: ")
print(student[student['Name'] == i])


问:
Visual Studio Code C/C++ Extension cannot find compiler path
Problem:
The program works but the intellisense doesnt recognize the compiler.

Specifications:
I use wsl. Installed from powershell

What i've tried:
I reinstalled both wsl,gcc and vscode and the c/c++ extension

Some Screenshots:

Gcc location in pc

The actual error

what is causes

答:
If you are using Windows, GCC installed on your virtual machine is independant of your primary OS. It seems GCC is installed on your VM. On Ubuntu/Linux, use the following commands to install a GCC compiler:

sudo apt update

sudo apt install build-essential

Furthermore, Visual Studio is simply a text editor. If you want to compile and execute C/C++ on VS, the simplest way is to compile via Powershell on Windows provided you have GCC installed.


问:
how to get to the key in an array of objects?
I hope you are all well

I would like to ask something that (I hope) is basic,  i have this function that is responsible for returning the filtered objects with a specific "key" variable that translates to color or size.

Well I put the color and size variables inside an array of objects, I would like to know what is the terminology I have to use now in my "item[key]" to be able to get to my "color" variable as shown in the last picture

picture showing what key im able to get now and then what key im looking to get!

Thanks in advance for any and all help, have a nice day!

here is the code for the two functions used in this process:

    const [filtros,setFiltros] = useState({});

    const gerirFiltros = (evento) =>{
    const valor = evento.target.value;
    console.log(evento.target.name + evento.target.value)

    if (evento.target.name === "cor" ) {
      const cor = evento.target.name
      setFiltros( {
        ...filtros,
        ["variacoes"]:[{
          [evento.target.name]:valor
        }],
      })

    }
    else {
    setFiltros({
      ...filtros,
      [evento.target.name]:valor,
    }) // THIS IS JUST TO PASS TO PAGE #2 (https://pastebin.com/4GH3Mi3H) THE VARIABLE `filtros` THAT IS AN ARRAY WITH MANY FILTERS LIKE -> {marca:"Paz rodrigues"}, etc..
```
<p>And the functio that receives the filter ( the one i think i need to change) :</p>
<pre class="lang-js prettyprint-override"><code>     useEffect(() => {

     categoria &&
      setProdutosFiltrados(
        produtos.filter((item) =>
          Object.entries(filtros).every(([key,value],i) =>
          //console.log("key ->" + key + "value->" + value[0].cor)  )
         item[key].includes(value)

          )
        )
      )
</code>```

答:
You can use some()

```<code>useEffect(() => {

 categoria &&
  setProdutosFiltrados(
    produtos.filter((item) =>
      Object.entries(filtros).every(([key,value],i) =>{
        //Here the value is an array 'variacoes' so to check colors use filter to get all the elements of 'variacoes' array;
        //Also assuming that the color you are passing will be available here as item[key]
        var allColors = item.map(i=>i.cor)
        return value.some((val)=>allColors.includes(val.cor))
       }
      )
    )
  )
</code>```

Body:
I hope you are all well

I would like to ask something that (I hope) is basic,  i have this function that is responsible for returning the filtered objects with a specific "key" variable that translates to color or size.

Well I put the color and size variables inside an array of objects, I would like to know what is the terminology I have to use now in my "item[key]" to be able to get to my "color" variable as shown in the last picture

picture showing what key im able to get now and then what key im looking to get!

Thanks in advance for any and all help, have a nice day!

here is the code for the two functions used in this process:

    const [filtros,setFiltros] = useState({});

    const gerirFiltros = (evento) =>{
    const valor = evento.target.value;
    console.log(evento.target.name + evento.target.value)

    if (evento.target.name === "cor" ) {
      const cor = evento.target.name
      setFiltros( {
        ...filtros,
        ["variacoes"]:[{
          [evento.target.name]:valor
        }],
      })

    }
    else {
    setFiltros({
      ...filtros,
      [evento.target.name]:valor,
    }) // THIS IS JUST TO PASS TO PAGE #2 (https://pastebin.com/4GH3Mi3H) THE VARIABLE `filtros` THAT IS AN ARRAY WITH MANY FILTERS LIKE -> {marca:"Paz rodrigues"}, etc..

And the functio that receives the filter ( the one i think i need to change) :

     useEffect(() => {

     categoria &&
      setProdutosFiltrados(
        produtos.filter((item) =>
          Object.entries(filtros).every(([key,value],i) =>
          //console.log("key ->" + key + "value->" + value[0].cor)  )
         item[key].includes(value)

          )
        )
      )

Body:
You can use some()

useEffect(() => {

 categoria &&
  setProdutosFiltrados(
    produtos.filter((item) =>
      Object.entries(filtros).every(([key,value],i) =>{
        //Here the value is an array 'variacoes' so to check colors use filter to get all the elements of 'variacoes' array;
        //Also assuming that the color you are passing will be available here as item[key]
        var allColors = item.map(i=>i.cor)
        return value.some((val)=>allColors.includes(val.cor))
       }
      )
    )
  )


问:
JMH using java 17, no dead code elimination
I run sample JHM benchmark which suppose to show dead code elimination. Code is rewritten for conciseness from jhm github sample.

import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
public class Sample08DeadCode {

    private double x = Math.PI;

    @Benchmark
    public void benchmark() {}

    @Benchmark
    public void measureIncorrect() { Math.log(x); }

    @Benchmark
    public double measureCorrect() { return Math.log(x); }
}
```
<p>Run using JDK 1.8.0_211, Java HotSpot(TM) 64-Bit Server VM, 25.211-b12 produces following results:</p>
```Benchmark                          Mode  Cnt   Score   Error  Units
Sample08DeadCode.benchmark         avgt    5   0,229 ± 0,018  ns/op
Sample08DeadCode.measureCorrect    avgt    5  12,013 ± 0,047  ns/op
Sample08DeadCode.measureIncorrect  avgt    5   0,228 ± 0,016  ns/op
```
<p>but using java JDK 17.0.2, Java HotSpot(TM) 64-Bit Server VM, 17.0.2+8-LTS-86 the results have no sign of dead code elimination:</p>
```Benchmark                          Mode  Cnt  Score   Error  Units
Sample08DeadCode.benchmark         avgt    5  0,341 ± 0,004  ns/op
Sample08DeadCode.measureCorrect    avgt    5  6,244 ± 0,072  ns/op
Sample08DeadCode.measureIncorrect  avgt    5  6,263 ± 0,094  ns/op
```

Why does the measureIncorrect() method is not optimized using java 17?

答:
Those samples depend on JDK internals.

Looks like since JDK 9 and JDK-8152907, Math.log is no longer intrinsified into C2 intermediate representation. Instead, a direct call to a quick LIBM-backed stub is made. This is usually faster for the code that actually uses the result. Notice how measureCorrect is faster in JDK 17 output in your case.

But for JMH samples, it limits the the compiler optimizations around the Math.log, and dead code / folding samples do not work properly. The fix it to make samples that do not rely on JDK internals without a good reason, and instead use a custom written payload.

This is being done in JMH here:

https://bugs.openjdk.java.net/browse/CODETOOLS-7903094

https://github.com/openjdk/jmh/pull/60

Body:
I run sample JHM benchmark which suppose to show dead code elimination. Code is rewritten for conciseness from jhm github sample.

import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
public class Sample08DeadCode {

    private double x = Math.PI;

    @Benchmark
    public void benchmark() {}

    @Benchmark
    public void measureIncorrect() { Math.log(x); }

    @Benchmark
    public double measureCorrect() { return Math.log(x); }
}

Run using JDK 1.8.0_211, Java HotSpot(TM) 64-Bit Server VM, 25.211-b12 produces following results:

Benchmark                          Mode  Cnt   Score   Error  Units
Sample08DeadCode.benchmark         avgt    5   0,229 ± 0,018  ns/op
Sample08DeadCode.measureCorrect    avgt    5  12,013 ± 0,047  ns/op
Sample08DeadCode.measureIncorrect  avgt    5   0,228 ± 0,016  ns/op

but using java JDK 17.0.2, Java HotSpot(TM) 64-Bit Server VM, 17.0.2+8-LTS-86 the results have no sign of dead code elimination:

Benchmark                          Mode  Cnt  Score   Error  Units
Sample08DeadCode.benchmark         avgt    5  0,341 ± 0,004  ns/op
Sample08DeadCode.measureCorrect    avgt    5  6,244 ± 0,072  ns/op
Sample08DeadCode.measureIncorrect  avgt    5  6,263 ± 0,094  ns/op

Why does the measureIncorrect() method is not optimized using java 17?


问:
MonetDB Crashes When Connecting. Will Not Restart. Large Logs
I recently migrated an instance of MonetDB to a machine with a more memory and a larger hard drive by transferring a machine image from one location to another. The database worked briefly but now when attempting to connect with mclient I get the following error:

$ mclient warehouse
user(monetdb):monetdb
password:
monetdbd: internal error while starting mserver 'database 'warehouse' has crashed after starting, manual intervention needed, check monetdbd's logfile (merovingian.log) for details'
```
<p>Upon checking merovingian.log I can see that the database started, but crashed when mclient attempted to connect:</p>
<pre class="lang-sh prettyprint-override"><code>2022-02-09 14:11:29 MSG merovingian[4368]: database 'warehouse' has crashed after start on 2022-02-09 14:03:23, attempting restart, up min/avg/max: 2m/6w/22w, crash average: 1.00 1.00 0.97 (135-6=129)
</code>```

The database then attempts to restart and appears normal until attempting to read through something referred to the write-ahead log.

2022-02-09 14:11:29 MSG warehouse[4403]: arguments:
2022-02-09 14:11:29 MSG warehouse[4403]: /usr/bin/mserver5 --dbpath=/home/db_user/monetDBDatabase/warehouse/warehouse --set merovingian_uri=mapi:monetdb://dev:50000/warehouse --set mapi_listenaddr=none --set mapi_usock=/home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock --set monet_vault_key=/home/db_user/monetDBDatabase/warehouse/warehouse/.vaultkey --set
2022-02-09 14:11:29 MSG warehouse[4403]: gdk_nr_threads=36 --set max_clients=64 --set sql_optimizer=default_pipe
2022-02-09 14:11:40 MSG warehouse[4403]: # MonetDB 5 server v11.39.17 (Oct2020-SP5)
2022-02-09 14:11:40 MSG warehouse[4403]: # Serving database 'warehouse', using 36 threads
2022-02-09 14:11:40 MSG warehouse[4403]: # Compiled for x86_64-pc-linux-gnu/64bit with 128bit integers
2022-02-09 14:11:40 MSG warehouse[4403]: # Found 125.609 GiB available main-memory of which we use 102.371 GiB
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) 1993 - July 2008 CWI.
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) August 2008 - 2021 MonetDB B.V., all rights reserved
2022-02-09 14:11:40 MSG warehouse[4403]: # Visit https://www.monetdb.org/ for further information
2022-02-09 14:11:40 MSG warehouse[4403]: # Listening for UNIX domain connection requests on mapi:monetdb:///home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock
2022-02-09 14:11:40 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (22% done)
2022-02-09 14:11:51 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (44% done)
2022-02-09 14:12:02 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (67% done)
```
<p>This process continues until the system appears to run out of virtual memory as seen in the log extract below:</p>
<pre class="lang-sh prettyprint-override"><code>2022-02-09 14:18:52 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95650" (92% done)
2022-02-09 14:18:56 ERR warehouse[4403]: #main thread: GDKmmap: !ERROR: requested too much virtual memory; memory requested: 43317329920, memory in use: 208390400, virtual memory in use: 4354888091904
</code>```

I've monitored the system throughout this and the memory usage is well within acceptable limits with the most being used about 1GB out of 126GB. What is strange is the size of the files being produced by MonetDB.

The original database was about 5Tb in size, although I can also see that the write-ahead log(s) found in warehouse/sql_logs/sql are 65GB with another file warehouse/mdbtrace.log taking up another 5Tb.

If I try to remove the write-ahead log(s) then the database does not start citing that the files are missing and the same for mdbtrace.log (I can recreate and post the exact messages if required). Other than this I've tried rebooting the machine. I get the impression that the large size of mdbtrace.log is preventing the virtual memory space to read the write-ahead log(s) by using up space that is needed for virtual memory.

Any assistance in solving these errors so that I can start and connect to the database with mclient would be most appreciated.

Regards,

James

答:
As Sjoerd pointed out above the mtrace.log file can be safely removed to make room on a disk. I completed this and got the following error in merovingian.log:

2022-02-09 15:57:08 ERR control[8803]: !monetdbd: an internal error has occurred 'unknown or impossible state: 4'
2022-02-09 15:57:13 ERR merovingian[8803]: client error: unknown or impossible state: 4
```
<p>This caused a shutdown and was solved by rebooting the machine. When attempting to connect with mclient from this point onwards the same errors as in the original post happened with the <code>write-ahead log</code>(s).</p>
<p>On investigation I noticed a file called <code>log</code> in <code>warehouse/sql_logs/sql</code> that had the following structure:</p>
<pre class="lang-sh prettyprint-override"><code>052205

95662
</code>```

Previously the range of the log numbers found in this directory was from 95638 to 95662 and modifying the second number to take a value closer to 95662 caused these write-ahead log(s) to be skipped when mclient attempted to connect to a recently started instance of monetdbd meaning that the virtual memory was not filled and that the client could connect and query the database as normal.

NOTE THAT SOME DATA LOSS WAS OBSERVED AFTER TAKING THIS ACTION

However considering that the alternative would have been deleting 5Tb of data and reloading everything from the original CSV's, a process of several weeks, this solution was welcome. Use at your own risk.

Body:
I recently migrated an instance of MonetDB to a machine with a more memory and a larger hard drive by transferring a machine image from one location to another. The database worked briefly but now when attempting to connect with mclient I get the following error:

$ mclient warehouse
user(monetdb):monetdb
password:
monetdbd: internal error while starting mserver 'database 'warehouse' has crashed after starting, manual intervention needed, check monetdbd's logfile (merovingian.log) for details'

Upon checking merovingian.log I can see that the database started, but crashed when mclient attempted to connect:

2022-02-09 14:11:29 MSG merovingian[4368]: database 'warehouse' has crashed after start on 2022-02-09 14:03:23, attempting restart, up min/avg/max: 2m/6w/22w, crash average: 1.00 1.00 0.97 (135-6=129)

The database then attempts to restart and appears normal until attempting to read through something referred to the write-ahead log.

2022-02-09 14:11:29 MSG warehouse[4403]: arguments:
2022-02-09 14:11:29 MSG warehouse[4403]: /usr/bin/mserver5 --dbpath=/home/db_user/monetDBDatabase/warehouse/warehouse --set merovingian_uri=mapi:monetdb://dev:50000/warehouse --set mapi_listenaddr=none --set mapi_usock=/home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock --set monet_vault_key=/home/db_user/monetDBDatabase/warehouse/warehouse/.vaultkey --set
2022-02-09 14:11:29 MSG warehouse[4403]: gdk_nr_threads=36 --set max_clients=64 --set sql_optimizer=default_pipe
2022-02-09 14:11:40 MSG warehouse[4403]: # MonetDB 5 server v11.39.17 (Oct2020-SP5)
2022-02-09 14:11:40 MSG warehouse[4403]: # Serving database 'warehouse', using 36 threads
2022-02-09 14:11:40 MSG warehouse[4403]: # Compiled for x86_64-pc-linux-gnu/64bit with 128bit integers
2022-02-09 14:11:40 MSG warehouse[4403]: # Found 125.609 GiB available main-memory of which we use 102.371 GiB
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) 1993 - July 2008 CWI.
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) August 2008 - 2021 MonetDB B.V., all rights reserved
2022-02-09 14:11:40 MSG warehouse[4403]: # Visit https://www.monetdb.org/ for further information
2022-02-09 14:11:40 MSG warehouse[4403]: # Listening for UNIX domain connection requests on mapi:monetdb:///home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock
2022-02-09 14:11:40 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (22% done)
2022-02-09 14:11:51 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (44% done)
2022-02-09 14:12:02 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (67% done)

This process continues until the system appears to run out of virtual memory as seen in the log extract below:

2022-02-09 14:18:52 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95650" (92% done)
2022-02-09 14:18:56 ERR warehouse[4403]: #main thread: GDKmmap: !ERROR: requested too much virtual memory; memory requested: 43317329920, memory in use: 208390400, virtual memory in use: 4354888091904

I've monitored the system throughout this and the memory usage is well within acceptable limits with the most being used about 1GB out of 126GB. What is strange is the size of the files being produced by MonetDB.

The original database was about 5Tb in size, although I can also see that the write-ahead log(s) found in warehouse/sql_logs/sql are 65GB with another file warehouse/mdbtrace.log taking up another 5Tb.

If I try to remove the write-ahead log(s) then the database does not start citing that the files are missing and the same for mdbtrace.log (I can recreate and post the exact messages if required). Other than this I've tried rebooting the machine. I get the impression that the large size of mdbtrace.log is preventing the virtual memory space to read the write-ahead log(s) by using up space that is needed for virtual memory.

Any assistance in solving these errors so that I can start and connect to the database with mclient would be most appreciated.

Regards,

James

Body:
As Sjoerd pointed out above the mtrace.log file can be safely removed to make room on a disk. I completed this and got the following error in merovingian.log:

2022-02-09 15:57:08 ERR control[8803]: !monetdbd: an internal error has occurred 'unknown or impossible state: 4'
2022-02-09 15:57:13 ERR merovingian[8803]: client error: unknown or impossible state: 4

This caused a shutdown and was solved by rebooting the machine. When attempting to connect with mclient from this point onwards the same errors as in the original post happened with the write-ahead log(s).

On investigation I noticed a file called log in warehouse/sql_logs/sql that had the following structure:

052205

95662

Previously the range of the log numbers found in this directory was from 95638 to 95662 and modifying the second number to take a value closer to 95662 caused these write-ahead log(s) to be skipped when mclient attempted to connect to a recently started instance of monetdbd meaning that the virtual memory was not filled and that the client could connect and query the database as normal.

NOTE THAT SOME DATA LOSS WAS OBSERVED AFTER TAKING THIS ACTION

However considering that the alternative would have been deleting 5Tb of data and reloading everything from the original CSV's, a process of several weeks, this solution was welcome. Use at your own risk.