问:
Bash, lines of a variable contain substring?
While trying to write a robust bash method that detects whether a variable that consists of multiple lines of text, contains a substring (that may contain spaces) I am experiencing some difficulties. Three functions were written and I wrote some tests for them using the BATS framework. The functions and the accompanying tests on which they fail, are included below.

Method I

```<code>lines_contain_string() {
    local substring="$1"
    shift
    local lines=("$@")

    local found_substring="NOTFOUND"

    for i in "${lines[@]}"; do
        if [[ $i == *"$substring"* ]]; then
            echo "FOUND"
            local found_substring="FOUND"
        fi
    done

    if [ "$found_substring" == "NOTFOUND" ]; then
        echo "NOTFOUND"
    fi
}
</code>```

This fails on test:

```<code>EXAMPLE_LINES=$(cat <<-END
First line
second line
third line
sometoken
END
)

@test "Substring in first line is found in lines by lines_contain_string." {
    contained_substring="First line"

    actual_result=$(lines_contain_string "$contained_substring" "\${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "\${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="FOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}
</code>```

So the first method does not catch all substrings.

Method II

And for the second method:

```<code>lines_contain_string_with_space() {
    local substring="$1"
    local lines="$@"
    if [ "$lines" == "" ]; then
        echo "NOTFOUND"
    # shellcheck disable=SC2154
    elif [[ "$lines" =~ "$substring" ]]; then
        echo "FOUND";
    else
        echo "NOTFOUND";
    fi
}
</code>```

This seems to return false positive/seems to always return "FOUND", for example, on test:

```<code>EXAMPLE_LINES=$(cat <<-END
First line
second line
third line
sometoken
END
)

@test "lines_contain_string returns NOTFOUND on non-existing substring." {
    contained_substring="Non-existing-substring"

    #actual_result=$(lines_contain_string "$contained_substring" "\${EXAMPLE_LINES}")
    actual_result=$(lines_contain_string_with_space "$contained_substring" "\${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="NOTFOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}
</code>```

Method III

This method is provided by choroba:

```<code>string_in_lines() {
    local substring=$1
    shift
    local lines=$1
    if [[ $lines = *"$substring"* ]] ; then
        echo FOUND
    else
        echo NOTFOUND
    fi
}
</code>```

And calling it with test:

```<code>@test "Substring in first line is found in lines by lines_contain_string." {
    contained_substring="First line"

    read -p "EXAMPLE_LINES=$EXAMPLE_LINES"

    #actual_result=$(lines_contain_string "$contained_substring" "\${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "\${EXAMPLE_LINES}")
    actual_result=$(string_in_lines "$contained_substring" "\${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="FOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}
</code>```

Produces output:

```<code> ✗ Substring in first line is found in lines by lines_contain_string.
   (from function `assert_equal' in file test/no_server_required/preserves_server/../../libs/bats-assert/src/assert_equal.bash, line 40,
    in test file test/no_server_required/preserves_server/test_parsing.bats, line 35)
     `assert_equal "$actual_result" "$EXPECTED_OUTPUT"' failed
   EXAMPLE_LINES=First line
   second line
   third line
   sometoken
   -- values do not equal --
   expected : FOUND
   actual   : NOTFOUND
   --
</code>```

Question

How can one echo "FOUND"/"NOTFOUND" in a bash function, based on whether an incoming variable, consisting of multiple lines, contains a substring that may contain spaces? (And test it accordingly.)

Note

Since my tests also fail on the method provided by choroba, which I assume has a large likelihood of being successful, I expect my test functions are not correct. I updated the question accordingly.

