问:
I received this code error each time I tried to deploy may app on Heroku:code: 'ERR_DLOPEN_FAILED'
I am new in Heroku and currently building an app with react (Node.js).

While I was able to push successfully my master branch to Heroku and Heroku confirms my app is deployed successfully, yet, the app is not deployed despite that is shows below deploy success message: "Deploy to Heroku".

Below is the error log in Heroku:

2022-02-08T00:45:18.702341+00:00 app[web.1]:     at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:18.702341+00:00 app[web.1]:     at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T00:45:18.702341+00:00 app[web.1]:   code: 'ERR_DLOPEN_FAILED'
2022-02-08T00:45:18.702342+00:00 app[web.1]: }
2022-02-08T00:45:18.924415+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T00:45:19.739614+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T00:45:31.255261+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=05cc8ef9-baa5-4af8-8167-ab18ec9fc909 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:45:31.413269+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=83016251-e4f0-4bf0-87d0-39ecb39ddd3f fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:20.928808+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=d243ef5c-56d8-4e22-b095-f3915e338c90 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:21.142923+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=49b1447a-2058-40c8-b85f-6934e1854ebb fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
```
<p>Below is the error log from CLI:</p>
<pre class="lang-none prettyprint-override"><code>2022-02-08T00:45:12.986742+00:00 app[web.1]: ^
2022-02-08T00:45:12.986743+00:00 app[web.1]:
2022-02-08T00:45:12.986744+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T00:45:12.986744+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T00:45:12.986745+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:12.986745+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T00:45:12.986747+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T00:45:12.986747+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:12.986747+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T00:45:12.986748+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T00:45:12.986748+00:00 app[web.1]: }
2022-02-08T00:45:13.178543+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T00:45:13.264905+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T00:45:13.273816+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-08T00:45:15.956822+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-08T00:45:18.232060+00:00 app[web.1]:
2022-02-08T00:45:18.232080+00:00 app[web.1]: > movie_api@1.0.0 start
2022-02-08T00:45:18.232081+00:00 app[web.1]: > node index.js
2022-02-08T00:45:18.232081+00:00 app[web.1]:
2022-02-08T00:45:18.702302+00:00 app[web.1]: node:internal/modules/cjs/loader:1183
2022-02-08T00:45:18.702328+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-08T00:45:18.702329+00:00 app[web.1]: ^
2022-02-08T00:45:18.702330+00:00 app[web.1]:
2022-02-08T00:45:18.702336+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T00:45:18.702337+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T00:45:18.702338+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:18.702338+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T00:45:18.702338+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T00:45:18.702339+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T00:45:18.702340+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T00:45:18.702340+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T00:45:18.702340+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T00:45:18.702341+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:18.702341+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T00:45:18.702341+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T00:45:18.702342+00:00 app[web.1]: }
2022-02-08T00:45:18.924415+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T00:45:19.739614+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T00:45:31.255261+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=05cc8ef9-baa5-4af8-8167-ab18ec9fc909 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:45:31.413269+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=83016251-e4f0-4bf0-87d0-39ecb39ddd3f fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:20.928808+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=d243ef5c-56d8-4e22-b095-f3915e338c90 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:21.142923+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=49b1447a-2058-40c8-b85f-6934e1854ebb fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T01:06:56.000000+00:00 app[api]: Build started by user hakeemkayodesulyman@gmail.com
2022-02-08T01:07:18.099531+00:00 app[api]: Deploy 759fe937 by user hakeemkayodesulyman@gmail.com
2022-02-08T01:07:18.099531+00:00 app[api]: Release v17 created by user hakeemkayodesulyman@gmail.com
2022-02-08T01:07:18.394025+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-08T01:07:21.000000+00:00 app[api]: Build succeeded
2022-02-08T01:07:21.034913+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-08T01:07:22.192406+00:00 app[web.1]:
2022-02-08T01:07:22.192420+00:00 app[web.1]: > movie_api@1.0.0 start
2022-02-08T01:07:22.192420+00:00 app[web.1]: > node index.js
2022-02-08T01:07:22.192420+00:00 app[web.1]:
2022-02-08T01:07:22.590438+00:00 app[web.1]: node:internal/modules/cjs/loader:1183
2022-02-08T01:07:22.590456+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-08T01:07:22.590456+00:00 app[web.1]: ^
2022-02-08T01:07:22.590457+00:00 app[web.1]:
2022-02-08T01:07:22.590458+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T01:07:22.590458+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T01:07:22.590459+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:22.590459+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T01:07:22.590459+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:22.590461+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T01:07:22.590461+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T01:07:22.590461+00:00 app[web.1]: }
2022-02-08T01:07:22.717250+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T01:07:22.786581+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T01:07:22.825527+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-08T01:07:25.399388+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-08T01:07:26.987095+00:00 app[web.1]:
2022-02-08T01:07:26.987107+00:00 app[web.1]: > movie_api@1.0.0 start
2022-02-08T01:07:26.987107+00:00 app[web.1]: > node index.js
2022-02-08T01:07:26.987108+00:00 app[web.1]:
2022-02-08T01:07:27.610704+00:00 app[web.1]: node:internal/modules/cjs/loader:1183
2022-02-08T01:07:27.610728+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-08T01:07:27.610729+00:00 app[web.1]: ^
2022-02-08T01:07:27.610730+00:00 app[web.1]:
2022-02-08T01:07:27.610731+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T01:07:27.610731+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T01:07:27.610732+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T01:07:27.610734+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T01:07:27.610734+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T01:07:27.610734+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:27.610735+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T01:07:27.610735+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T01:07:27.610735+00:00 app[web.1]: }
2022-02-08T01:07:27.789789+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T01:07:27.876090+00:00 heroku[web.1]: State changed from starting to crashed
</code>```

I have tried all tricks including many suggested here but it has not been helpful.

Of course, my package.json has this script. "start": "node index.js",

Could anyone help with a precise solution?

答:
The issue was probably connected the caches in the Node_Modules. I fixed this issue by running this in the terminal:

```<code>$ git rm -r --cached .
$ git add .
$ git commit -m "fixed untracked files"
</code>```

Body:
I am new in Heroku and currently building an app with react (Node.js).

While I was able to push successfully my master branch to Heroku and Heroku confirms my app is deployed successfully, yet, the app is not deployed despite that is shows below deploy success message: "Deploy to Heroku".

Below is the error log in Heroku:

2022-02-08T00:45:18.702341+00:00 app[web.1]:     at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:18.702341+00:00 app[web.1]:     at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T00:45:18.702341+00:00 app[web.1]:   code: 'ERR_DLOPEN_FAILED'
2022-02-08T00:45:18.702342+00:00 app[web.1]: }
2022-02-08T00:45:18.924415+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T00:45:19.739614+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T00:45:31.255261+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=05cc8ef9-baa5-4af8-8167-ab18ec9fc909 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:45:31.413269+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=83016251-e4f0-4bf0-87d0-39ecb39ddd3f fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:20.928808+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=d243ef5c-56d8-4e22-b095-f3915e338c90 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:21.142923+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=49b1447a-2058-40c8-b85f-6934e1854ebb fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https

Below is the error log from CLI:

2022-02-08T00:45:12.986742+00:00 app[web.1]: ^
2022-02-08T00:45:12.986743+00:00 app[web.1]:
2022-02-08T00:45:12.986744+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T00:45:12.986744+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T00:45:12.986745+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:12.986745+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T00:45:12.986746+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T00:45:12.986747+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T00:45:12.986747+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:12.986747+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T00:45:12.986748+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T00:45:12.986748+00:00 app[web.1]: }
2022-02-08T00:45:13.178543+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T00:45:13.264905+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T00:45:13.273816+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-08T00:45:15.956822+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-08T00:45:18.232060+00:00 app[web.1]:
2022-02-08T00:45:18.232080+00:00 app[web.1]: > movie_api@1.0.0 start
2022-02-08T00:45:18.232081+00:00 app[web.1]: > node index.js
2022-02-08T00:45:18.232081+00:00 app[web.1]:
2022-02-08T00:45:18.702302+00:00 app[web.1]: node:internal/modules/cjs/loader:1183
2022-02-08T00:45:18.702328+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-08T00:45:18.702329+00:00 app[web.1]: ^
2022-02-08T00:45:18.702330+00:00 app[web.1]:
2022-02-08T00:45:18.702336+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T00:45:18.702337+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T00:45:18.702338+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:18.702338+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T00:45:18.702338+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T00:45:18.702339+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T00:45:18.702340+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T00:45:18.702340+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T00:45:18.702340+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T00:45:18.702341+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T00:45:18.702341+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T00:45:18.702341+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T00:45:18.702342+00:00 app[web.1]: }
2022-02-08T00:45:18.924415+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T00:45:19.739614+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T00:45:31.255261+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=05cc8ef9-baa5-4af8-8167-ab18ec9fc909 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:45:31.413269+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=83016251-e4f0-4bf0-87d0-39ecb39ddd3f fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:20.928808+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=haksuly1movieapp.herokuapp.com request_id=d243ef5c-56d8-4e22-b095-f3915e338c90 fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T00:46:21.142923+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=haksuly1movieapp.herokuapp.com request_id=49b1447a-2058-40c8-b85f-6934e1854ebb fwd="88.130.53.4" dyno= connect= service= status=503 bytes= protocol=https
2022-02-08T01:06:56.000000+00:00 app[api]: Build started by user hakeemkayodesulyman@gmail.com
2022-02-08T01:07:18.099531+00:00 app[api]: Deploy 759fe937 by user hakeemkayodesulyman@gmail.com
2022-02-08T01:07:18.099531+00:00 app[api]: Release v17 created by user hakeemkayodesulyman@gmail.com
2022-02-08T01:07:18.394025+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-08T01:07:21.000000+00:00 app[api]: Build succeeded
2022-02-08T01:07:21.034913+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-08T01:07:22.192406+00:00 app[web.1]:
2022-02-08T01:07:22.192420+00:00 app[web.1]: > movie_api@1.0.0 start
2022-02-08T01:07:22.192420+00:00 app[web.1]: > node index.js
2022-02-08T01:07:22.192420+00:00 app[web.1]:
2022-02-08T01:07:22.590438+00:00 app[web.1]: node:internal/modules/cjs/loader:1183
2022-02-08T01:07:22.590456+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-08T01:07:22.590456+00:00 app[web.1]: ^
2022-02-08T01:07:22.590457+00:00 app[web.1]:
2022-02-08T01:07:22.590458+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T01:07:22.590458+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T01:07:22.590459+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:22.590459+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T01:07:22.590459+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T01:07:22.590460+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:22.590461+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T01:07:22.590461+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T01:07:22.590461+00:00 app[web.1]: }
2022-02-08T01:07:22.717250+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T01:07:22.786581+00:00 heroku[web.1]: State changed from starting to crashed
2022-02-08T01:07:22.825527+00:00 heroku[web.1]: State changed from crashed to starting
2022-02-08T01:07:25.399388+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-08T01:07:26.987095+00:00 app[web.1]:
2022-02-08T01:07:26.987107+00:00 app[web.1]: > movie_api@1.0.0 start
2022-02-08T01:07:26.987107+00:00 app[web.1]: > node index.js
2022-02-08T01:07:26.987108+00:00 app[web.1]:
2022-02-08T01:07:27.610704+00:00 app[web.1]: node:internal/modules/cjs/loader:1183
2022-02-08T01:07:27.610728+00:00 app[web.1]: return process.dlopen(module, path.toNamespacedPath(filename));
2022-02-08T01:07:27.610729+00:00 app[web.1]: ^
2022-02-08T01:07:27.610730+00:00 app[web.1]:
2022-02-08T01:07:27.610731+00:00 app[web.1]: Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
2022-02-08T01:07:27.610731+00:00 app[web.1]: at Object.Module._extensions..node (node:internal/modules/cjs/loader:1183:18)
2022-02-08T01:07:27.610732+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-08T01:07:27.610733+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
2022-02-08T01:07:27.610734+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1101:14)
2022-02-08T01:07:27.610734+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
2022-02-08T01:07:27.610734+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-08T01:07:27.610735+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
2022-02-08T01:07:27.610735+00:00 app[web.1]: code: 'ERR_DLOPEN_FAILED'
2022-02-08T01:07:27.610735+00:00 app[web.1]: }
2022-02-08T01:07:27.789789+00:00 heroku[web.1]: Process exited with status 1
2022-02-08T01:07:27.876090+00:00 heroku[web.1]: State changed from starting to crashed

I have tried all tricks including many suggested here but it has not been helpful.

Of course, my package.json has this script. "start": "node index.js",

Could anyone help with a precise solution?

Body:
The issue was probably connected the caches in the Node_Modules. I fixed this issue by running this in the terminal:

$ git rm -r --cached .
$ git add .
$ git commit -m "fixed untracked files"


来源: stackexchange

问:
Google Apps Script Not Reading editable fields on PDF
I created a code on GoogleAppScript with ORC to get text from a PDF file on Google Drive, using the getFileById() but the problem is that this file is an Adobe PDF Forms type and the code reads only the texts that are not in the fields that were edited in the form. Does anyone have any suggestions on how I can get this?

The file that I used as an example: http://foersom.com/net/HowTo/data/OoPdfFormExample.pdf (Please, fill the file and save on your drive to test it)

The PDF on my Drive:
PDF file image

This is the result:
values shown when code is executed

Here is my code:

```<code>function extractTextFromPDF() {

 var fileId = '[File ID here]';
 const ss = SpreadsheetApp.getActiveSpreadsheet()
 //Get all PDF files:
 const fileID = DriveApp.getFileById(fileId);

 var blob = DriveApp.getFileById(fileId).getBlob()
 var resource = {
title: blob.getName(),
mimeType: blob.getContentType(),
};

// Enable the Advanced Drive API Service
var file = Drive.Files.insert( resource, blob, { ocr: true, ocrLanguage: 'en'  } );
//,supportsAllDrives: true

// Extract Text from PDF file
var doc = DocumentApp.openById(file.id);
var text = doc.getBody().getText();

Logger.log(text)
return text;
}
</code>```

答:
The FDF data does not need to be stored in the order you see on the page, often may  be the order the fields were added. The easiest way to see the text /V(alues) in reply to /T(ext field) entries is via the FDF a user can save and send without the Source PDF. This has the added advantage that a CHECK box will be sent as /V /Yes or /V /OFF (= NOT checked) which is notoriously difficult with a binary PDF, however you need to know which text on the page was Language 1 since the author did not tag it as Deutsch!

What intrigues me most (without looking closer) is the count of attached objects only went up by 12 but there are more than that number of potentially added answers,
from a field :-) of 17.

```<code>/Lang(en-GB)
/AcroForm<</Fields[
5 0 R 7 0 R 8 0 R 9 0 R 10 0 R
11 0 R 12 0 R 13 0 R 14 0 R 16 0 R
17 0 R 18 0 R 19 0 R 20 0 R 21 0 R
22 0 R 23 0 R
]/DR 37 0 R/NeedAppearances true>>
</code>```

Anyway if you dont want to do it the easy way you will need to program something to read those object chains. Personally it takes each user a few seconds to export the forms or have them sent in the background by email however most modern users dont use historic mailto: so you have to get them to web mail the form for you to press the extract button.

So here is object 5 and we can see it is for your Given Name

```<code>5 0 obj
<</Type/Annot/Subtype/Widget/F 4
/Rect[165.7 453.7 315.7 467.9]
/FT/Tx
/P 1 0 R
/T(Given Name Text Box)
/TU<FEFF004600690072007300740020006E0061006D0065>
/V <FEFF>
/DV <FEFF>
/MaxLen 40
/DR<</Font 6 0 R>>
/DA(0 0 0 rg /F3 11 Tf)
/AP<<
/N 38 0 R
>>
>>
endobj
</code>```

so the entry for 004600690072007300740020006E0061006D0065 converts to First name and we can see the answer when the user sends back the form as a PDF

