问:
nodejs recoginise imports defined in package.json
it is possible to define static paths in package json using this:

```<code>"imports": {
  "#hooks/*": "./hooks/*",
  "#libs/*": "./libs/*",
  "#components/*": "./components/*",
  "#components-ui/*": "./components-ui/*"
},
</code>```

It works fine, however VSC can't resolve the packages, consequently not autocomplete and not type definitions.
There must be some way to configure this.
Anyone an idea?

Body:
it is possible to define static paths in package json using this:

"imports": {
  "#hooks/*": "./hooks/*",
  "#libs/*": "./libs/*",
  "#components/*": "./components/*",
  "#components-ui/*": "./components-ui/*"
},

It works fine, however VSC can't resolve the packages, consequently not autocomplete and not type definitions.
There must be some way to configure this.
Anyone an idea?


来源: stackexchange

问:
How to pass string value as request body to the post method of third party API
I am trying for call external API call using POST method,

So for above POST API call i am facing an issue for content body not able to pass file path weblink as parameter.

```<code>   postBody, _ := json.Marshal(map[string]string{
    "www://xyz.org/file.txt",

   })

   requestBody := bytes.NewBuffer(postBody)

`  resp, err := http.Post(("--POST API call--", "application/json", requestBody )
`
</code>```

So if requestBody will fetch POST API call then, it should be allow to pass as a parameter with content body.

but its creating issue as below I have attached Postman snap where we can get to know content body is passing as null which should be like value of "www://xyz.org/file.txt"

normally POST call having requestBody body like below

```<code> postBody, _ := json.Marshal(map[string]string{
      "Key1":  "Value1",
      "key2": "Value2",
   })
</code>```

**But in my case as below **
whichever file path I am calling that pass as a default web url value without key

```<code> postBody, _ := json.Marshal(map[string]string{
       "www://xyz.org/file.txt",--------> // here no key available, only value as a string value
   })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying for call external API call using POST method,

So for above POST API call i am facing an issue for content body not able to pass file path weblink as parameter.

   postBody, _ := json.Marshal(map[string]string{
    "www://xyz.org/file.txt",

   })

   requestBody := bytes.NewBuffer(postBody)

`  resp, err := http.Post(("--POST API call--", "application/json", requestBody )
`

So if requestBody will fetch POST API call then, it should be allow to pass as a parameter with content body.

but its creating issue as below I have attached Postman snap where we can get to know content body is passing as null which should be like value of "www://xyz.org/file.txt"

normally POST call having requestBody body like below

 postBody, _ := json.Marshal(map[string]string{
      "Key1":  "Value1",
      "key2": "Value2",
   })

**But in my case as below **
whichever file path I am calling that pass as a default web url value without key

 postBody, _ := json.Marshal(map[string]string{
       "www://xyz.org/file.txt",--------> // here no key available, only value as a string value
   })


问:
How to capture an object that has had its state changed?
I have the following object:

```<code>[
    {
        id: "1",
        name:"House 1",
        status:"Reserved",
    },
    {
        id: "2",
        name:"House 2",
        status: "Open",
    },
    {
        id: "3",
        name: "House 3",
        status: "Reserved"
    }
]
</code>```

When there is a change in the status of the object from Open to Reserved, I need to display this on the screen

I tried to create a map for this, but all elements with status "Reserved" are displayed on screen and not just the last value to be updated for this state. What did I do wrong?

```<code>export default function States(House){

    const[data, setData] = useState(House);
    const[newArray, setNewArray] = useState();

    useEffect(() => {
        const statusHouse = data.map(data => data.status)
        // Here I created a new Array that receives data from my newArray variable in the last position
        setNewArray(statusHome);

        const newArrayStatusHouse = []
        newArrayStatushouse.push(newArray)
    },[])

    return (
        <div>
            {data.map(data => {
                return (
                    <div>
                        <p>Status House</p>
                        <p>data.status</p>
                    </div>
                )
            }}
        </div>
    )
}
</code>```

Body:
I have the following object:

[
    {
        id: "1",
        name:"House 1",
        status:"Reserved",
    },
    {
        id: "2",
        name:"House 2",
        status: "Open",
    },
    {
        id: "3",
        name: "House 3",
        status: "Reserved"
    }
]

When there is a change in the status of the object from Open to Reserved, I need to display this on the screen

I tried to create a map for this, but all elements with status "Reserved" are displayed on screen and not just the last value to be updated for this state. What did I do wrong?

export default function States(House){

    const[data, setData] = useState(House);
    const[newArray, setNewArray] = useState();

    useEffect(() => {
        const statusHouse = data.map(data => data.status)
        // Here I created a new Array that receives data from my newArray variable in the last position
        setNewArray(statusHome);

        const newArrayStatusHouse = []
        newArrayStatushouse.push(newArray)
    },[])

    return (

            {data.map(data => {
                return (

Status House

data.status

                )
            }}

    )
}


问:
Set up automatic uploading of native symbols for BUILD_VARIANT
I am currently integrating firebase crashlytics for my native code. In firebase native crashlytics documentation, I have found step number 4, now can anyone help me how I can upload a native symbol in my project according to step number 4? I'm unable to understand how to integrate it. I am using CMake to build my project.

I am attaching the image of step number 4.[enter image description here]


问:
Targetting specific PHP minor version in Azure App Services
I tried targeting a specific minor version of PHP in my YAML file and it crashed my pipeline.

I previously had 8.1 and attempted 8.1.10 (to match our current development environments). Without this, the app service seems to deploy 8.1.12.

However, it seems that composer was finding 8.2 and failed to update based on this as my requirements in composer.json were 8.1.

The App Service, in Azure, is configured for 8.1.

Current code:

```<code>variables:
    phpVersion: '8.1'
</code>```

Attempted:

```<code>variables:
    phpVersion: '8.1.10'
</code>```

Edit #1

Pipeline info:

```<code>Pool: Azure Pipelines
Image: ubuntu-20.04
Agent: Hosted Agent
</code>```

Body:
I tried targeting a specific minor version of PHP in my YAML file and it crashed my pipeline.

I previously had 8.1 and attempted 8.1.10 (to match our current development environments). Without this, the app service seems to deploy 8.1.12.

However, it seems that composer was finding 8.2 and failed to update based on this as my requirements in composer.json were 8.1.

The App Service, in Azure, is configured for 8.1.

Current code:

variables:
    phpVersion: '8.1'

Attempted:

variables:
    phpVersion: '8.1.10'

Edit #1

Pipeline info:

Pool: Azure Pipelines
Image: ubuntu-20.04
Agent: Hosted Agent


问:
why unpickling functions is not possible using pickle?
when i use pickle package to serialize a dict object for example, i can load it in another context without problem. but it's not the case for functions unless i import it again as explained here (i don't know if it's feasible in case of functions defined inside notebooks).  But why this behaviour?, how function object is different from dict object?

example:

open notebook A, run the following:

```<code>def func(x):
   return x**2
with open("myfile", "wb") as f:
    pickle.dump(func,f)
</code>```

open notebook B, run the following:

```<code>with open("myfile", "rb") as f:
    func = pickle.load(f)
</code>```

this would return

```<code>AttributeError: Can't get attribute 'func' on <module '__main__'>
</code>```

Body:
when i use pickle package to serialize a dict object for example, i can load it in another context without problem. but it's not the case for functions unless i import it again as explained here (i don't know if it's feasible in case of functions defined inside notebooks).  But why this behaviour?, how function object is different from dict object?

example:

open notebook A, run the following:

def func(x):
   return x**2
with open("myfile", "wb") as f:
    pickle.dump(func,f)

open notebook B, run the following:

with open("myfile", "rb") as f:
    func = pickle.load(f)

this would return

AttributeError: Can't get attribute 'func' on <module '__main__'>


问:
Why facebook APP Review team cant access our web-application during review?
During the app review, the Facebook team is open our website https://jivochat.com and then should log into web-application: https://app.jivosite.com, but they faced with ERR_SSL_PROTOCOL_ERROR problem. This is a strange situation as we have more than 250 000 customers around the world without any problems. We are using goDaddy (OV) SSL Certificate for our web-application: https://app.jivosite.com

As it is a problem on app review team side, we don't know what we should do to fix this issue. Is there any suggestions?


问:
LSTM on CPU is significantly slower on PyTorch compared to other frameworks
I’ve been experimenting with different models and different frameworks, and I’ve noticed that when using CPU, training a LSTM model on the IMDB dataset is 3x to 5x slower on PyTorch (v1.10) (around 739 seconds) compared to the Keras and TensorFlow implementations (around 201 seconds and around 135 seconds, respectively). Moreover, I’ve also noticed that the first epoch takes significantly more time than the rest of the epochs:

```<code>-PyTorch: Epoch 1 done in 235.0469572544098s
-PyTorch: Epoch 2 done in 125.87335634231567s
-PyTorch: Epoch 3 done in 125.26632475852966s
-PyTorch: Epoch 4 done in 126.59195327758789s
-PyTorch: Epoch 5 done in 126.00697541236877s
</code>```

Which doesn’t occur when using the other frameworks:

Keras:

```<code>Epoch 1/5
98/98 [==============================] - 41s 408ms/step - loss: 0.5280 - accuracy: 0.7300
Epoch 2/5
98/98 [==============================] - 40s 404ms/step - loss: 0.3441 - accuracy: 0.8566
Epoch 3/5
98/98 [==============================] - 40s 406ms/step - loss: 0.2384 - accuracy: 0.9080
Epoch 4/5
98/98 [==============================] - 40s 406ms/step - loss: 0.1625 - accuracy: 0.9386
Epoch 5/5
98/98 [==============================] - 40s 406ms/step - loss: 0.1176 - accuracy: 0.9580
</code>```

TensorFlow:

```<code>-TensorFlow: Epoch 1 done in 37.287458419799805s
-TensorFlow: Epoch 2 done in 36.93708920478821s
-TensorFlow: Epoch 3 done in 36.85307550430298s
-TensorFlow: Epoch 4 done in 37.23605704307556s
-TensorFlow: Epoch 5 done in 37.04216718673706s
</code>```

While using GPU, the problem seems to disappear.

PyTorch:

```<code>-PyTorch: Epoch 1 done in 2.6681089401245117s
-PyTorch: Epoch 2 done in 2.623263120651245s
-PyTorch: Epoch 3 done in 2.6285109519958496s
-PyTorch: Epoch 4 done in 2.6813976764678955s
-PyTorch: Epoch 5 done in 2.6470844745635986s
</code>```

Keras:

```<code>Epoch 1/5
98/98 [==============================] - 6s 44ms/step - loss: 0.5434 - accuracy: 0.7220
Epoch 2/5
98/98 [==============================] - 4s 44ms/step - loss: 0.4673 - accuracy: 0.7822
Epoch 3/5
98/98 [==============================] - 4s 45ms/step - loss: 0.2500 - accuracy: 0.8998
Epoch 4/5
98/98 [==============================] - 4s 46ms/step - loss: 0.1581 - accuracy: 0.9434
Epoch 5/5
98/98 [==============================] - 4s 46ms/step - loss: 0.0985 - accuracy: 0.9660
</code>```

TensorFlow:

```<code>-TensorFlow: Epoch 1 done in 4.04967999458313s
-TensorFlow: Epoch 2 done in 2.443302869796753s
-TensorFlow: Epoch 3 done in 2.450983762741089s
-TensorFlow: Epoch 4 done in 2.4626052379608154s
-TensorFlow: Epoch 5 done in 2.4663102626800537s
</code>```

Here’s the information on my PyTorch build:

PyTorch built with:

```<code>  - GCC 7.3
  - C++ Version: 201402
  - Intel(R) Math Kernel Library Version 2020.0.0 Product Build 20191122 for Intel(R) 64 architecture applications
  - Intel(R) MKL-DNN v2.2.3 (Git Hash 7336ca9f055cf1bfa13efb658fe15dc9b41f0740)
  - OpenMP 201511 (a.k.a. OpenMP 4.5)
  - LAPACK is enabled (usually provided by MKL)
  - NNPACK is enabled
  - CPU capability usage: AVX2
  - CUDA Runtime 10.2
  - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70
  - CuDNN 7.6.5
  - Magma 2.5.2
  - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=10.2, CUDNN_VERSION=7.6.5, CXX_COMPILER=/opt/rh/devtoolset-7/root/usr/bin/c++, CXX_FLAGS= -Wno-deprecated -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -fopenmp -DNDEBUG -DUSE_KINETO -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -DEDGE_PROFILER_USE_KINETO -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-unused-local-typedefs -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-psabi -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=1.10.0, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON
</code>```

Here’s the model’s code:

```<code>class PyTorchLSTMMod(torch.nn.Module):
    """This class implements the LSTM model using PyTorch.

    Arguments
    ---------
    initializer: function
        The weight initialization function from the torch.nn.init module that is used to initialize
        the initial weights of the models.
    vocabulary_size: int
        The number of words that are to be considered among the words that used most frequently.
    embedding_size: int
        The number of dimensions to which the words will be mapped to.
    hidden_size: int
        The number of features of the hidden state.
    dropout: float
        The dropout rate that will be considered during training.
    """
    def __init__(self, initializer, vocabulary_size, embedding_size, hidden_size, dropout):
        super().__init__()

        self.embed = torch.nn.Embedding(num_embeddings=vocabulary_size, embedding_dim=embedding_size)

        self.dropout1 = torch.nn.Dropout(dropout)

        self.lstm = torch.nn.LSTM(input_size=embedding_size, hidden_size=hidden_size, batch_first=True)
        initializer(self.lstm.weight_ih_l0)
        torch.nn.init.orthogonal_(self.lstm.weight_hh_l0)

        self.dropout2 = torch.nn.Dropout(dropout)

        self.fc = torch.nn.Linear(in_features=hidden_size, out_features=1)

    def forward(self, inputs, is_training=False):
        """This function implements the forward pass of the model.

        Arguments
        ---------
        inputs: Tensor
            The set of samples the model is to infer.
        is_training: boolean
            This indicates whether the forward pass is occuring during training
            (i.e., if we should consider dropout).
        """
        x = inputs
        x = self.embed(x)
        if is_training:
            x = self.dropout1(x)

        o, (h, c) = self.lstm(x)
        out = h[-1]
        if is_training:
            out = self.dropout2(out)
        f = self.fc(out)
        return f.flatten()#torch.sigmoid(f).flatten()

    def train_pytorch(self, optimizer, epoch, train_loader, device, data_type, log_interval):
        """This function implements a single epoch of the training process of the PyTorch model.

        Arguments
        ---------
        self: PyTorchLSTMMod
            The model that is to be trained.
        optimizer: torch.nn.optim
            The optimizer to be used during the training process.
        epoch: int
            The epoch associated with the training process.
        train_loader: DataLoader
            The DataLoader that is used to load the training data during the training process.
            Note that the DataLoader loads the data according to the batch size
            defined with it was initialized.
        device: string
            The string that indicates which device is to be used at runtime (i.e., GPU or CPU).
        data_type: string
            This string indicates whether mixed precision is to be used or not.
        log_interval: int
            The interval at which the model logs the process of the training process
            in terms of number of batches passed through the model.
        """
        self.train()

        epoch_start = time.time()

        loss_fn = torch.nn.BCEWithLogitsLoss()

        if data_type == 'mixed':
            scaler = torch.cuda.amp.GradScaler()

        for batch_idx, (data, target) in enumerate(train_loader):
            data, target = data.to(device), target.to(device)

            optimizer.zero_grad()

            if data_type == 'mixed':
                with torch.cuda.amp.autocast():
                    output = self(data, is_training=True)

                    loss = loss_fn(output, target)

                scaler.scale(loss).backward()

                scaler.step(optimizer)
                scaler.update()
            else:

                output = self(data, is_training=True)

                loss = loss_fn(output, target)

                loss.backward()

                optimizer.step()

            if log_interval == -1:
                continue

            if batch_idx % log_interval == 0:
                print('Train set, Epoch {}\tLoss: {:.6f}'.format(
                    epoch, loss.item()))
        print("-PyTorch: Epoch {} done in {}s\n".format(epoch, time.time() - epoch_start))

    def test_pytorch(self, test_loader, device, data_type):
        """This function implements the testing process of the PyTorch model and returns the accuracy
        obtained on the testing dataset.

        Arguments
        ---------
        model: torch.nn.Module
            The model that is to be tested.
        test_loader: DataLoader
            The DataLoader that is used to load the testing data during the testing process.
            Note that the DataLoader loads the data according to the batch size
            defined with it was initialized.
        device: string
            The string that indicates which device is to be used at runtime (i.e., GPU or CPU).
        data_type: string
            This string indicates whether mixed precision is to be used or not.

        """

        self.eval()

        with torch.no_grad():

            #Loss and correct prediction accumulators
            test_loss = 0
            correct = 0
            total = 0

            loss_fn = torch.nn.BCEWithLogitsLoss()

            for data, target in test_loader:

                data, target = data.to(device), target.to(device)

                if data_type == 'mixed':
                    with torch.cuda.amp.autocast():

                        outputs = self(data).detach()

                        test_loss += loss_fn(outputs, target).detach()

                        preds = (outputs >= 0.5).float() == target
                        correct += preds.sum().item()
                        total += preds.size(0)

                else:
                    outputs = self(data).detach()

                    test_loss += loss_fn(outputs, target).detach()

                    preds = (outputs >= 0.5).float() == target

                    correct += preds.sum().item()
                    total += preds.size(0)

            #Print log
            test_loss /= len(test_loader.dataset)
            print('\nTest set, Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
                test_loss, correct, len(test_loader.dataset),
                100. * (correct / total)))

            return 100. * (correct / total)
</code>```

I'm on a Ubuntu 18.04.4 system equipped with an NVIDIA Quadro RTX 4000 GPU with 8GB of VRAM and an Intel(R) Core(TM) i9-9900K CPU running at 3.60GHz. I've already tried to run this code on separate machines, but the behavior seems to occur only on the system described above. I've also try to play around with number of threads, to no avail.

Any ideas what could be the cause of this?

Thanks!

Body:
I’ve been experimenting with different models and different frameworks, and I’ve noticed that when using CPU, training a LSTM model on the IMDB dataset is 3x to 5x slower on PyTorch (v1.10) (around 739 seconds) compared to the Keras and TensorFlow implementations (around 201 seconds and around 135 seconds, respectively). Moreover, I’ve also noticed that the first epoch takes significantly more time than the rest of the epochs:

-PyTorch: Epoch 1 done in 235.0469572544098s
-PyTorch: Epoch 2 done in 125.87335634231567s
-PyTorch: Epoch 3 done in 125.26632475852966s
-PyTorch: Epoch 4 done in 126.59195327758789s
-PyTorch: Epoch 5 done in 126.00697541236877s

Which doesn’t occur when using the other frameworks:

Keras:

Epoch 1/5
98/98 [==============================] - 41s 408ms/step - loss: 0.5280 - accuracy: 0.7300
Epoch 2/5
98/98 [==============================] - 40s 404ms/step - loss: 0.3441 - accuracy: 0.8566
Epoch 3/5
98/98 [==============================] - 40s 406ms/step - loss: 0.2384 - accuracy: 0.9080
Epoch 4/5
98/98 [==============================] - 40s 406ms/step - loss: 0.1625 - accuracy: 0.9386
Epoch 5/5
98/98 [==============================] - 40s 406ms/step - loss: 0.1176 - accuracy: 0.9580

TensorFlow:

-TensorFlow: Epoch 1 done in 37.287458419799805s
-TensorFlow: Epoch 2 done in 36.93708920478821s
-TensorFlow: Epoch 3 done in 36.85307550430298s
-TensorFlow: Epoch 4 done in 37.23605704307556s
-TensorFlow: Epoch 5 done in 37.04216718673706s

While using GPU, the problem seems to disappear.

PyTorch:

-PyTorch: Epoch 1 done in 2.6681089401245117s
-PyTorch: Epoch 2 done in 2.623263120651245s
-PyTorch: Epoch 3 done in 2.6285109519958496s
-PyTorch: Epoch 4 done in 2.6813976764678955s
-PyTorch: Epoch 5 done in 2.6470844745635986s

Keras:

Epoch 1/5
98/98 [==============================] - 6s 44ms/step - loss: 0.5434 - accuracy: 0.7220
Epoch 2/5
98/98 [==============================] - 4s 44ms/step - loss: 0.4673 - accuracy: 0.7822
Epoch 3/5
98/98 [==============================] - 4s 45ms/step - loss: 0.2500 - accuracy: 0.8998
Epoch 4/5
98/98 [==============================] - 4s 46ms/step - loss: 0.1581 - accuracy: 0.9434
Epoch 5/5
98/98 [==============================] - 4s 46ms/step - loss: 0.0985 - accuracy: 0.9660

TensorFlow:

-TensorFlow: Epoch 1 done in 4.04967999458313s
-TensorFlow: Epoch 2 done in 2.443302869796753s
-TensorFlow: Epoch 3 done in 2.450983762741089s
-TensorFlow: Epoch 4 done in 2.4626052379608154s
-TensorFlow: Epoch 5 done in 2.4663102626800537s

Here’s the information on my PyTorch build:

PyTorch built with:

  - GCC 7.3
  - C++ Version: 201402
  - Intel(R) Math Kernel Library Version 2020.0.0 Product Build 20191122 for Intel(R) 64 architecture applications
  - Intel(R) MKL-DNN v2.2.3 (Git Hash 7336ca9f055cf1bfa13efb658fe15dc9b41f0740)
  - OpenMP 201511 (a.k.a. OpenMP 4.5)
  - LAPACK is enabled (usually provided by MKL)
  - NNPACK is enabled
  - CPU capability usage: AVX2
  - CUDA Runtime 10.2
  - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70
  - CuDNN 7.6.5
  - Magma 2.5.2
  - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=10.2, CUDNN_VERSION=7.6.5, CXX_COMPILER=/opt/rh/devtoolset-7/root/usr/bin/c++, CXX_FLAGS= -Wno-deprecated -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -fopenmp -DNDEBUG -DUSE_KINETO -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -DEDGE_PROFILER_USE_KINETO -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-unused-local-typedefs -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-psabi -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=1.10.0, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON

Here’s the model’s code:

class PyTorchLSTMMod(torch.nn.Module):
    """This class implements the LSTM model using PyTorch.

    Arguments
    ---------
    initializer: function
        The weight initialization function from the torch.nn.init module that is used to initialize
        the initial weights of the models.
    vocabulary_size: int
        The number of words that are to be considered among the words that used most frequently.
    embedding_size: int
        The number of dimensions to which the words will be mapped to.
    hidden_size: int
        The number of features of the hidden state.
    dropout: float
        The dropout rate that will be considered during training.
    """
    def __init__(self, initializer, vocabulary_size, embedding_size, hidden_size, dropout):
        super().__init__()

        self.embed = torch.nn.Embedding(num_embeddings=vocabulary_size, embedding_dim=embedding_size)

        self.dropout1 = torch.nn.Dropout(dropout)

        self.lstm = torch.nn.LSTM(input_size=embedding_size, hidden_size=hidden_size, batch_first=True)
        initializer(self.lstm.weight_ih_l0)
        torch.nn.init.orthogonal_(self.lstm.weight_hh_l0)

        self.dropout2 = torch.nn.Dropout(dropout)

        self.fc = torch.nn.Linear(in_features=hidden_size, out_features=1)

    def forward(self, inputs, is_training=False):
        """This function implements the forward pass of the model.

        Arguments
        ---------
        inputs: Tensor
            The set of samples the model is to infer.
        is_training: boolean
            This indicates whether the forward pass is occuring during training
            (i.e., if we should consider dropout).
        """
        x = inputs
        x = self.embed(x)
        if is_training:
            x = self.dropout1(x)

        o, (h, c) = self.lstm(x)
        out = h[-1]
        if is_training:
            out = self.dropout2(out)
        f = self.fc(out)
        return f.flatten()#torch.sigmoid(f).flatten()

    def train_pytorch(self, optimizer, epoch, train_loader, device, data_type, log_interval):
        """This function implements a single epoch of the training process of the PyTorch model.

        Arguments
        ---------
        self: PyTorchLSTMMod
            The model that is to be trained.
        optimizer: torch.nn.optim
            The optimizer to be used during the training process.
        epoch: int
            The epoch associated with the training process.
        train_loader: DataLoader
            The DataLoader that is used to load the training data during the training process.
            Note that the DataLoader loads the data according to the batch size
            defined with it was initialized.
        device: string
            The string that indicates which device is to be used at runtime (i.e., GPU or CPU).
        data_type: string
            This string indicates whether mixed precision is to be used or not.
        log_interval: int
            The interval at which the model logs the process of the training process
            in terms of number of batches passed through the model.
        """
        self.train()

        epoch_start = time.time()

        loss_fn = torch.nn.BCEWithLogitsLoss()

        if data_type == 'mixed':
            scaler = torch.cuda.amp.GradScaler()

        for batch_idx, (data, target) in enumerate(train_loader):
            data, target = data.to(device), target.to(device)

            optimizer.zero_grad()

            if data_type == 'mixed':
                with torch.cuda.amp.autocast():
                    output = self(data, is_training=True)

                    loss = loss_fn(output, target)

                scaler.scale(loss).backward()

                scaler.step(optimizer)
                scaler.update()
            else:

                output = self(data, is_training=True)

                loss = loss_fn(output, target)

                loss.backward()

                optimizer.step()

            if log_interval == -1:
                continue

            if batch_idx % log_interval == 0:
                print('Train set, Epoch {}\tLoss: {:.6f}'.format(
                    epoch, loss.item()))
        print("-PyTorch: Epoch {} done in {}s\n".format(epoch, time.time() - epoch_start))

    def test_pytorch(self, test_loader, device, data_type):
        """This function implements the testing process of the PyTorch model and returns the accuracy
        obtained on the testing dataset.

        Arguments
        ---------
        model: torch.nn.Module
            The model that is to be tested.
        test_loader: DataLoader
            The DataLoader that is used to load the testing data during the testing process.
            Note that the DataLoader loads the data according to the batch size
            defined with it was initialized.
        device: string
            The string that indicates which device is to be used at runtime (i.e., GPU or CPU).
        data_type: string
            This string indicates whether mixed precision is to be used or not.

        """

        self.eval()

        with torch.no_grad():

            #Loss and correct prediction accumulators
            test_loss = 0
            correct = 0
            total = 0

            loss_fn = torch.nn.BCEWithLogitsLoss()

            for data, target in test_loader:

                data, target = data.to(device), target.to(device)

                if data_type == 'mixed':
                    with torch.cuda.amp.autocast():

                        outputs = self(data).detach()

                        test_loss += loss_fn(outputs, target).detach()

                        preds = (outputs >= 0.5).float() == target
                        correct += preds.sum().item()
                        total += preds.size(0)

                else:
                    outputs = self(data).detach()

                    test_loss += loss_fn(outputs, target).detach()

                    preds = (outputs >= 0.5).float() == target

                    correct += preds.sum().item()
                    total += preds.size(0)

            #Print log
            test_loss /= len(test_loader.dataset)
            print('\nTest set, Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
                test_loss, correct, len(test_loader.dataset),
                100. * (correct / total)))

            return 100. * (correct / total)

I'm on a Ubuntu 18.04.4 system equipped with an NVIDIA Quadro RTX 4000 GPU with 8GB of VRAM and an Intel(R) Core(TM) i9-9900K CPU running at 3.60GHz. I've already tried to run this code on separate machines, but the behavior seems to occur only on the system described above. I've also try to play around with number of threads, to no avail.

Any ideas what could be the cause of this?

Thanks!


问:
Where to activate/deactivate ProgressView?
I have following code and trying to simulate a heavy task. Where do I have to activate and deactivate the progressView? In this Video it doesn't look right (the cirle should as long rotate as the number is about to change, when it’s changing the circle should disappear): Video_imgur

```<code>struct ContentViewDispatch: View{
    @State var button_tap_count = 0
    @State var dispatch_start = 0
    @State var i = 0
    @State var showProgress = false
    var body: some View{
        VStack{
            Text("Tapped: \(button_tap_count)")
            Text("Dispatch: \(dispatch_start)")
            Text("number: \(i)")
            Button("reset"){
                i = 0
            }
            ProgressView().progressViewStyle(CircularProgressViewStyle()).opacity(showProgress ? 1 : 0)

            Button("count"){
                button_tap_count += 1
                var k = i
                DispatchQueue.global(qos: .userInitiated).async {
                    DispatchQueue.main.async {
                        showProgress = true                    <----- activate
                        dispatch_start += 1
                    }
                    for _ in 0..<5_000_000{
                        k += 1
                    }
                    DispatchQueue.main.async {
                        showProgress = false                   <------ deactivate
                        i = k
                    }
                }
            }
        }
    }
}
</code>```

Body:
I have following code and trying to simulate a heavy task. Where do I have to activate and deactivate the progressView? In this Video it doesn't look right (the cirle should as long rotate as the number is about to change, when it’s changing the circle should disappear): Video_imgur

struct ContentViewDispatch: View{
    @State var button_tap_count = 0
    @State var dispatch_start = 0
    @State var i = 0
    @State var showProgress = false
    var body: some View{
        VStack{
            Text("Tapped: \(button_tap_count)")
            Text("Dispatch: \(dispatch_start)")
            Text("number: \(i)")
            Button("reset"){
                i = 0
            }
            ProgressView().progressViewStyle(CircularProgressViewStyle()).opacity(showProgress ? 1 : 0)

            Button("count"){
                button_tap_count += 1
                var k = i
                DispatchQueue.global(qos: .userInitiated).async {
                    DispatchQueue.main.async {
                        showProgress = true                    <----- activate
                        dispatch_start += 1
                    }
                    for _ in 0..<5_000_000{
                        k += 1
                    }
                    DispatchQueue.main.async {
                        showProgress = false                   <------ deactivate
                        i = k
                    }
                }
            }
        }
    }
}


问:
How do I handle this case (value to classify dosn't exist under node) using decision tree?
I implemented decision tree and let's say for example the following tree is what i got :

and my instance to classify is educationField = '2' and departement = 'HR'

How can i handle this ? i thought of taking the max class where educationField = 2
So the prediction will be YES, will  this  be correct ?


问:
We are facing error while training the model
Project Description :
This is a code for Sign language detection
We are using following libraries

```<code>from keras.models import Sequential
</code>```

This is the Code
This block of code is of training model of our project and we are getting error while training the model

```<code>classifier.fit(
        training_set,
        steps_per_epoch=12841,
        epochs=5,
        validation_data=test_set,
        validation_steps=4268)
</code>```

Error which we are facing....

```<code>Traceback (most recent call last):
  File "c:/Users/nagar/Desktop/Sign-Language-to-Text-master/train.py", line 66, in <module>
    classifier.fit(
  File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\tensorflow\python\eager\execute.py", line 52, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

Detected at node 'categorical_crossentropy/softmax_cross_entropy_with_logits' defined at (most recent call last):
    File "c:/Users/nagar/Desktop/Sign-Language-to-Text-master/train.py",
line 66, in <module>
      classifier.fit(
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1650, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1249, in train_function
      return step_function(self, iterator)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1233, in step_function      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1222, in run_step
      outputs = model.train_step(data)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1024, in train_step
      loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1082, in compute_loss
      return self.compiled_loss(
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\compile_utils.py", line 265, in __call__
      loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\losses.py", line 152, in __call__
      losses = call_fn(y_true, y_pred)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\losses.py", line 284, in call
      return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\losses.py", line 2004, in categorical_crossentropy
      return backend.categorical_crossentropy(
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\backend.py", line 5538, in categorical_crossentropy
      return tf.nn.softmax_cross_entropy_with_logits(
Node: 'categorical_crossentropy/softmax_cross_entropy_with_logits'
logits and labels must be broadcastable: logits_size=[10,27] labels_size=[10,29]
         [[{{node categorical_crossentropy/softmax_cross_entropy_with_logits}}]] [Op:__inference_train_function_1784]
2022-12-16 19:17:46.716640: W tensorflow/core/kernels/data/generator_dataset_op.cc:108] Error occurred when finalizing GeneratorDataset iterator:
FAILED_PRECONDITION: Python interpreter state is not initialized. The process may be terminated.
         [[{{node PyFunc}}]]
</code>```

Please if any one knows to resolve the error can help.

We tried to google the error but we are able to find the exact solution for the problem which we are facing

Body:
Project Description :
This is a code for Sign language detection
We are using following libraries

from keras.models import Sequential

This is the Code
This block of code is of training model of our project and we are getting error while training the model

classifier.fit(
        training_set,
        steps_per_epoch=12841,
        epochs=5,
        validation_data=test_set,
        validation_steps=4268)

Error which we are facing....

Traceback (most recent call last):
  File "c:/Users/nagar/Desktop/Sign-Language-to-Text-master/train.py", line 66, in <module>
    classifier.fit(
  File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\tensorflow\python\eager\execute.py", line 52, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

Detected at node 'categorical_crossentropy/softmax_cross_entropy_with_logits' defined at (most recent call last):
    File "c:/Users/nagar/Desktop/Sign-Language-to-Text-master/train.py",
line 66, in <module>
      classifier.fit(
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
      return fn(*args, **kwargs)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1650, in fit
      tmp_logs = self.train_function(iterator)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1249, in train_function
      return step_function(self, iterator)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1233, in step_function      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1222, in run_step
      outputs = model.train_step(data)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1024, in train_step
      loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\training.py", line 1082, in compute_loss
      return self.compiled_loss(
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\engine\compile_utils.py", line 265, in __call__
      loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\losses.py", line 152, in __call__
      losses = call_fn(y_true, y_pred)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\losses.py", line 284, in call
      return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\losses.py", line 2004, in categorical_crossentropy
      return backend.categorical_crossentropy(
    File "C:\Users\nagar\Desktop\Sign-Language-to-Text-master\Virtual-Env\lib\site-packages\keras\backend.py", line 5538, in categorical_crossentropy
      return tf.nn.softmax_cross_entropy_with_logits(
Node: 'categorical_crossentropy/softmax_cross_entropy_with_logits'
logits and labels must be broadcastable: logits_size=[10,27] labels_size=[10,29]
         [[{{node categorical_crossentropy/softmax_cross_entropy_with_logits}}]] [Op:__inference_train_function_1784]
2022-12-16 19:17:46.716640: W tensorflow/core/kernels/data/generator_dataset_op.cc:108] Error occurred when finalizing GeneratorDataset iterator:
FAILED_PRECONDITION: Python interpreter state is not initialized. The process may be terminated.
         [[{{node PyFunc}}]]

Please if any one knows to resolve the error can help.

We tried to google the error but we are able to find the exact solution for the problem which we are facing


问:
Should I avoid nested Streambuilder?
I'm using Firestore and Streambuilder to get realtime datas. In my app, I faced the situation that need 5 nested Streambuilder. I'm wondering should I avoid nested Streambuilder?
Is there any way better?

In addition, this is my firestore collection structure.
<[] --> collection, () --> doc>

[collection1] - (doc1, doc2 ..) - each doc has [collection2] - (doc1, doc2) - ...

I want to get whole docs, so I used nested Streambuilder.

Title: Should I avoid nested Streambuilder?


问:
How can I modify/overwrite a pointcloud ply file with python?
I have read the lon dress pointcloud.ply file and I converted theRGB channel into ycbcr so from x,y,z,r,g,b 6channelt to  x,y,z,ycbcr 4 channel. But I couldn't find how to overwrite the original ply flw with the changes I made.</p>


问:
"gunicorn/finish 127. exec: gunicorn: not found" when updating local azure ml deployment in docker
Yesterday I was following along a tutorial provided by Azure in deploying machine learning models to endpoints:

https://learn.microsoft.com/en-us/azure/machine-learning/how-to-deploy-online-endpoints?tabs=azure-cli

In this tutorial I ended up successfully deploying a simple linear regression model to a local endpoint with a docker container. However any time I try to update the deployment (i.e. by adding a simple python package dependency in the conda yaml file) and subsequently running:

```<code>az ml online-deployment update --local -n blue --endpoint $ENDPOINT_NAME -f endpoints/online/managed/sample/blue-deployment.yml
</code>```

The container containing model goes into a failed state and logs that exec: gunicorn cannot be found. Using the same command as above works fine for updating the deployment that is actually deployed to azure online (with removing --local). However I would like to develop locally, and redeploying my container for each time my environment changes feels silly. For context the relevant yaml files are provided below, strangely enough in the tutorial I do not touch a docker file. Any thoughts or comments on how to proceed are appreciated!

blue-deployment.yml

$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: blue
endpoint_name: my-endpoint
model:
  path: ../../model-1/model/
code_configuration:
  code: ../../model-1/onlinescoring/
  scoring_script: score.py
environment:
  conda_file: ../../model-1/environment/conda.yml
  image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04:latest
instance_type: Standard_DS2_v2
instance_count: 1
```
<p><strong>conda.yml</strong></p>
<pre class="lang-yaml prettyprint-override"><code>name: model-env
channels:
  - conda-forge
dependencies:
  - python=3.8
  - numpy=1.21.2
  - pip=21.2.4
  - scikit-learn=0.24.2
  - scipy=1.7.1
  - pyodbc=4.0.34
  - pip:
    - azureml-defaults==1.47.0
    - inference-schema[numpy-support]==1.5
    - joblib==1.0.1
</code>```

endpoint.yml

$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
name: my-endpoint
auth_mode: key
```

I tried to update an existing local docker container that contained a sklearn regression model which was originally deployed through Azure cli. I expected the containers environment to be updated with a new dependency such that I could use newly added python packages in my code. However, the container goes into a failed state and cannot be restarted as it fails to find gunicorn. I also tried adding gunicorn as a dependency in the conda.yml but to no avail.

Body:
Yesterday I was following along a tutorial provided by Azure in deploying machine learning models to endpoints:

https://learn.microsoft.com/en-us/azure/machine-learning/how-to-deploy-online-endpoints?tabs=azure-cli

In this tutorial I ended up successfully deploying a simple linear regression model to a local endpoint with a docker container. However any time I try to update the deployment (i.e. by adding a simple python package dependency in the conda yaml file) and subsequently running:

az ml online-deployment update --local -n blue --endpoint $ENDPOINT_NAME -f endpoints/online/managed/sample/blue-deployment.yml

The container containing model goes into a failed state and logs that exec: gunicorn cannot be found. Using the same command as above works fine for updating the deployment that is actually deployed to azure online (with removing --local). However I would like to develop locally, and redeploying my container for each time my environment changes feels silly. For context the relevant yaml files are provided below, strangely enough in the tutorial I do not touch a docker file. Any thoughts or comments on how to proceed are appreciated!

blue-deployment.yml

$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: blue
endpoint_name: my-endpoint
model:
  path: ../../model-1/model/
code_configuration:
  code: ../../model-1/onlinescoring/
  scoring_script: score.py
environment:
  conda_file: ../../model-1/environment/conda.yml
  image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04:latest
instance_type: Standard_DS2_v2
instance_count: 1

conda.yml

name: model-env
channels:
  - conda-forge
dependencies:
  - python=3.8
  - numpy=1.21.2
  - pip=21.2.4
  - scikit-learn=0.24.2
  - scipy=1.7.1
  - pyodbc=4.0.34
  - pip:
    - azureml-defaults==1.47.0
    - inference-schema[numpy-support]==1.5
    - joblib==1.0.1

endpoint.yml

$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
name: my-endpoint
auth_mode: key

I tried to update an existing local docker container that contained a sklearn regression model which was originally deployed through Azure cli. I expected the containers environment to be updated with a new dependency such that I could use newly added python packages in my code. However, the container goes into a failed state and cannot be restarted as it fails to find gunicorn. I also tried adding gunicorn as a dependency in the conda.yml but to no avail.


问:
Check if data exists in firebase realtime database for adding it

I want to check if a particular device exists in the firebase database before adding it. I have tried using valueevent listener and singlevalue event listener but both were prone to race conditions.

So I tried using Firebase transaction, but even that doesn't work.

Here is the code:

```<code>Devices devices=new Devices(devicename,timein,email,timeout);

myRef.child("Device-1").runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        if (mutableData.getValue() != devicename) {
            myRef.child("Device-1").push().setValue(devices);
            // Data does not exist, add it

            return Transaction.success(mutableData);
        }
        return Transaction.abort();
    }

    @Override
    public void onComplete(DatabaseError error, boolean committed, DataSnapshot snapshot) {
        if (error != null) {
            // Handle error
        }
    }
});
</code>```

I was expecting it to not add the data the second time, as there was always already an entry in the database with the same devicename

Body:
I want to check if a particular device exists in the firebase database before adding it. I have tried using valueevent listener and singlevalue event listener but both were prone to race conditions.

So I tried using Firebase transaction, but even that doesn't work.

Here is the code:

Devices devices=new Devices(devicename,timein,email,timeout);

myRef.child("Device-1").runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        if (mutableData.getValue() != devicename) {
            myRef.child("Device-1").push().setValue(devices);
            // Data does not exist, add it

            return Transaction.success(mutableData);
        }
        return Transaction.abort();
    }

    @Override
    public void onComplete(DatabaseError error, boolean committed, DataSnapshot snapshot) {
        if (error != null) {
            // Handle error
        }
    }
});

I was expecting it to not add the data the second time, as there was always already an entry in the database with the same devicename


问:
How to serve a web app running on a Mac on a local network, without a router?

The problem

I'm working on a little local web app, relaying on two independant devices, a mobile used as a remote and a laptop used as a display, connected to the same local server (running on the laptop) through a shared network. The client-side app (Vite + Vue) serves on localhost:5173 , the server-side (PHP) serves on localhost:8888.
For now, it works since both devices are connected to the same WIFI network. The desktop runs the local server that the mobile can access through its IP address (http://168.192.X.XX:5173). But the app is supposed to be able to work in an area without internet, neither 3G/4G/5G nor WIFI.

I wonder if it's possible to make it work without a WIFI router ? If yes, how ?

What I tried

Following an Apple guide, I tried to create a network on the Mac. I can connect to it from the mobile but I can't access the localhost, maybe because the network isn't secure ?

Please, tell me if my question isn't clear before disliking it.


问:
How to search for given word or character in ArrayList and show those who match and sort them
I'm still new to java. My task was to find all Producers in ArrayList who matches the word or character that the user inserts and return a list of those words sorted by their field.

For example, we have Producers {"Alex","Bob","Amanda","Jack", "Jari"}

User wants to seach for "A"program returns sorted==>"Alex","Amanda" User wants to seach for "Ja"program returns sorted==>"Jack", "Jari" User wants to seach for "Bob"program returns sorted==>"Bob"

this is all code I have for now in my main method:

```<code>Producers producer1 = new Producers("Alex");
Producers producer2 = new Producers("Jack");
Producers producer3 = new Producers("Jari");
</code>```

Adding all producers into ArrayList

```<code>Producers.allProducers.add(producer1);
Producers.allProducers.add(producer2);
Producers.allProducers.add(producer3);`
</code>```

Then we have another Object called Clothing where we had a task to add our producer for each piece of clothing

```<code>Clothing wClothing1 = new Clothing("Sneakers", 6.99, ProductsType.SHOES); // name,price,ProductsType as ENUMClothing
Clothing wClothing2 = new Clothing("AShoe", 1.99, ProductsType.SHOES);
Clothing wClothing3 = new Clothing("Cocktail dress", 15.99, ProductsType.DRESSES);
wClothing1.setProducers(producer1);
wClothing2.setProducers(producer2);
wClothing3.setProducers(producer3);
</code>```

Adding all clothing into ArrayList

```<code>Items.clothingItemList.add(wClothing1);
Items.clothingItemList.add(wClothing2);
Items.clothingItemList.add(wClothing3);`
</code>```

We need to search, find and sort words only by producers in Items.clothingItemList. So I created a sorting method that can only sort all producers but can't search for them and then sort.

```<code>public static void getItemByProducer() {
 Collections.sort(Items.clothingItemList, new SortByProducersComparator());
    System.out.println(Items.clothingItemList.toString());
}
</code>```

I created also a new class called SortByProducersComparator():

```<code>import java.util.Comparator;

public class SortByProducersComparator implements Comparator<Items> {
    @Override
    public int compare(Items o1, Items o2) {
        int c =0;
        c=o1.getProducersName().compareTo(o2.getProducersName());
        return c;
}}
</code>```

We need to do this task using: Comparator, Comparable.
we cant use it to stream.

Please help, I hope my explanation of the task was good enough

Body:
I'm still new to java. My task was to find all Producers in ArrayList who matches the word or character that the user inserts and return a list of those words sorted by their field.

For example, we have Producers {"Alex","Bob","Amanda","Jack", "Jari"}

User wants to seach for "A"program returns sorted==>"Alex","Amanda" User wants to seach for "Ja"program returns sorted==>"Jack", "Jari" User wants to seach for "Bob"program returns sorted==>"Bob"

this is all code I have for now in my main method:

Producers producer1 = new Producers("Alex");
Producers producer2 = new Producers("Jack");
Producers producer3 = new Producers("Jari");

Adding all producers into ArrayList

Producers.allProducers.add(producer1);
Producers.allProducers.add(producer2);
Producers.allProducers.add(producer3);`

Then we have another Object called Clothing where we had a task to add our producer for each piece of clothing

Clothing wClothing1 = new Clothing("Sneakers", 6.99, ProductsType.SHOES); // name,price,ProductsType as ENUMClothing
Clothing wClothing2 = new Clothing("AShoe", 1.99, ProductsType.SHOES);
Clothing wClothing3 = new Clothing("Cocktail dress", 15.99, ProductsType.DRESSES);
wClothing1.setProducers(producer1);
wClothing2.setProducers(producer2);
wClothing3.setProducers(producer3);

Adding all clothing into ArrayList

Items.clothingItemList.add(wClothing1);
Items.clothingItemList.add(wClothing2);
Items.clothingItemList.add(wClothing3);`

We need to search, find and sort words only by producers in Items.clothingItemList. So I created a sorting method that can only sort all producers but can't search for them and then sort.

public static void getItemByProducer() {
 Collections.sort(Items.clothingItemList, new SortByProducersComparator());
    System.out.println(Items.clothingItemList.toString());
}

I created also a new class called SortByProducersComparator():

import java.util.Comparator;

public class SortByProducersComparator implements Comparator<Items> {
    @Override
    public int compare(Items o1, Items o2) {
        int c =0;
        c=o1.getProducersName().compareTo(o2.getProducersName());
        return c;
}}

We need to do this task using: Comparator, Comparable.
we cant use it to stream.

Please help, I hope my explanation of the task was good enough


问:
Why eureka-client register to naming-service before embed-tomcat(servlet container) is ready on start?
I use tomcat as servlet container in springboot, and use eureka-server as the naming service.
the version is : spring-boot-2.0.3.RELEASE and spring-boot-2.5.?.RELEASE

I notice that when I turn on tomcat's min-spare-threads to a big number, see 100, I'll get many error requests when I restart the application. （in our production env）

Then I check the code inside and find that, spring application registers to naming-service before it starts tomcat server(start the worker and accepter threads), that is to say, the application may be available(to other eureka clients) before tomcat gets ready. Which confuse me ver much, why not start tomcat first?(when tomcat start, it will created minSpareThreads to its threadPool) Is there any reason?

You can have a breakpoint here to see this(2.0.3.RELEASE)

```<code>org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java:160
</code>```

enter image description here

Or follow me:

start a eureka-server
enter image description here

add a break point here
enter image description here

debug-start this application
enter image description here

now we can see
this application is accessible to other eureka clients
enter image description here
this application's servlet container is not ready
enter image description here

Body:
I use tomcat as servlet container in springboot, and use eureka-server as the naming service.
the version is : spring-boot-2.0.3.RELEASE and spring-boot-2.5.?.RELEASE

I notice that when I turn on tomcat's min-spare-threads to a big number, see 100, I'll get many error requests when I restart the application. （in our production env）

Then I check the code inside and find that, spring application registers to naming-service before it starts tomcat server(start the worker and accepter threads), that is to say, the application may be available(to other eureka clients) before tomcat gets ready. Which confuse me ver much, why not start tomcat first?(when tomcat start, it will created minSpareThreads to its threadPool) Is there any reason?

You can have a breakpoint here to see this(2.0.3.RELEASE)

org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java:160

enter image description here

Or follow me:

start a eureka-server
enter image description here

add a break point here
enter image description here

debug-start this application
enter image description here

now we can see
this application is accessible to other eureka clients
enter image description here
this application's servlet container is not ready
enter image description here


问:
Put a textbox inside an image
I am trying to insert a textbox inside an image with a dropdown pin to extend the text area.

What I am trying to replicate is the following textbox: ( https://www.spanishdict.com/ )

With the image in the background and the text drop down in the foreground.

App:

```<code>#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
  titlePanel(title=div(img(src="https://img.freepik.com/premium-vector/street-city-scenery-background_711433-2.jpg"), "My Title")),

    # Sidebar with a slider input for number of bins
    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$distPlot <- renderPlot({
        # generate bins based on input$bins from ui.R
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        # draw the histogram with the specified number of bins
        hist(x, breaks = bins, col = 'darkgray', border = 'white',
             xlab = 'Waiting time to next eruption (in mins)',
             main = 'Histogram of waiting times')
    })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Title: Put a textbox inside an image

Body:
I am trying to insert a textbox inside an image with a dropdown pin to extend the text area.

What I am trying to replicate is the following textbox: ( https://www.spanishdict.com/ )

With the image in the background and the text drop down in the foreground.

App:

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
  titlePanel(title=div(img(src="https://img.freepik.com/premium-vector/street-city-scenery-background_711433-2.jpg"), "My Title")),

    # Sidebar with a slider input for number of bins
    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$distPlot <- renderPlot({
        # generate bins based on input$bins from ui.R
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        # draw the histogram with the specified number of bins
        hist(x, breaks = bins, col = 'darkgray', border = 'white',
             xlab = 'Waiting time to next eruption (in mins)',
             main = 'Histogram of waiting times')
    })
}

# Run the application
shinyApp(ui = ui, server = server)


问:
How to stop pynput listener
I'm working on a vim clone made in python, I use pynput to keep track of the current mode (insert, normal), so I'd like so when I press i it switched to insert mode, so i decided to use pynput, to keep track of the inputs, for example, I'd like it so that when i press l, the writing cursor goes right, and h make it go left (the index variable), but when I switch back to normal mode and close the program, this error shows up: <Xlib.error.ConnectionClosedError: Display connection closed by client>,
Here's the code:

# Entering writing mode...
def write_mode():
    with Listener(on_press=on_press) as listener :
        listener.join()
        listener.stop()
```
<pre class="lang-py prettyprint-override"><code>index = 0
is_writing_mode = False

def on_press(key):
    global index
    global is_writing_mode
    if str(key) == "'l'":
        index += 1
        print(index)
    if str(key) == "'h'":
        index -= 1
        print(index)

    if str(key) == "'q'":
        is_writing_mode = False
        print("Normal mode")
        line_return()
</code>```

The thig is, i don't know why it does that, cuz i can exit insert mode, but the aftermath of closing the program shows this error and i don't know what it means

Title: How to stop pynput listener

Body:
I'm working on a vim clone made in python, I use pynput to keep track of the current mode (insert, normal), so I'd like so when I press i it switched to insert mode, so i decided to use pynput, to keep track of the inputs, for example, I'd like it so that when i press l, the writing cursor goes right, and h make it go left (the index variable), but when I switch back to normal mode and close the program, this error shows up: <Xlib.error.ConnectionClosedError: Display connection closed by client>,
Here's the code:

# Entering writing mode...
def write_mode():
    with Listener(on_press=on_press) as listener :
        listener.join()
        listener.stop()

index = 0
is_writing_mode = False

def on_press(key):
    global index
    global is_writing_mode
    if str(key) == "'l'":
        index += 1
        print(index)
    if str(key) == "'h'":
        index -= 1
        print(index)

    if str(key) == "'q'":
        is_writing_mode = False
        print("Normal mode")
        line_return()

The thig is, i don't know why it does that, cuz i can exit insert mode, but the aftermath of closing the program shows this error and i don't know what it means


问:
Javascript mail function with attachments
I have a html page with a form, where the end user generates a pdf of the form by pressing a specific button.
My code:

```<code><button onclick="generatePDF()">PDF</button>
        <script>
            function generatePDF()
            {
                const element = document.getElementById('container');/Container is where the form is located

                var filecommessa = document.getElementById("commessajava").value;
                var filedata = document.getElementById("datajava").value;
                var filerapporto = "Rapporto_";
                var fileunderscore = "_";
                var fileName = filerapporto+filecommessa+fileunderscore+filedata;
                console.log(fileName);

                var opt = {
                filename: fileName,
                jsPDF: { unit: 'in', format: 'A3', orientation: 'landscape' }
                };
                html2pdf()
                .from(element)
                .set(opt)
                .save();

            }
        </script>
</code>```

I have another function, which allows the user to send an email to a customer.

```<code><script>
            function sendMail()
            {
                var mailcommessa = document.getElementById("commessajava").value;
                var maildata = document.getElementById("datajava").value;
                var mailrapporto = "Rapporto ";
                var space = " ";
                var mailsubject = mailrapporto+mailcommessa+space+maildata;

                var link = "mailto:"
                + "?cc="
                + "&subject=" + encodeURIComponent(mailsubject)
                + "&body=" + encodeURIComponent(document.getElementById('myText').value)
                ;

                window.location.href = link;
            }
        </script>
</code>```

I would to know how can I attach the generated pdf to the email automatically, instead of downloading it and then attaching the downloaded file to the email.
If this is not possible with the mailto function, other similar suggestions will be appreciated.
Thanks for your help.

I tried adding this line of code

```<code>                + "&attachments=" + "test.pdf"
</code>```

in the mail to function, but I have no idea how to do it.

Body:
I have a html page with a form, where the end user generates a pdf of the form by pressing a specific button.
My code:

<button onclick="generatePDF()">PDF</button>

I have another function, which allows the user to send an email to a customer.

I would to know how can I attach the generated pdf to the email automatically, instead of downloading it and then attaching the downloaded file to the email.
If this is not possible with the mailto function, other similar suggestions will be appreciated.
Thanks for your help.

I tried adding this line of code

                + "&attachments=" + "test.pdf"

in the mail to function, but I have no idea how to do it.


问:
Why does this animation start not to have transition when I add a linear gradient over it?
I'm trying to set background images with smooth transition on my hero page, the problem is when I add linear gradient over the images the transition becomes sharp (0s transition). here is the code...</p>
```<code>.hero{
    width: 100%;
    height: 100vh;
    background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/main-bg.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    animation-name: hero-a;
    animation-duration: 20s;
    animation-iteration-count: infinite;
}
</code>```
```<code>@keyframes hero-a{
    0%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/main-bg.jpg);
        background-position: center;
        background-size: cover;
    }
    20%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-2.jpg);
        background-position: center;
        background-size: cover;
    }
    40%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-3.jpg);
        background-position: center;
        background-size: cover;
    }
    60%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-4.jpg);
        background-position: center;
        background-size: cover;
    }
    80%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-5.jpg);
        background-position: center;
        background-size: cover;
    }
}
</code>```

Body:
I'm trying to set background images with smooth transition on my hero page, the problem is when I add linear gradient over the images the transition becomes sharp (0s transition). here is the code...

.hero{
    width: 100%;
    height: 100vh;
    background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/main-bg.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    animation-name: hero-a;
    animation-duration: 20s;
    animation-iteration-count: infinite;
}

@keyframes hero-a{
    0%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/main-bg.jpg);
        background-position: center;
        background-size: cover;
    }
    20%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-2.jpg);
        background-position: center;
        background-size: cover;
    }
    40%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-3.jpg);
        background-position: center;
        background-size: cover;
    }
    60%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-4.jpg);
        background-position: center;
        background-size: cover;
    }
    80%{
        background: linear-gradient(rgba(167, 45, 167, .3), rgba(167, 45, 167, .3)), url(img/alt-bg-5.jpg);
        background-position: center;
        background-size: cover;
    }
}


问:
How to configure "@cypress/grep" 3.1.0 plugin with cypress v 10.11.0
I'm trying to filter tests using the '@cypress/grep' plugin
but it doesn't filter tests with tags

What am I doing wrong?


问:
Change VeinsInetSampleMessage in Inet example
How do you change the sample message that gets broadcast to vehicles in the veins_inet sample application?

I can see that TraCI comes equipped with many functions that generate information about a node, such as speed, acceleration, location etc. I would like to include such information in the messages the nodes broadcast and that can be read in Pcap recordings made by each node. Currently the default message is just the RoadID of the node.


问:
Creating a system-wide hook that adds a menu item to the system menu of every Windows program?
In a 32-bit Windows 10 VCL Application in Delphi 11 Alexandria, I am trying to implement a system-wide hook that adds a menu item to the system menu of every Windows program. For this purpose, I have created and built this DLL:

```<code>library SystemMenuHookDLL;

