问:
Angular material : Navigation schematics doesn't work
I want to create angular material navigation schematics.
when i run
ng generate @angular/material:navigation   command it gives error.

The 'path' option in 'C:\Users\Pradeepa saravanan\Documents\TS\HotelInventoryApp\node_modules@angular\material\schematics\ng-generate\navigation\schema.json' is using deprecated behaviour. 'workingDirectory' smart default provider should be used instead.
(0 , validation_1.validateName) is not a function

After that i update angular material using     ng update @angular/material  command. Again i got some error.

The installed Angular CLI version is outdated.
Installing a temporary Angular CLI versioned 15.0.4 to perform the update.
✔ Packages successfully installed.
Using package manager: npm
Collecting installed dependencies...
Found 30 dependencies.
Fetching dependency metadata from registry...
Updating multiple major versions of '@angular/material' at once is not supported. Please migrate each major version individually.
Run 'ng update @angular/material@14' in your workspace directory to update to latest '14.x' version of '@angular/material'.

After I run  'ng update @angular/material@14' command, again getting error

```<code>Packages successfully installed.
Using package manager: npm
Collecting installed dependencies...
Found 30 dependencies.
Fetching dependency metadata from registry...
× Migration failed: 404 Not Found - GET https://registry.npmjs.org/@angular%2fCLI - Not found
  See "C:\Users\PRADEE~1\AppData\Local\Temp\ng-aPCtDl\angular-errors.log" for further details.
</code>```

Help me to solve the issue

I tried to add angular material navigation schematics. continuously i got error and not able to solve myself.

Body:
I want to create angular material navigation schematics.
when i run
ng generate @angular/material:navigation   command it gives error.

The 'path' option in 'C:\Users\Pradeepa saravanan\Documents\TS\HotelInventoryApp\node_modules@angular\material\schematics\ng-generate\navigation\schema.json' is using deprecated behaviour. 'workingDirectory' smart default provider should be used instead.
(0 , validation_1.validateName) is not a function

After that i update angular material using     ng update @angular/material  command. Again i got some error.

The installed Angular CLI version is outdated.
Installing a temporary Angular CLI versioned 15.0.4 to perform the update.
✔ Packages successfully installed.
Using package manager: npm
Collecting installed dependencies...
Found 30 dependencies.
Fetching dependency metadata from registry...
Updating multiple major versions of '@angular/material' at once is not supported. Please migrate each major version individually.
Run 'ng update @angular/material@14' in your workspace directory to update to latest '14.x' version of '@angular/material'.

After I run  'ng update @angular/material@14' command, again getting error

Packages successfully installed.
Using package manager: npm
Collecting installed dependencies...
Found 30 dependencies.
Fetching dependency metadata from registry...
× Migration failed: 404 Not Found - GET https://registry.npmjs.org/@angular%2fCLI - Not found
  See "C:\Users\PRADEE~1\AppData\Local\Temp\ng-aPCtDl\angular-errors.log" for further details.

Help me to solve the issue

I tried to add angular material navigation schematics. continuously i got error and not able to solve myself.


来源: stackexchange

问:
Not Able to Change Certificate Subject for the Certificate generated from KeyStore
While using AndroidKeyStore KeyGenerator to create a new ceritificate for key attestation, why Android doesn't provide an option in KeyGenParameterSpec to allow developer to create a CA with additional SubjectAltName?

The reason to ask is that if we would like to create a self-defined gRPC channel (over HTTP2) for example, using this AndroidKeyStore-generated CA for attestation, the CN will always be unchanged as "Android Keystore Key" even setCertificateSubject() is invoked and there is no valid hostname (FQDN, IP-Address) can be verified in TLS session in GrpcUtil.checkAuthority().

The current workaround is to modified the gRPC library to call disableCheckAuthority() when utilizing OkHttp Connection.

How to set SubAltName in an attestation CA generated from Android KeyStore?

ContentLicense: CC BY-SA 4.0


问:
Quarto book publish produces "LaTeX Error: File `scrreprt.cls' not found"
When I attempt to re-publish a Quarto Book to an established url on Quarto Pub, I receive an error in the terminal. The error message in the terminal upon which it stops before republishing is:

```<code>"compilation failed- no matching packages
LaTeX Error: File `scrreprt.cls' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: cls)

Enter file name:
Emergency stop.
<read *>

l.10 ^^M
</code>```

I am unclear on how to interpret the error message.

I recently transitioned this document from bookdown to a Quarto Book. In the past I have successfully published the content to a Quarto Pub url using the following terminal command:

```<code>quarto publish quarto-pub
</code>```

The full index.log file is available on the project GitHub repository at https://github.com/Kenai-Watershed-Forum/kenai_thermal_imagery_v2/blob/main/index.log

The main repository is located at https://github.com/Kenai-Watershed-Forum/kenai_thermal_imagery_v2.

I have verified the most current versions of R, RStudio, and TeXWorks are installed.

```<code>> version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
crt            ucrt
system         x86_64, mingw32
status
major          4
minor          2.2
year           2022
month          10
day            31
svn rev        83211
language       R
version.string R version 4.2.2 (2022-10-31 ucrt)
nickname       Innocent and Trusting

</code>```

Body:
When I attempt to re-publish a Quarto Book to an established url on Quarto Pub, I receive an error in the terminal. The error message in the terminal upon which it stops before republishing is:

"compilation failed- no matching packages
LaTeX Error: File `scrreprt.cls' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: cls)

Enter file name:
Emergency stop.
<read *>

l.10 ^^M

I am unclear on how to interpret the error message.

I recently transitioned this document from bookdown to a Quarto Book. In the past I have successfully published the content to a Quarto Pub url using the following terminal command:

quarto publish quarto-pub

The full index.log file is available on the project GitHub repository at https://github.com/Kenai-Watershed-Forum/kenai_thermal_imagery_v2/blob/main/index.log

The main repository is located at https://github.com/Kenai-Watershed-Forum/kenai_thermal_imagery_v2.

I have verified the most current versions of R, RStudio, and TeXWorks are installed.

> version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
crt            ucrt
system         x86_64, mingw32
status
major          4
minor          2.2
year           2022
month          10
day            31
svn rev        83211
language       R
version.string R version 4.2.2 (2022-10-31 ucrt)
nickname       Innocent and Trusting


问:
What is the meaning of this wsgi apache error log message (in django)
My django site seems to be working without any problems.
But, looking at the apache2 error log, I frequently see this message (but no traceback or anything like it)

```<code>[Thu Dec 22 16:37:32.948596 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] [<JobsListUser: Jillian>]
[Thu Dec 22 16:37:32.948671 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] ja
</code>```