```<code>5 0 obj
<</AP<</N 38 0 R >>/DA(0 0 0 rg /F3 11 Tf)/DR<</Font 6 0 R >>/DV<FEFF>/F 4/FT/Tx/MaxLen 40/P 1 0 R /Rect[ 165.7 453.7 315.7 467.9]/Subtype/Widget/T(Given Name Text Box)
/TU<FEFF004600690072007300740020006E0061006D0065>/Type/Annot/V(Brunno)>>
endobj
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a code on GoogleAppScript with ORC to get text from a PDF file on Google Drive, using the getFileById() but the problem is that this file is an Adobe PDF Forms type and the code reads only the texts that are not in the fields that were edited in the form. Does anyone have any suggestions on how I can get this?

The file that I used as an example: http://foersom.com/net/HowTo/data/OoPdfFormExample.pdf (Please, fill the file and save on your drive to test it)

The PDF on my Drive:
PDF file image

This is the result:
values shown when code is executed

Here is my code:

function extractTextFromPDF() {

 var fileId = '[File ID here]';
 const ss = SpreadsheetApp.getActiveSpreadsheet()
 //Get all PDF files:
 const fileID = DriveApp.getFileById(fileId);

 var blob = DriveApp.getFileById(fileId).getBlob()
 var resource = {
title: blob.getName(),
mimeType: blob.getContentType(),
};

// Enable the Advanced Drive API Service
var file = Drive.Files.insert( resource, blob, { ocr: true, ocrLanguage: 'en'  } );
//,supportsAllDrives: true

// Extract Text from PDF file
var doc = DocumentApp.openById(file.id);
var text = doc.getBody().getText();

Logger.log(text)
return text;
}

Body:
The FDF data does not need to be stored in the order you see on the page, often may  be the order the fields were added. The easiest way to see the text /V(alues) in reply to /T(ext field) entries is via the FDF a user can save and send without the Source PDF. This has the added advantage that a CHECK box will be sent as /V /Yes or /V /OFF (= NOT checked) which is notoriously difficult with a binary PDF, however you need to know which text on the page was Language 1 since the author did not tag it as Deutsch!

What intrigues me most (without looking closer) is the count of attached objects only went up by 12 but there are more than that number of potentially added answers,
from a field :-) of 17.

/Lang(en-GB)
/AcroForm<</Fields[
5 0 R 7 0 R 8 0 R 9 0 R 10 0 R
11 0 R 12 0 R 13 0 R 14 0 R 16 0 R
17 0 R 18 0 R 19 0 R 20 0 R 21 0 R
22 0 R 23 0 R
]/DR 37 0 R/NeedAppearances true>>

Anyway if you dont want to do it the easy way you will need to program something to read those object chains. Personally it takes each user a few seconds to export the forms or have them sent in the background by email however most modern users dont use historic mailto: so you have to get them to web mail the form for you to press the extract button.

So here is object 5 and we can see it is for your Given Name

5 0 obj
<</Type/Annot/Subtype/Widget/F 4
/Rect[165.7 453.7 315.7 467.9]
/FT/Tx
/P 1 0 R
/T(Given Name Text Box)
/TU<FEFF004600690072007300740020006E0061006D0065>
/V <FEFF>
/DV <FEFF>
/MaxLen 40
/DR<</Font 6 0 R>>
/DA(0 0 0 rg /F3 11 Tf)
/AP<<
/N 38 0 R
>>
>>
endobj

so the entry for 004600690072007300740020006E0061006D0065 converts to First name and we can see the answer when the user sends back the form as a PDF

5 0 obj
<</AP<</N 38 0 R >>/DA(0 0 0 rg /F3 11 Tf)/DR<</Font 6 0 R >>/DV<FEFF>/F 4/FT/Tx/MaxLen 40/P 1 0 R /Rect[ 165.7 453.7 315.7 467.9]/Subtype/Widget/T(Given Name Text Box)
/TU<FEFF004600690072007300740020006E0061006D0065>/Type/Annot/V(Brunno)>>
endobj


问:
Plot the multiple values returned by a function
My function returns 2 different values which I want to utilise in 2 different graphs using Matplotlib. How can I achieve it?

```<code>def option_value_european_put(T, m, r, sigma, mu, E):
    cost_value_at_initial_t_put = []
    portfolio_payoff_put = []
    for e in E:
        delta_t = T / m
        u = (1 + (sigma * math.sqrt(delta_t)) * (math.sqrt(1 + ((mu ** 2) * delta_t) / math.pow(sigma, 2))))
        v = 2 - u
        option_stock_price_matrix_put = np.zeros((m + 1, m + 1))
        sum = 0
        k = m
        start = m
        for i in range(m + 1):
            option_stock_price_matrix_put[i][start] = max(
                (e - stock_price_binomial_model(
                    mu, sigma, T, m,
                    S
                )[i][start], 0)
            )

        for j in range(m - 1, -1, -1):
            for i in range(0, j + 1):
                v_plus = option_stock_price_matrix_put[i][j + 1]
                v_minus = option_stock_price_matrix_put[i + 1][j + 1]
                v_t = ((((v_plus - v_minus) / (u - v)) * (1 + r * delta_t)) + (u * v_minus - v * v_plus) / (u - v)) / (
                        1 + r * delta_t)
                option_stock_price_matrix_put[i][j] = v_t
        cost_value_at_initial_t_put.append(option_stock_price_matrix_put[0][0])

        for i in range(0, m+1):
            sum = sum + option_stock_price_matrix_put[k][i]

        portfolio_return_average = math.average(sum)
        portfolio_payoff_put.append(portfolio_return_average-option_stock_price_matrix_put[0][0] )

    return cost_value_at_initial_t_put, portfolio_payoff_put

</code>```

I want to use cost_value_at_initial_t_put in 1 Matplotlib plot and the other value in another plot. How can I use it?

答:
Supposing that cost_value_at_initial_t_put and portfolio_payoff_cut are both lists you can create subplots:

import matplotlib.pyplot as plt

fig, (ax_cost, ax_payoff) = plt.subplots(nrows=2)

ax_cost.plot(cost_value_at_initial_t_put)
ax_payoff.plot(portfolio_payoff_cut)
```

Body:
My function returns 2 different values which I want to utilise in 2 different graphs using Matplotlib. How can I achieve it?

def option_value_european_put(T, m, r, sigma, mu, E):
    cost_value_at_initial_t_put = []
    portfolio_payoff_put = []
    for e in E:
        delta_t = T / m
        u = (1 + (sigma * math.sqrt(delta_t)) * (math.sqrt(1 + ((mu ** 2) * delta_t) / math.pow(sigma, 2))))
        v = 2 - u
        option_stock_price_matrix_put = np.zeros((m + 1, m + 1))
        sum = 0
        k = m
        start = m
        for i in range(m + 1):
            option_stock_price_matrix_put[i][start] = max(
                (e - stock_price_binomial_model(
                    mu, sigma, T, m,
                    S
                )[i][start], 0)
            )

        for j in range(m - 1, -1, -1):
            for i in range(0, j + 1):
                v_plus = option_stock_price_matrix_put[i][j + 1]
                v_minus = option_stock_price_matrix_put[i + 1][j + 1]
                v_t = ((((v_plus - v_minus) / (u - v)) * (1 + r * delta_t)) + (u * v_minus - v * v_plus) / (u - v)) / (
                        1 + r * delta_t)
                option_stock_price_matrix_put[i][j] = v_t
        cost_value_at_initial_t_put.append(option_stock_price_matrix_put[0][0])

        for i in range(0, m+1):
            sum = sum + option_stock_price_matrix_put[k][i]

        portfolio_return_average = math.average(sum)
        portfolio_payoff_put.append(portfolio_return_average-option_stock_price_matrix_put[0][0] )

    return cost_value_at_initial_t_put, portfolio_payoff_put

I want to use cost_value_at_initial_t_put in 1 Matplotlib plot and the other value in another plot. How can I use it?


问:
Problems using circular array to take inputs and stop/print the last 10 elements once "-1" is entered
I have a Java program that should be doing what the above title describes. Unfortunately, I am now having the issue of having nothing but zeros and a Error message no matter what I input into Scanner.

The code:

```<code> public static void main(String[] args) {

  //Set variable
  int count = 0;
  int numInput = 0;
  int arrSize = 10;

  //Set and initialize string
  int[] numArray = new int[arrSize];

  //Set and initialize Scanner
  Scanner sc = new Scanner(System.in);
  System.out.println("Please input some numbers. Stop by typing -1:");

  while (numInput != -1) {
     numInput = sc.nextInt();
     //Check if input is integer or not
     if (numInput == (int)numInput) {
        if (count == -1) {
           count = numArray.length - 1;
        } else if (count == numArray.length) {
           //Append input to array
           numArray[count] = numInput;
           count++;
        }//End of conditional
     } else {
        //Error message
        System.out.println("Enter a valid integer:");
     }//End of conditional
  }//End of while loop

  //Print array with for loop
  for (int i = 0; i <= 10; i++) {
     System.out.print(numArray[i] + " ");
  }//End of for loop

  System.out.println("\n");

  sc.close();

}// End of main
</code>```

The output:

```<code>0 0 0 0 0 0 0 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at last10.main(last10.java:42)
</code>```

答:
Like Namandeep_Kaur comment said, your for loop condition is incorrect. You want it to be i < 10 and not i <= 10 because your numArray length is set to 10, however array index is zero-based in Java. So, you will access elements starting with index 0. numArray will have elements at indexes 0-9. Essentially your loop will want to stop when i is equal to 10 because then the condition 10 < 10 is false and you will not try to be accessing the element at numArray[10] which does not exist. Also I have re-factored your program.