uses
  Winapi.Windows,
  System.SysUtils,
  System.Classes;

{$R *.res}

function AddMenuItem(WindowHandle: HWND): Boolean;
var
  MenuHandle: HMENU;
  MenuItemID: UINT;
  WindowStyles: DWORD;
begin
  Result := False;
  MenuHandle := GetSystemMenu(WindowHandle, False);
  if MenuHandle <> 0 then
  begin
    MenuItemID := 999;
    AppendMenu(MenuHandle, MF_STRING, MenuItemID, 'My Menu Item');
    SetMenuDefaultItem(MenuHandle, MenuItemID, MF_BYCOMMAND);
    WindowStyles := GetWindowLong(WindowHandle, GWL_STYLE);
    WindowStyles := WindowStyles or WS_SYSMENU;
    SetWindowLong(WindowHandle, GWL_STYLE, WindowStyles);
    DrawMenuBar(WindowHandle);
    Result := True;
  end;
end;

function HookFunc(Code: Integer; WParam: WPARAM; LParam: LPARAM): LRESULT; stdcall;
begin
  if Code = HCBT_CREATEWND then
  begin
    AddMenuItem(HWND(WParam));
  end;
  Result := CallNextHookEx(0, Code, WParam, LParam);
end;

exports HookFunc;