I have a model called JobsListUser, and these 2 lines appear repeatedly for all users (for example, [<JobsListUser: Kelly>] etc.)
I assume the 'ja' is code of some kind for japanese (the site is viewable in english and japanese, but i've never seen an error)

Can someone explain this to me? I want to know what the error is and if I need to fix it. I can't see any information in the log telling me which part of the code is generating the error.

Body:
My django site seems to be working without any problems.
But, looking at the apache2 error log, I frequently see this message (but no traceback or anything like it)

[Thu Dec 22 16:37:32.948596 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] [<JobsListUser: Jillian>]
[Thu Dec 22 16:37:32.948671 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] ja

I have a model called JobsListUser, and these 2 lines appear repeatedly for all users (for example, [<JobsListUser: Kelly>] etc.)
I assume the 'ja' is code of some kind for japanese (the site is viewable in english and japanese, but i've never seen an error)

Can someone explain this to me? I want to know what the error is and if I need to fix it. I can't see any information in the log telling me which part of the code is generating the error.


问:
post quantization int8 and prune my model after i trained it using ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8
im trying to inference my model in Arduino 33BLE and to do so i trained my model using ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8  i got a model size with 6.5mb with 88%map@0.5IOU which is nice so i tried to quantize the model using int8 but the model size increased to 11.5mb and the accuracy was trash i dont know what happened if someone can help me it will be great

my code to quantize the model

```<code>import tensorflow as tf
import io
import PIL
import numpy as np
import tensorflow_datasets as tfds

def representative_dataset_gen():
    folder = "/content/dataset/train/images"
    image_size = 320
    raw_test_data = []

    files = glob.glob(folder+'/*.jpeg')
    for file in files:
        image = Image.open(file)
        image = image.convert("RGB")
        image = image.resize((image_size, image_size))
        #Quantizing the image between -1,1;
        image = (2.0 / 255.0) * np.uint8(image) - 1.0
        #image = np.asarray(image).astype(np.float32)
        image = image[np.newaxis,:,:,:]
        raw_test_data.append(image)

    for data in raw_test_data:
        yield [data]

converter = tf.lite.TFLiteConverter.from_saved_model('/content/gdrive/MyDrive/customTF2/data/tflite/saved_model')
converter.representative_dataset = representative_dataset_gen
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8  # or tf.uint8
converter.inference_output_type = tf.int8  # or tf.uint8
tflite_model = converter.convert()

with open('/mydrive/customTF2/data/tflite/saved_model/detect8.tflite', 'wb') as f:
  f.write(tflite_model)
</code>```

also if there is away to prune the model it will also help with reducing the size to less than 1mb.
i also tried yolov5 and pruned and quantize the model to 1.9mb but couldnt go further, and then tried to convert the tflite model to .h model to inference in esp32 (instead since my tflite model is larger than 1mb), but the model size also increased to 11mb.

i tried post training quantization for my model but the model size increased instead of decreasing, not only that,the model performance reduced drastically. for the pruning part i couldnt do using movbilenetV2 and i hope someone can help

Body:
im trying to inference my model in Arduino 33BLE and to do so i trained my model using ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8  i got a model size with 6.5mb with 88%map@0.5IOU which is nice so i tried to quantize the model using int8 but the model size increased to 11.5mb and the accuracy was trash i dont know what happened if someone can help me it will be great

my code to quantize the model

import tensorflow as tf
import io
import PIL
import numpy as np
import tensorflow_datasets as tfds

def representative_dataset_gen():
    folder = "/content/dataset/train/images"
    image_size = 320
    raw_test_data = []

    files = glob.glob(folder+'/*.jpeg')
    for file in files:
        image = Image.open(file)
        image = image.convert("RGB")
        image = image.resize((image_size, image_size))
        #Quantizing the image between -1,1;
        image = (2.0 / 255.0) * np.uint8(image) - 1.0
        #image = np.asarray(image).astype(np.float32)
        image = image[np.newaxis,:,:,:]
        raw_test_data.append(image)

    for data in raw_test_data:
        yield [data]

converter = tf.lite.TFLiteConverter.from_saved_model('/content/gdrive/MyDrive/customTF2/data/tflite/saved_model')
converter.representative_dataset = representative_dataset_gen
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8  # or tf.uint8
converter.inference_output_type = tf.int8  # or tf.uint8
tflite_model = converter.convert()

with open('/mydrive/customTF2/data/tflite/saved_model/detect8.tflite', 'wb') as f:
  f.write(tflite_model)

also if there is away to prune the model it will also help with reducing the size to less than 1mb.
i also tried yolov5 and pruned and quantize the model to 1.9mb but couldnt go further, and then tried to convert the tflite model to .h model to inference in esp32 (instead since my tflite model is larger than 1mb), but the model size also increased to 11mb.

i tried post training quantization for my model but the model size increased instead of decreasing, not only that,the model performance reduced drastically. for the pruning part i couldnt do using movbilenetV2 and i hope someone can help


问:
Click button to Sync using retrofit: "IllegalStateException: already executed."
I have an app with a sync button. When the user clicks it, it syncs the local Room database with the cloud server's database using retrofit.

I've set it up so the user can only click the button while it's not processing, i.e. Only allow the user to sync if the previous sync operation is already complete.

The sync works great the first time loading the activity. But if the user clicks the button more than once, I get the IllegalStateException error at the allUsersRemoteCall.enqueue() line. Am I missing a step? Like allUsersRemoteCall.cancel() when the sync is complete?

So, how do I allow the user to sync twice without having to reload the Activity??

```<code>allUsersRemoteCall = repositoryRemote.getAllUsers();
        defineAllUsersRemoteCallback();
        allUsersRemoteCall.enqueue(allUsersRemoteCallback); // IllegalStateException here.
</code>```

After some reading, I tried using close instead of enqueue:

```<code>allUsersRemoteCall = repositoryRemote.getAllUsers();
        defineAllUsersRemoteCallback();
        try{
            allUsersRemoteCall.enqueue(allUsersRemoteCallback);
        } catch (IllegalStateException e){
            allUsersRemoteCall.clone().enqueue(allUsersRemoteCallback);
        }
</code>```

But this seems inelegant and it could potentially cause dual syncing if I'm not careful down the road.

Thanks for the help.

Body:
I have an app with a sync button. When the user clicks it, it syncs the local Room database with the cloud server's database using retrofit.

I've set it up so the user can only click the button while it's not processing, i.e. Only allow the user to sync if the previous sync operation is already complete.

The sync works great the first time loading the activity. But if the user clicks the button more than once, I get the IllegalStateException error at the allUsersRemoteCall.enqueue() line. Am I missing a step? Like allUsersRemoteCall.cancel() when the sync is complete?

So, how do I allow the user to sync twice without having to reload the Activity??

allUsersRemoteCall = repositoryRemote.getAllUsers();
        defineAllUsersRemoteCallback();
        allUsersRemoteCall.enqueue(allUsersRemoteCallback); // IllegalStateException here.

After some reading, I tried using close instead of enqueue:

allUsersRemoteCall = repositoryRemote.getAllUsers();
        defineAllUsersRemoteCallback();
        try{
            allUsersRemoteCall.enqueue(allUsersRemoteCallback);
        } catch (IllegalStateException e){
            allUsersRemoteCall.clone().enqueue(allUsersRemoteCallback);
        }

But this seems inelegant and it could potentially cause dual syncing if I'm not careful down the road.

Thanks for the help.


问:
Firefox PDF previewer assign Firefox tab title, as PDF's meta title and PDF's file name, how change
I am not interested any meta title of PDFs while viewing them on Firefox's PDF previewer. I only want to see PDF files' names on Firefox tabs.

Any about:config > pdfjs setting related to it?


问:
Shader graph bloom effect not working on Unity Oculus Quest 2 Build
I have been experimenting with shader graphs bloom effect with URP in unity which is coming out well on my laptop but not on Oculus Quest 2 build. Is there any way I can get that effect?
Note: I have already tried Post Processing bloom</p>


问:
How to connect to camera
How can I connect to phone camera with react native.  I want to access the phone's camera and connect to the phone's camera at any time and watch what's happening with the camera.  Kind of like a mini stalker.  Is it possible to do this with react native?

Haven't tried anything yet.  I can't figure out how to implement it.  Is there an article somewhere about this?

Title: How to connect to camera


问:
Hiding a label with Chart.js
I am working with Chart.js to craft a bar chart, but due to certain demands I have had to pull off a stacked bar chart to make it look the way I require (basically, like a bar that was being filled up).

How would I make it so the label for the "unrequired" part of the stack would not show up?

Please, do NOT suggest doing "{legend:{display:false}}" in the options - I want to keep the legend for the important value.

Title: Hiding a label with Chart.js


问:
invalid keys: card Number, cvv, expiration Month, expiration Year in braintree method
I'm trying to create a card token by using Braintree with language of PHP

```<code>$gateway = new Braintree\Gateway([
    'environment'   => 'sandbox',
    'merchantId'    => 'your_merchantId',
    'publicKey'     => 'publicKey',
    'privateKey'    => 'privateKey'
]);

$clientToken = $gateway->clientToken()->generate();
$nonce = $gateway->paymentMethodNonce()->create($clientToken, [
    'cardNumber'        => '2223000048400011',
    'expirationMonth'   => '05',
    'expirationYear'    => '2023',
    'cvv'               => '321'
]);
$cardToken = $nonce->paymentMethodNonce->nonce;
print_r($cardToken);
exit;
</code>```

In this code, I have replaced my all required key from Braintree.
Then I'm trying to create a card token by the method of payment nonce but am not able to create a token

Please help me or suggest how to create this token.

Body:
I'm trying to create a card token by using Braintree with language of PHP

$gateway = new Braintree\Gateway([
    'environment'   => 'sandbox',
    'merchantId'    => 'your_merchantId',
    'publicKey'     => 'publicKey',
    'privateKey'    => 'privateKey'
]);

$clientToken = $gateway->clientToken()->generate();
$nonce = $gateway->paymentMethodNonce()->create($clientToken, [
    'cardNumber'        => '2223000048400011',
    'expirationMonth'   => '05',
    'expirationYear'    => '2023',
    'cvv'               => '321'
]);
$cardToken = $nonce->paymentMethodNonce->nonce;
print_r($cardToken);
exit;

In this code, I have replaced my all required key from Braintree.
Then I'm trying to create a card token by the method of payment nonce but am not able to create a token

Please help me or suggest how to create this token.


问:
Some contract functions runs on hardhat network While others don't
I Got following error while testing my contract

$ npx hardhat test

  NftyplayLicense
    buyLicense
done!
      1) should buy the license successfully

  0 passing (2s)
  1 failing

  1) NftyplayLicense
       buyLicense
         should buy the license successfully:
     Error: invalid address or ENS name (argument="name", value=undefined, code=INVALID_ARGUMENT, version=contracts/5.7.0)
      at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:269:28)
      at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:281:20)
      at Logger.throwArgumentError (node_modules/@ethersproject/logger/src.ts/index.ts:285:21)
      at /home/bhavesh/Documents/boilerplate/node_modules/@ethersproject/contracts/src.ts/index.ts:123:16
      at step (node_modules/@ethersproject/contracts/lib/index.js:48:23)
      at Object.next (node_modules/@ethersproject/contracts/lib/index.js:29:53)
      at fulfilled (node_modules/@ethersproject/contracts/lib/index.js:20:58)
      at processTicksAndRejections (node:internal/process/task_queues:95:5)