```<code>import java.util.Scanner;
import java.util.InputMismatchException;

public class LimboProgram {

public static void main(String[] args) {

 //Set variable
 int count = 0;
 int numInput = 0;
 int arrSize = 10;

 //Set and initialize string
 int[] numArray = new int[arrSize];

 //Set and initialize Scanner
 Scanner sc = new Scanner(System.in);
 System.out.println("Please input some numbers. Stop by typing -1:");

 while (numInput != -1) {

  try
  {
     // you do not need to check if numInput is a number because
     // sc.nextInt() will throw an error if the input is not a number.
     numInput = sc.nextInt();

     if ( numInput == -1 ) {
        break;
     }

     // You can achieve a circular rotation using the modulo (%) operator.
     // So, if count becomes 10, then 10 % 10 results in 0. If count is 11,
     // then 11 % 10 results in 1. This allows you to "circle" the array.
     count = count % numArray.length;
     numArray[count] = numInput;
     count++;
  }
  catch (InputMismatchException e) {
     System.out.println(e);
  }

 }

 for (int i = 0; i < 10; i++) {
    System.out.print(numArray[i] + " ");
 }

 System.out.println("\n");

 sc.close();

 }

}
</code>```

I hope this is the result you were looking for in your program. If there's anything I can clarify further I would be happy to.

Body:
I have a Java program that should be doing what the above title describes. Unfortunately, I am now having the issue of having nothing but zeros and a Error message no matter what I input into Scanner.

The code:

 public static void main(String[] args) {

  //Set variable
  int count = 0;
  int numInput = 0;
  int arrSize = 10;

  //Set and initialize string
  int[] numArray = new int[arrSize];

  //Set and initialize Scanner
  Scanner sc = new Scanner(System.in);
  System.out.println("Please input some numbers. Stop by typing -1:");

  while (numInput != -1) {
     numInput = sc.nextInt();
     //Check if input is integer or not
     if (numInput == (int)numInput) {
        if (count == -1) {
           count = numArray.length - 1;
        } else if (count == numArray.length) {
           //Append input to array
           numArray[count] = numInput;
           count++;
        }//End of conditional
     } else {
        //Error message
        System.out.println("Enter a valid integer:");
     }//End of conditional
  }//End of while loop

  //Print array with for loop
  for (int i = 0; i <= 10; i++) {
     System.out.print(numArray[i] + " ");
  }//End of for loop

  System.out.println("\n");

  sc.close();

}// End of main

The output:

0 0 0 0 0 0 0 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at last10.main(last10.java:42)

Body:
Like Namandeep_Kaur comment said, your for loop condition is incorrect. You want it to be i < 10 and not i <= 10 because your numArray length is set to 10, however array index is zero-based in Java. So, you will access elements starting with index 0. numArray will have elements at indexes 0-9. Essentially your loop will want to stop when i is equal to 10 because then the condition 10 < 10 is false and you will not try to be accessing the element at numArray[10] which does not exist. Also I have re-factored your program.

import java.util.Scanner;
import java.util.InputMismatchException;

public class LimboProgram {

public static void main(String[] args) {

 //Set variable
 int count = 0;
 int numInput = 0;
 int arrSize = 10;

 //Set and initialize string
 int[] numArray = new int[arrSize];

 //Set and initialize Scanner
 Scanner sc = new Scanner(System.in);
 System.out.println("Please input some numbers. Stop by typing -1:");

 while (numInput != -1) {

  try
  {
     // you do not need to check if numInput is a number because
     // sc.nextInt() will throw an error if the input is not a number.
     numInput = sc.nextInt();

     if ( numInput == -1 ) {
        break;
     }

     // You can achieve a circular rotation using the modulo (%) operator.
     // So, if count becomes 10, then 10 % 10 results in 0. If count is 11,
     // then 11 % 10 results in 1. This allows you to "circle" the array.
     count = count % numArray.length;
     numArray[count] = numInput;
     count++;
  }
  catch (InputMismatchException e) {
     System.out.println(e);
  }

 }

 for (int i = 0; i < 10; i++) {
    System.out.print(numArray[i] + " ");
 }

 System.out.println("\n");

 sc.close();

 }

}

I hope this is the result you were looking for in your program. If there's anything I can clarify further I would be happy to.


问:
How can I remove/delete a HTML element using JavaScript?
I'm creating a warning paragraph that shows an error if the email is incorrect, is empty, or if it was sent. And what happens is that after showing the first warning, I want to cancel the creation of another one, so that doesn't pile up.

The current option I'm trying is to remove the warning if it already exists, otherwise, it can be created. But I don't know why it's not happening.

JS:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    if (document.getElementById(warning) == null){
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id','warning');
        input.insertAdjacentElement('afterend',warning);
    }

    else{
        const error = getElementById(warning)
        error.remove()
    }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">

  <title>Frontend Mentor | Ping coming soon page</title>

PING.

We are launching soon!

Subscribe and get notified

        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>

      Challenge by Frontend Mentor.
      Coded by Henrique Bortolim.

```

答:
You're confusing the string identifier 'warning' with a warning variable:

```<code>let warning = document.createElement('p');
</code>```

This is setting the variable warning to a paragraph element.

```<code>if (document.getElementById(warning) == null){
</code>```

Here you're passing that warning variable, which is set to an HTML element to getElementById, so it's never going to find it.

```<code>const error = getElementById(warning)
error.remove()
</code>```

Here you're making that same mistake.

With some adjustments it'll work a bit better:

```<code>function createWarning(message){
    const existingWarning = document.getElementById('warning');
    if (existingWarning) {
      existingWarning.remove();
    }

    const warning = document.createElement('p');
    warning.innerHTML = message;
    warning.classList.add('warning');
    warning.setAttribute('id','warning');
    input.insertAdjacentElement('afterend',warning);
}
</code>```

Body:
I'm creating a warning paragraph that shows an error if the email is incorrect, is empty, or if it was sent. And what happens is that after showing the first warning, I want to cancel the creation of another one, so that doesn't pile up.

The current option I'm trying is to remove the warning if it already exists, otherwise, it can be created. But I don't know why it's not happening.

JS:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    if (document.getElementById(warning) == null){
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id','warning');
        input.insertAdjacentElement('afterend',warning);
    }

    else{
        const error = getElementById(warning)
        error.remove()
    }

}

@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">

  <title>Frontend Mentor | Ping coming soon page</title>

PING.

We are launching soon!

Subscribe and get notified

        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>

      Challenge by Frontend Mentor.
      Coded by Henrique Bortolim.

Body:
You're confusing the string identifier 'warning' with a warning variable:

let warning = document.createElement('p');

This is setting the variable warning to a paragraph element.

if (document.getElementById(warning) == null){

Here you're passing that warning variable, which is set to an HTML element to getElementById, so it's never going to find it.

const error = getElementById(warning)
error.remove()

Here you're making that same mistake.

With some adjustments it'll work a bit better:

function createWarning(message){
    const existingWarning = document.getElementById('warning');
    if (existingWarning) {
      existingWarning.remove();
    }

    const warning = document.createElement('p');
    warning.innerHTML = message;
    warning.classList.add('warning');
    warning.setAttribute('id','warning');
    input.insertAdjacentElement('afterend',warning);
}


问:
Get datetime for USA from local time
I can able to get time of local sql server by GetDate() function. Sql server machine is in india.

Now I want to get the current datetime of USA on same sql server what can I do.

答:
You can do it this way

```<code>dateadd(hh,differense_between_India_and_USA,getdate())
</code>```

Time zones of the USA:

Pacific Standard Time (GMT -8)

Mountain Standard Time (GMT -7)

Central Standard Time (GMT -6)

Eastern Standard Time (GMT -5)

Alaska Standard time (GMT -9)

Hawaii Standard Time and Aleutian Standard Time (GMT -10)

ContentLicense: CC BY-SA 3.0

Title: Get datetime for USA from local time

Body:
You can do it this way

dateadd(hh,differense_between_India_and_USA,getdate())

Time zones of the USA:

Pacific Standard Time (GMT -8)

Mountain Standard Time (GMT -7)

Central Standard Time (GMT -6)

Eastern Standard Time (GMT -5)

Alaska Standard time (GMT -9)

Hawaii Standard Time and Aleutian Standard Time (GMT -10)


问:
Spring MVC: IOException parsing XML document from ServletContext resource
Intended functionality of the website: You enter two numbers, and you get a page which says Result: (the sum of the two numbers)

When I delete my example-servlet.xml file to use a configuration class, I get the error:

```<code>org.springframework.beans.factory.BeanDefinitionStoreException:
IOException parsing XML document from ServletContext resource
[/WEB-INF/example-servlet.xml]; nested exception is
java.io.FileNotFoundException: Could not open ServletContext
resource [/WEB-INF/example-servlet.xml]
</code>```

AddController.java:

```<code>package com.example.demo1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AddController {

    @RequestMapping("/add")
    public ModelAndView add(HttpServletRequest request, HttpServletResponse response) {
        int i = Integer.parseInt(request.getParameter("t1"));
        int j = Integer.parseInt(request.getParameter("t2"));
        int k = i + j;

        ModelAndView mv = new ModelAndView();
        mv.setViewName("result.jsp");
        mv.addObject("k", k);
        return mv;

    }
}
</code>```

SpringConfig.java:

```<code>package com.example.demo1;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan({"com.example.demo1"})
public class SpringConfig {
}
</code>```

WebInit.java:

```<code>package com.example.demo1;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[0];
    }
}
</code>```

my web.xml:

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

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

my index.jsp:

```<code><html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>
<form action="add" method="get">
    <input type="text" name="t1"/><br>
    <input type="text" name="t2"/><br>
    <input type="submit"/>