begin
end.
</code>```

This is the code for the Host Application for the DLL:

```<code>unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type
  TForm1 = class(TForm)
    procedure FormDestroy(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  CodeSiteLogging;

type
  THookProc = function(Code: Integer; WParam: WPARAM; LParam: LPARAM): LRESULT; stdcall;

var
  DLLHandle: HMODULE;
  HookProc: THookProc;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  UnhookWindowsHookEx(WH_CBT);
  FreeLibrary(DLLHandle);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  DLLHandle := LoadLibrary('SystemMenuHookDLL.dll');
  CodeSite.Send('TForm1.FormCreate: DLLHandle', DLLHandle);
  if DLLHandle <> 0 then
  begin
    @HookProc := GetProcAddress(DLLHandle, 'HookFunc');
    CodeSite.Send('TForm1.FormCreate: @HookProc', @HookProc);
    if Assigned(HookProc) then
    begin
      CodeSite.Send('TForm1.FormCreate: Assigned');
      SetWindowsHookEx(WH_CBT, HookProc, DLLHandle, 0);
    end;
  end;
end;

end.
</code>```

I have put the DLL in the same directory of the host application exe file. Unfortunately, it does not work: After having started the host application, and then trying to start a 32-bit program, the program does not start! It seems that the hook is blocking the program.

Body:
In a 32-bit Windows 10 VCL Application in Delphi 11 Alexandria, I am trying to implement a system-wide hook that adds a menu item to the system menu of every Windows program. For this purpose, I have created and built this DLL:

library SystemMenuHookDLL;

uses
  Winapi.Windows,
  System.SysUtils,
  System.Classes;

{$R *.res}

function AddMenuItem(WindowHandle: HWND): Boolean;
var
  MenuHandle: HMENU;
  MenuItemID: UINT;
  WindowStyles: DWORD;
begin
  Result := False;
  MenuHandle := GetSystemMenu(WindowHandle, False);
  if MenuHandle <> 0 then
  begin
    MenuItemID := 999;
    AppendMenu(MenuHandle, MF_STRING, MenuItemID, 'My Menu Item');
    SetMenuDefaultItem(MenuHandle, MenuItemID, MF_BYCOMMAND);
    WindowStyles := GetWindowLong(WindowHandle, GWL_STYLE);
    WindowStyles := WindowStyles or WS_SYSMENU;
    SetWindowLong(WindowHandle, GWL_STYLE, WindowStyles);
    DrawMenuBar(WindowHandle);
    Result := True;
  end;
end;

function HookFunc(Code: Integer; WParam: WPARAM; LParam: LPARAM): LRESULT; stdcall;
begin
  if Code = HCBT_CREATEWND then
  begin
    AddMenuItem(HWND(WParam));
  end;
  Result := CallNextHookEx(0, Code, WParam, LParam);
end;

exports HookFunc;

begin
end.

This is the code for the Host Application for the DLL:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type
  TForm1 = class(TForm)
    procedure FormDestroy(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  CodeSiteLogging;

type
  THookProc = function(Code: Integer; WParam: WPARAM; LParam: LPARAM): LRESULT; stdcall;

var
  DLLHandle: HMODULE;
  HookProc: THookProc;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  UnhookWindowsHookEx(WH_CBT);
  FreeLibrary(DLLHandle);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  DLLHandle := LoadLibrary('SystemMenuHookDLL.dll');
  CodeSite.Send('TForm1.FormCreate: DLLHandle', DLLHandle);
  if DLLHandle <> 0 then
  begin
    @HookProc := GetProcAddress(DLLHandle, 'HookFunc');
    CodeSite.Send('TForm1.FormCreate: @HookProc', @HookProc);
    if Assigned(HookProc) then
    begin
      CodeSite.Send('TForm1.FormCreate: Assigned');
      SetWindowsHookEx(WH_CBT, HookProc, DLLHandle, 0);
    end;
  end;
end;

end.

I have put the DLL in the same directory of the host application exe file. Unfortunately, it does not work: After having started the host application, and then trying to start a 32-bit program, the program does not start! It seems that the hook is blocking the program.


问:
React context with object value - Alternative?
I've been working with a React context that takes in a value that is an object, and facing rerendering issues that I didn't understand fully until I saw this statement:

If you are passing down an object on your React context provider and any property on it updates, what happens? Any component which consumes that context will re-render.

My question is... Is there an alternative to using a context when it comes to holding global state stuff in an object that will be updated?


问:
How to calculate table height in watch in vue
I have a table and I give a ref to it.

```<code><table ref="table"></table>
</code>```

I want to calculate the height of this table in watcher:

```<code>watch: {

   buttonClicked: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          const tableElement = this.$refs.table.$el;
          const tableOffsetTop = tableElement.getBoundingClientRect().top;
        });
      },
    },
}
</code>```

But I am getting an error: Uncaught TypeError: Cannot read properties of undefined (reading '$el')

I tried ti fix it with this.$nextTick but this time I cannot calculate it right.

How can I fix it?

Body:
I have a table and I give a ref to it.

I want to calculate the height of this table in watcher:

watch: {

   buttonClicked: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          const tableElement = this.$refs.table.$el;
          const tableOffsetTop = tableElement.getBoundingClientRect().top;
        });
      },
    },
}

But I am getting an error: Uncaught TypeError: Cannot read properties of undefined (reading '$el')

I tried ti fix it with this.$nextTick but this time I cannot calculate it right.

How can I fix it?


问:
Sonata Admin (4.17 or higher) Override list__action_delete.html.twig globally
I want to do exactly this (see link below) - override the list__action_delete.html.twig template globally for the entire project.
But with the newer sonata-admin and symfony version (without the app-directory) I have no clue where to place the list__action_xxx.html.twig files

See:
SonataAdminBundle - rewrite action button teplates in config.yml


问:
Subquery in Django ORM
I have following models. My goal is to extract 2 recent Comments per Post. Is that possible?

```<code>class Post(models.Model):
    author = models.ForeignKey(Author, related_name="posts", on_delete=models.CASCADE)
    title = models.CharField(max_length=256)
    text = models.TextField(blank=True, default="")
    created_at = models.DateTimeField(default=datetime.now, blank=True)

    @property
    def comments_number(self):
        return self.comments.count()

    def __str__(self, *args, **kwargs):
        return f"{self.title}"

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    author = models.ForeignKey(Author, related_name="comment", on_delete=models.CASCADE)
    text = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)