```
<p>Following is the Test that I have written</p>
<pre class="lang-js prettyprint-override"><code>

const { assert, expect } = require("chai")
const { network, ethers, deployments } = require("hardhat")
const { developmentChains } = require("../helper-hardhat-config")

!developmentChains.includes(network.name)
    ? describe.skip()
    : describe("NftyplayLicense", function () {
          let nftyplayLicenseContract, nftyPlayLicense, deployer, player, param

          beforeEach(async function () {
              const accounts = await ethers.getSigners()
              deployer = accounts[0]
              player = accounts[1]
              await deployments.fixture(["all"])

              nftyplayLicenseContract = await ethers.getContract("NftyPlayLicensing")
              nftyPlayLicense = nftyplayLicenseContract.connect(deployer)

              param = {
                  name: "NftyPlayLicensing",
                  category: "1",
                  durationInDays: "1",
                  licenseType: "1",
                  nftAddress: "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
                  nonce: 735,
                  price: "1000000000000000000",
                  r: "0xb07df588e0674bc28050a58a7f2cfd315f7e0aec136d0ebcf89fdcd9fa8aa928",
                  s: "0x109a8b6ff70709d2fecdba8b385097f2f979738518e4c444d4cf95b7e2c9621b",
                  signer: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
                  tokenId: "1",
                  v: 27,
              }
          })
          describe("buyLicense", function () {
              it("should buy the license successfully", async function () {
                  nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")
                  console.log("done!")
                  nftyPlayLicense = nftyplayLicenseContract.connect(player)
                  await expect(
                      nftyPlayLicense.buyLicense(param, "https://uri.com", {
                          value: ethers.utils.parseEther("1"),
                      })
                  ).to.emit("NftyPlayLicensing", "LicenseBought")
                  const result = await nftyPlayLicense.getExecutedOrder(735)

                  assert.equal(result, true)
              })
          })
      })
</code>```

Note that

  nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")
```
<p>is running fine, not not in case of</p>
<pre class="lang-js prettyprint-override"><code> nftyPlayLicense.buyLicense(param, "https://uri.com", {
                          value: ethers.utils.parseEther("1"),
                      })
</code>```

I've made order and signature object by metamask and stored it locally and then using that i am calling buyLicense function from contract using that object as params.

this is my contract function:

```<code>function buyLicense(OrderTypes.LicenseOrder calldata order, string memory uri) public payable {
        require(isOrderExecuted[order.nonce] == false, "Order is already Executed");
        require(isCancelled[order.signer][order.nonce] == false, "Listing is Cancelled");
        bytes32 orderHash = SignatureVerifier.hashMakerOrder(order, ORDER_TYPE_HASH);
        validateMakerOrder(order, orderHash);
        uint256 licenseTokenId = mintLicenseToken(msg.sender, uri, order);

        isOrderExecuted[order.nonce] = true;

        emit LicenseBought(
            licenseTokenId,
            order.price,
            order.category,
            order.tokenId,
            order.signer,
            order.licenseType,
            order.nftContract
        );
    }
</code>```

But I am unable to run that function

Body:
I Got following error while testing my contract

$ npx hardhat test

  NftyplayLicense
    buyLicense
done!
      1) should buy the license successfully

  0 passing (2s)
  1 failing

  1) NftyplayLicense
       buyLicense
         should buy the license successfully:
     Error: invalid address or ENS name (argument="name", value=undefined, code=INVALID_ARGUMENT, version=contracts/5.7.0)
      at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:269:28)
      at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:281:20)
      at Logger.throwArgumentError (node_modules/@ethersproject/logger/src.ts/index.ts:285:21)
      at /home/bhavesh/Documents/boilerplate/node_modules/@ethersproject/contracts/src.ts/index.ts:123:16
      at step (node_modules/@ethersproject/contracts/lib/index.js:48:23)
      at Object.next (node_modules/@ethersproject/contracts/lib/index.js:29:53)
      at fulfilled (node_modules/@ethersproject/contracts/lib/index.js:20:58)
      at processTicksAndRejections (node:internal/process/task_queues:95:5)

Following is the Test that I have written

const { assert, expect } = require("chai")
const { network, ethers, deployments } = require("hardhat")
const { developmentChains } = require("../helper-hardhat-config")

!developmentChains.includes(network.name)
    ? describe.skip()
    : describe("NftyplayLicense", function () {
          let nftyplayLicenseContract, nftyPlayLicense, deployer, player, param

          beforeEach(async function () {
              const accounts = await ethers.getSigners()
              deployer = accounts[0]
              player = accounts[1]
              await deployments.fixture(["all"])

              nftyplayLicenseContract = await ethers.getContract("NftyPlayLicensing")
              nftyPlayLicense = nftyplayLicenseContract.connect(deployer)

              param = {
                  name: "NftyPlayLicensing",
                  category: "1",
                  durationInDays: "1",
                  licenseType: "1",
                  nftAddress: "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
                  nonce: 735,
                  price: "1000000000000000000",
                  r: "0xb07df588e0674bc28050a58a7f2cfd315f7e0aec136d0ebcf89fdcd9fa8aa928",
                  s: "0x109a8b6ff70709d2fecdba8b385097f2f979738518e4c444d4cf95b7e2c9621b",
                  signer: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
                  tokenId: "1",
                  v: 27,
              }
          })
          describe("buyLicense", function () {
              it("should buy the license successfully", async function () {
                  nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")
                  console.log("done!")
                  nftyPlayLicense = nftyplayLicenseContract.connect(player)
                  await expect(
                      nftyPlayLicense.buyLicense(param, "https://uri.com", {
                          value: ethers.utils.parseEther("1"),
                      })
                  ).to.emit("NftyPlayLicensing", "LicenseBought")
                  const result = await nftyPlayLicense.getExecutedOrder(735)

                  assert.equal(result, true)
              })
          })
      })

Note that

  nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")

is running fine, not not in case of

 nftyPlayLicense.buyLicense(param, "https://uri.com", {
                          value: ethers.utils.parseEther("1"),
                      })

I've made order and signature object by metamask and stored it locally and then using that i am calling buyLicense function from contract using that object as params.

this is my contract function:

function buyLicense(OrderTypes.LicenseOrder calldata order, string memory uri) public payable {
        require(isOrderExecuted[order.nonce] == false, "Order is already Executed");
        require(isCancelled[order.signer][order.nonce] == false, "Listing is Cancelled");
        bytes32 orderHash = SignatureVerifier.hashMakerOrder(order, ORDER_TYPE_HASH);
        validateMakerOrder(order, orderHash);
        uint256 licenseTokenId = mintLicenseToken(msg.sender, uri, order);

        isOrderExecuted[order.nonce] = true;

        emit LicenseBought(
            licenseTokenId,
            order.price,
            order.category,
            order.tokenId,
            order.signer,
            order.licenseType,
            order.nftContract
        );
    }

But I am unable to run that function


问:
DropDownButton in the BottomNavigationBar overflow issue when the aliged dropdown is true?
I have a DropDownButton in the bottom bar navigation. To reduce the size of the DropDownMenuItem. i have given true to the alignedDropdown in the ButtonTheme. But, It causing the DropDownButton to overflow on the right side. I tried to reduce the space between the text and the dropdown icon. But there is no way to reduce the space between them. How do I solve this?

Language DropDown:

```<code>class LanguageDropDown extends GetView {
  const LanguageDropDown({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LanguageDropDownController>(
      init: LanguageDropDownController(),
      builder: (languageDropDownController) {
        return ButtonTheme(
          alignedDropdown: true,
          child: DropdownButton<Flag>(
            value: languageDropDownController.selectedLanguage,
            underline: const SizedBox.shrink(),
            isDense: true,
            onChanged: (Flag? language) =>
                languageDropDownController.onchange(language),
            items: kLanguageDropDown.map(
              (language) {
                return DropdownMenuItem<Flag>(
                  alignment: AlignmentDirectional.center,
                  value: language,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        radius: kWidth * 0.035,
                        backgroundImage: NetworkImage(
                          "$baseUrl/${language.image}",
                        ),
                        onBackgroundImageError: <AssetImage>(context, _) {
                          return Image.asset(
                            "assets/images/nl.png",
                          );
                        },
                      ),
                      SizedBox(
                        width: kWidth * 0.025,
                      ),
                      CommonText(
                          text: language.country, size: 1, boldText: false)
                    ],
                  ),
                );
              },
            ).toList(),
          ),
        );
      },
    );
  }
}
</code>```

BottomNavigationBar :