</form>
</body>
</html>
</code>```

Result.jsp:

```<code><%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Result</title>
</head>
<body>
<h1>Result is <%=request.getAttribute("k")%></h1>
</body>
</html>
</code>```

My project structure:

Project structure

答:
The exception message is meanning full, your spring webapplication does not found the servlet configuration file /WEB-INF/example-servlet.xml.

Seek where you must put your servlet file in any webapp.
You will find the answer yourself as soon as you try to work like that.

If you want to autodetect some configuration, in Spring Boot configuration, we use that kind of annotations :

```<code>@ServletComponentScan
@SpringBootApplication(scanBasePackages = "com.bendathierry.web")
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
@PropertySource(value = "classpath:application-${spring.profiles.active}.properties", encoding = "UTF-8")
public class YourWebApplicationMainClass {
    // Beans definitions...
}
</code>```

And, of course, bad way to display data : <%=request.getAttribute("k")%>.
You should find another way to go in order to escape any user provided datas nor calculated ones, because sometimes calculated ones are just leaks if you do not follow strict protectives programming rules.

Body:
Intended functionality of the website: You enter two numbers, and you get a page which says Result: (the sum of the two numbers)

When I delete my example-servlet.xml file to use a configuration class, I get the error:

org.springframework.beans.factory.BeanDefinitionStoreException:
IOException parsing XML document from ServletContext resource
[/WEB-INF/example-servlet.xml]; nested exception is
java.io.FileNotFoundException: Could not open ServletContext
resource [/WEB-INF/example-servlet.xml]

AddController.java:

package com.example.demo1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AddController {

    @RequestMapping("/add")
    public ModelAndView add(HttpServletRequest request, HttpServletResponse response) {
        int i = Integer.parseInt(request.getParameter("t1"));
        int j = Integer.parseInt(request.getParameter("t2"));
        int k = i + j;

        ModelAndView mv = new ModelAndView();
        mv.setViewName("result.jsp");
        mv.addObject("k", k);
        return mv;

    }
}

SpringConfig.java:

package com.example.demo1;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan({"com.example.demo1"})
public class SpringConfig {
}

WebInit.java:

package com.example.demo1;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[0];
    }
}

my web.xml:

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

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

my index.jsp:

    <title>JSP - Hello World</title>

<form action="add" method="get">
    <input type="text" name="t1"/>

    <input type="text" name="t2"/>

    <input type="submit"/>
</form>

Result.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

    <title>Result</title>

Result is <%=request.getAttribute("k")%>

My project structure:

Project structure

Body:
The exception message is meanning full, your spring webapplication does not found the servlet configuration file /WEB-INF/example-servlet.xml.

Seek where you must put your servlet file in any webapp.
You will find the answer yourself as soon as you try to work like that.

If you want to autodetect some configuration, in Spring Boot configuration, we use that kind of annotations :

@ServletComponentScan
@SpringBootApplication(scanBasePackages = "com.bendathierry.web")
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
@PropertySource(value = "classpath:application-${spring.profiles.active}.properties", encoding = "UTF-8")
public class YourWebApplicationMainClass {
    // Beans definitions...
}

And, of course, bad way to display data : <%=request.getAttribute("k")%>.
You should find another way to go in order to escape any user provided datas nor calculated ones, because sometimes calculated ones are just leaks if you do not follow strict protectives programming rules.


问:
Terraform plan error - Missing Expected {
I am using terraform 0.14.3 with custom provider to manage resources on on-perm infrastructure. Things are running fine as long as I am running Terraform to store state locally. However, when I switch to PG as backend, it gives me an error on plan:

```<code>Error: Missing Expected {
</code>```

Below is how i am using PG configuration:

```<code>terraform {
   required_providers {
       mycloud = {
         source = "terraform.provider/proj/cloud"
         version = "0.0.x"
      }
   }

  backend "pg" {
       conn_str = "postgres://connection.url.for.postgres"
  }
}
</code>```

Again if remove the backend config, it works fine.

答:
I am having the same problem.  My debugging consisted of downloading the unhealthy tfstate and deleting resources until it started working again, which identified the broken resource.  Then when I found the errant resource depicted below, I compared it to another healthy workspace :

```<code>{
  "module": "module.mongodb_project",
  "mode": "managed",
  "type": "mongodbatlas_cloud_provider_access",
  "name": "encryption_access",
  "provider": "provider[\"registry.terraform.io/mongodb/mongodbatlas\"]",
  "instances": [
    {
      "schema_version": 0,
      "attributes": {
        "atlas_assumed_role_external_id": "48491470-626e-4091-8b5e-..........",
        "atlas_aws_account_arn": "arn:aws:iam::536727724300:root",
        "authorized_date": "2021-04-19T18:40:22Z",
        "created_date": "2021-03-12T18:51:17Z",
        "feature_usages": [
          {
            "feature_id": "",     <<<< ==== THIS IS THE PROBLEM
            "feature_type": "ENCRYPTION_AT_REST"
          }
        ],
        "iam_assumed_role_arn": "arn:aws:iam::2411360.....:role/bluescape-kms",
        "id": "...",
        "project_id": "604bb8221347fxxxxxxxxxx",
        "provider_name": "AWS",
        "role_id": "604bb82577962xxxxxxxxxx"
      },
      "sensitive_attributes": [],
      "private": "xxxxxxxx",
      "dependencies": [
        "module.mongodb_project.mongodbatlas_project.project"
      ]
    }
  ]
},
</code>```

In my healthy workspace, "feature_id" is {}, whereas in this unhealthy workspace, "feature_id" is "".  Apparently, when there is a schema upgrade to a new version of a provider, they sometimes forget to run a conversion on the data and so this error represents a failure to upgrade the data structure from "" to {} (map).  It is also happening for another resource of mine in the same workspace but I have to convert {} -> null!

Terraform should do a better job of printing errors when it encounters an error in tfstate.  We have never edited the tfstate for this workspace before, the error is a result of schema upgrades that were not properly implemented by the mongo backend-provider developer.

Body:
I am using terraform 0.14.3 with custom provider to manage resources on on-perm infrastructure. Things are running fine as long as I am running Terraform to store state locally. However, when I switch to PG as backend, it gives me an error on plan:

Error: Missing Expected {

Below is how i am using PG configuration:

terraform {
   required_providers {
       mycloud = {
         source = "terraform.provider/proj/cloud"
         version = "0.0.x"
      }
   }

  backend "pg" {
       conn_str = "postgres://connection.url.for.postgres"
  }
}

Again if remove the backend config, it works fine.

Body:
I am having the same problem.  My debugging consisted of downloading the unhealthy tfstate and deleting resources until it started working again, which identified the broken resource.  Then when I found the errant resource depicted below, I compared it to another healthy workspace :

{
  "module": "module.mongodb_project",
  "mode": "managed",
  "type": "mongodbatlas_cloud_provider_access",
  "name": "encryption_access",
  "provider": "provider[\"registry.terraform.io/mongodb/mongodbatlas\"]",
  "instances": [
    {
      "schema_version": 0,
      "attributes": {
        "atlas_assumed_role_external_id": "48491470-626e-4091-8b5e-..........",
        "atlas_aws_account_arn": "arn:aws:iam::536727724300:root",
        "authorized_date": "2021-04-19T18:40:22Z",
        "created_date": "2021-03-12T18:51:17Z",
        "feature_usages": [
          {
            "feature_id": "",     <<<< ==== THIS IS THE PROBLEM
            "feature_type": "ENCRYPTION_AT_REST"
          }
        ],
        "iam_assumed_role_arn": "arn:aws:iam::2411360.....:role/bluescape-kms",
        "id": "...",
        "project_id": "604bb8221347fxxxxxxxxxx",
        "provider_name": "AWS",
        "role_id": "604bb82577962xxxxxxxxxx"
      },
      "sensitive_attributes": [],
      "private": "xxxxxxxx",
      "dependencies": [
        "module.mongodb_project.mongodbatlas_project.project"
      ]
    }
  ]
},

In my healthy workspace, "feature_id" is {}, whereas in this unhealthy workspace, "feature_id" is "".  Apparently, when there is a schema upgrade to a new version of a provider, they sometimes forget to run a conversion on the data and so this error represents a failure to upgrade the data structure from "" to {} (map).  It is also happening for another resource of mine in the same workspace but I have to convert {} -> null!

Terraform should do a better job of printing errors when it encounters an error in tfstate.  We have never edited the tfstate for this workspace before, the error is a result of schema upgrades that were not properly implemented by the mongo backend-provider developer.


问:
What is the most efficient way to see whether one item of a list is the sum of two other items in the list?
The script is supposed to take in three whole numbers from the user(who will input the numbers) and

determine whether one of them is divisible by ten.

determine whether two of the numbers can add up to the remaining number.

I believe the first one is done, but the second one puzzled me for a bit. first I did "trial and error" which worked but took up too many lines for my taste, then I tried this:

```<code>num_list = [num_1, num_2, num_3]
for i in num_list:
    a = num_list.index(i)
    if i % 10 == 0:
        is_div_by_10 = True

    if i == num_list[a-1] + num_list[a-2]:
        addsUpToNumber = True
</code>```

sure my phrasing isn't great, but I cant find a way to use lesser lines of code to get the same  result.

答:
Without changing too much, I think you were pretty close. I'd split it up into two separate loops though:

```<code>is_divisible = False
is_summable = False

num_list = [1, 2, 3]

for num in num_list:
    if num % 10 == 0:
        is_divisible = True
        break # we don't need to check the other numbers.

for i, num in enumerate(num_list):
    if num == num_list[i-1] + num_list[i-2]:
        is_summable = True
        break # we don't need to check the other numbers.
</code>```

Alternatively:

```<code>is_divisible = any(num % 10 == 0 for num in num_list)
is_summable = any(num == num_list[i-1] + num_list[i-2] for i, num in enumerate(num_list))
</code>```

Body:
The script is supposed to take in three whole numbers from the user(who will input the numbers) and

determine whether one of them is divisible by ten.

determine whether two of the numbers can add up to the remaining number.

I believe the first one is done, but the second one puzzled me for a bit. first I did "trial and error" which worked but took up too many lines for my taste, then I tried this:

num_list = [num_1, num_2, num_3]
for i in num_list:
    a = num_list.index(i)
    if i % 10 == 0:
        is_div_by_10 = True

    if i == num_list[a-1] + num_list[a-2]:
        addsUpToNumber = True

sure my phrasing isn't great, but I cant find a way to use lesser lines of code to get the same  result.

Body:
Without changing too much, I think you were pretty close. I'd split it up into two separate loops though:

is_divisible = False
is_summable = False

num_list = [1, 2, 3]

for num in num_list:
    if num % 10 == 0:
        is_divisible = True
        break # we don't need to check the other numbers.

for i, num in enumerate(num_list):
    if num == num_list[i-1] + num_list[i-2]:
        is_summable = True
        break # we don't need to check the other numbers.

Alternatively:

is_divisible = any(num % 10 == 0 for num in num_list)
is_summable = any(num == num_list[i-1] + num_list[i-2] for i, num in enumerate(num_list))


问:
Batch file to delete specific files in multiple folders
I need to delete specific files from 28 folders on the same server.
e.g

C:/folder/DMP/app_x0

C:/folder/DMP/app_x1

C:/folder/DMP/app_x2

DeleteList.txt has a list of files names (with path).

C:/folder/DMP/app_x0/ABC1.txt

C:/folder/DMP/app_x0/ABC1.doc

The batch file needs to have a loop to go through each folder one by one and delete all files mentioned in a text file. Following worked ok for one folder only if I specify the full path before each file's names in  DeleteList.txt file.

```<code>for /f "delims=" %%f in (DeleteList.txt) do del "%%f"
</code>```

How to use above so that same code could run 28 times in batch file but each time replaces folder location path. DeleteList.txt will not change.

Any sample code/suggestion would help.
Thx.

答:
One of these questions where we need to read between the lines.

Given we have on file of full filenames with the incorrect path separator, and a requirement to delete the files from 28 directories (but there's no list) then I conclude that since the required subdirectories shown are all subdirectories of C:\folder\DMP\ then the requirement actually is to delete all of the files that match the filenames in the file in all subdirectories of the parent directory of the full filename in the list.

So my suggestion would be

```<code> for /f "delims=" %%b in (DeleteList.txt) do del /s "%%~dpb..\%%~nxb"
</code>```

Naturally, you should test this on a dummy tree before implementing it.

del /s deletes in the target directory and all subdirectories. The target subdirectory is the drive and path of %%b; its parent (..); the name and extension part of %%b.

I prefer to use metavariables that are not available as metavariable-modifiers.

To delete in subdirectories but not in the parent:

```<code>for /f "delims=" %%b in (DeleteList.txt) do FOR /d %%c IN ("%%~dpb..\*") DO del /s "%%c\%%~nxb">nul
</code>```

This time, %%c is set to all subdirectorynames in turn, and the del/s applied to each subdirectory. The /s (...and subdirectories) probably isn't required. The >nul suppresses the deletion report if desired.

Body:
I need to delete specific files from 28 folders on the same server.
e.g

C:/folder/DMP/app_x0

C:/folder/DMP/app_x1

C:/folder/DMP/app_x2

DeleteList.txt has a list of files names (with path).

C:/folder/DMP/app_x0/ABC1.txt

C:/folder/DMP/app_x0/ABC1.doc

The batch file needs to have a loop to go through each folder one by one and delete all files mentioned in a text file. Following worked ok for one folder only if I specify the full path before each file's names in  DeleteList.txt file.

for /f "delims=" %%f in (DeleteList.txt) do del "%%f"

How to use above so that same code could run 28 times in batch file but each time replaces folder location path. DeleteList.txt will not change.

Any sample code/suggestion would help.
Thx.

Body:
One of these questions where we need to read between the lines.

Given we have on file of full filenames with the incorrect path separator, and a requirement to delete the files from 28 directories (but there's no list) then I conclude that since the required subdirectories shown are all subdirectories of C:\folder\DMP\ then the requirement actually is to delete all of the files that match the filenames in the file in all subdirectories of the parent directory of the full filename in the list.

So my suggestion would be

 for /f "delims=" %%b in (DeleteList.txt) do del /s "%%~dpb..\%%~nxb"

Naturally, you should test this on a dummy tree before implementing it.

del /s deletes in the target directory and all subdirectories. The target subdirectory is the drive and path of %%b; its parent (..); the name and extension part of %%b.

I prefer to use metavariables that are not available as metavariable-modifiers.

To delete in subdirectories but not in the parent:

for /f "delims=" %%b in (DeleteList.txt) do FOR /d %%c IN ("%%~dpb..\*") DO del /s "%%c\%%~nxb">nul

This time, %%c is set to all subdirectorynames in turn, and the del/s applied to each subdirectory. The /s (...and subdirectories) probably isn't required. The >nul suppresses the deletion report if desired.


问:
Where is the auto-increment check box option in phpMyAdmin when creating a table?
I've been working on my XAMPP local server and I've been just checking off the A_I column when creating a table for auto-increment. Now I'm trying to upload a website and on my godaddy's phpMyAdmin, I can't find the auto-increment button. I even tried the search function while on the page's source code, so I'm a bit confused now. How do I make a column auto-increment in the more recent versions of phpMyAdmin?</p>

答: As it turns out, it's under the 'extras' tab. Considering they only have the one option of 'auto-increment' under it, it boggles my mind why they would hide it under a tab and label it extras rather than just leaving it as a check mark, unless there are more options under 'extras' under different config.php settings for phpMyAdmin.</p>


问:
How to limit concurrent http requests with Mono & Flux
I want to handle Flux to limit concurrent HTTP requests made by List of Mono.

When some requests are done (received responses), then service requests another until the total count of waiting requests is 15.

A single request returns a list and triggers another request depending on the result.

At this point, I want to send requests with limited concurrency.
Because consumer side, too many HTTP requests make an opposite server in trouble.

I used flatMapMany like below.

```<code>public Flux<JsonNode> syncData() {
    return service1
        .getData(param1)
        .flatMapMany(res -> {
                List<Mono<JsonNode>> totalTask = new ArrayList<>();
                Map<String, Object> originData = service2.getDataFromDB(param2);
                res.withArray("data").forEach(row -> {
                       String id = row.get("id").asText();
                       if (originData.containsKey(id)) {
                           totalTask.add(service1.updateRequest(param3));
                       } else {
                            totalTask.add(service1.deleteRequest(param4));
                       }
                       originData.remove(id);
                });
                for (left) {
                    totalTask.add(service1.createRequest(param5));
                }
                return Flux.merge(totalTask);
        });
}
</code>```
```<code>void syncData() {
    syncDataService.syncData().????;
}
</code>```

I tried chaining .window(15), but it doesn't work. All the requests are sent simultaneously.

How can I handle Flux for my goal?

答:
flatMap takes a concurrency parameter: https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#flatMap-java.util.function.Function-int-

Mono<User> getById(int userId) { ... }

Flux.just(1, 2, 3, 4).flatMap(client::getById, 2)

```

will limit the number of concurrent requests to 2.

Body:
I want to handle Flux to limit concurrent HTTP requests made by List of Mono.

When some requests are done (received responses), then service requests another until the total count of waiting requests is 15.

A single request returns a list and triggers another request depending on the result.

At this point, I want to send requests with limited concurrency.
Because consumer side, too many HTTP requests make an opposite server in trouble.

I used flatMapMany like below.

public Flux<JsonNode> syncData() {
    return service1
        .getData(param1)
        .flatMapMany(res -> {
                List<Mono<JsonNode>> totalTask = new ArrayList<>();
                Map<String, Object> originData = service2.getDataFromDB(param2);
                res.withArray("data").forEach(row -> {
                       String id = row.get("id").asText();
                       if (originData.containsKey(id)) {
                           totalTask.add(service1.updateRequest(param3));
                       } else {
                            totalTask.add(service1.deleteRequest(param4));
                       }
                       originData.remove(id);
                });
                for (left) {
                    totalTask.add(service1.createRequest(param5));
                }
                return Flux.merge(totalTask);
        });
}

void syncData() {
    syncDataService.syncData().????;
}

I tried chaining .window(15), but it doesn't work. All the requests are sent simultaneously.

How can I handle Flux for my goal?

Body:
flatMap takes a concurrency parameter: https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#flatMap-java.util.function.Function-int-

Mono<User> getById(int userId) { ... }

Flux.just(1, 2, 3, 4).flatMap(client::getById, 2)

will limit the number of concurrent requests to 2.


问:
Handling socket time-out in express router
In express app (serving as API server) I would like on router level to know that client that is been currently served was disconnected because of the socket timeout and keep the response for the next time the client sends the request. This specific route sometimes leads to some long operation.
What would be the proper way to handle such flow (without switching the client to polling) ?</p>

答:
First off, to keep a response for a specific client, you will need some sort of server-side session object and corresponding client cookie to store the client-specific response in.

Then, you probably need to determine some amount of time for which you want to keep this result (how long until it gets stale?).

Third, Express by default does not timeout client requests.  So, unless you set a timeout in Express, if you're getting a timeout, then it's either coming from the client or from your hosting provider.  In some ways, it doesn't really matter where it comes from.  You can detect that the socket has been closed, but no Express request has been sent.  See the code below for how to do that.

```<code>const kMaxSaveResponseTime = 10 * 60 * 1000; // 10 minutes

app.get("/someRequest", (req, res) => {
    const priorResult = req?.session?.priorResult?.expirationTime;
    if (priorResult && priorResult >= Date.now()) {
        // if there is a prior result that hasn't yet expired, use it
        let data = req.session.priorResult.data;
        delete req.session.priorResult;
        res.send(data);
        return;
    }
    // otherwise calculate new result and attempt to send it
    // simulate some function that takes a long time
    // The setTimeout() here is just to simulate taking awhile
    setTimeout(() => {
        // We have the eventual result here
        let data = someDateWeBuilt;

        // See if the request socket is still alive
        // If not, save the result we just finished calculating
        if (res.socket.destroyed) {
            // client connection has already been killed
            // save the data we have for next connection
            req.session.priorResult = {
                expirationTime: Date.now() + kMaxSaveResponseTime,
                data: data
            };
        } else {
            // connection still alive, send the result
            res.send(data)
        }
    }, 5000);

});
</code>```

This assumes you are using express-session for server-side session state.  It assumes the client has already established a valid session.

The general idea is that you first check to see if there's a non-expired priorResult already in the session.  If so, you grab that data, removed it from the session and send it as the response.  If not, you do whatever time consuming thing you do to calculate the eventual result and when you finally have that result, you check res.socket.destroyed to see if the client socket is still alive or not.  If it is not, you cache the data in the session.  If it is still alive, you send the response.

Body:
First off, to keep a response for a specific client, you will need some sort of server-side session object and corresponding client cookie to store the client-specific response in.

Then, you probably need to determine some amount of time for which you want to keep this result (how long until it gets stale?).

Third, Express by default does not timeout client requests.  So, unless you set a timeout in Express, if you're getting a timeout, then it's either coming from the client or from your hosting provider.  In some ways, it doesn't really matter where it comes from.  You can detect that the socket has been closed, but no Express request has been sent.  See the code below for how to do that.

const kMaxSaveResponseTime = 10 * 60 * 1000; // 10 minutes

app.get("/someRequest", (req, res) => {
    const priorResult = req?.session?.priorResult?.expirationTime;
    if (priorResult && priorResult >= Date.now()) {
        // if there is a prior result that hasn't yet expired, use it
        let data = req.session.priorResult.data;
        delete req.session.priorResult;
        res.send(data);
        return;
    }
    // otherwise calculate new result and attempt to send it
    // simulate some function that takes a long time
    // The setTimeout() here is just to simulate taking awhile
    setTimeout(() => {
        // We have the eventual result here
        let data = someDateWeBuilt;

        // See if the request socket is still alive
        // If not, save the result we just finished calculating
        if (res.socket.destroyed) {
            // client connection has already been killed
            // save the data we have for next connection
            req.session.priorResult = {
                expirationTime: Date.now() + kMaxSaveResponseTime,
                data: data
            };
        } else {
            // connection still alive, send the result
            res.send(data)
        }
    }, 5000);

});

This assumes you are using express-session for server-side session state.  It assumes the client has already established a valid session.

The general idea is that you first check to see if there's a non-expired priorResult already in the session.  If so, you grab that data, removed it from the session and send it as the response.  If not, you do whatever time consuming thing you do to calculate the eventual result and when you finally have that result, you check res.socket.destroyed to see if the client socket is still alive or not.  If it is not, you cache the data in the session.  If it is still alive, you send the response.


问:
Is there a way to convert wildcard imports in java source code to named imports based on the code?
I am trying to sort through a lot of Java code and see exactly what the imports are. I am looking for a script, or some functionality from an IDE that would replace wildcard import statements with named import statements. So this:

```<code>import java.io.*; //Wildcard import

public class hello {
  public static void main(String[] args) {
    File myObj = new File("hello.txt");
    System.out.println(myObj);
  }
}
</code>```

Would become this:

```<code>import java.io.File; //Named import

public class hello {
  public static void main(String[] args) {
    File myObj = new File("hello.txt");
    System.out.println(myObj);
  }
}
</code>```

Based on 'File', from java.io appearing in the code. Any ideas?

答:
Yes, in Eclipse there are two steps.

First, you want to change your "organize imports" preferences, so that a large number of individual imports are never replaced with an asterisk.  I do that by changing both the numeric fields under Window | Preferences | Java | Code Style | Organize Imports to an impossibly large number, as shown here.

Once you've done that, the Source | Organize Imports option (also available as Ctrl+Shift+O) will arrange your import statements in order, and replace any asterisks with the full names of every class that's being imported.

Body:
I am trying to sort through a lot of Java code and see exactly what the imports are. I am looking for a script, or some functionality from an IDE that would replace wildcard import statements with named import statements. So this:

import java.io.*; //Wildcard import

public class hello {
  public static void main(String[] args) {
    File myObj = new File("hello.txt");
    System.out.println(myObj);
  }
}

Would become this:

import java.io.File; //Named import

public class hello {
  public static void main(String[] args) {
    File myObj = new File("hello.txt");
    System.out.println(myObj);
  }
}

Based on 'File', from java.io appearing in the code. Any ideas?


问:
How to input Promise string value into an object
In the code below

```<code>const getOptionName = async(id): Promise<void> => {
  const data = await dealStore.findById(id)
  console.log('data.optionName', data.optionName)
  console.log('typeof(data.optionName)', typeof(data.optionName))

  return data.optionName
}

const openRemoveDialog = (): void => {
  const checkedItems = grid1.current.getCustomCheckedList().map(item => {
    return {
      optionName: getOptionName(item.id),
      channelName: item?.channelName,
      name: item?.name,
      id: item.id,
    }
  })
  console.log('checkedItems', checkedItems)
}
</code>```

My console.log('data.optionName', data.optionName) outputs

```<code>data.optionName 딜 옵션명 테스트
</code>```

My console.log('typeof(data.optionName)', typeof (data.optionName)) outputs

```<code>typeof(data.optionName) string
</code>```

My console.log('checkedItems', checkedItems) gives the following output

I am confused why my optionName value is a Promise instead of a string when console.log('typeof(data.optionName)', typeof (data.optionName)) shows me that data.optionName is a string

I want my optionName value to be a string and not a Promise. How do I input the PromiseResult string value into my optionName?

答:
If possible you should change your Promise to ask for findByIds(ids: number[]) to get all data matching a set of IDs rather than one singular ID - this will reduce the number of network calls and remove the anti-pattern of making Promises within your map closure.

But if you want to not retrieve a Promise for optionName you'll also have to await the result of that promise as well.

return await data.optionName;
```

Body:
In the code below

const getOptionName = async(id): Promise<void> => {
  const data = await dealStore.findById(id)
  console.log('data.optionName', data.optionName)
  console.log('typeof(data.optionName)', typeof(data.optionName))

  return data.optionName
}

const openRemoveDialog = (): void => {
  const checkedItems = grid1.current.getCustomCheckedList().map(item => {
    return {
      optionName: getOptionName(item.id),
      channelName: item?.channelName,
      name: item?.name,
      id: item.id,
    }
  })
  console.log('checkedItems', checkedItems)
}

My console.log('data.optionName', data.optionName) outputs

data.optionName 딜 옵션명 테스트

My console.log('typeof(data.optionName)', typeof (data.optionName)) outputs

typeof(data.optionName) string

My console.log('checkedItems', checkedItems) gives the following output

I am confused why my optionName value is a Promise instead of a string when console.log('typeof(data.optionName)', typeof (data.optionName)) shows me that data.optionName is a string

I want my optionName value to be a string and not a Promise. How do I input the PromiseResult string value into my optionName?


问:
How can I write a where clause in SQL to filter a DATETIME column by the time of day?
I have data that is timestamped with a DATETIME column and I want to filter it down to the set of records where the DATETIME is between 9:30am and 5:30pm for any day.  What's the best way to do this?

UPDATE: Changed because I need precision to the minute, not just hour.  Sorry about that.

答:
```<code>SELECT *
FROM table1
WHERE
    (DatePart(hh, DateColumn) >= 9 and DatePart(mm, DateColumn) >= 30)
        AND (DatePart(hh, DateColumn) <= 17 AND DatePart(mm, DateColumn) <= 30)
</code>```

OwnerDisplayName: Bialecki

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milen A. Radev

OwnerDisplayName: TheTXI

LastEditorDisplayName: TheTXI


问:
How to Remove selected item from listbox C#
i currently trying to view all the files and folder selected by the user in a listbox. At the Moment i am able to list what the user have chosen using the openfiledialogue HOWEVER i am now facing prob when i try to remove it form the listbox. i trying to allow the user to click on the checkbox beside the file and press the remove button to remove it

this is my code for remove button

```<code>      private void button2_Click(object sender, EventArgs e)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            listView1.Items.Remove(listView1.SelectedItems[i]);
        }

    }