</code>```

The closest try I've got is this one:

```<code>newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
recent_comments = Post.objects.annotate(newest_comments=Subquery(newest.values('text')[:2]))
</code>```

And than when I call recent_comments.values_list() I can see the newest one comment per Post obj (only one) but this is not what I want exactly. I have spend a lot of time on it guys and have no clue...

Title: Subquery in Django ORM

Body:
I have following models. My goal is to extract 2 recent Comments per Post. Is that possible?

class Post(models.Model):
    author = models.ForeignKey(Author, related_name="posts", on_delete=models.CASCADE)
    title = models.CharField(max_length=256)
    text = models.TextField(blank=True, default="")
    created_at = models.DateTimeField(default=datetime.now, blank=True)

    @property
    def comments_number(self):
        return self.comments.count()

    def __str__(self, *args, **kwargs):
        return f"{self.title}"

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    author = models.ForeignKey(Author, related_name="comment", on_delete=models.CASCADE)
    text = models.TextField()
    created_at = models.DateTimeField(default=datetime.now, blank=True)

The closest try I've got is this one:

newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
recent_comments = Post.objects.annotate(newest_comments=Subquery(newest.values('text')[:2]))

And than when I call recent_comments.values_list() I can see the newest one comment per Post obj (only one) but this is not what I want exactly. I have spend a lot of time on it guys and have no clue...


问:
Mageno 2.4.4. Transactional Emails with Google Business not working
We have a Google Workspace email address support@company.com which we want to use to send transactional/newsletter emails. So we installed Mageplaza SMTP plugin, chose Google Workspace configuration, everything setup. But when it comes to testing, then there is an Error:

```<code>5.7.0 Authentication Required. Learn more at 5.7.0 https://support.google.com/mail/?p=WantAuthError ca18-20020a05622a1f1200b003a7ee9613a6sm1380414qtb.25 - gsmtp