```<code>class CommonBottomNavigationBar extends StatelessWidget {
  const CommonBottomNavigationBar({
    Key? key,
    required this.itemList,
    this.onWillPop,
    this.title,
    this.onPressed,
  }) : super(key: key);

  final List<Widget> itemList;

  final WillPopCallback? onWillPop;

  final String? title;

  final VoidCallback? onPressed;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: onWillPop ??
          () async {
            Get.back();
            return true;
          },
      child: Scaffold(
        backgroundColor: kWhite,
        endDrawer: const CommonDrawer(),
        endDrawerEnableOpenDragGesture: false,
        appBar: CommonAppBar(
          title: title != null ? "$title" : "",
          onPressed: onPressed ??
              () {
                Get.back();
              },
        ),
        body: SizedBox(
          width: kWidth,
          height: kHeight,
          child: Obx(() => itemList.elementAt(kSelectedBar.value)),
        ),
        bottomNavigationBar: Obx(
          () => BottomNavigationBar(
            currentIndex: kSelectedBar.value,
            backgroundColor: kWhite,
            selectedItemColor: kOrange,
            unselectedItemColor: kBlack45,
            showSelectedLabels: false,
            showUnselectedLabels: false,
            elevation: 1,
            type: BottomNavigationBarType.fixed,
            onTap: (int index) {
              if (Get.currentRoute != "/tasklist" &&
                  Get.currentRoute != "/login" &&
                  Get.currentRoute != "/password") {
                Get.offNamed("/tasklist");
              }
              kSelectedBar.value = index;
            },
            items: [
              const BottomNavigationBarItem(
                tooltip: "",
                label: "Language",
                icon: LanguageDropDown(),
              ),
              BottomNavigationBarItem(
                tooltip: "",
                label: "List",
                icon: Icon(
                  Icons.list,
                  size: kWidth * 0.08,
                ),
              ),
              BottomNavigationBarItem(
                tooltip: "",
                label: "Notifications",
                icon: Icon(
                  Icons.notifications_none,
                  size: kWidth * 0.08,
                ),
              ),
              BottomNavigationBarItem(
                tooltip: "",
                label: "Profile",
                icon: Icon(
                  Icons.person_outline,
                  size: kWidth * 0.08,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
I have a DropDownButton in the bottom bar navigation. To reduce the size of the DropDownMenuItem. i have given true to the alignedDropdown in the ButtonTheme. But, It causing the DropDownButton to overflow on the right side. I tried to reduce the space between the text and the dropdown icon. But there is no way to reduce the space between them. How do I solve this?

Language DropDown:

class LanguageDropDown extends GetView {
  const LanguageDropDown({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LanguageDropDownController>(
      init: LanguageDropDownController(),
      builder: (languageDropDownController) {
        return ButtonTheme(
          alignedDropdown: true,
          child: DropdownButton<Flag>(
            value: languageDropDownController.selectedLanguage,
            underline: const SizedBox.shrink(),
            isDense: true,
            onChanged: (Flag? language) =>
                languageDropDownController.onchange(language),
            items: kLanguageDropDown.map(
              (language) {
                return DropdownMenuItem<Flag>(
                  alignment: AlignmentDirectional.center,
                  value: language,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        radius: kWidth * 0.035,
                        backgroundImage: NetworkImage(
                          "$baseUrl/${language.image}",
                        ),
                        onBackgroundImageError: <AssetImage>(context, _) {
                          return Image.asset(
                            "assets/images/nl.png",
                          );
                        },
                      ),
                      SizedBox(
                        width: kWidth * 0.025,
                      ),
                      CommonText(
                          text: language.country, size: 1, boldText: false)
                    ],
                  ),
                );
              },
            ).toList(),
          ),
        );
      },
    );
  }
}

BottomNavigationBar :

class CommonBottomNavigationBar extends StatelessWidget {
  const CommonBottomNavigationBar({
    Key? key,
    required this.itemList,
    this.onWillPop,
    this.title,
    this.onPressed,
  }) : super(key: key);

  final List<Widget> itemList;

  final WillPopCallback? onWillPop;

  final String? title;

  final VoidCallback? onPressed;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: onWillPop ??
          () async {
            Get.back();
            return true;
          },
      child: Scaffold(
        backgroundColor: kWhite,
        endDrawer: const CommonDrawer(),
        endDrawerEnableOpenDragGesture: false,
        appBar: CommonAppBar(
          title: title != null ? "$title" : "",
          onPressed: onPressed ??
              () {
                Get.back();
              },
        ),
        body: SizedBox(
          width: kWidth,
          height: kHeight,
          child: Obx(() => itemList.elementAt(kSelectedBar.value)),
        ),
        bottomNavigationBar: Obx(
          () => BottomNavigationBar(
            currentIndex: kSelectedBar.value,
            backgroundColor: kWhite,
            selectedItemColor: kOrange,
            unselectedItemColor: kBlack45,
            showSelectedLabels: false,
            showUnselectedLabels: false,
            elevation: 1,
            type: BottomNavigationBarType.fixed,
            onTap: (int index) {
              if (Get.currentRoute != "/tasklist" &&
                  Get.currentRoute != "/login" &&
                  Get.currentRoute != "/password") {
                Get.offNamed("/tasklist");
              }
              kSelectedBar.value = index;
            },
            items: [
              const BottomNavigationBarItem(
                tooltip: "",
                label: "Language",
                icon: LanguageDropDown(),
              ),
              BottomNavigationBarItem(
                tooltip: "",
                label: "List",
                icon: Icon(
                  Icons.list,
                  size: kWidth * 0.08,
                ),
              ),
              BottomNavigationBarItem(
                tooltip: "",
                label: "Notifications",
                icon: Icon(
                  Icons.notifications_none,
                  size: kWidth * 0.08,
                ),
              ),
              BottomNavigationBarItem(
                tooltip: "",
                label: "Profile",
                icon: Icon(
                  Icons.person_outline,
                  size: kWidth * 0.08,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


问:
Rstudio toolbar flipped to right-to-left after update
I just updated my Rstudio following a prompt, to "Elsbeth Geranium" Release (7d165dcf, 2022-12-03) for Windows. This somehow resulted in the top toolbar getting flipped and is not presented right-to-left (see screenshot).

Has anyone encountered this, and know why this is happening and how to fix it?

I tried to find a setting for it in the Global Options but no luck there.


问:
How to implement aggregation with script query using SearchTemplateRequest with Elasticsearch 8.x version
I'm migrating my application from Elasticsearch 7.15 version to 8.x but I'm facing some issues while writing aggregation with script query using SearchTemplateRequest with Java API Client because after 7.15 version they removed some methods from the SearchTemplateResponse that include aggregation method as well now I'm trying to get the aggregation response from the script query by using 8.x version way but not able to replace. If anyone can help me with us then it will be a great help for me.

Below is the old code of the method (7.15 v):

```<code>public SearchTemplateResponse getScriptResponse(String indexName, String scriptName,
            Map<String, Object> scriptParams) throws IOException {
        SearchTemplateRequest request = null;
        SearchTemplateResponse response = null;
        try {
            SearchTemplateRequest request = new SearchTemplateRequest();
        request.setRequest(new SearchRequest(new String[] { indexName }, trackTotalHitsSourceBuilder()));
        request.setScriptType(ScriptType.STORED);
        request.setScript(scriptName);
        request.setScriptParams(scriptParams);
        request.getRequest().source().trackTotalHits();
        return request;
            response = getClient().searchTemplate(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw e;
        }
        return response;
    }
</code>```

Somewhere in the code i'm using below aggregation method of the older SearchTemplateResponse class but now in the 8.x its not available.

```<code>templateResponse.getResponse().getAggregations().get(DATE_HIST_AGG_NAME);
</code>```

Please someone help me to migrate the above method into Elasticsearch 8.x version.

I tired to migrate the above method like this but it is still not returning the aggregation response which I need as per my existing implementation

```<code>public SearchTemplateResponse getScriptResponse(String indexName, String scriptName,
                                                    Map<String, Object> scriptParams) throws IOException {
        Map<String, JsonData> params = new HashMap<>(scriptParams.size());
        for (String key : scriptParams.keySet()){
            params.put(key, JsonData.of(scriptParams.get(key)));
        }
        SearchTemplateRequest searchTemplateRequest = new SearchTemplateRequest.Builder()
                .index(indexName).params(params).source(scriptName).build();
        return getClient().searchTemplate(searchTemplateRequest,SearchTemplateResponse.class);
}
</code>```

Body:
I'm migrating my application from Elasticsearch 7.15 version to 8.x but I'm facing some issues while writing aggregation with script query using SearchTemplateRequest with Java API Client because after 7.15 version they removed some methods from the SearchTemplateResponse that include aggregation method as well now I'm trying to get the aggregation response from the script query by using 8.x version way but not able to replace. If anyone can help me with us then it will be a great help for me.

Below is the old code of the method (7.15 v):

public SearchTemplateResponse getScriptResponse(String indexName, String scriptName,
            Map<String, Object> scriptParams) throws IOException {
        SearchTemplateRequest request = null;
        SearchTemplateResponse response = null;
        try {
            SearchTemplateRequest request = new SearchTemplateRequest();
        request.setRequest(new SearchRequest(new String[] { indexName }, trackTotalHitsSourceBuilder()));
        request.setScriptType(ScriptType.STORED);
        request.setScript(scriptName);
        request.setScriptParams(scriptParams);
        request.getRequest().source().trackTotalHits();
        return request;
            response = getClient().searchTemplate(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw e;
        }
        return response;
    }

Somewhere in the code i'm using below aggregation method of the older SearchTemplateResponse class but now in the 8.x its not available.

templateResponse.getResponse().getAggregations().get(DATE_HIST_AGG_NAME);

Please someone help me to migrate the above method into Elasticsearch 8.x version.

I tired to migrate the above method like this but it is still not returning the aggregation response which I need as per my existing implementation

public SearchTemplateResponse getScriptResponse(String indexName, String scriptName,
                                                    Map<String, Object> scriptParams) throws IOException {
        Map<String, JsonData> params = new HashMap<>(scriptParams.size());
        for (String key : scriptParams.keySet()){
            params.put(key, JsonData.of(scriptParams.get(key)));
        }
        SearchTemplateRequest searchTemplateRequest = new SearchTemplateRequest.Builder()
                .index(indexName).params(params).source(scriptName).build();
        return getClient().searchTemplate(searchTemplateRequest,SearchTemplateResponse.class);
}


问:
How to do kerberos authentication in Node js
I'm changing my NTLM authentication to kerberos authentication in my node js code. But I'm not able to find any reference to add kerberos configuration and I'm using sequelize ORM. Do I have to change it to any other ORM in order to add kerberos configuration?

I have already referred this page https://www.npmjs.com/package/kerberos but I don't have miniconda 2.7 and python 2.7. please suggest me how to proceed with this python 3.7 version. I want to know the steps to install kerberos file in my machine and do the configuration to make it work.


问:
Databricks Type error in Feature Store model logging
I have trained XGBoost and Lightgbm models and now I would like to log both by using FeatureStore
logmodel function. For some reason both attempts failed due to TypeError. Is this related to databricks environment?

```<code>    model,
    "recommendation_model",
    flavor=mlflow.lightgbm,
    training_set=training_set,
    registered_model_name="model"
  ) ```

TypeError: join() argument must be str, bytes, or os.PathLike object, not 'dict'
```