The comments by choroba suggested the backslash in: `"${EXAMPLE_LINES}" was incorrect. I tested whether that was incorrect, and it turned out it was incorrect. So the solution was to write the test as:

```<code>@test "Substring in first line is found in lines by lines_contain_string." {
    contained_substring="First line"

    #actual_result=$(lines_contain_string "$contained_substring" "${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "${EXAMPLE_LINES}")
    actual_result=$(string_in_lines "$contained_substring" "${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="FOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}

@test "lines_contain_string returns NOTFOUND on non-existing substring." {
    contained_substring="Non-existing-substring"

    #actual_result=$(lines_contain_string "$contained_substring" "${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "${EXAMPLE_LINES}")
    actual_result=$(string_in_lines "$contained_substring" "${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="NOTFOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}
</code>```

答:
Use = with a wildcard pattern.

string_in_lines() {
    local substring=$1
    shift
    local lines=$1
    if [[ $lines = *"$substring"* ]] ; then
        echo FOUND
    else
        echo NOTFOUND
    fi
}
```

Body:
While trying to write a robust bash method that detects whether a variable that consists of multiple lines of text, contains a substring (that may contain spaces) I am experiencing some difficulties. Three functions were written and I wrote some tests for them using the BATS framework. The functions and the accompanying tests on which they fail, are included below.

Method I

lines_contain_string() {
    local substring="$1"
    shift
    local lines=("$@")

    local found_substring="NOTFOUND"

    for i in "${lines[@]}"; do
        if [[ $i == *"$substring"* ]]; then
            echo "FOUND"
            local found_substring="FOUND"
        fi
    done

    if [ "$found_substring" == "NOTFOUND" ]; then
        echo "NOTFOUND"
    fi
}

This fails on test:

EXAMPLE_LINES=$(cat <<-END
First line
second line
third line
sometoken
END
)

@test "Substring in first line is found in lines by lines_contain_string." {
    contained_substring="First line"

    actual_result=$(lines_contain_string "$contained_substring" "\${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "\${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="FOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}

So the first method does not catch all substrings.

Method II

And for the second method:

lines_contain_string_with_space() {
    local substring="$1"
    local lines="$@"
    if [ "$lines" == "" ]; then
        echo "NOTFOUND"
    # shellcheck disable=SC2154
    elif [[ "$lines" =~ "$substring" ]]; then
        echo "FOUND";
    else
        echo "NOTFOUND";
    fi
}

This seems to return false positive/seems to always return "FOUND", for example, on test:

EXAMPLE_LINES=$(cat <<-END
First line
second line
third line
sometoken
END
)

@test "lines_contain_string returns NOTFOUND on non-existing substring." {
    contained_substring="Non-existing-substring"

    #actual_result=$(lines_contain_string "$contained_substring" "\${EXAMPLE_LINES}")
    actual_result=$(lines_contain_string_with_space "$contained_substring" "\${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="NOTFOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}

Method III

This method is provided by choroba:

string_in_lines() {
    local substring=$1
    shift
    local lines=$1
    if [[ $lines = *"$substring"* ]] ; then
        echo FOUND
    else
        echo NOTFOUND
    fi
}

And calling it with test:

@test "Substring in first line is found in lines by lines_contain_string." {
    contained_substring="First line"

    read -p "EXAMPLE_LINES=$EXAMPLE_LINES"

    #actual_result=$(lines_contain_string "$contained_substring" "\${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "\${EXAMPLE_LINES}")
    actual_result=$(string_in_lines "$contained_substring" "\${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="FOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}

Produces output:

 ✗ Substring in first line is found in lines by lines_contain_string.
   (from function `assert_equal' in file test/no_server_required/preserves_server/../../libs/bats-assert/src/assert_equal.bash, line 40,
    in test file test/no_server_required/preserves_server/test_parsing.bats, line 35)
     `assert_equal "$actual_result" "$EXPECTED_OUTPUT"' failed
   EXAMPLE_LINES=First line
   second line
   third line
   sometoken
   -- values do not equal --
   expected : FOUND
   actual   : NOTFOUND
   --

Question

How can one echo "FOUND"/"NOTFOUND" in a bash function, based on whether an incoming variable, consisting of multiple lines, contains a substring that may contain spaces? (And test it accordingly.)

Note

Since my tests also fail on the method provided by choroba, which I assume has a large likelihood of being successful, I expect my test functions are not correct. I updated the question accordingly.

The comments by choroba suggested the backslash in: `"${EXAMPLE_LINES}" was incorrect. I tested whether that was incorrect, and it turned out it was incorrect. So the solution was to write the test as:

@test "Substring in first line is found in lines by lines_contain_string." {
    contained_substring="First line"

    #actual_result=$(lines_contain_string "$contained_substring" "${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "${EXAMPLE_LINES}")
    actual_result=$(string_in_lines "$contained_substring" "${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="FOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}

@test "lines_contain_string returns NOTFOUND on non-existing substring." {
    contained_substring="Non-existing-substring"

    #actual_result=$(lines_contain_string "$contained_substring" "${EXAMPLE_LINES}")
    #actual_result=$(lines_contain_string_with_space "$contained_substring" "${EXAMPLE_LINES}")
    actual_result=$(string_in_lines "$contained_substring" "${EXAMPLE_LINES}")
    EXPECTED_OUTPUT="NOTFOUND"

    assert_equal "$actual_result" "$EXPECTED_OUTPUT"
}


来源: stackexchange

问:
Error installing existing project dependencies with npm install
Trying to install dependencies for an existing project on my machine where I'm using WSL2 with Ubuntu 20.04. I'm hoping someone can help me understand the problem. Here are what I felt were the most relevant lines from the logs:

```<code>6003 verbose pkgid node-sass@4.14.1
6004 verbose cwd /home/...
6005 verbose Linux 5.10.60.1-microsoft-standard-WSL2
6006 verbose argv "/home/.../.nvm/versions/node/v16.14.0/bin/node" "/home/.../.nvm/versions/node/v16.14.0/bin/npm" "install"
6007 verbose node v16.14.0
6008 verbose npm  v8.5.0
6009 error code 1
6010 error path /home/.../node_modules/node-sass
6011 error command failed
6012 error command sh -c node scripts/build.js
6013 error Building: /home/.../.nvm/versions/node/v16.14.0/bin/node /home/.../node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=

...

6014 error gyp info spawn /usr/bin/python2
6014 error gyp info spawn args [
6014 error gyp info spawn args   '/home/.../node_modules/node-gyp/gyp/gyp_main.py',
6014 error gyp info spawn args   'binding.gyp',
6014 error gyp info spawn args   '-f',
6014 error gyp info spawn args   'make',
6014 error gyp info spawn args   '-I',
6014 error gyp info spawn args   '/home/.../node_modules/node-sass/build/config.gypi',
6014 error gyp info spawn args   '-I',
6014 error gyp info spawn args   '/home/.../node_modules/node-gyp/addon.gypi',
6014 error gyp info spawn args   '-I',
6014 error gyp info spawn args   '/home/.../.node-gyp/16.14.0/include/node/common.gypi',
6014 error gyp info spawn args   '-Dlibrary=shared_library',
6014 error gyp info spawn args   '-Dvisibility=default',
6014 error gyp info spawn args   '-Dnode_root_dir=/home/.../.node-gyp/16.14.0',
6014 error gyp info spawn args   '-Dnode_gyp_dir=/home/.../node_modules/node-gyp',
6014 error gyp info spawn args   '-Dnode_lib_file=/home/.../.node-gyp/16.14.0/<(target_arch)/node.lib',
6014 error gyp info spawn args   '-Dmodule_root_dir=/home/.../node_modules/node-sass',
6014 error gyp info spawn args   '-Dnode_engine=v8',
6014 error gyp info spawn args   '--depth=.',
6014 error gyp info spawn args   '--no-parallel',
6014 error gyp info spawn args   '--generator-output',
6014 error gyp info spawn args   'build',
6014 error gyp info spawn args   '-Goutput_dir=.'
6014 error gyp info spawn args ]
6014 error gyp: Call to 'node -e "require('nan')"' returned exit status 0 while in binding.gyp. while trying to load binding.gyp
6014 error gyp ERR! configure error
6014 error gyp ERR! stack Error: `gyp` failed with exit code: 1
6014 error gyp ERR! stack     at ChildProcess.onCpExit (/home/.../node_modules/node-gyp/lib/configure.js:345:16)
6014 error gyp ERR! stack     at ChildProcess.emit (node:events:520:28)
6014 error gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
6014 error gyp ERR! System Linux 5.10.60.1-microsoft-standard-WSL2
6014 error gyp ERR! command "/home/.../.nvm/versions/node/v16.14.0/bin/node" "/home/.../node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
6014 error gyp ERR! cwd /home/.../node_modules/node-sass
6014 error gyp ERR! node -v v16.14.0
6014 error gyp ERR! node-gyp -v v3.8.0
6014 error gyp ERR! not ok
6014 error Build failed with error code: 1
</code>```

Here are the dev dependencies in my package.json file in case that's helpful.

```<code>    "devDependencies": {
        "@babel/cli": "^7.12.8",
        "@babel/core": "^7.12.9",
        "@babel/preset-env": "^7.12.7",
        "archiver": "^5.1.0",
        "autoprefixer": "^10.0.2",
        "axios": "^0.21.1",
        "bootstrap": "^4.6.0",
        "browser-sync": "^2.26.14",
        "browser-sync-webpack-plugin": "^2.0.1",
        "clean-css-cli": "^4.3.0",
        "cross-env": "^7.0",
        "csvjson": "^5.1.0",
        "eslint": "^7.14.0",
        "eslint-config-standard": "^16.0.2",
        "eslint-plugin-import": "^2.22.1",
        "eslint-plugin-node": "^11.1.0",
        "eslint-plugin-promise": "^4.2.1",
        "eslint-plugin-standard": "^5.0.0",
        "express": "^4.17.1",
        "express-handlebars": "^5.2.0",
        "glob": "^7.1.6",
        "handlebars": "^4.7.6",
        "jquery": "^3.2",
        "karma": "^5.2.3",
        "karma-chrome-launcher": "^3.1.0",
        "karma-qunit": "^4.1.1",
        "karma-viewport": "^1.0.7",
        "laravel-mix": "^5.0.1",
        "lodash": "^4.17.19",
        "node-sass": "^4.14.1",
        "npm-run-all": "^4.1.5",
        "pkg-dir": "^5.0.0",
        "popper.js": "^1.12",
        "postcss": "^8.1.10",
        "postcss-cli": "^8.3.0",
        "postcss-loader": "^3.0.0",
        "pretty": "^2.0.0",
        "qunit": "^2.12.0",
        "relative": "^3.0.2",
        "resolve": "^1.19.0",
        "resolve-pkg": "^2.0.0",
        "resolve-url-loader": "^3.1.0",
        "rollup": "^2.33.3",
        "rollup-plugin-babel": "^4.4.0",
        "rtlcss": "^2.6.1",
        "sass": "^1.32.0",
        "sass-loader": "^8.0.0",
        "uglify-js": "^3.12.0",
        "vue-template-compiler": "^2.6.12",
        "xtend": "^4.0.2"
    }
}
</code>```

I deleted my node_modules folder and ran npm install and I get this:

```<code>npm ERR! /home/.../.node-gyp/16.14.0/include/node/v8-internal.h: In function ‘void v8::internal::PerformCastCheck(T*)’:
npm ERR! /home/.../.node-gyp/16.14.0/include/node/v8-internal.h:492:38: error: ‘remove_cv_t’ is not a member of ‘std’; did you mean ‘remove_cv’?
npm ERR!   492 |             !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!       |                                      ^~~~~~~~~~~
npm ERR!       |                                      remove_cv
</code>```

答: I found this SO answer: https://stackoverflow.com/a/54507679/4113027, created the .nvmrc file with version 14.19.0, then ran nvm use. Once I did that I was able to install the dependencies.

ContentLicense: CC BY-SA 4.0

Body:
Trying to install dependencies for an existing project on my machine where I'm using WSL2 with Ubuntu 20.04. I'm hoping someone can help me understand the problem. Here are what I felt were the most relevant lines from the logs:

6003 verbose pkgid node-sass@4.14.1
6004 verbose cwd /home/...
6005 verbose Linux 5.10.60.1-microsoft-standard-WSL2
6006 verbose argv "/home/.../.nvm/versions/node/v16.14.0/bin/node" "/home/.../.nvm/versions/node/v16.14.0/bin/npm" "install"
6007 verbose node v16.14.0
6008 verbose npm  v8.5.0
6009 error code 1
6010 error path /home/.../node_modules/node-sass
6011 error command failed
6012 error command sh -c node scripts/build.js
6013 error Building: /home/.../.nvm/versions/node/v16.14.0/bin/node /home/.../node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=

...

6014 error gyp info spawn /usr/bin/python2
6014 error gyp info spawn args [
6014 error gyp info spawn args   '/home/.../node_modules/node-gyp/gyp/gyp_main.py',
6014 error gyp info spawn args   'binding.gyp',
6014 error gyp info spawn args   '-f',
6014 error gyp info spawn args   'make',
6014 error gyp info spawn args   '-I',
6014 error gyp info spawn args   '/home/.../node_modules/node-sass/build/config.gypi',
6014 error gyp info spawn args   '-I',
6014 error gyp info spawn args   '/home/.../node_modules/node-gyp/addon.gypi',
6014 error gyp info spawn args   '-I',
6014 error gyp info spawn args   '/home/.../.node-gyp/16.14.0/include/node/common.gypi',
6014 error gyp info spawn args   '-Dlibrary=shared_library',
6014 error gyp info spawn args   '-Dvisibility=default',
6014 error gyp info spawn args   '-Dnode_root_dir=/home/.../.node-gyp/16.14.0',
6014 error gyp info spawn args   '-Dnode_gyp_dir=/home/.../node_modules/node-gyp',
6014 error gyp info spawn args   '-Dnode_lib_file=/home/.../.node-gyp/16.14.0/<(target_arch)/node.lib',
6014 error gyp info spawn args   '-Dmodule_root_dir=/home/.../node_modules/node-sass',
6014 error gyp info spawn args   '-Dnode_engine=v8',
6014 error gyp info spawn args   '--depth=.',
6014 error gyp info spawn args   '--no-parallel',
6014 error gyp info spawn args   '--generator-output',
6014 error gyp info spawn args   'build',
6014 error gyp info spawn args   '-Goutput_dir=.'
6014 error gyp info spawn args ]
6014 error gyp: Call to 'node -e "require('nan')"' returned exit status 0 while in binding.gyp. while trying to load binding.gyp
6014 error gyp ERR! configure error
6014 error gyp ERR! stack Error: `gyp` failed with exit code: 1
6014 error gyp ERR! stack     at ChildProcess.onCpExit (/home/.../node_modules/node-gyp/lib/configure.js:345:16)
6014 error gyp ERR! stack     at ChildProcess.emit (node:events:520:28)
6014 error gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
6014 error gyp ERR! System Linux 5.10.60.1-microsoft-standard-WSL2
6014 error gyp ERR! command "/home/.../.nvm/versions/node/v16.14.0/bin/node" "/home/.../node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
6014 error gyp ERR! cwd /home/.../node_modules/node-sass
6014 error gyp ERR! node -v v16.14.0
6014 error gyp ERR! node-gyp -v v3.8.0
6014 error gyp ERR! not ok
6014 error Build failed with error code: 1

Here are the dev dependencies in my package.json file in case that's helpful.

    "devDependencies": {
        "@babel/cli": "^7.12.8",
        "@babel/core": "^7.12.9",
        "@babel/preset-env": "^7.12.7",
        "archiver": "^5.1.0",
        "autoprefixer": "^10.0.2",
        "axios": "^0.21.1",
        "bootstrap": "^4.6.0",
        "browser-sync": "^2.26.14",
        "browser-sync-webpack-plugin": "^2.0.1",
        "clean-css-cli": "^4.3.0",
        "cross-env": "^7.0",
        "csvjson": "^5.1.0",
        "eslint": "^7.14.0",
        "eslint-config-standard": "^16.0.2",
        "eslint-plugin-import": "^2.22.1",
        "eslint-plugin-node": "^11.1.0",
        "eslint-plugin-promise": "^4.2.1",
        "eslint-plugin-standard": "^5.0.0",
        "express": "^4.17.1",
        "express-handlebars": "^5.2.0",
        "glob": "^7.1.6",
        "handlebars": "^4.7.6",
        "jquery": "^3.2",
        "karma": "^5.2.3",
        "karma-chrome-launcher": "^3.1.0",
        "karma-qunit": "^4.1.1",
        "karma-viewport": "^1.0.7",
        "laravel-mix": "^5.0.1",
        "lodash": "^4.17.19",
        "node-sass": "^4.14.1",
        "npm-run-all": "^4.1.5",
        "pkg-dir": "^5.0.0",
        "popper.js": "^1.12",
        "postcss": "^8.1.10",
        "postcss-cli": "^8.3.0",
        "postcss-loader": "^3.0.0",
        "pretty": "^2.0.0",
        "qunit": "^2.12.0",
        "relative": "^3.0.2",
        "resolve": "^1.19.0",
        "resolve-pkg": "^2.0.0",
        "resolve-url-loader": "^3.1.0",
        "rollup": "^2.33.3",
        "rollup-plugin-babel": "^4.4.0",
        "rtlcss": "^2.6.1",
        "sass": "^1.32.0",
        "sass-loader": "^8.0.0",
        "uglify-js": "^3.12.0",
        "vue-template-compiler": "^2.6.12",
        "xtend": "^4.0.2"
    }
}

I deleted my node_modules folder and ran npm install and I get this:

npm ERR! /home/.../.node-gyp/16.14.0/include/node/v8-internal.h: In function ‘void v8::internal::PerformCastCheck(T*)’:
npm ERR! /home/.../.node-gyp/16.14.0/include/node/v8-internal.h:492:38: error: ‘remove_cv_t’ is not a member of ‘std’; did you mean ‘remove_cv’?
npm ERR!   492 |             !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!       |                                      ^~~~~~~~~~~
npm ERR!       |                                      remove_cv


问:
Nifi, how to produce via Kafka avro files with multiple records each file
I created a pipeline that handles a single json file (a vector of 5890 elements, each a record) and send it via Kafka in avro format. The producer works fine, then when I read it with a consumer I get a flowfile (a avro file) each record. 5890 avro files. How can I set or merge more records in a single avro file?

I simply use a PublishKafkaRecord_0_10 1.5.0 (jsonTreeReader 1.5.0 and AvroRecordSetWriter 1.5.0) and ConsumeKafka_0_10 1.5.0 .

答:
Firstly, NiFi 1.5.0 is from January 2018. Please consider upgrading as this is terribly out of date. NiFi 1.15.3 is the latest as of today.

Secondly, the *Kafka_0_10 processors are geared at very old versions of Kafka - are you really using v0.10 of Kafka? You have the following processors for later Kafka versions:

*Kafka_1.0 for Kafka 1.0+

*Kafka_2.0 for Kafka 2.0+

*Kafka_2.6 for Kafka 2.6+.

It would be useful if you provide examples of your input and desired output and what you are actually trying to achieve.

If you are looking to consume those message in NiFi and you want a single FlowFile with many messages, you should use ConsumeKafkaRecord rather than ConsumeKafka. This will let you control how many records you'd like to see per 'file'.

If your consumer is not NiFi, then either they need to merge on their end, or you need to bundle all your records into one larger message when producing. However, this is not really the point of Kafka as it's not geared towards large messages/files.


问:
Why Picker not filled with data from json web api - Xamarin
I trying to fill a picker with json data from web api

```<code> <Picker x:Name="picker"
        Title="Изберете станция"
        TitleColor="Black">
        </Picker>
</code>```

In c# file:

```<code>public async Task FillStation_HQ_AHSAsync()
    {
        var result = await _restServiceStations.Get_HQ_AHS(Constants.EndPoint);

        foreach (var item in result)
        {
            var stationsList = new List<string>();
            stationsList.Add(item.ToString());
            picker.ItemsSource = stationsList;
        }
    }
</code>```

So result have more than 200 items with two properties: "Station" and "Ime".. but when I click on the picker he is empty..

答:
the logic for building your list is bad</p>
```<code>var stationsList = new List<string>();

foreach (var item in result)
{
    stationsList.Add(item.ToString());
}

picker.ItemsSource = stationsList;

</code>```

Body:
I trying to fill a picker with json data from web api

 <Picker x:Name="picker"
        Title="Изберете станция"
        TitleColor="Black">
        </Picker>

In c# file:

public async Task FillStation_HQ_AHSAsync()
    {
        var result = await _restServiceStations.Get_HQ_AHS(Constants.EndPoint);

        foreach (var item in result)
        {
            var stationsList = new List<string>();
            stationsList.Add(item.ToString());
            picker.ItemsSource = stationsList;
        }
    }

So result have more than 200 items with two properties: "Station" and "Ime".. but when I click on the picker he is empty..

Body:
the logic for building your list is bad

var stationsList = new List<string>();

foreach (var item in result)
{
    stationsList.Add(item.ToString());
}

picker.ItemsSource = stationsList;


问:
How to create a login, logout, signin system in html
I searched everywhere but I couldn't get a way to create a login logout system, Most of it has how to create a login system UI but not the backend javascript, I want a login logout system like many websites do we can create an account.</p>

答:
There are a several ways to create a Auth system in web application.

One of the simple ones without a server is usage of Firebase.

You can find the docs here : https://firebase.google.com/

Or If you need a back-end to do all your needs there are another third-party applications such Auth0 and more

Hope you find this helpful.


问:
How to filter objects based on given condition in JavaScript?
I'm new to this community and just started programming I couldn't find anything about this topic can anyone please solve this.
I need to filter names who's each points in array above 75.
i have tried this and unable iterate over an array.

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=[]
  for(let object of candidatesList){
      if (candidatesList.every(candidatesList.points>75)){
         arrayOfSelecetedCandidates.push(candidatesList.name)
      }
  }
  console.log(arrayOfSelecetedCandidates);```

答:
You can achieve this by using Array.filter() method along with Array.every() to test whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Working Demo :

const candidatesList = [{
    'name': 'Blake Hodges',
    'points': [76, 98, 88, 84]
}, {
    'name': 'James Anderson',
    'points': [0, 98, 12, 13]
}];

let res = candidatesList.filter((obj) => {
    return obj.points.every((item) => item > 75)
});

console.log(res);```


问:
Calculate difference between min and max for each Pandas group
I want to calculate difference between max and min value for each group in pandas dataframe.
For example, I wrote a code that calculates standard deviation for each group.

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

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

print(df)

df = df.groupby('Month')[['values_1', 'values_2']].std().round(2)
df = df.reset_index(drop = False)
print(df)
</code>```

Result looks like this:

```<code>    Month  values_1  values_2
0   Feb      2.94      1.63
1   Jan      2.87      1.26
2   Mar      4.27      0.50
</code>```

Now I want to modify the code so that I get the same type/looks of the result, but with max-min values instead of standard deviation.

答:
To get the difference between max and min for each group, try:

import pandas as pd

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

def process(s):
  return s.max() - s.min()
df = process(df.groupby('Month')[['values_1', 'values_2']])
df = df.reset_index(drop = False)
```
```  Month  values_1  values_2
0   Feb         6         4
1   Jan         6         3
2   Mar        10         1
```
<p>Or simply:</p>
```df = df.groupby('Month')[['values_1', 'values_2']].apply(lambda g: g.max() - g.min())
```

Body:
I want to calculate difference between max and min value for each group in pandas dataframe.
For example, I wrote a code that calculates standard deviation for each group.

import pandas as pd
import statistics

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

print(df)

df = df.groupby('Month')[['values_1', 'values_2']].std().round(2)
df = df.reset_index(drop = False)
print(df)

Result looks like this:

    Month  values_1  values_2
0   Feb      2.94      1.63
1   Jan      2.87      1.26
2   Mar      4.27      0.50

Now I want to modify the code so that I get the same type/looks of the result, but with max-min values instead of standard deviation.

Body:
To get the difference between max and min for each group, try:

import pandas as pd

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

def process(s):
  return s.max() - s.min()
df = process(df.groupby('Month')[['values_1', 'values_2']])
df = df.reset_index(drop = False)

  Month  values_1  values_2
0   Feb         6         4
1   Jan         6         3
2   Mar        10         1

Or simply:

df = df.groupby('Month')[['values_1', 'values_2']].apply(lambda g: g.max() - g.min())


问:
Android firestore using "whereTo()" many times causes cost a lot?
I am making a function to classify by user's region and MBTI.

Here is a code.

```<code>private void EventChangeListener() {
    //firestore.collection("Users").orderBy("time",Query.Direction.DESCENDING).limit(50)
    firestore.collection("Users").orderBy("time",Query.Direction.DESCENDING).limit(50)
            .whereEqualTo("gender","여자")
            .whereEqualTo("mbti","ENTP")
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                    if(error != null){

                        if(progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }

                        Log.e("Firestore error",error.getMessage());
                        return;

                    }

                    for (DocumentChange dc : value.getDocumentChanges()){

                        if (dc.getType() == DocumentChange.Type.ADDED){
                            userArrayList.add(dc.getDocument().toObject(User.class));
                        }

                        myAdapter.notifyDataSetChanged();
                        if(progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                    }

                }
            });
}
</code>```

Like this whereEqualTo().whereEqualTo().whereEqualTo() causes a lot cost??

If It is right, then is there any other way?

答:
You are charged for number of documents that match your query and are returned. Number of query clauses do not affect cost. Using more filters like whereEqualTo().whereEqualTo().whereEqualTo() will ideally reduce number of matches and cost less.

For example, if you have a collection of 50 restaurants and you use 1 whereEqualTo on 'city' field then it'll return and cost N only for restaurants that are present in that city. If you add another whereEqualTo on 'ratings' then number of matches might be even less than N.

Body:
I am making a function to classify by user's region and MBTI.

Here is a code.

private void EventChangeListener() {
    //firestore.collection("Users").orderBy("time",Query.Direction.DESCENDING).limit(50)
    firestore.collection("Users").orderBy("time",Query.Direction.DESCENDING).limit(50)
            .whereEqualTo("gender","여자")
            .whereEqualTo("mbti","ENTP")
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                    if(error != null){

                        if(progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }

                        Log.e("Firestore error",error.getMessage());
                        return;

                    }

                    for (DocumentChange dc : value.getDocumentChanges()){

                        if (dc.getType() == DocumentChange.Type.ADDED){
                            userArrayList.add(dc.getDocument().toObject(User.class));
                        }

                        myAdapter.notifyDataSetChanged();
                        if(progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                    }

                }
            });
}

Like this whereEqualTo().whereEqualTo().whereEqualTo() causes a lot cost??

If It is right, then is there any other way?


问:
help with event click
I'm developing a html with this structure

```<code>div id="menuContainer">
    <div class = "menu ui-accordion-header ui-state-default ui-corner-all">
        <label class="formatText">Cliente</label><span class="ui-icon ui-icon-triangle-1-e menuIcon" style="float: right"></span>
            <div class = "subMenu ui-accordion-header ui-state-default ui-corner-all">
                <ul class="options">
                    <li>
                        <label class="formatText">Ver Cliente</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                <ul class="options">
                                    <li>
                                        <label class="formatText">Por Nombre</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                                <ul class="options">
                                                    <li><label class="formatText">sub sub menu</label></li>
                                                    <li><label class="formatText">prueba</label></li>
                                                </ul>
                                            </div>
                                    </li>
                                    <li>
                                        <label class="formatText">Por Campana</label>
                                    </li>
                                </ul>
                            </div>
                    </li>
                    <li>
                        <label class="formatText">Reportes para Cliente</label>
                    </li>
                </ul>
            </div>
    </div>
</div>
</code>```

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

```<code>$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});
</code>```

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??

答:
```<code>$('#menuContainer')
    .delegate('.menu', 'click', function() {
        alert(1);
        return false;
    })
    .delegate('.subMenu li', 'click', function() {
        alert(2);
        return false;
    })
    .delegate('.subMenuRight li', 'click', function() {
        alert(3);
        return false; // this stops triggering events on parent els
    })
</code>```

ContentLicense: CC BY-SA 3.0

Title: help with event click

Body:
I'm developing a html with this structure

div id="menuContainer">

        Cliente

                        Ver Cliente

                                        Por Nombre

sub sub menu

prueba

                                        Por Campana

                        Reportes para Cliente

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??


问:
Promise support for Chrome Extensions API?
I've been writing some browser extensions in the last few weeks and until today I thought that a WebExtension for Firefox should work pretty much automatically in Chrome. So I tried to write my code according to Mozilla's examples.

But today I realized that there is no mention of Promises in the API documentation for Chrome Extensions.

I have strictly used Promises throughout the code for all my Extensions.

So now my question is, will my code work in Chrome? Or would it work if I add a var browser = chrome declaration at the very top?

Or does Chrome not support Promises on the API at all?

If Chrome doesn't support Promises on the API functions yet, will it support them in the future?

Note, I am aware of this project: https://github.com/mozilla/webextension-polyfill

But I'm not willing to go through the hassle of including that library everywhere. Also, it has annoying bugs in it.

And besides that I don't have Chrome or Chromium and I can't install them for privacy and security reasons.

Edit: They're finally starting to implement support for promises.

答:
My approach on Spellbook has been to turn the necessary methods to return promises and check chrome.runtime.lastError on a wrapped callback.

But now I just go through all suitable chrome API methods, and turn them into promise based methods with the above approach.

Here is a relevant commit on Spellbook.

I am planning to extract this into a small library called Rosegarden, because Mozilla's webextension-polyfill seems too complicated...


问:
Move multiple-choice cursors back and forth on multiple lines in Notepad++
In notepad++, when I do a multiple choice, for example "characters" string, I want to move the cursor back and forth to modify the content on multiple lines. However, the cursor only focuses on the last selection, e.g. "characters" string at Line 6.

Does anyone know how to do this action by the same way Sublime Text can do ?

Or Is any notepad++ plugin able to do this action ?

答:
At least you can go back and forward word by word once. I dont know multiple words at a time.

Backward: CTRL+Left arrow.
Forward: CTRL+Right arrow.


问:
Google Cloud Managed Instances Group: Slow autoscaling based on pub-sub num_undelivered_messages
I've setup autoscaling for a MIG based on pub-sub queue size:

```<code>gcloud compute instance-groups managed set-autoscaling my-group \
  --zone=us-central1-a \
  --max-num-replicas=10 \
  --min-num-replicas=0 \
  --update-stackdriver-metric=pubsub.googleapis.com/subscription/num_undelivered_messages \
  --stackdriver-metric-filter="resource.type = pubsub_subscription AND resource.labels.subscription_id = my_subscription" \
  --stackdriver-metric-single-instance-assignment=10
</code>```

I notice that scaling down takes significant time AFTER the num_undelivered_messages reaches 0. Last time I checked it took 16 minutes since the moment when the last message has been acked before the MIG finally scaled down to 0.

How do I decrease it to ~60 seconds?

答:
If we look at the following article link, we see that scaling in (by default) doesn't occur until the signal that caused the scale out has ceased 10 minutes ago.  I read this as:

If at 9:00am your signal (pub/sub) was breached then assuming the condition is no longer present immediately, scale in won't happen until at least 9:10am.

I seem to see that the scaling in looks for the signal in the last 10 minute window.  Given also that you are looking a GCP monitoring metrics and these don't get updated in real time but instead have latencies, even though the trigger may no longer be present immediately, it may be 9:05am before monitoring reports all is now well.  This means it might be 9:15am (9:05am + 10 minutes) before scale in occurs.

Looking at the docs again, we seem to see that we can change the scale-in policy using the --scale-in-control flag of gcloud.  See scale-in-control flag documentation. Looking closely, it has a parameter called time-window that is documented as:

How long back autoscaling should look when computing recommendations. The autoscaler will not resize below the maximum allowed deduction subtracted from the peak size observed in this period. Measured in seconds.

This seems to allow us to over-ride the default 10 minutes period.

Body:
I've setup autoscaling for a MIG based on pub-sub queue size:

gcloud compute instance-groups managed set-autoscaling my-group \
  --zone=us-central1-a \
  --max-num-replicas=10 \
  --min-num-replicas=0 \
  --update-stackdriver-metric=pubsub.googleapis.com/subscription/num_undelivered_messages \
  --stackdriver-metric-filter="resource.type = pubsub_subscription AND resource.labels.subscription_id = my_subscription" \
  --stackdriver-metric-single-instance-assignment=10

I notice that scaling down takes significant time AFTER the num_undelivered_messages reaches 0. Last time I checked it took 16 minutes since the moment when the last message has been acked before the MIG finally scaled down to 0.

How do I decrease it to ~60 seconds?


问:
Call Githooks as standalone scripts
I've been given a git pre-push hook to include in some checking inside a VS Code extension.

The request made to me was to run this hook against some code, but not actually push anything, just return the result.

The file I've been given has no file type from what I can tell, so my question is --- In theory couldn't I just copy this as a separate file and make it a .sh script, and then call it with whatever arguments it accepts (in this case two)?

答:
Call Githooks as standalone scripts

This will be officially supported with Git 2.36 (Q2 2022):

```<code>git hook run [--ignore-missing] <hook-name> [-- <hook-args>]
</code>```

See commit 95ba86a, commit 306f445, commit dbb1c61, commit f443246, commit 0c8ac06, commit a755530, commit 1a3017d, commit 72ddf34, commit 67ad630, commit 432a50b, commit 25d4e02, commit 593ffdd, commit bad62a8, commit 96e7225 (22 Dec 2021) by Emily Shaffer (nasamuffin).

See commit 0d3979c, commit ab81cf2, commit 474c119 (22 Dec 2021) by Ævar Arnfjörð Bjarmason (avar).

(Merged by Junio C Hamano -- gitster -- in commit c70bc33, 09 Feb 2022)

hook: add 'run' subcommand

Signed-off-by: Emily Shaffer

Signed-off-by: Ævar Arnfjörð Bjarmason

Acked-by: Emily Shaffer

In order to enable hooks to be run as an external process, by a standalone Git command, or by tools which wrap Git, provide an external means to run all configured hook commands for a given hook event.

Most of our hooks require more complex functionality than this, but let's start with the bare minimum required to support our simplest hooks.

In terms of implementation the usage_with_options() and "goto usage" pattern here mirrors that of builtin/{commit-graph,multi-pack-index}.c.

Some of the implementation here, such as a function being named run_hooks_opt() when it's tasked with running one hook, to using the run_processes_parallel_tr2() API to run with jobs=1 is somewhere between a bit odd and and an overkill for the current features of this "hook run" command and the hook.[ch] API.

This code will eventually be able to run multiple hooks declared in config in parallel, by starting out with these names and APIs we reduce the later churn of renaming functions, switching from the run_command() to run_processes_parallel_tr2() API etc.

git hook now includes in its man page:

git-hook(1)

NAME

git-hook - Run git hooks

SYNOPSIS

[verse]

```<code> 'git hook' run <hook-name> [-- <hook-args>]
</code>```

DESCRIPTION

A command interface to running git hooks (see linkgit:githooks[5]),
for use by other scripted git commands.

SUBCOMMANDS

run

Run the <hook-name> hook.

Any positional arguments to the hook should be passed after a
mandatory -- (or --end-of-options).

And:

git hook run: add an --ignore-missing flag

Signed-off-by: Ævar Arnfjörð Bjarmason

Reviewed-by: Emily Shaffer

For certain one-shot hooks we'd like to optimistically run them, and not complain if they don't exist.

This was already supported by the underlying hook.c library, but had not been exposed via "git hook"(man) run".

The command version of this will be used by send-email in a subsequent commit.

git hook now includes in its man page:

```<code>'git hook' run [--ignore-missing] <hook-name> [-- <hook-args>]
</code>```

git hook now includes in its man page:

OPTIONS

--ignore-missing

Ignore any missing hook by quietly returning zero.

Used for
tools that want to do a blind one-shot run of a hook that may
or may not be present.

Warning: in Git 2.36 we revamped the way how hooks are invoked.

One change that is end-user visible is that the output of a hook is no longer directly connected to the standard output of "git" that spawns the hook, which was noticed post release.

This is getting corrected with Git 2.37 (Q3 2022).

See commit a082345, commit fd3aaf5 (07 Jun 2022) by Ævar Arnfjörð Bjarmason (avar).

(Merged by Junio C Hamano -- gitster -- in commit 1a7f6be, 13 Jun 2022)

hook API: fix v2.36.0 regression: hooks should be connected to a TTY

Reported-by: Anthony Sottile

Signed-off-by: Ævar Arnfjörð Bjarmason

Fix a regression reported against f443246 (commit: convert {pre-commit, 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) (commit: convert {pre-commit,prepare-commit-msg} hook to hook.h, 2021-12-22): Due to using the run_process_parallel() API in the earlier 96e7225 ("hook: add 'run' subcommand", 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) we'd capture the hook's stderr and stdout, and thus lose the connection to the TTY in the case of e.g. the "pre-commit" hook.

As a preceding commit notes GNU parallel's similar --ungroup option also has it emit output faster.

While we're unlikely to have hooks that emit truly massive amounts of output (or where the performance thereof matters) it's still informative to measure the overhead.

In a similar "seq" test we're now ~30% faster:

```<code>$ cat .git/hooks/seq-hook; git hyperfine -L rev origin/master,HEAD~0 -s 'make CFLAGS=-O3' './git hook run seq-hook'
#!/bin/sh

seq 100000000
Benchmark 1: ./git hook run seq-hook' in 'origin/master
  Time (mean ± σ):     787.1 ms ±  13.6 ms    [User: 701.6 ms, System: 534.4 ms]
  Range (min … max):   773.2 ms … 806.3 ms    10 runs

Benchmark 2: ./git hook run seq-hook' in 'HEAD~0
  Time (mean ± σ):     603.4 ms ±   1.6 ms    [User: 573.1 ms, System: 30.3 ms]
  Range (min … max):   601.0 ms … 606.2 ms    10 runs

Summary
  './git hook run seq-hook' in 'HEAD~0' ran
    1.30 ± 0.02 times faster than './git hook run seq-hook' in 'origin/master'
</code>```

Git 2.37.3 (Q3 2022) adds a follow-up fix to a fix for a regression in 2.36.

See commit 99ddc24 (05 Aug 2022) by Ævar Arnfjörð Bjarmason (avar).

(Merged by Junio C Hamano -- gitster -- in commit d86ac14, 14 Aug 2022)

hook API: don't segfault on strbuf_addf() to NULL "out"

Reported-by: Ilya K

Signed-off-by: Ævar Arnfjörð Bjarmason

Reviewed-by: Emily Shaffer

Reviewed-by: Đoàn Trần Công Danh

Fix a logic error in a082345 ("hook API: fix v2.36.0 regression: hooks should be connected to a TTY", 2022-06-07, Git v2.37.0-rc0 -- merge).

When it started using the "ungroup" API added in fd3aaf5 (run-command: add an , 2022-06-07, Git v2.37.0-rc0 -- merge) (run-command: add an "ungroup" option to run_process_parallel(), 2022-06-07) it should have made the same sort of change that fd3aaf5 itself made in "t/helper/test-run-command.c".

The correct way to emit this "Couldn't start" output with "ungroup" would be:

```<code>fprintf(stderr, _("Couldn't start hook '%s'\n"), hook_path);
</code>```

But we should instead remove the emitting of this output.

The "cannot run" output here is emitted by run-command.c's child_err_spew().

So the addition of the "Couldn't start hook" output here in 96e7225 ("hook: add 'run' subcommand", 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) was always redundant.

For the pre-commit hook we'll now emit exactly the same output as we did before f443246 (commit: convert {pre-commit, 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) (commit: convert {pre-commit,prepare-commit-msg} hook to hook.h, 2021-12-22) (and likewise for others).

Title: Call Githooks as standalone scripts

Body:
Call Githooks as standalone scripts

This will be officially supported with Git 2.36 (Q2 2022):

git hook run [--ignore-missing] <hook-name> [-- <hook-args>]

See commit 95ba86a, commit 306f445, commit dbb1c61, commit f443246, commit 0c8ac06, commit a755530, commit 1a3017d, commit 72ddf34, commit 67ad630, commit 432a50b, commit 25d4e02, commit 593ffdd, commit bad62a8, commit 96e7225 (22 Dec 2021) by Emily Shaffer (nasamuffin).

See commit 0d3979c, commit ab81cf2, commit 474c119 (22 Dec 2021) by Ævar Arnfjörð Bjarmason (avar).

(Merged by Junio C Hamano -- gitster -- in commit c70bc33, 09 Feb 2022)

hook: add 'run' subcommand

Signed-off-by: Emily Shaffer

Signed-off-by: Ævar Arnfjörð Bjarmason

Acked-by: Emily Shaffer

In order to enable hooks to be run as an external process, by a standalone Git command, or by tools which wrap Git, provide an external means to run all configured hook commands for a given hook event.

Most of our hooks require more complex functionality than this, but let's start with the bare minimum required to support our simplest hooks.

In terms of implementation the usage_with_options() and "goto usage" pattern here mirrors that of builtin/{commit-graph,multi-pack-index}.c.

Some of the implementation here, such as a function being named run_hooks_opt() when it's tasked with running one hook, to using the run_processes_parallel_tr2() API to run with jobs=1 is somewhere between a bit odd and and an overkill for the current features of this "hook run" command and the hook.[ch] API.

This code will eventually be able to run multiple hooks declared in config in parallel, by starting out with these names and APIs we reduce the later churn of renaming functions, switching from the run_command() to run_processes_parallel_tr2() API etc.

git hook now includes in its man page:

git-hook(1)

NAME

git-hook - Run git hooks

SYNOPSIS

[verse]

 'git hook' run <hook-name> [-- <hook-args>]

DESCRIPTION

A command interface to running git hooks (see linkgit:githooks[5]),
for use by other scripted git commands.

SUBCOMMANDS

run

Run the <hook-name> hook.

Any positional arguments to the hook should be passed after a
mandatory -- (or --end-of-options).

And:

git hook run: add an --ignore-missing flag

Signed-off-by: Ævar Arnfjörð Bjarmason

Reviewed-by: Emily Shaffer

For certain one-shot hooks we'd like to optimistically run them, and not complain if they don't exist.

This was already supported by the underlying hook.c library, but had not been exposed via "git hook"(man) run".

The command version of this will be used by send-email in a subsequent commit.

git hook now includes in its man page:

'git hook' run [--ignore-missing] <hook-name> [-- <hook-args>]

git hook now includes in its man page:

OPTIONS

--ignore-missing

Ignore any missing hook by quietly returning zero.

Used for
tools that want to do a blind one-shot run of a hook that may
or may not be present.

Warning: in Git 2.36 we revamped the way how hooks are invoked.

One change that is end-user visible is that the output of a hook is no longer directly connected to the standard output of "git" that spawns the hook, which was noticed post release.

This is getting corrected with Git 2.37 (Q3 2022).

See commit a082345, commit fd3aaf5 (07 Jun 2022) by Ævar Arnfjörð Bjarmason (avar).

(Merged by Junio C Hamano -- gitster -- in commit 1a7f6be, 13 Jun 2022)

hook API: fix v2.36.0 regression: hooks should be connected to a TTY

Reported-by: Anthony Sottile

Signed-off-by: Ævar Arnfjörð Bjarmason

Fix a regression reported against f443246 (commit: convert {pre-commit, 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) (commit: convert {pre-commit,prepare-commit-msg} hook to hook.h, 2021-12-22): Due to using the run_process_parallel() API in the earlier 96e7225 ("hook: add 'run' subcommand", 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) we'd capture the hook's stderr and stdout, and thus lose the connection to the TTY in the case of e.g. the "pre-commit" hook.

As a preceding commit notes GNU parallel's similar --ungroup option also has it emit output faster.

While we're unlikely to have hooks that emit truly massive amounts of output (or where the performance thereof matters) it's still informative to measure the overhead.

In a similar "seq" test we're now ~30% faster:

$ cat .git/hooks/seq-hook; git hyperfine -L rev origin/master,HEAD~0 -s 'make CFLAGS=-O3' './git hook run seq-hook'
#!/bin/sh

seq 100000000
Benchmark 1: ./git hook run seq-hook' in 'origin/master
  Time (mean ± σ):     787.1 ms ±  13.6 ms    [User: 701.6 ms, System: 534.4 ms]
  Range (min … max):   773.2 ms … 806.3 ms    10 runs

Benchmark 2: ./git hook run seq-hook' in 'HEAD~0
  Time (mean ± σ):     603.4 ms ±   1.6 ms    [User: 573.1 ms, System: 30.3 ms]
  Range (min … max):   601.0 ms … 606.2 ms    10 runs

Summary
  './git hook run seq-hook' in 'HEAD~0' ran
    1.30 ± 0.02 times faster than './git hook run seq-hook' in 'origin/master'

Git 2.37.3 (Q3 2022) adds a follow-up fix to a fix for a regression in 2.36.

See commit 99ddc24 (05 Aug 2022) by Ævar Arnfjörð Bjarmason (avar).

(Merged by Junio C Hamano -- gitster -- in commit d86ac14, 14 Aug 2022)

hook API: don't segfault on strbuf_addf() to NULL "out"

Reported-by: Ilya K

Signed-off-by: Ævar Arnfjörð Bjarmason

Reviewed-by: Emily Shaffer

Reviewed-by: Đoàn Trần Công Danh

Fix a logic error in a082345 ("hook API: fix v2.36.0 regression: hooks should be connected to a TTY", 2022-06-07, Git v2.37.0-rc0 -- merge).

When it started using the "ungroup" API added in fd3aaf5 (run-command: add an , 2022-06-07, Git v2.37.0-rc0 -- merge) (run-command: add an "ungroup" option to run_process_parallel(), 2022-06-07) it should have made the same sort of change that fd3aaf5 itself made in "t/helper/test-run-command.c".

The correct way to emit this "Couldn't start" output with "ungroup" would be:

fprintf(stderr, _("Couldn't start hook '%s'\n"), hook_path);

But we should instead remove the emitting of this output.

The "cannot run" output here is emitted by run-command.c's child_err_spew().

So the addition of the "Couldn't start hook" output here in 96e7225 ("hook: add 'run' subcommand", 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) was always redundant.

For the pre-commit hook we'll now emit exactly the same output as we did before f443246 (commit: convert {pre-commit, 2021-12-22, Git v2.36.0-rc0 -- merge listed in batch #2) (commit: convert {pre-commit,prepare-commit-msg} hook to hook.h, 2021-12-22) (and likewise for others).


答:
You can do this:

groups = df.groupby('Month')[['values_1', 'values_2']]
df = groups.max() - groups.min()
```

Title: Calculate difference between min and max for each Pandas group


问:
MySQL REGEXP matching positive numbers
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

```<code>REGEXP '[^-,][0-9]+'
</code>```

but this pulls -886 as 88 matches the regexp

答:
Try using this :

```<code>"[^-\d]\d+\b"
</code>```

which should work if i understood your question correctly.

a good regex reference table : http://www.regular-expressions.info/reference.html

Title: MySQL REGEXP matching positive numbers

Body:
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

REGEXP '[^-,][0-9]+'

but this pulls -886 as 88 matches the regexp

Body:
Try using this :

"[^-\d]\d+\b"

which should work if i understood your question correctly.

a good regex reference table : http://www.regular-expressions.info/reference.html


问:
False error? `Variable used before being initialized` DURING initialization in init()
Sorry for the non-sense example. Tried to simplify it, still don’t get what’s going on. The following gives me Variable 'self.greeting' used before being initialized:

struct MyView: View {
    @State var greeting: String
    var length = Measurement<UnitLength>(value: 5, unit: UnitLength.miles)
    init() {
        greeting = "Hello, World!" // Variable 'self.greeting' used before being initialized
    }
    var body: some View {
        Text(greeting)
    }
}
```
<p>While this is working fine (<code>var length</code> differs; otherwise identical):</p>
<pre class="lang-swift prettyprint-override"><code>struct MyView: View {
    @State var greeting: String
    var length = 5 // now Int
    init() {
        greeting = "Hello, World!"
    }
    var body: some View {
        Text(greeting)
    }
}
</code>```

Also, this is working (here I removed the @State):

struct MyView: View {
    var greeting: String // @State removed
    var length = Measurement<UnitLength>(value: 5, unit: UnitLength.miles)
    init() {
        greeting = "Hello, World!"
    }
    var body: some View {
        Text(greeting)
    }
}
```

If the compiler wants me to initialize greeting before init() where would that be? preinit()?

Why does it think greeting is being “used” uninitialized when actually I am initializing it here?

Is there a different way to initialize @State vars? If so, why does it work when the unrelated var length is of Int rather than Measurement?

答:
This code:

```<code>@State var greeting: String
</code>```

Creates a backing variable behind the scenes:

```<code>let _greeting: State<String>
</code>```

If you want to initialize it yourself in init(), you can do:

```<code>init() {
    _greeting = new State<String>(initialValue: "Hello, World!")
}
</code>```

but since you have a constant, it is simpler to set it like this:

```<code>@State var greeting: String = "Hello, World!"
</code>```

The 3rd variant works, because without @State there's no magic.

The 1st option doesn't work, because the code gets translated to:

```<code>init() {
    self._greeting.wrappedValue = "Hello, World!"
}
</code>```

and _greeting is not initialized at this point (no initialValue is specified). Yes, the error is misleading.

I don't know why the 2nd version works. No initialValue is specified, and the String has no implicit default value. Maybe this is a new feature of iOS 15 SwiftUI that should work, but doesn't work in all cases due to some limitations?

P.S. There is something like "preinit": all properties that are assigned with some expressions like length = Measurement<UnitLength>(...) are run there before init, but there's no access to it, it is internal.

Body:
Sorry for the non-sense example. Tried to simplify it, still don’t get what’s going on. The following gives me Variable 'self.greeting' used before being initialized:

struct MyView: View {
    @State var greeting: String
    var length = Measurement<UnitLength>(value: 5, unit: UnitLength.miles)
    init() {
        greeting = "Hello, World!" // Variable 'self.greeting' used before being initialized
    }
    var body: some View {
        Text(greeting)
    }
}

While this is working fine (var length differs; otherwise identical):

struct MyView: View {
    @State var greeting: String
    var length = 5 // now Int
    init() {
        greeting = "Hello, World!"
    }
    var body: some View {
        Text(greeting)
    }
}

Also, this is working (here I removed the @State):

struct MyView: View {
    var greeting: String // @State removed
    var length = Measurement<UnitLength>(value: 5, unit: UnitLength.miles)
    init() {
        greeting = "Hello, World!"
    }
    var body: some View {
        Text(greeting)
    }
}

If the compiler wants me to initialize greeting before init() where would that be? preinit()?

Why does it think greeting is being “used” uninitialized when actually I am initializing it here?

Is there a different way to initialize @State vars? If so, why does it work when the unrelated var length is of Int rather than Measurement?

Body:
This code:

@State var greeting: String

Creates a backing variable behind the scenes:

let _greeting: State<String>

If you want to initialize it yourself in init(), you can do:

init() {
    _greeting = new State<String>(initialValue: "Hello, World!")
}

but since you have a constant, it is simpler to set it like this:

@State var greeting: String = "Hello, World!"

The 3rd variant works, because without @State there's no magic.

The 1st option doesn't work, because the code gets translated to:

init() {
    self._greeting.wrappedValue = "Hello, World!"
}

and _greeting is not initialized at this point (no initialValue is specified). Yes, the error is misleading.

I don't know why the 2nd version works. No initialValue is specified, and the String has no implicit default value. Maybe this is a new feature of iOS 15 SwiftUI that should work, but doesn't work in all cases due to some limitations?

P.S. There is something like "preinit": all properties that are assigned with some expressions like length = Measurement<UnitLength>(...) are run there before init, but there's no access to it, it is internal.


问:
Calculate first day of week as a special result string
I've got a special request for a new project. We've got a date like "2022-02-01" and we have to calculate it to get the following string as result "WB - Jan-31". It has to be always the date of the first day of the week. First day of week is Monday. A colleague give the hint to solve it with the to_char () function, but how do I manage to get a result like this?

date
week

2022-02-01
WS - Jan 31

2022-02-02
WS - Jan 31

2022-02-07
WS - Feb 07

2022-02-08
WS - Feb 07

What I have right now:

This gives a number of day of the week back as integer for calculation.

```<code>SELECT create_date, to_char(create_date, 'ID')::integer as dow
FROM customer;
</code>```

I also figured how to produce a string.

```<code>SELECT create_date, to_char(create_date, '"WB - " Mon DD')
FROM customer;
</code>```

What I don't know how to mange to get as result the first day of week for Monday to Friday like "WS - Jan 31"?

I also figured how to calculate first day of week as date but how put it in this result?

```<code>SELECT create_date - to_char(create_date, 'ID')::integer + 1
FROM customer;
</code>```

I appreciate every help, I'm still into learning SQL from scratch and it's my first week of doing this at my new position.

答:
Assuming the WS is week starting , and WB is week beginning, so no real issue, try this:

```<code>WITH
indata(dt,wk) AS (
          SELECT DATE '2022-02-01','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-02','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-03','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-04','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-05','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-07','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-08','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-09','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-10','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-11','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-12','WS - Feb 07'
)
SELECT
  *
, EXTRACT(DOW FROM dt)
, 'WS - ' || TO_CHAR(dt - EXTRACT(DOW FROM dt)  + 2, 'Mon DD') AS wk_calc
FROM indata
ORDER BY 1;
-- out      dt     |     wk      | date_part |   wk_calc
-- out ------------+-------------+-----------+-------------
-- out  2022-02-01 | WS - Jan 31 |         2 | WS - Feb 01
-- out  2022-02-02 | WS - Jan 31 |         3 | WS - Feb 01
-- out  2022-02-03 | WS - Jan 31 |         4 | WS - Feb 01
-- out  2022-02-04 | WS - Jan 31 |         5 | WS - Feb 01
-- out  2022-02-05 | WS - Jan 31 |         6 | WS - Feb 01
-- out  2022-02-07 | WS - Feb 07 |         1 | WS - Feb 08
-- out  2022-02-08 | WS - Feb 07 |         2 | WS - Feb 08
-- out  2022-02-09 | WS - Feb 07 |         3 | WS - Feb 08
-- out  2022-02-10 | WS - Feb 07 |         4 | WS - Feb 08
-- out  2022-02-11 | WS - Feb 07 |         5 | WS - Feb 08
-- out  2022-02-12 | WS - Feb 07 |         6 | WS - Feb 08
-- out (11 rows)
</code>```

Body:
I've got a special request for a new project. We've got a date like "2022-02-01" and we have to calculate it to get the following string as result "WB - Jan-31". It has to be always the date of the first day of the week. First day of week is Monday. A colleague give the hint to solve it with the to_char () function, but how do I manage to get a result like this?

date
week

2022-02-01
WS - Jan 31

2022-02-02
WS - Jan 31

2022-02-07
WS - Feb 07

2022-02-08
WS - Feb 07

What I have right now:

This gives a number of day of the week back as integer for calculation.

SELECT create_date, to_char(create_date, 'ID')::integer as dow
FROM customer;

I also figured how to produce a string.

SELECT create_date, to_char(create_date, '"WB - " Mon DD')
FROM customer;

What I don't know how to mange to get as result the first day of week for Monday to Friday like "WS - Jan 31"?

I also figured how to calculate first day of week as date but how put it in this result?

SELECT create_date - to_char(create_date, 'ID')::integer + 1
FROM customer;

I appreciate every help, I'm still into learning SQL from scratch and it's my first week of doing this at my new position.

Body:
Assuming the WS is week starting , and WB is week beginning, so no real issue, try this:

WITH
indata(dt,wk) AS (
          SELECT DATE '2022-02-01','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-02','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-03','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-04','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-05','WS - Jan 31'
UNION ALL SELECT DATE '2022-02-07','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-08','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-09','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-10','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-11','WS - Feb 07'
UNION ALL SELECT DATE '2022-02-12','WS - Feb 07'
)
SELECT
  *
, EXTRACT(DOW FROM dt)
, 'WS - ' || TO_CHAR(dt - EXTRACT(DOW FROM dt)  + 2, 'Mon DD') AS wk_calc
FROM indata
ORDER BY 1;
-- out      dt     |     wk      | date_part |   wk_calc
-- out ------------+-------------+-----------+-------------
-- out  2022-02-01 | WS - Jan 31 |         2 | WS - Feb 01
-- out  2022-02-02 | WS - Jan 31 |         3 | WS - Feb 01
-- out  2022-02-03 | WS - Jan 31 |         4 | WS - Feb 01
-- out  2022-02-04 | WS - Jan 31 |         5 | WS - Feb 01
-- out  2022-02-05 | WS - Jan 31 |         6 | WS - Feb 01
-- out  2022-02-07 | WS - Feb 07 |         1 | WS - Feb 08
-- out  2022-02-08 | WS - Feb 07 |         2 | WS - Feb 08
-- out  2022-02-09 | WS - Feb 07 |         3 | WS - Feb 08
-- out  2022-02-10 | WS - Feb 07 |         4 | WS - Feb 08
-- out  2022-02-11 | WS - Feb 07 |         5 | WS - Feb 08
-- out  2022-02-12 | WS - Feb 07 |         6 | WS - Feb 08
-- out (11 rows)


问:
How asynchronous code runs in node.js without using browser
asynchronous code such as setTimeout can only be run by using a browser; as the engine hands over the code to the browser till the time of execution comes. But in node, we have only an engine and no browser then how does setTimeout work on the node.</p>

答:
Asynchronous code is achieved using Promises, and optionally the async/await syntactic sugar.

Promises are implemented using raw JavaScript, and has nothing to do with whether the code is ran in the browser or not.

In your case you are referring to setTimeout. This function simply delays code execution by scheduling for the function to be called in JavaScript's event loop.

This is part of the core engine of JavaScript, and once again has nothing to do with the browser.

What makes you think that the browser makes any difference here?

Any implementation will have a mechanism in place for being able to wait for a certain amount of time to pass, this is not something special to a browser.


问:
How do I resolve 'PY_SSIZE_T_CLEAN macro must be defined for '#' formats' for Pybluez on Windows 10
I am trying to run the Pybluez server example but I am getting an error that I don't understand. Is there any way to resolve this? I am running Windows 10.

```<code>Traceback (most recent call last):
  File "C:\Users\cmbro\PycharmProjects\test\server.py", line 10, in <module>
    server_sock.bind(("", PORT_ANY))
  File "C:\Users\cmbro\PycharmProjects\test\venv\lib\site-packages\bluetooth\msbt.py", line 84, in bind
    bt.bind (self._sockfd, addr, port)
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats
</code>```

Here is the code

```<code>from bluetooth import *

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service( server_sock, "SampleServer",
                   service_id = uuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ],
#                   protocols = [ OBEX_UUID ]
                    )

print("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print("received [%s]" % data)
except IOError:
    pass

print("disconnected")

client_sock.close()
server_sock.close()
print("all done")
</code>```

答: Looks like you're using Python 3.10? There was a breaking change introduced in Python 3.10 (see bpo-40943 and PEP-0353). You need to update pybluez, see: https://github.com/pybluez/pybluez/issues/426.</p>

Body:
I am trying to run the Pybluez server example but I am getting an error that I don't understand. Is there any way to resolve this? I am running Windows 10.

Traceback (most recent call last):
  File "C:\Users\cmbro\PycharmProjects\test\server.py", line 10, in <module>
    server_sock.bind(("", PORT_ANY))
  File "C:\Users\cmbro\PycharmProjects\test\venv\lib\site-packages\bluetooth\msbt.py", line 84, in bind
    bt.bind (self._sockfd, addr, port)
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats

Here is the code

from bluetooth import *

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service( server_sock, "SampleServer",
                   service_id = uuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ],
#                   protocols = [ OBEX_UUID ]
                    )

print("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print("received [%s]" % data)
except IOError:
    pass

print("disconnected")

client_sock.close()
server_sock.close()
print("all done")


问:
Append to array in async for loop
I've got this function which contains other nested async functions.

I'm unzipping a zipfile and then appending each HTMLImageElement to an array.

However, the array is printing like this

16 is the correct number of images I'm expecting, but they're undefined when I console.log() them.

```<code>export async function fetchVisuals(TestID: number) {
    var zip = new JSZip();
    const res = await fetch('*DJANGO URL*', {
        body: JSON.stringify(TestID),
        method: 'POST'
    })
    let http_ok = res.ok
    const blob = await res.blob()
    var bufferPromise = await blob.arrayBuffer();
    zip.loadAsync(bufferPromise).then(async ({files}) => {
        const mediaFiles = Object.entries(files).filter(([fileName]) =>
            fileName.endsWith('.jpg'),
        );
        if (!mediaFiles.length) {
            throw new Error('No media files found in archive');
        }
        // I'm very confident the issue is to do with the below function
        let promiseArray = mediaFiles.map(function([,image]) {
            image.async('blob').then((blob: Blob | MediaSource) => {
                console.log("mediaFiles loop")
                const img = new Image();
                img.src = URL.createObjectURL(blob)
                console.log(img)
                return img
            })
        })
        Promise.all(promiseArray).then(function(resultsArray) {
            console.log(resultsArray)
        })
    })
}
</code>```

I'm mapping the promise of each image to an array then doing Promise.all() on this array, so I'm not sure why it's still coming back as undefined.

Inside of mediaFiles.map() I do some prints and they print the img data successfully.

How can I fill this array with the HTMLImageElements?

答:
You don't return your promise in the map function:

        let promiseArray = mediaFiles.map(function([,image]) {
            image.async('blob').then((blob: Blob | MediaSource) => {
                console.log("mediaFiles loop")
                const img = new Image();
                img.src = URL.createObjectURL(blob)
                console.log(img)
                return img
            })
        })

```
<p>Must become :</p>
<pre class="lang-js prettyprint-override"><code>
 // I'm very confident the issue is to do with the below function
        let promiseArray = mediaFiles.map(function([,image]) {
            /*just there : */ return image.async('blob').then((blob: Blob | MediaSource) => {
                console.log("mediaFiles loop")
                const img = new Image();
                img.src = URL.createObjectURL(blob)
                console.log(img)
                return img
            })
        })

</code>```

For your second question, you must await your promises and return their results :

export async function fetchVisuals(TestID: number) {
    var zip = new JSZip();
    const res = await fetch('*DJANGO URL*', {
        body: JSON.stringify(TestID),
        method: 'POST'
    })
    let http_ok = res.ok
    const blob = await res.blob()
    var bufferPromise = await blob.arrayBuffer();
    const {files} = await zip.loadASync(bufferPromise);
    const mediaFiles = Object.entries(files).filter(([fileName]) =>
        fileName.endsWith('.jpg'),
    );
    if (!mediaFiles.length) {
        throw new Error('No media files found in archive');
    }
    // I'm very confident the issue is to do with the below function
    let promiseArray = mediaFiles.map(function([,image]) {
        return image.async('blob').then((blob: Blob | MediaSource) => {
            console.log("mediaFiles loop")
            const img = new Image();
            img.src = URL.createObjectURL(blob)
            console.log(img)
            return img
        })
    })
    return await Promise.all(promiseArray);
}

```

Title: Append to array in async for loop

Body:
I've got this function which contains other nested async functions.

I'm unzipping a zipfile and then appending each HTMLImageElement to an array.

However, the array is printing like this

16 is the correct number of images I'm expecting, but they're undefined when I console.log() them.

export async function fetchVisuals(TestID: number) {
    var zip = new JSZip();
    const res = await fetch('*DJANGO URL*', {
        body: JSON.stringify(TestID),
        method: 'POST'
    })
    let http_ok = res.ok
    const blob = await res.blob()
    var bufferPromise = await blob.arrayBuffer();
    zip.loadAsync(bufferPromise).then(async ({files}) => {
        const mediaFiles = Object.entries(files).filter(([fileName]) =>
            fileName.endsWith('.jpg'),
        );
        if (!mediaFiles.length) {
            throw new Error('No media files found in archive');
        }
        // I'm very confident the issue is to do with the below function
        let promiseArray = mediaFiles.map(function([,image]) {
            image.async('blob').then((blob: Blob | MediaSource) => {
                console.log("mediaFiles loop")
                const img = new Image();
                img.src = URL.createObjectURL(blob)
                console.log(img)
                return img
            })
        })
        Promise.all(promiseArray).then(function(resultsArray) {
            console.log(resultsArray)
        })
    })
}

I'm mapping the promise of each image to an array then doing Promise.all() on this array, so I'm not sure why it's still coming back as undefined.

Inside of mediaFiles.map() I do some prints and they print the img data successfully.

How can I fill this array with the HTMLImageElements?

Body:
You don't return your promise in the map function:

        let promiseArray = mediaFiles.map(function([,image]) {
            image.async('blob').then((blob: Blob | MediaSource) => {
                console.log("mediaFiles loop")
                const img = new Image();
                img.src = URL.createObjectURL(blob)
                console.log(img)
                return img
            })
        })

Must become :

 // I'm very confident the issue is to do with the below function
        let promiseArray = mediaFiles.map(function([,image]) {
            /*just there : */ return image.async('blob').then((blob: Blob | MediaSource) => {
                console.log("mediaFiles loop")
                const img = new Image();
                img.src = URL.createObjectURL(blob)
                console.log(img)
                return img
            })
        })

For your second question, you must await your promises and return their results :

export async function fetchVisuals(TestID: number) {
    var zip = new JSZip();
    const res = await fetch('*DJANGO URL*', {
        body: JSON.stringify(TestID),
        method: 'POST'
    })
    let http_ok = res.ok
    const blob = await res.blob()
    var bufferPromise = await blob.arrayBuffer();
    const {files} = await zip.loadASync(bufferPromise);
    const mediaFiles = Object.entries(files).filter(([fileName]) =>
        fileName.endsWith('.jpg'),
    );
    if (!mediaFiles.length) {
        throw new Error('No media files found in archive');
    }
    // I'm very confident the issue is to do with the below function
    let promiseArray = mediaFiles.map(function([,image]) {
        return image.async('blob').then((blob: Blob | MediaSource) => {
            console.log("mediaFiles loop")
            const img = new Image();
            img.src = URL.createObjectURL(blob)
            console.log(img)
            return img
        })
    })
    return await Promise.all(promiseArray);
}


问:
BroadcastReceiver receive extra with ADB --es not working
I registered a broadcast receiver in the MainActivity.onCreate method with the following statements:

```<code>...
// in onCreate()
val filter = IntentFilter("com.example.my_receiver.TEST_FILTER")
registerReceiver(myReceiver, filter)
...
</code>```

with the following receiver

```<code>private val myReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        // do something
    }
}
</code>```

when I executed the add command

```<code>adb shell am broadcast -a com.example.my_receiver.TEST_FILTER
</code>```

the onReceive method will be executed. But when I try to add some extra data with the following

```<code>adb shell am broadcast -a com.example.my_receiver.TEST_FILTER --es test_data "My testdata"
</code>```

nothing will be executed. How can I send extra data with adb and receive it in the BroadcastReceiver implementation? The compileSdk and targetSdk is 31.

答:
I would recommend that you try without whitespace in the first place, or just escape the whitespace, seen also here:

adb command fail to execute if path contain spaces

Body:
I registered a broadcast receiver in the MainActivity.onCreate method with the following statements:

...
// in onCreate()
val filter = IntentFilter("com.example.my_receiver.TEST_FILTER")
registerReceiver(myReceiver, filter)
...

with the following receiver

private val myReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        // do something
    }
}

when I executed the add command

adb shell am broadcast -a com.example.my_receiver.TEST_FILTER

the onReceive method will be executed. But when I try to add some extra data with the following

adb shell am broadcast -a com.example.my_receiver.TEST_FILTER --es test_data "My testdata"

nothing will be executed. How can I send extra data with adb and receive it in the BroadcastReceiver implementation? The compileSdk and targetSdk is 31.


问:
Im trying to validate a password and the error "cant convert from string to double" comes up
This is a runtime error in visual basic and it should be pretty easy to fix but I dont know how.</p>

答: Mid returns a String and Asc returns an Integer. Comparing the two results in syntax error. In order to fix it, you will need to explicitly convert your result from Mid into an Integer, for example via CInt if the result of Mid is numeric.


问:
Normalize nested json columns within DataFrame
I have a dataframe where some columns are fine as they are, while others are deeply nested jsons. I would like to flatten these columns while not losing the data I have in the others. I have been trying many things with the json_normalize function, but with not success so far. Here is the original dicitonary from which I created the dataframe:

```<code>{'event_no': 1,
'post_time': {'$date': 1501780860000},
'conditions': 'FOR MAIDENS, FILLIES TWO YEARS OLD. Weight, 118 lbs. Claiming Price $35,000, For Each $5,000 To $25,000 1 lb.',
'odds_updated': {'$date': 1501780944000},
'status': 'Unknown',
'distance': '4 1/2F',
'purse': 2600000,
'runners': [{'number': 1, 'scratched': False, 'name': 'Indian Myth', 'morning_odds': 4, 'current_odds': 3, 'win_pool': 11293, 'place_pool': 3560, 'show_pool': 1087},
            {'number': 4, 'scratched': False, 'name': 'Awesome Omi', 'morning_odds': '7/2', 'current_odds': 10, 'win_pool': 4297, 'place_pool': 1752, 'show_pool': 658},
            {'number': 3, 'scratched': False, 'name': 'La Reyna Bella', 'morning_odds': 12, 'current_odds': '7/2', 'win_pool': 9897, 'place_pool': 4047, 'show_pool': 874},
            {'number': 6, 'scratched': False, 'name': 'Spirited Tale', 'morning_odds': 6, 'current_odds': 35, 'win_pool': 1347, 'place_pool': 563, 'show_pool': 431},
            {'number': 5, 'scratched': False, 'name': 'Lucky Stiff', 'morning_odds': 3, 'current_odds': '5/2', 'win_pool': 12611, 'place_pool': 4506, 'show_pool': 1190},
            {'number': 2, 'scratched': False, 'name': 'Helen Rose', 'morning_odds': '5/2', 'current_odds': '3/2', 'win_pool': 19236, 'place_pool': 6709, 'show_pool': 2481}],
'results': {'finisher':
              [{'runner_name': 'Helen Rose', 'finish_position': 1, 'win_amount': 5.0, 'place_amount': 2.8, 'show_amount': 2.1, 'dead_heat': False, 'jockey': 'Aby Medina', 'program_number': 2},
              {'runner_name': 'Lucky Stiff', 'finish_position': 2, 'win_amount': None, 'place_amount': 3.4, 'show_amount': 2.4, 'dead_heat': False, 'jockey': 'Nicky Figueroa', 'program_number': 5},
              {'runner_name': 'Indian Myth', 'finish_position': 3, 'win_amount': None, 'place_amount': None, 'show_amount': 2.6, 'dead_heat': False, 'jockey': 'Gerardo Corrales', 'program_number': 1}],
           'dividends':
              [{'bet_type': 'EXA', 'finishers': '2-5', 'base_amount': 200, 'amount': 16.6},
              {'bet_type': 'TRI', 'finishers': '2-5-1', 'base_amount': 100, 'amount': 18.0},
              {'bet_type': 'SFC', 'finishers': '2-5-1-6', 'base_amount': 100, 'amount': 90.7}]}}
</code>```

Ideally, I would wish for each key within the jsons to be an individual column with its corresponding value. After making the dictionary into a dataframe, the four columns with the jsons I need to normalize are 'post_time', 'odds_updated', 'runners' and 'results', these last two being the ones I am having trouble with.

I was able to normalize the 'runners' column with the following code, but in the process I am losing all the other columns along with the ids, so I can not concat afterwards either:

```<code>df = pd.DataFrame.from_dict(my_dict)
json_df = json.loads(df.to_json(orient="records"))
flat_df = pd.json_normalize(json_df, record_path=['runners')
</code>```

When trying this, but with record_path set to 'results', I get the following error:

```<code>TypeError: {'event_no': 1, 'post_time': {'$date': 1501780860000}, 'conditions': 'FOR MAIDENS, FILLIES TWO YEARS OLD. Weight, 118 lbs. Claiming Price $35,000, For Each $5,000 To $25,000 1 lb.', 'odds_updated': {'$date': 1501780944000}, 'status': 'Unknown', 'distance': '4 1/2F', 'purse': 2600000, 'runners': [{'number': 1, 'scratched': False, 'name': 'Indian Myth', 'morning_odds': 4, 'current_odds': 3, 'win_pool': 11293, 'place_pool': 3560, 'show_pool': 1087}, {'number': 4, 'scratched': False, 'name': 'Awesome Omi', 'morning_odds': '7/2', 'current_odds': 10, 'win_pool': 4297, 'place_pool': 1752, 'show_pool': 658}, {'number': 3, 'scratched': False, 'name': 'La Reyna Bella', 'morning_odds': 12, 'current_odds': '7/2', 'win_pool': 9897, 'place_pool': 4047, 'show_pool': 874}, {'number': 6, 'scratched': False, 'name': 'Spirited Tale', 'morning_odds': 6, 'current_odds': 35, 'win_pool': 1347, 'place_pool': 563, 'show_pool': 431}, {'number': 5, 'scratched': False, 'name': 'Lucky Stiff', 'morning_odds': 3, 'current_odds': '5/2', 'win_pool': 12611, 'place_pool': 4506, 'show_pool': 1190}, {'number': 2, 'scratched': False, 'name': 'Helen Rose', 'morning_odds': '5/2', 'current_odds': '3/2', 'win_pool': 19236, 'place_pool': 6709, 'show_pool': 2481}], 'results': {'finisher': [{'runner_name': 'Helen Rose', 'finish_position': 1, 'win_amount': 5.0, 'place_amount': 2.8, 'show_amount': 2.1, 'dead_heat': False, 'jockey': 'Aby Medina', 'program_number': 2}, {'runner_name': 'Lucky Stiff', 'finish_position': 2, 'win_amount': None, 'place_amount': 3.4, 'show_amount': 2.4, 'dead_heat': False, 'jockey': 'Nicky Figueroa', 'program_number': 5}, {'runner_name': 'Indian Myth', 'finish_position': 3, 'win_amount': None, 'place_amount': None, 'show_amount': 2.6, 'dead_heat': False, 'jockey': 'Gerardo Corrales', 'program_number': 1}], 'dividends': [{'bet_type': 'EXA', 'finishers': '2-5', 'base_amount': 200, 'amount': 16.6}, {'bet_type': 'TRI', 'finishers': '2-5-1', 'base_amount': 100, 'amount': 18.0}, {'bet_type': 'SFC', 'finishers': '2-5-1-6', 'base_amount': 100, 'amount': 90.7}]}} has non list value {'finisher': [{'runner_name': 'Helen Rose', 'finish_position': 1, 'win_amount': 5.0, 'place_amount': 2.8, 'show_amount': 2.1, 'dead_heat': False, 'jockey': 'Aby Medina', 'program_number': 2}, {'runner_name': 'Lucky Stiff', 'finish_position': 2, 'win_amount': None, 'place_amount': 3.4, 'show_amount': 2.4, 'dead_heat': False, 'jockey': 'Nicky Figueroa', 'program_number': 5}, {'runner_name': 'Indian Myth', 'finish_position': 3, 'win_amount': None, 'place_amount': None, 'show_amount': 2.6, 'dead_heat': False, 'jockey': 'Gerardo Corrales', 'program_number': 1}], 'dividends': [{'bet_type': 'EXA', 'finishers': '2-5', 'base_amount': 200, 'amount': 16.6}, {'bet_type': 'TRI', 'finishers': '2-5-1', 'base_amount': 100, 'amount': 18.0}, {'bet_type': 'SFC', 'finishers': '2-5-1-6', 'base_amount': 100, 'amount': 90.7}]} for path results. Must be list or null.
</code>```

Any suggestions? Thanks in advance.

答:
You can use the meta argument of pd.json_normalize to add additional columns to your data frame:

runners = pd.json_normalize(my_dict, "runners", meta="event_no")
finishers = pd.json_normalize(my_dict, ["results", "finisher"], meta="event_no")
```

Now you can join the two data frames on (runners.event_no, runners.number) == (finishers.event_no, finishers.program_number).

Body:
I have a dataframe where some columns are fine as they are, while others are deeply nested jsons. I would like to flatten these columns while not losing the data I have in the others. I have been trying many things with the json_normalize function, but with not success so far. Here is the original dicitonary from which I created the dataframe:

{'event_no': 1,
'post_time': {'$date': 1501780860000},
'conditions': 'FOR MAIDENS, FILLIES TWO YEARS OLD. Weight, 118 lbs. Claiming Price $35,000, For Each $5,000 To $25,000 1 lb.',
'odds_updated': {'$date': 1501780944000},
'status': 'Unknown',
'distance': '4 1/2F',
'purse': 2600000,
'runners': [{'number': 1, 'scratched': False, 'name': 'Indian Myth', 'morning_odds': 4, 'current_odds': 3, 'win_pool': 11293, 'place_pool': 3560, 'show_pool': 1087},
            {'number': 4, 'scratched': False, 'name': 'Awesome Omi', 'morning_odds': '7/2', 'current_odds': 10, 'win_pool': 4297, 'place_pool': 1752, 'show_pool': 658},
            {'number': 3, 'scratched': False, 'name': 'La Reyna Bella', 'morning_odds': 12, 'current_odds': '7/2', 'win_pool': 9897, 'place_pool': 4047, 'show_pool': 874},
            {'number': 6, 'scratched': False, 'name': 'Spirited Tale', 'morning_odds': 6, 'current_odds': 35, 'win_pool': 1347, 'place_pool': 563, 'show_pool': 431},
            {'number': 5, 'scratched': False, 'name': 'Lucky Stiff', 'morning_odds': 3, 'current_odds': '5/2', 'win_pool': 12611, 'place_pool': 4506, 'show_pool': 1190},
            {'number': 2, 'scratched': False, 'name': 'Helen Rose', 'morning_odds': '5/2', 'current_odds': '3/2', 'win_pool': 19236, 'place_pool': 6709, 'show_pool': 2481}],
'results': {'finisher':
              [{'runner_name': 'Helen Rose', 'finish_position': 1, 'win_amount': 5.0, 'place_amount': 2.8, 'show_amount': 2.1, 'dead_heat': False, 'jockey': 'Aby Medina', 'program_number': 2},
              {'runner_name': 'Lucky Stiff', 'finish_position': 2, 'win_amount': None, 'place_amount': 3.4, 'show_amount': 2.4, 'dead_heat': False, 'jockey': 'Nicky Figueroa', 'program_number': 5},
              {'runner_name': 'Indian Myth', 'finish_position': 3, 'win_amount': None, 'place_amount': None, 'show_amount': 2.6, 'dead_heat': False, 'jockey': 'Gerardo Corrales', 'program_number': 1}],
           'dividends':
              [{'bet_type': 'EXA', 'finishers': '2-5', 'base_amount': 200, 'amount': 16.6},
              {'bet_type': 'TRI', 'finishers': '2-5-1', 'base_amount': 100, 'amount': 18.0},
              {'bet_type': 'SFC', 'finishers': '2-5-1-6', 'base_amount': 100, 'amount': 90.7}]}}

Ideally, I would wish for each key within the jsons to be an individual column with its corresponding value. After making the dictionary into a dataframe, the four columns with the jsons I need to normalize are 'post_time', 'odds_updated', 'runners' and 'results', these last two being the ones I am having trouble with.

I was able to normalize the 'runners' column with the following code, but in the process I am losing all the other columns along with the ids, so I can not concat afterwards either:

df = pd.DataFrame.from_dict(my_dict)
json_df = json.loads(df.to_json(orient="records"))
flat_df = pd.json_normalize(json_df, record_path=['runners')

When trying this, but with record_path set to 'results', I get the following error:

TypeError: {'event_no': 1, 'post_time': {'$date': 1501780860000}, 'conditions': 'FOR MAIDENS, FILLIES TWO YEARS OLD. Weight, 118 lbs. Claiming Price $35,000, For Each $5,000 To $25,000 1 lb.', 'odds_updated': {'$date': 1501780944000}, 'status': 'Unknown', 'distance': '4 1/2F', 'purse': 2600000, 'runners': [{'number': 1, 'scratched': False, 'name': 'Indian Myth', 'morning_odds': 4, 'current_odds': 3, 'win_pool': 11293, 'place_pool': 3560, 'show_pool': 1087}, {'number': 4, 'scratched': False, 'name': 'Awesome Omi', 'morning_odds': '7/2', 'current_odds': 10, 'win_pool': 4297, 'place_pool': 1752, 'show_pool': 658}, {'number': 3, 'scratched': False, 'name': 'La Reyna Bella', 'morning_odds': 12, 'current_odds': '7/2', 'win_pool': 9897, 'place_pool': 4047, 'show_pool': 874}, {'number': 6, 'scratched': False, 'name': 'Spirited Tale', 'morning_odds': 6, 'current_odds': 35, 'win_pool': 1347, 'place_pool': 563, 'show_pool': 431}, {'number': 5, 'scratched': False, 'name': 'Lucky Stiff', 'morning_odds': 3, 'current_odds': '5/2', 'win_pool': 12611, 'place_pool': 4506, 'show_pool': 1190}, {'number': 2, 'scratched': False, 'name': 'Helen Rose', 'morning_odds': '5/2', 'current_odds': '3/2', 'win_pool': 19236, 'place_pool': 6709, 'show_pool': 2481}], 'results': {'finisher': [{'runner_name': 'Helen Rose', 'finish_position': 1, 'win_amount': 5.0, 'place_amount': 2.8, 'show_amount': 2.1, 'dead_heat': False, 'jockey': 'Aby Medina', 'program_number': 2}, {'runner_name': 'Lucky Stiff', 'finish_position': 2, 'win_amount': None, 'place_amount': 3.4, 'show_amount': 2.4, 'dead_heat': False, 'jockey': 'Nicky Figueroa', 'program_number': 5}, {'runner_name': 'Indian Myth', 'finish_position': 3, 'win_amount': None, 'place_amount': None, 'show_amount': 2.6, 'dead_heat': False, 'jockey': 'Gerardo Corrales', 'program_number': 1}], 'dividends': [{'bet_type': 'EXA', 'finishers': '2-5', 'base_amount': 200, 'amount': 16.6}, {'bet_type': 'TRI', 'finishers': '2-5-1', 'base_amount': 100, 'amount': 18.0}, {'bet_type': 'SFC', 'finishers': '2-5-1-6', 'base_amount': 100, 'amount': 90.7}]}} has non list value {'finisher': [{'runner_name': 'Helen Rose', 'finish_position': 1, 'win_amount': 5.0, 'place_amount': 2.8, 'show_amount': 2.1, 'dead_heat': False, 'jockey': 'Aby Medina', 'program_number': 2}, {'runner_name': 'Lucky Stiff', 'finish_position': 2, 'win_amount': None, 'place_amount': 3.4, 'show_amount': 2.4, 'dead_heat': False, 'jockey': 'Nicky Figueroa', 'program_number': 5}, {'runner_name': 'Indian Myth', 'finish_position': 3, 'win_amount': None, 'place_amount': None, 'show_amount': 2.6, 'dead_heat': False, 'jockey': 'Gerardo Corrales', 'program_number': 1}], 'dividends': [{'bet_type': 'EXA', 'finishers': '2-5', 'base_amount': 200, 'amount': 16.6}, {'bet_type': 'TRI', 'finishers': '2-5-1', 'base_amount': 100, 'amount': 18.0}, {'bet_type': 'SFC', 'finishers': '2-5-1-6', 'base_amount': 100, 'amount': 90.7}]} for path results. Must be list or null.

Any suggestions? Thanks in advance.

Body:
You can use the meta argument of pd.json_normalize to add additional columns to your data frame:

runners = pd.json_normalize(my_dict, "runners", meta="event_no")
finishers = pd.json_normalize(my_dict, ["results", "finisher"], meta="event_no")

Now you can join the two data frames on (runners.event_no, runners.number) == (finishers.event_no, finishers.program_number).