</code>```

As I understood need to allow in Gmail Settings to use it with "less secure apps". But it also turns out that Gmail no longer supports that feature.

So, the question remains, how can I connect Google Workspace with Magento so all the mails are being sent out from company email (support@company.com)? Or what workaround I could do to make it running?

__

Summary of what we did try: Installing Mageplaza SMTP, Load Google Workspace configuration, Send test mail (unsuccessfully - error happens), Changing Gmail settings (unsuccessfully - feature no longer available).

Body:
We have a Google Workspace email address support@company.com which we want to use to send transactional/newsletter emails. So we installed Mageplaza SMTP plugin, chose Google Workspace configuration, everything setup. But when it comes to testing, then there is an Error:

5.7.0 Authentication Required. Learn more at 5.7.0 https://support.google.com/mail/?p=WantAuthError ca18-20020a05622a1f1200b003a7ee9613a6sm1380414qtb.25 - gsmtp

As I understood need to allow in Gmail Settings to use it with "less secure apps". But it also turns out that Gmail no longer supports that feature.

So, the question remains, how can I connect Google Workspace with Magento so all the mails are being sent out from company email (support@company.com)? Or what workaround I could do to make it running?

__

Summary of what we did try: Installing Mageplaza SMTP, Load Google Workspace configuration, Send test mail (unsuccessfully - error happens), Changing Gmail settings (unsuccessfully - feature no longer available).


问:
Invalid token when password resetting on Microsoft.AspNetCore.Identity but ONLY on server side, not localhost
I'm currently a beginner developer and I'm coding a password reset on my WebApp.

So as you can see everything is good in localhost but in live I got an invalid token and I don't know why:

```<code>public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return RedirectToAction(nameof(ForgotPasswordConfirmation));
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                // Go to the change password page
                Response.Redirect(callbackUrl);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
}