The model works and I can register it with standard mlflow.sklearn.log_model function. So problem is probably in training_set?
Training set is a ft object <databricks.feature_store.training_set.TrainingSet>
and it contains 5 features (bigint/double) + target label (double))

Body:
I have trained XGBoost and Lightgbm models and now I would like to log both by using FeatureStore
logmodel function. For some reason both attempts failed due to TypeError. Is this related to databricks environment?

    model,
    "recommendation_model",
    flavor=mlflow.lightgbm,
    training_set=training_set,
    registered_model_name="model"
  ) ```

TypeError: join() argument must be str, bytes, or os.PathLike object, not 'dict'

The model works and I can register it with standard mlflow.sklearn.log_model function. So problem is probably in training_set?
Training set is a ft object <databricks.feature_store.training_set.TrainingSet>
and it contains 5 features (bigint/double) + target label (double))


问:
Can zone and zonegroups have the same name CEPH 5
I'm currently creating a new ceph cluster, and I was wondering, can a zone and its zonegroup share the same name ?
Like this:

Realm: GOLD
Zonegroup: eu-east-1
Zone: eu-east-1
Realm: Silver-1
Zonegroup: eu-east-2
Zone: eu-east-2
Realm: Silver-2
Zonegroup: eu-east-3
Zone: eu-east-3

Thanks in advance


问:
How to serialize empty list with JAXB as tag with empty body
I use feign to communicate via soap with service hosted by external company. I have definition of collection as below which is generated based on wsdl file:

```<code>@XmlElement(name = "someName", nillable = true)
protected List<String> someName;
</code>```

And when I send request with empty list, I receive empty tag in the body like:

```<code><someName />
</code>```

Is it possible to configure feign/JAXB or create some adapter to get this collection in this way:

```<code><someName></someName>
</code>```

Body:
I use feign to communicate via soap with service hosted by external company. I have definition of collection as below which is generated based on wsdl file:

@XmlElement(name = "someName", nillable = true)
protected List<String> someName;

And when I send request with empty list, I receive empty tag in the body like:

<someName />

Is it possible to configure feign/JAXB or create some adapter to get this collection in this way:

<someName></someName>


问:
Jenkins doesn't show the last changes after "git checkout master"
I have a Jenkins pipeline:

```<code>pipeline {
    agent any
    stages {
        stage('clean') {
            steps {
                cleanWs()
            }
        }
        stage('clone') {
            steps {
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: '*/master']],
                    doGenerateSubmoduleConfigurations: false,
                    extensions: [[
                        $class: 'SubmoduleOption',
                        disableSubmodules: false,
                        parentCredentials: true,
                        recursiveSubmodules: true,
                        reference: '',
                        trackingSubmodules: false
                    ]],
                    submoduleCfg: [],
                    userRemoteConfigs: [[
                        credentialsId: 'credentials_id',
                        url: 'git_url'
                    ]]
                ])
            }
        }
        stage('checkout') {
            steps {
                sh 'cd subproject'
                sh 'git status' //HEAD detached at commit_hash
                sh 'git branch' //* (HEAD detached at commit_hash)
                sh 'git checkout master' //Switched to branch 'master'. Your branch is up to date with 'origin/master'.
                sh 'git status' //On branch master. Your branch is up to date with 'origin/master'. nothing to commit, working tree clean
                sh 'git branch' //* master
                sh 'cat /var/lib/jenkins/workspace/jenkins_pipeline_name/file.txt' //Not showing the last changes
            }
        }
    }
}
</code>```

I do git checkout master but the last changes don't show. I spent several days but I couldn't find why.

Any ideas?

I found several articles about "HEAD detached at commit_hash" problem. It said that just add git checkout master but it doesn't help me.

Body:
I have a Jenkins pipeline:

pipeline {
    agent any
    stages {
        stage('clean') {
            steps {
                cleanWs()
            }
        }
        stage('clone') {
            steps {
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: '*/master']],
                    doGenerateSubmoduleConfigurations: false,
                    extensions: [[
                        $class: 'SubmoduleOption',
                        disableSubmodules: false,
                        parentCredentials: true,
                        recursiveSubmodules: true,
                        reference: '',
                        trackingSubmodules: false
                    ]],
                    submoduleCfg: [],
                    userRemoteConfigs: [[
                        credentialsId: 'credentials_id',
                        url: 'git_url'
                    ]]
                ])
            }
        }
        stage('checkout') {
            steps {
                sh 'cd subproject'
                sh 'git status' //HEAD detached at commit_hash
                sh 'git branch' //* (HEAD detached at commit_hash)
                sh 'git checkout master' //Switched to branch 'master'. Your branch is up to date with 'origin/master'.
                sh 'git status' //On branch master. Your branch is up to date with 'origin/master'. nothing to commit, working tree clean
                sh 'git branch' //* master
                sh 'cat /var/lib/jenkins/workspace/jenkins_pipeline_name/file.txt' //Not showing the last changes
            }
        }
    }
}

I do git checkout master but the last changes don't show. I spent several days but I couldn't find why.

Any ideas?

I found several articles about "HEAD detached at commit_hash" problem. It said that just add git checkout master but it doesn't help me.


问:
Update a value in another collection for multiple documents when one value is changed in one document in another collection MongoDb
I am making a group chat type of functionality where my database (Mongodb) have two collections

Groups

Users

Now the Groups collection have the data of all the groups that exists in my app and each document conatains information about an individual group and have information about the users who are in this group.

On the other hand the user have the information of all the groups he/she is joined in.

Now the problem is i have implemented the "Leave Group" functionality as it was pretty simple i just had to remove the data of that group from that particular user's information, but i dont know how to implement the "Delete Group" functionality.

Because if i delete the information about the group from group's collection by changing the active field to false , then still the users have that information and when they log in they will see that group listed because its not deleted from there document ,this is the code according to what i explained:-

```<code>app.post('/delete_group' , function(req,res){
  const group_id = req.body.group_id

  var delete_group= { $set: {active:false}}

  group.updateOne({_id:server_id} , delete_group, function(err,data){
    if(err) console.log(err)
    else{
      if(data.modifiedCount>0){
        console.log('deleted the group')
        res.json({status:200})
      }
    }
  })

})
</code>```

Now if i use the brute force approach of using either updateMany or updateOne with for loop i have to update the information in each user's document, and that feels a little ineffecient way , so is there any way to do this more efficiently? Like some refrence system or anything else , I can't think of anything else.

Body:
I am making a group chat type of functionality where my database (Mongodb) have two collections

Groups

Users

Now the Groups collection have the data of all the groups that exists in my app and each document conatains information about an individual group and have information about the users who are in this group.

On the other hand the user have the information of all the groups he/she is joined in.

Now the problem is i have implemented the "Leave Group" functionality as it was pretty simple i just had to remove the data of that group from that particular user's information, but i dont know how to implement the "Delete Group" functionality.

Because if i delete the information about the group from group's collection by changing the active field to false , then still the users have that information and when they log in they will see that group listed because its not deleted from there document ,this is the code according to what i explained:-

app.post('/delete_group' , function(req,res){
  const group_id = req.body.group_id

  var delete_group= { $set: {active:false}}

  group.updateOne({_id:server_id} , delete_group, function(err,data){
    if(err) console.log(err)
    else{
      if(data.modifiedCount>0){
        console.log('deleted the group')
        res.json({status:200})
      }
    }
  })

})

Now if i use the brute force approach of using either updateMany or updateOne with for loop i have to update the information in each user's document, and that feels a little ineffecient way , so is there any way to do this more efficiently? Like some refrence system or anything else , I can't think of anything else.


问:
Gradle: Generate folder structure dynamically during build
I have a gradle project where I want to convert WSDLs to Java classes using a gradle task. Requirement is to dynamically generate the individual java classes in separate sub-directories under a package/folder based on the number of WSDLs present. Currently my java classes are being generated under a single package/folder.

For example, if I have 2 WSDLs in my source folder then the gradle task should generate 2 java classes in separate sub-directories under the package/folder.

Please help me with a script code for the directories creation based on above scenario.


问:
How to automatically launch an application on scanning on a Honeywell eda51?
I want to create an app to do some items counting, I'm using honeywell eda51 to do so

I'm using BroadcastReceiver library to receive the scanned barcode into my app

I want to auto lunch my app when i press the scanner button on the device .. any help ?

this is my main code where i am dealing with the incoming barcode

```<code>public class MainActivity extends AppCompatActivity {

    private TextView _codeTV;
    private ListView _bsrcodlistLV;
    private List<String> list = new ArrayList<String>();
    static String TAG="Barcode Intent Example";

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        _codeTV=findViewById(R.id.codeTV);
        _bsrcodlistLV=findViewById(R.id.bsrcodlistLV);

        //Create an Intent Filter
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("mhd.nihad");

        BroadcastReceiver MyReceiver = new MyReceiver();
        registerReceiver(MyReceiver, intentFilter );

    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            String d = intent.getStringExtra("data");
            if(d!=null && d.length()>0){
                _codeTV.setText("The received barcodes are : ");

                //Filling the list
                list.add("The received barcode is : "+ d);
                final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
                        MainActivity.this, android.R.layout.simple_list_item_1, list);
                _bsrcodlistLV.setAdapter(dataAdapter);}

        }

    }
}
</code>```

it's working well, i just need to open the app when any barcode is scanned

Body:
I want to create an app to do some items counting, I'm using honeywell eda51 to do so

I'm using BroadcastReceiver library to receive the scanned barcode into my app

I want to auto lunch my app when i press the scanner button on the device .. any help ?

this is my main code where i am dealing with the incoming barcode

public class MainActivity extends AppCompatActivity {

    private TextView _codeTV;
    private ListView _bsrcodlistLV;
    private List<String> list = new ArrayList<String>();
    static String TAG="Barcode Intent Example";

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        _codeTV=findViewById(R.id.codeTV);
        _bsrcodlistLV=findViewById(R.id.bsrcodlistLV);

        //Create an Intent Filter
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("mhd.nihad");

        BroadcastReceiver MyReceiver = new MyReceiver();
        registerReceiver(MyReceiver, intentFilter );

    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            String d = intent.getStringExtra("data");
            if(d!=null && d.length()>0){
                _codeTV.setText("The received barcodes are : ");

                //Filling the list
                list.add("The received barcode is : "+ d);
                final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
                        MainActivity.this, android.R.layout.simple_list_item_1, list);
                _bsrcodlistLV.setAdapter(dataAdapter);}

        }

    }
}

it's working well, i just need to open the app when any barcode is scanned


问:
How to implement associated types in Python/Mypy? Or, what to do when wanting sub-classes to have subclass arguments?
Consider the (simplified) code, where I want Lean* and Isabelle* extend the Base*.

class BaseProblem: ...
class BaseStep: ...

class LeanProblem(BaseProblem): ...
class LeanStep(BaseStep): ...

class IsabelleProblem(BaseProblem): ...
class IsabelleStep(BaseStep): ...

class BaseProver:
    def f(self, problem: BaseProblem, step: BaseStep): ...
class LeanProver(BaseProver):
    def f(self, problem: LeanProblem, step: LeanStep): ...
class IsabelleProver(BaseProver):
    def f(self, problem: IsabelleProblem, step: IsabelleStep): ...
```
<p>However, the <code>f</code> function will have problem in mypy:</p>
```Argument 1 of "f" is incompatible with supertype "LeanProblem";
supertype defines the argument type as "BaseProblem"  [override]
```
<p>I know it can be solved by generics, such as:</p>
<pre class="lang-py prettyprint-override"><code>TProblem = TypeVar('TProblem', bound=BaseProblem)
TStep = TypeVar('TStep', bound=BaseStep)