</code>```

this is the add file to listbox for reference jsut in case

```<code>    private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog openfiledialog = new OpenFileDialog();
        // Display open file dialog
        openfiledialog.InitialDirectory = "C:\\";
        //openfiledialog.Multiselect = true;
        openfiledialog.Title = "Lock File";
        openfiledialog.Filter = "All Files | *.*";
        openfiledialog.ShowDialog();

        if (openfiledialog.FileName != "")
        {

        //move through FileInfo array and store in new array of fi
            listView1.Items.Clear();
            foreach (string file in openfiledialog.FileNames)
            {
                listView1.Items.Add(file);
            }
        }

    }
</code>```

and i pressed the remove button nothing happen and i saw some answer on google on the using of selectionmode but when i used that, my listbox does not have the property of selectionmode and have red lines underlined

答:
Instead of using listView1.SelectedItems use listView1.CheckedItems and change your button2_click to:

```<code>private void button2_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem i in listView1.CheckedItems)
                listView1.Items.Remove(i);

        }
</code>```

Body:
i currently trying to view all the files and folder selected by the user in a listbox. At the Moment i am able to list what the user have chosen using the openfiledialogue HOWEVER i am now facing prob when i try to remove it form the listbox. i trying to allow the user to click on the checkbox beside the file and press the remove button to remove it

this is my code for remove button

      private void button2_Click(object sender, EventArgs e)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            listView1.Items.Remove(listView1.SelectedItems[i]);
        }

    }

this is the add file to listbox for reference jsut in case

    private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog openfiledialog = new OpenFileDialog();
        // Display open file dialog
        openfiledialog.InitialDirectory = "C:\\";
        //openfiledialog.Multiselect = true;
        openfiledialog.Title = "Lock File";
        openfiledialog.Filter = "All Files | *.*";
        openfiledialog.ShowDialog();

        if (openfiledialog.FileName != "")
        {

        //move through FileInfo array and store in new array of fi
            listView1.Items.Clear();
            foreach (string file in openfiledialog.FileNames)
            {
                listView1.Items.Add(file);
            }
        }

    }

and i pressed the remove button nothing happen and i saw some answer on google on the using of selectionmode but when i used that, my listbox does not have the property of selectionmode and have red lines underlined

Body:
Instead of using listView1.SelectedItems use listView1.CheckedItems and change your button2_click to:

private void button2_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem i in listView1.CheckedItems)
                listView1.Items.Remove(i);

        }


问:
Should I Avoid Getting the Size of a Collection in a Loop?
According to https://www.geeksforgeeks.org/12-tips-to-optimize-java-code-performance/ at number 3, it says that during a for loop, you should define size beforehand and call that in the comparator. At first, that made sense to me assuming that the .size() method has to count up the elements every time it is called.

To verify this, I went to the source code for an ArrayList and went to the size method. What I found though was that it would just return an integer size that is stored as a value in the object. This is more of what I was expecting to find, but if this is the case, then why does the article say to avoid it? It does not explain why, it merely says to never do it. From what I saw, the list is already calling a variable that is stored in memory.

So, my question is: Is it actually going to help, or is it just something that the article got wrong?

答:
yes,it is actually going to help.
i think call a method is coast more time than use a variable。</p>


答:
getOptionName is an async function, so it will return a promise. To get the value out of that promise you'll need to await it. In order to await it your map function needs to be an async function, which means you're creating an array of promises. You can then use Promise.all to combine the array of promises, and await it to get your finished array of objects.

```<code>const openRemoveDialog = async (): void => {
  const promises = grid1.current.getCustomCheckedList().map(async (item) => {
    return {
      optionName: await getOptionName(item.id),
      channelName: item?.channelName,
      name: item?.name,
      id: item.id,
    }
  })
  const checkedItems = await Promise.all(promises);
  console.log('checkedItems', checkedItems)
}
</code>```

Title: How to input Promise string value into an object

Body:
getOptionName is an async function, so it will return a promise. To get the value out of that promise you'll need to await it. In order to await it your map function needs to be an async function, which means you're creating an array of promises. You can then use Promise.all to combine the array of promises, and await it to get your finished array of objects.

const openRemoveDialog = async (): void => {
  const promises = grid1.current.getCustomCheckedList().map(async (item) => {
    return {
      optionName: await getOptionName(item.id),
      channelName: item?.channelName,
      name: item?.name,
      id: item.id,
    }
  })
  const checkedItems = await Promise.all(promises);
  console.log('checkedItems', checkedItems)
}


问:
Azure Function App & Web API in same solution
I need a both a Web API project and a function app project which share the same services / class libraries etc. A few questions

Is it bad practice to place them both in the same solution (or should they be in seperate repositories

Should the services be registered in the Startup class of the Web Api or the function app, or a mixture of the 2? Is it okay to register services only used by the function app in the web api startup class as this would make life easier? The services will do similar things and in some cases the same services will be used by both.

I am likely to only require a few timer trigger functions, most of the application will be build on the web api.

Specifically, the rest API will serve a frontend UI and the function app will provide updates to products on timer triggers.

Thanks for any guidance in advance and apologise if these are silly questions!

答:
For #1 - I think it's totally fine to have them both in the same (git) repository - you might be following a monorepo strategy, OR these projects might be closely related e.g. part of the same business domain/capability where you might have something like a a core Web API project (ASP.NET Core WebApi) as well as some Function App event handlers (in a Function App project) that respond to external async events and invoke the core Web API. Alternatively, if they're completely unrelated repos and you're not following a monorepo strategy then maybe they should be in separate repos.

For #2 - some services might be exclusive to the ASP.NET Core WebApi, some exclusive to the Function App, and some might be shared. Assuming all the code is in the same repo; for the shared dependencies, you might consider having a third 'class library' project in the same git repo that can be referenced by both the ASP.NET Core WebApi project as well as the Function app project. This 'class library' project could contain all the shared dependencies. Dependencies should be registered in the startup of both the Web Api AND the function app.


问:
3.2.0 not available on https://downloads.apache.org/spark/
Why is 3.2.0 not available here any more? https://downloads.apache.org/spark/

Just to be clear, it was here until a few days ago. This link is checked into our internal repo. Realized this artifact is no longer available when the build broke.
Need to make sure we don't go to prod with this version if there is any known major issue with it that caused it to be taken down.

答: Download Spark page has only the latest version of every major version of Spark. If you want a specific version not listed on the main downloads page, you can use Archived libraries link.</p>