</code>```

I have checked the files in my FTP and everything is the same in AccountController.cs.
My token is supposed to be built with some special characters as "+" and I know my url will be like http://localhost:5000/Account/ResetPassword?userId=00c2a3ad-64c8-49d3-95e5-49a120831b85&code=CfDJ8MVJi%2BoeOmp....
I have figured my callbackUrl has a different behavior onlineat the %25
Do I have decoded the URL and I found %25 means "%" in UTF-8 and I think it's an encoding/decoding problem so I trued to encode like this code = HttpUtility.UrlEecode(code) and decoding it but it's even worse because my token is getting invalid so maybe I got completely my theory is wrong.

Have you any clues? any soution to my problem? Glad to disscuss with.
Thanks for paying attention to my issue,

BR X-MAS Greetings,

Lap1

EDIT:

Okay first of all thanks for so I checked my versions on the both environnemnets by using dotnet -- info and here are my versions. and . So I know I installed a newer version of .NET Framework on my PC. But there is remaining the 2.0.0 version and it's used for every debugging. I don't know if the problem is here so If you have any clues I'm here to exploit this.

EDIT 2: so I uninstalled the newer versions (not a good idea buut I did just in case) to keep the same versions in 2.2.202 and my code still running

EDIT3: ok so I will keep updating my thoughts about my issue. I think it's because the code is encoded once before I see the URL. e.g. + becomes %2F and it becomes %252F in the URL. I never encoded the code string but  there is somewhere in the server some options...

Body:
I'm currently a beginner developer and I'm coding a password reset on my WebApp.

So as you can see everything is good in localhost but in live I got an invalid token and I don't know why:

public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return RedirectToAction(nameof(ForgotPasswordConfirmation));
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                // Go to the change password page
                Response.Redirect(callbackUrl);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
}

I have checked the files in my FTP and everything is the same in AccountController.cs.
My token is supposed to be built with some special characters as "+" and I know my url will be like http://localhost:5000/Account/ResetPassword?userId=00c2a3ad-64c8-49d3-95e5-49a120831b85&code=CfDJ8MVJi%2BoeOmp....
I have figured my callbackUrl has a different behavior onlineat the %25
Do I have decoded the URL and I found %25 means "%" in UTF-8 and I think it's an encoding/decoding problem so I trued to encode like this code = HttpUtility.UrlEecode(code) and decoding it but it's even worse because my token is getting invalid so maybe I got completely my theory is wrong.

Have you any clues? any soution to my problem? Glad to disscuss with.
Thanks for paying attention to my issue,

BR X-MAS Greetings,

Lap1

EDIT:

Okay first of all thanks for so I checked my versions on the both environnemnets by using dotnet -- info and here are my versions. and . So I know I installed a newer version of .NET Framework on my PC. But there is remaining the 2.0.0 version and it's used for every debugging. I don't know if the problem is here so If you have any clues I'm here to exploit this.

EDIT 2: so I uninstalled the newer versions (not a good idea buut I did just in case) to keep the same versions in 2.2.202 and my code still running

EDIT3: ok so I will keep updating my thoughts about my issue. I think it's because the code is encoded once before I see the URL. e.g. + becomes %2F and it becomes %252F in the URL. I never encoded the code string but  there is somewhere in the server some options...


问:
Button with hyperlink to OpenVPN connection
Is it any possibility to create hyperlink to open connection OpenVPN?

I suppose Telegram works on the same principle, which has the hyperlink telegram://XYZ and it opens the Telegram application on the computer but how can I do it with openVPN Connect?

I tried also put link to local file .ovpn but chrome download it instead open...


问:
create glyphs with diacritic marks
I would like to add a letter h with a dot below (U+1E25) to a free font from google. Is it possible to just duplicate the letter h and paste it to another position and draw a dot under it?

If so, what are the exact steps?

Thanks

Unfortunately i can't find the time to learn fontforge. I have attempted but have not been successful

Title: create glyphs with diacritic marks


问:
Adding telemetry properties without having to use an ITelemetryInitializer
I've found that in the application I've been set to work on, there's a TelemetryInitialier which is called at every web api call and adds some properties from the appsettings.json.

Here's the defined class

```<code>   public class AppInsightTelemetryInitializer : ITelemetryInitializer
    {
        private readonly AppInsightsMetrics _appInsightsMetrics;
        public AppInsightTelemetryInitializer(IOptions<AppInsightsMetrics> appInsightsMetrics)
        {
            _appInsightsMetrics = appInsightsMetrics.Value;
        }

        public void Initialize(ITelemetry telemetry)
        {
            var propTelemetry = (ISupportProperties)telemetry;

            propTelemetry.Properties["Application"] = _appInsightsMetrics.Application;
            propTelemetry.Properties["Version"] = _appInsightsMetrics.Version;
            propTelemetry.Properties["LatestCommit"] = _appInsightsMetrics.LatestCommit;
        }
    }