class BaseProver(Generic[TProblem, TStep]):
    def f(self, problem: TProblem, step: TStep): ...
class LeanProver(BaseProver[LeanProblem, LeanStep]):
    def f(self, problem: LeanProblem, step: LeanStep): ...
...
</code>```

However, instead of only "Problem" and "Step", indeed I have more of such types (say, 10). Thus, the approach to use generic will be quite ugly IMHO.

When using Rust, I know we can have associated types and it can solve the problem; but I have not found an equivalent in Python.

Body:
Consider the (simplified) code, where I want Lean* and Isabelle* extend the Base*.

class BaseProblem: ...
class BaseStep: ...

class LeanProblem(BaseProblem): ...
class LeanStep(BaseStep): ...

class IsabelleProblem(BaseProblem): ...
class IsabelleStep(BaseStep): ...

class BaseProver:
    def f(self, problem: BaseProblem, step: BaseStep): ...
class LeanProver(BaseProver):
    def f(self, problem: LeanProblem, step: LeanStep): ...
class IsabelleProver(BaseProver):
    def f(self, problem: IsabelleProblem, step: IsabelleStep): ...

However, the f function will have problem in mypy:

Argument 1 of "f" is incompatible with supertype "LeanProblem";
supertype defines the argument type as "BaseProblem"  [override]

I know it can be solved by generics, such as:

TProblem = TypeVar('TProblem', bound=BaseProblem)
TStep = TypeVar('TStep', bound=BaseStep)

class BaseProver(Generic[TProblem, TStep]):
    def f(self, problem: TProblem, step: TStep): ...
class LeanProver(BaseProver[LeanProblem, LeanStep]):
    def f(self, problem: LeanProblem, step: LeanStep): ...
...

However, instead of only "Problem" and "Step", indeed I have more of such types (say, 10). Thus, the approach to use generic will be quite ugly IMHO.

When using Rust, I know we can have associated types and it can solve the problem; but I have not found an equivalent in Python.


问:
How to prevent bash environment variables from autoconverting to absolute path while using envsubst?
I am working on a shell script and need to replace some parameters in a .yaml file. I am using envsubst command but instead of getting the exact output, the leading / in one value is converted to absolute path which I do not want.

The file I am working on, test.yaml is as given below:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-azuredisk
spec:
  capacity:
    storage: ${SIZE}Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: managed-csi
  csi:
    driver: disk.csi.azure.com
    readOnly: false
    volumeHandle: ${VALUE}
    volumeAttributes:
      fsType: ext4
```
<p>I am using <code>envsubst</code> command to replace <code>${SIZE}</code> and <code>${VALUE}</code> parameters as follows:</p>
<pre class="lang-bash prettyprint-override"><code>value="/some/handle/for/volume"
size=20

export VALUE=$value SIZE=$size

echo "$(envsubst '$VALUE:$SIZE' < ./test.yaml)"
</code>```

The leading / in /some/handle/for/volume is converted to absolute path i.e., ${VALUE} is replaced by C:/Program Files/Git/some/handle/for/volume.

Is there any way to tell bash or envsubst to not consider this value as a path and just as a string?

I did experiment and calling echo $VALUE after export gives /some/handle/for/volume which might mean envsubst is causing this problem.

I did try a export VALUE="$value" SIZE="$size" as suggested by @Lea Gris but it results in the same problem.

ALTERNATIVE SOLUTION:

I am able to achieve what I want by using sed command to replace the elements, however that command is not convenient if I want to deal with multiple replacements, so I would still prefer to solve this with envsubst.

PROBLEM (MOST PROBABLE)

Looks like this problem only exists with bash on windows and the translation. From what I understand, I will not get this issue on linux. Will test it out and see.

Body:
I am working on a shell script and need to replace some parameters in a .yaml file. I am using envsubst command but instead of getting the exact output, the leading / in one value is converted to absolute path which I do not want.

The file I am working on, test.yaml is as given below:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-azuredisk
spec:
  capacity:
    storage: ${SIZE}Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: managed-csi
  csi:
    driver: disk.csi.azure.com
    readOnly: false
    volumeHandle: ${VALUE}
    volumeAttributes:
      fsType: ext4

I am using envsubst command to replace ${SIZE} and ${VALUE} parameters as follows:

value="/some/handle/for/volume"
size=20

export VALUE=$value SIZE=$size

echo "$(envsubst '$VALUE:$SIZE' < ./test.yaml)"

The leading / in /some/handle/for/volume is converted to absolute path i.e., ${VALUE} is replaced by C:/Program Files/Git/some/handle/for/volume.

Is there any way to tell bash or envsubst to not consider this value as a path and just as a string?

I did experiment and calling echo $VALUE after export gives /some/handle/for/volume which might mean envsubst is causing this problem.

I did try a export VALUE="$value" SIZE="$size" as suggested by @Lea Gris but it results in the same problem.

ALTERNATIVE SOLUTION:

I am able to achieve what I want by using sed command to replace the elements, however that command is not convenient if I want to deal with multiple replacements, so I would still prefer to solve this with envsubst.

PROBLEM (MOST PROBABLE)

Looks like this problem only exists with bash on windows and the translation. From what I understand, I will not get this issue on linux. Will test it out and see.


问:
Hide v-html while loading
I've got a v-html in my code:

```

In a slower network speed, it took a few seconds to render the HTML content. Until that, I only see plain text. Is it possible to show the div itself when the HTML is rendered?

Title: Hide v-html while loading

Body:
I've got a v-html in my code:

In a slower network speed, it took a few seconds to render the HTML content. Until that, I only see plain text. Is it possible to show the div itself when the HTML is rendered?


问:
FIle getting closed before getting downloaded?
Here is my download_file() function, Here the file should be closed after the downloading is complete, because I am awaiting for axios function Promise to complete.

async function download_file(url, filename) {
  const file_stream = fs.createWriteStream(filename);
  await axios({
    method: "GET",
    url: url,
    responseType: "stream",
  })
    .then(function (response) {
      response.data.pipe(file_stream);
    })
    .catch(function (error) {
      console.error(error);
    });

  file_stream.close();
}