</code>```

This class is registered this way

```<code>   appBuilder.Services.Configure<AppInsightsMetrics>(appBuilder.Configuration.GetSection(AppInsightsMetrics.InsightsMetrics));
            appBuilder.Services.AddSingleton<ITelemetryInitializer, AppInsightTelemetryInitializer>();

            if (env.IsDevelopment())
            {
                services.AddApplicationInsightsTelemetry(x =>
                {
                    x.EnableDebugLogger = false;
                    x.InstrumentationKey = "instrumentation key";
                });
            }
            else
            {
                services.AddApplicationInsightsTelemetry();
            }
</code>```

And the data are loaded from the appsettings.json file as

```<code>  "AppInsightsMetrics": {
    "Application": "xxx.Api",
    "Version": "",
    "LatestCommit": ""
  },
</code>```

Those data are replaced in production by CI/CD azure pipeline.

I was wondering, is there a way of defining them at configuration time and remove this middleware from each call?

Thanks in advance

Body:
I've found that in the application I've been set to work on, there's a TelemetryInitialier which is called at every web api call and adds some properties from the appsettings.json.

Here's the defined class

   public class AppInsightTelemetryInitializer : ITelemetryInitializer
    {
        private readonly AppInsightsMetrics _appInsightsMetrics;
        public AppInsightTelemetryInitializer(IOptions<AppInsightsMetrics> appInsightsMetrics)
        {
            _appInsightsMetrics = appInsightsMetrics.Value;
        }

        public void Initialize(ITelemetry telemetry)
        {
            var propTelemetry = (ISupportProperties)telemetry;

            propTelemetry.Properties["Application"] = _appInsightsMetrics.Application;
            propTelemetry.Properties["Version"] = _appInsightsMetrics.Version;
            propTelemetry.Properties["LatestCommit"] = _appInsightsMetrics.LatestCommit;
        }
    }

This class is registered this way

   appBuilder.Services.Configure<AppInsightsMetrics>(appBuilder.Configuration.GetSection(AppInsightsMetrics.InsightsMetrics));
            appBuilder.Services.AddSingleton<ITelemetryInitializer, AppInsightTelemetryInitializer>();

            if (env.IsDevelopment())
            {
                services.AddApplicationInsightsTelemetry(x =>
                {
                    x.EnableDebugLogger = false;
                    x.InstrumentationKey = "instrumentation key";
                });
            }
            else
            {
                services.AddApplicationInsightsTelemetry();
            }

And the data are loaded from the appsettings.json file as

  "AppInsightsMetrics": {
    "Application": "xxx.Api",
    "Version": "",
    "LatestCommit": ""
  },

Those data are replaced in production by CI/CD azure pipeline.

I was wondering, is there a way of defining them at configuration time and remove this middleware from each call?

Thanks in advance