await download_file(
  "https://assets.vercel.com/image/upload/v1662090959/front/nextjs/twitter-card.png",
  "twitter.png"
);
```
<p>But, the error is</p>
```node:events:505
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (node:internal/errors:377:5)
    at _write (node:internal/streams/writable:320:11)
    at Writable.write (node:internal/streams/writable:335:10)
    at IncomingMessage.ondata (node:internal/streams/readable:766:22)
    at IncomingMessage.emit (node:events:527:28)
    at Readable.read (node:internal/streams/readable:539:10)
    at flow (node:internal/streams/readable:1023:34)
    at resume_ (node:internal/streams/readable:1004:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on WriteStream instance at:
    at WriteStream.onerror (node:internal/streams/readable:785:14)
    at WriteStream.emit (node:events:527:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}

Node.js v18.2.0
```

It turns out that the file is getting closed before it is downloaded. Then, what is the point of awating the axios function.

PLEASE NOTE:

Tell me what's wrong with my code. I want to learn what's
wrong with axios. And don't post fully alternative working code.
because I've already found alternative code that works fine. But, I want to know what is the problem with awaiting axios

Body:
Here is my download_file() function, Here the file should be closed after the downloading is complete, because I am awaiting for axios function Promise to complete.

async function download_file(url, filename) {
  const file_stream = fs.createWriteStream(filename);
  await axios({
    method: "GET",
    url: url,
    responseType: "stream",
  })
    .then(function (response) {
      response.data.pipe(file_stream);
    })
    .catch(function (error) {
      console.error(error);
    });

  file_stream.close();
}

await download_file(
  "https://assets.vercel.com/image/upload/v1662090959/front/nextjs/twitter-card.png",
  "twitter.png"
);

But, the error is

node:events:505
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (node:internal/errors:377:5)
    at _write (node:internal/streams/writable:320:11)
    at Writable.write (node:internal/streams/writable:335:10)
    at IncomingMessage.ondata (node:internal/streams/readable:766:22)
    at IncomingMessage.emit (node:events:527:28)
    at Readable.read (node:internal/streams/readable:539:10)
    at flow (node:internal/streams/readable:1023:34)
    at resume_ (node:internal/streams/readable:1004:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on WriteStream instance at:
    at WriteStream.onerror (node:internal/streams/readable:785:14)
    at WriteStream.emit (node:events:527:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}

Node.js v18.2.0

It turns out that the file is getting closed before it is downloaded. Then, what is the point of awating the axios function.

PLEASE NOTE:

Tell me what's wrong with my code. I want to learn what's
wrong with axios. And don't post fully alternative working code.
because I've already found alternative code that works fine. But, I want to know what is the problem with awaiting axios


问:
How to Authenticate signup and login frontend form with Passport JS at backend
Getting my signup and login form to connect to my local MongoDB is not working. I am using a Passport for authentication. At first, it threw up "no username was given error". I fixed that by defining usernameField. Now, when I fill in details on the frontend form, it is not sending to the MongoDB database on clicking submit. The values are just there.

Here is My Server.js

```<code>const express = require("express"),
    connect = require("./config/db"),
    passport = require("passport"),
    bodyParser = require("body-parser"),
    User = require("./model/trialModel");
    LocalStrategy = require("passport-local").Strategy,
    routes = require('./route/userRoute')
    const path = require('path')

connect()
const app = express();
app.engine('html', require('ejs').renderFile)
app.set("view engine", "html");
app.set('views', path.join(__dirname, 'views'))
app.use(bodyParser.urlencoded({ extended: true }));

app.use(require("express-session")({
    secret: "Rusty is a dog",
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

// passport.use(User.createStrategy());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

//=====================
// ROUTES
//=====================

// Showing home page
app.get("/", function (req, res) {
    res.render("home");
});

// Showing secret page
app.get("/secrete", isLoggedIn, function (req, res) {
    res.render("secrete");
});

// Showing register form
app.get("/register", function (req, res) {
    res.render("register");
});

//Showing registration success page
app.get("/success", function (req, res) {
    res.render("success");
});

// // Handling user signup
// app.post("/register", function (req, res) {
//  var username = req.body.username
//  var password = req.body.password
//  var fullname = req.body.fullname
//  var email = req.body.email
//  User.findByUsername(username, function(err, user) {
//      if (err) {
//          console.log(err)
//      } else if (user){
//          res.send('username already exist!')
//      } else{
//          User.register(new User({ username: username, fullname: fullname, email: email}), password,
//          function (err, user) {
//              if (err) {
//                  console.log(err);
//                  return res.render("register");
//              } else{
//                  res.redirect('/success')
//              }
//              passport.authenticate("local")(
//                  req, res, function () {
//                  res.render("secrete");
//              });
//          });
//      }
//  })

// });

//Showing login form
app.get("/login", function (req, res) {
    res.render("login");
});

// //Handling user login
// app.post("/login", passport.authenticate("local", {
//  successRedirect: "/secrete",
//  failureRedirect: "/login"
// }), function (req, res) {
// });

// //Handling user logout
// app.get("/logout", function (req, res) {
//  req.logout(function(err){
//      if (err){
//          return next(err)
//      }
//      res.redirect("/");
//  });
// });

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) return next();
    res.redirect("/login");
}

app.use('/', routes)

var port = process.env.PORT || 4000;
app.listen(port, function () {
    console.log("Server Has Started!");
});
</code>```

Here is my controller.js

```<code>const User = require('../model/trialModel')
passport = require("passport")

//sign up
exports.signUp = (req, res) => {
    var username = req.body.username
    var password = req.body.password
    var fullname = req.body.fullname
    var email = req.body.email
    User.findByUsername(username, function(err, user) {
        if (err) {
            console.log(err)
        } else if (user){
            res.send('username already exist!')
        } else{
            User.register(new User({ username: username, fullname: fullname, email: email}), password,
            function (err, user) {
                if (err) {
                    console.log(err);
                    return res.render("register");
                } else{
                passport.authenticate("local")(
                    req, res, function () {
                    res.send('User registered successfully')
                })}
            });
        }
    })

};

//login
exports.login = passport.authenticate("local", {
    successRedirect: "/secrete",
    failureRedirect: "/login"
}), function (req, res) {
}

//logout

exports.logout = (req, res) => {
    req.logout(function(err){
        if (err){
            return next(err)
        }
        res.redirect("/");
    });
}
</code>```

Here is my Schema Model:

```<code>const {Schema, model} =  require('mongoose')
const passportLocalMongoose = require('passport-local-mongoose');
const newSchema = new Schema({
    username: {
       type: String,
       require : true
    },
    fullname: {type: String,
      require: true
   },
   email: {
      type: String,
      require: true
   }
},
{timestamps: true})
newSchema.plugin(passportLocalMongoose,{
   usernameField: 'fullname'
});

const todoModel = model('trial', newSchema);

module.exports = todoModel
</code>```

Here is my HTML for Signup:

```<code>    <h1> Sign up form </h1>

    <h1>Auth-wiki</h1>
    <h2>Create your free account</h2>

    <form action="" id="register">
      <div class="input-details">
        <label for="">Full name</label> <br />
        <input type="text" name="fullname" placeholder="Enter full name" id="" />
        <br />
        <label for="">Username</label> <br />
        <input type="text" name="username" placeholder="Enter username" id="" />
        <br />
        <label for=""> Email</label> <br />
        <input
          type="email"
          name="email"
          placeholder="Enter username or email"
          id="email"
        />
        <h5 id="email-msg"></h5>
        <br />
        <label for="">Password</label> <br />
        <input
          type="password"
          name="password"
          placeholder="Enter Password"
          id="Password"

        />

        <h5 id="pass-msg"></h5>
      </div>
      <div class="check">
        <input type="checkbox" id="checkbox" />
        <label for="">Remember Password</label>
      </div>
      <button id="creat-account" type="submit">Create account</button>
    </form>

<h1>This is home page</h1>

<li><a href="./register">Sign up!!</a></li>
<li><a href="./login">Login</a></li>
<li><a href="/logout">Logout</a></li>
</code>```

Here is my codes to consume the API from the Frontend:

```<code>const registerForm = document.getElementById('register')
    function registerUser(event) {
    event.preventDefault();
let fullname = event.target.fullname.value
let username = event.target.username.value
let password = event.target.password.value

//validation

if (!username || !password || !fullname) {
    alert('All fields must be entered')
    return;
}

        let userObj = {
    fullname,
    username,
    password
 }
 console.log(userObj)
 fetchAPI(userObj,'register', 'POST').then((data) =>{
if (data) {
     alert('user created successfully! Click ok to sign in')
    // window.location.href = "../"
 }
})
    }

const API = 'http://localhost:4000';

async function fetchAPI(data, endpointurl, method) {
    try {
        //response from form
        const response = await fetch(`${API}/${endpointurl}`, {
            method: 'POST',
            headers: {
                "content-type": "application/json"
            },
            body:JSON.stringify(data) //convert the plain data to json so server is able to read it
        })
        const result = await response.json()
        console.log(result)
    } catch (error) {

    }
}

    registerForm.addEventListener('submit', registerUser)
</code>```

Body:
Getting my signup and login form to connect to my local MongoDB is not working. I am using a Passport for authentication. At first, it threw up "no username was given error". I fixed that by defining usernameField. Now, when I fill in details on the frontend form, it is not sending to the MongoDB database on clicking submit. The values are just there.

Here is My Server.js

const express = require("express"),
    connect = require("./config/db"),
    passport = require("passport"),
    bodyParser = require("body-parser"),
    User = require("./model/trialModel");
    LocalStrategy = require("passport-local").Strategy,
    routes = require('./route/userRoute')
    const path = require('path')

connect()
const app = express();
app.engine('html', require('ejs').renderFile)
app.set("view engine", "html");
app.set('views', path.join(__dirname, 'views'))
app.use(bodyParser.urlencoded({ extended: true }));

app.use(require("express-session")({
    secret: "Rusty is a dog",
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

// passport.use(User.createStrategy());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

//=====================
// ROUTES
//=====================

// Showing home page
app.get("/", function (req, res) {
    res.render("home");
});

// Showing secret page
app.get("/secrete", isLoggedIn, function (req, res) {
    res.render("secrete");
});

// Showing register form
app.get("/register", function (req, res) {
    res.render("register");
});

//Showing registration success page
app.get("/success", function (req, res) {
    res.render("success");
});

// // Handling user signup
// app.post("/register", function (req, res) {
//  var username = req.body.username
//  var password = req.body.password
//  var fullname = req.body.fullname
//  var email = req.body.email
//  User.findByUsername(username, function(err, user) {
//      if (err) {
//          console.log(err)
//      } else if (user){
//          res.send('username already exist!')
//      } else{
//          User.register(new User({ username: username, fullname: fullname, email: email}), password,
//          function (err, user) {
//              if (err) {
//                  console.log(err);
//                  return res.render("register");
//              } else{
//                  res.redirect('/success')
//              }
//              passport.authenticate("local")(
//                  req, res, function () {
//                  res.render("secrete");
//              });
//          });
//      }
//  })

// });

//Showing login form
app.get("/login", function (req, res) {
    res.render("login");
});

// //Handling user login
// app.post("/login", passport.authenticate("local", {
//  successRedirect: "/secrete",
//  failureRedirect: "/login"
// }), function (req, res) {
// });

// //Handling user logout
// app.get("/logout", function (req, res) {
//  req.logout(function(err){
//      if (err){
//          return next(err)
//      }
//      res.redirect("/");
//  });
// });

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) return next();
    res.redirect("/login");
}

app.use('/', routes)

var port = process.env.PORT || 4000;
app.listen(port, function () {
    console.log("Server Has Started!");
});

Here is my controller.js

const User = require('../model/trialModel')
passport = require("passport")

//sign up
exports.signUp = (req, res) => {
    var username = req.body.username
    var password = req.body.password
    var fullname = req.body.fullname
    var email = req.body.email
    User.findByUsername(username, function(err, user) {
        if (err) {
            console.log(err)
        } else if (user){
            res.send('username already exist!')
        } else{
            User.register(new User({ username: username, fullname: fullname, email: email}), password,
            function (err, user) {
                if (err) {
                    console.log(err);
                    return res.render("register");
                } else{
                passport.authenticate("local")(
                    req, res, function () {
                    res.send('User registered successfully')
                })}
            });
        }
    })

};

//login
exports.login = passport.authenticate("local", {
    successRedirect: "/secrete",
    failureRedirect: "/login"
}), function (req, res) {
}

//logout

exports.logout = (req, res) => {
    req.logout(function(err){
        if (err){
            return next(err)
        }
        res.redirect("/");
    });
}

Here is my Schema Model:

const {Schema, model} =  require('mongoose')
const passportLocalMongoose = require('passport-local-mongoose');
const newSchema = new Schema({
    username: {
       type: String,
       require : true
    },
    fullname: {type: String,
      require: true
   },
   email: {
      type: String,
      require: true
   }
},
{timestamps: true})
newSchema.plugin(passportLocalMongoose,{
   usernameField: 'fullname'
});

const todoModel = model('trial', newSchema);

module.exports = todoModel

Here is my HTML for Signup:

 Sign up form

Auth-wiki

Create your free account

    <form action="" id="register">

        Full name

        <input type="text" name="fullname" placeholder="Enter full name" id="" />

        Username

        <input type="text" name="username" placeholder="Enter username" id="" />

         Email

        <input
          type="email"
          name="email"
          placeholder="Enter username or email"
          id="email"
        />

        Password

        <input
          type="password"
          name="password"
          placeholder="Enter Password"
          id="Password"

        />

        <input type="checkbox" id="checkbox" />
        Remember Password

      <button id="creat-account" type="submit">Create account</button>
    </form>

This is home page

Sign up!!

Login

Logout

Here is my codes to consume the API from the Frontend:

const registerForm = document.getElementById('register')
    function registerUser(event) {
    event.preventDefault();
let fullname = event.target.fullname.value
let username = event.target.username.value
let password = event.target.password.value

//validation

if (!username || !password || !fullname) {
    alert('All fields must be entered')
    return;
}

        let userObj = {
    fullname,
    username,
    password
 }
 console.log(userObj)
 fetchAPI(userObj,'register', 'POST').then((data) =>{
if (data) {
     alert('user created successfully! Click ok to sign in')
    // window.location.href = "../"
 }
})
    }

const API = 'http://localhost:4000';

async function fetchAPI(data, endpointurl, method) {
    try {
        //response from form
        const response = await fetch(`${API}/${endpointurl}`, {
            method: 'POST',
            headers: {
                "content-type": "application/json"
            },
            body:JSON.stringify(data) //convert the plain data to json so server is able to read it
        })
        const result = await response.json()
        console.log(result)
    } catch (error) {

    }
}

    registerForm.addEventListener('submit', registerUser)


问:
I got this error when using sessionFactory. I tried to fix it but it didn't work
This is the error when I try to run it</p>
```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/configs/spring-config-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.cfg.beanvalidation.IntegrationException: Error activating Bean Validation integration
```
`
</code>```

Body:
This is the error when I try to run it

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/configs/spring-config-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.cfg.beanvalidation.IntegrationException: Error activating Bean Validation integration
```
`


问:
Sequelize List all unmanaged instances of transactions MySQL
I have a doubt that there are one or more areas in my node.js app where I did not commit or rollback the unmanaged transaction. I want to know a way to list down all opened unmanaged instances of Sequelize transactions. I am using Sequelize ver 3 and dialect is mysql.

Thank you


问:
My Node Api is missing records randomly in reactjs but when I try on postman its works fine
I created the Nodejs with express mongoose for the API's and when I try to fetch the products it behaves very abnormally to me. For example, I'm requesting 4 products then it responds me only 2 products and something 1 and something 4 products. I'm confused why this is happing.

My Api Link

The Above Link is the API of the fectching products with Get Method. If I run this api in post its works fine and if I run this on the reactjs application then the data missed.

enter image description here

As you can see in this Image, I'm requesting for 4 products and It gives me only 3.

That's the function I'm using for the API's.

```<code>exports.getPackages = async function (req, res) {
  const pids = req.query.p_id;
  let newObject = [];

  let obj = {};
  for (i = 0; i < pids.length; i++) {
    let cr = [];
    const package = await priceModel
      .find({ pid: pids[i] })
      .select({ pro_config_options: 0 });
    //res.json(package);
    const packageFeatures = await featuresModel
      .find({ pid: pids[i] })
      .select({ pid: 0 });
    //res.json(packageFeatures);
    for (j = 0; j < package.length; j++) {
      let ccr = {
        currency: package[j].currency,
        annually: package[j].annually,
        biennially: package[j].biennially,
        triennially: package[j].triennially,
        monthly: package[j].monthly,
        quarterly: package[j].quarterly,
        semiannually: package[j].semiannually,
        qsetupfee: package[j].qsetupfee,
        ssetupfee: package[j].ssetupfee,
        asetupfee: package[j].asetupfee,
        bsetupfee: package[j].bsetupfee,
        tsetupfee: package[j].tsetupfee,
      };
      cr.push(ccr);
    }

    obj = {
      id: package[0]._id,
      pid: package[0].pid,
      name: package[0].name,
      title: package[0].title,
      tid: "",
      fname: package[0].fname,
      currency: cr,
      addons: [],
      freedomain: [],
      packageFeatures,
      addonids: package[0].addonids,
    };
    // res.json(obj);
    newObject.push(obj);
    //package.push(newObject);
  }
  res.json(newObject);
};
</code>```

The above code is fecthing and generating the objects for my frontend. It fecth the multiple data from the model.

Kindly if anyone know how to fix this please letme know. Thank you.

I tried a lot but nothing happened. Firstly I think it's on my frontend issue but I tried multiple things like react query, fetch, Axios, etc for API calling but same it's giving me random data.

Body:
I created the Nodejs with express mongoose for the API's and when I try to fetch the products it behaves very abnormally to me. For example, I'm requesting 4 products then it responds me only 2 products and something 1 and something 4 products. I'm confused why this is happing.

My Api Link

The Above Link is the API of the fectching products with Get Method. If I run this api in post its works fine and if I run this on the reactjs application then the data missed.

enter image description here

As you can see in this Image, I'm requesting for 4 products and It gives me only 3.

That's the function I'm using for the API's.

exports.getPackages = async function (req, res) {
  const pids = req.query.p_id;
  let newObject = [];

  let obj = {};
  for (i = 0; i < pids.length; i++) {
    let cr = [];
    const package = await priceModel
      .find({ pid: pids[i] })
      .select({ pro_config_options: 0 });
    //res.json(package);
    const packageFeatures = await featuresModel
      .find({ pid: pids[i] })
      .select({ pid: 0 });
    //res.json(packageFeatures);
    for (j = 0; j < package.length; j++) {
      let ccr = {
        currency: package[j].currency,
        annually: package[j].annually,
        biennially: package[j].biennially,
        triennially: package[j].triennially,
        monthly: package[j].monthly,
        quarterly: package[j].quarterly,
        semiannually: package[j].semiannually,
        qsetupfee: package[j].qsetupfee,
        ssetupfee: package[j].ssetupfee,
        asetupfee: package[j].asetupfee,
        bsetupfee: package[j].bsetupfee,
        tsetupfee: package[j].tsetupfee,
      };
      cr.push(ccr);
    }

    obj = {
      id: package[0]._id,
      pid: package[0].pid,
      name: package[0].name,
      title: package[0].title,
      tid: "",
      fname: package[0].fname,
      currency: cr,
      addons: [],
      freedomain: [],
      packageFeatures,
      addonids: package[0].addonids,
    };
    // res.json(obj);
    newObject.push(obj);
    //package.push(newObject);
  }
  res.json(newObject);
};

The above code is fecthing and generating the objects for my frontend. It fecth the multiple data from the model.

Kindly if anyone know how to fix this please letme know. Thank you.

I tried a lot but nothing happened. Firstly I think it's on my frontend issue but I tried multiple things like react query, fetch, Axios, etc for API calling but same it's giving me random data.