问:
Jupyterlab extension jupyterlab_templates not finding template files
I'm trying to work with the jupyterlab_templates extension. For some reason, it's not finding the corresponding template files, even though I've set the correct path?
When running jupyter lab, it finds the extension and confirms the search path I set, but isn't finding any files:

```<code>[I 2022-01-11 18:10:09.108 ServerApp] jupyterlab_templates | extension was successfully loaded.
Installing jupyterlab_templates handler on path /templates
Search paths:
    /Users/emilaz/.jupyter/templates
Available templates:

[I 2022-01-11 18:10:09.108 ServerApp] jupyterlab_templates.extension | extension was successfully loaded.
</code>```

Here is what the content of /Users/my_username/.jupyter/templates looks like:

```<code>$ ls /Users/emilaz/.jupyter/templates
new_template.ipynb  some_template.ipynb
</code>```

Here is my jupyter_notebook_config.py file:

```<code>c.JupyterLabTemplates.template_dirs = ['/Users/emilaz/.jupyter/templates']
c.JupyterLabTemplates.include_default = False
c.JupyterLabTemplates.include_core_paths = False
</code>```

I've tried

un- and reinstalling both jupyterlab and jupyterlab_templates

changing the permission on the template files to 660

running jupyter trust on the two files.

moving the files elsewhere (in a non-hidden folder)

I then tried to include the default templates (set c.JupyterLabTemplates.include_default=True, c.JupyterLabTemplates.include_core_paths=True). This makes the sample template available for selection. I then tried to move my own .ipynb files into the same folder as the sample template ipynb, but they still don't show.

The package versions are

jupyterlab==3.2.6

jupyterlab-templates==0.3.1

答: Dirty solution: add os link to your template_dir near the folder where it sees Sample.ipynb</p>

Body:
I'm trying to work with the jupyterlab_templates extension. For some reason, it's not finding the corresponding template files, even though I've set the correct path?
When running jupyter lab, it finds the extension and confirms the search path I set, but isn't finding any files:

[I 2022-01-11 18:10:09.108 ServerApp] jupyterlab_templates | extension was successfully loaded.
Installing jupyterlab_templates handler on path /templates
Search paths:
    /Users/emilaz/.jupyter/templates
Available templates:

[I 2022-01-11 18:10:09.108 ServerApp] jupyterlab_templates.extension | extension was successfully loaded.

Here is what the content of /Users/my_username/.jupyter/templates looks like:

$ ls /Users/emilaz/.jupyter/templates
new_template.ipynb  some_template.ipynb

Here is my jupyter_notebook_config.py file:

c.JupyterLabTemplates.template_dirs = ['/Users/emilaz/.jupyter/templates']
c.JupyterLabTemplates.include_default = False
c.JupyterLabTemplates.include_core_paths = False

I've tried

un- and reinstalling both jupyterlab and jupyterlab_templates

changing the permission on the template files to 660

running jupyter trust on the two files.

moving the files elsewhere (in a non-hidden folder)

I then tried to include the default templates (set c.JupyterLabTemplates.include_default=True, c.JupyterLabTemplates.include_core_paths=True). This makes the sample template available for selection. I then tried to move my own .ipynb files into the same folder as the sample template ipynb, but they still don't show.

The package versions are

jupyterlab==3.2.6

jupyterlab-templates==0.3.1


来源: stackexchange

问:
ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' in AWS CodeBuild
ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc'

(/python3.7/site-packages/botocore/docs/bcdoc/init.py)

```<code>Traceback (most recent call last):
  File "/root/.pyenv/versions/3.7.6/bin/aws", line 19, in <module>
    import awscli.clidriver

  File "/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages/awscli/clidriver.py", line 36, in <module>
    from awscli.help import ProviderHelpCommand

  File "/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages/awscli/help.py", line 23, in <module>
    from botocore.docs.bcdoc import docevents

ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' (/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages/botocore/docs/bcdoc/__init__.py)

[Container] 2020/10/29 16:48:39 Command did not exit successfully aws --version exit status 1
</code>```

The failure occurs in the PRE_BUILD.

And this is my spec build file: buildspec-cd.yml

```<code>pre_build:
    commands:
      - AWS_REGION=${AWS_DEFAULT_REGION}
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_VERSION=${COMMIT_HASH}
      - REPOSITORY_URI=${CONTAINER_REGISTRY}/${APPLICATION_NAME}
      - aws --version
      - echo Logging in to Amazon ECR...
      - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
</code>```

The codebuild was working correctly and nothing has been changed.
Only stopped working.

答:
I also got this error on Ubuntu 20.04 (though not in CodeBuild, I was running aws lambda invoke).  Installing the AWS CLI v2 (https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html) worked for me:

```<code>curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
</code>```

ContentLicense: CC BY-SA 4.0

Body:
ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc'

(/python3.7/site-packages/botocore/docs/bcdoc/init.py)

Traceback (most recent call last):
  File "/root/.pyenv/versions/3.7.6/bin/aws", line 19, in <module>
    import awscli.clidriver

  File "/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages/awscli/clidriver.py", line 36, in <module>
    from awscli.help import ProviderHelpCommand

  File "/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages/awscli/help.py", line 23, in <module>
    from botocore.docs.bcdoc import docevents

ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' (/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages/botocore/docs/bcdoc/__init__.py)

[Container] 2020/10/29 16:48:39 Command did not exit successfully aws --version exit status 1

The failure occurs in the PRE_BUILD.

And this is my spec build file: buildspec-cd.yml

pre_build:
    commands:
      - AWS_REGION=${AWS_DEFAULT_REGION}
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_VERSION=${COMMIT_HASH}
      - REPOSITORY_URI=${CONTAINER_REGISTRY}/${APPLICATION_NAME}
      - aws --version
      - echo Logging in to Amazon ECR...
      - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)

The codebuild was working correctly and nothing has been changed.
Only stopped working.

Body:
I also got this error on Ubuntu 20.04 (though not in CodeBuild, I was running aws lambda invoke).  Installing the AWS CLI v2 (https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html) worked for me:

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install


问:
Why does my Resnet56 implementation have less accuracy than in the original paper?
I was trying to implement Resnet56 in Tensorflow to classify the CIFAR10 images, but somehow I got a lower accuracy than the original creators.

I did everything exactly as described in the paper: same architecture, same data augmentation, same learning rate scheduling, same batch size...

But somehow my implementation produced an accuracy of only 91.84%, while in the original paper they reached 93.03% for the 56 layer Resnet.

Here is the link to the Resnet paper: https://arxiv.org/pdf/1512.03385.pdf

I found what my problem was (see answers if interested) and here you can find my (now correct) implementation, that can now reach the exact same accuracy:

```<code>import argparse
import datetime
import os
import re

import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow_addons as tfa
import tensorflow_datasets as tfds

os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")  # Report only TF errors and warnings by default

parser = argparse.ArgumentParser()
parser.add_argument("--resnet_n", default=9, type=int, help="n from Resnet paper.")
parser.add_argument("--seed", default=42, type=int, help="Random seed.")
parser.add_argument("--threads", default=1, type=int, help="Maximum number of threads to use.")

class ResNet(keras.Model):
    class ResidualBlock(tf.Module):
        def __init__(self, filters: int, down_sample: bool):
            super().__init__()
            self.filters = filters
            self.down_sample = down_sample

        def __call__(self, x):
            out = x

            out = keras.layers.Conv2D(filters=self.filters,
                                      kernel_size=(3, 3),
                                      strides=(1, 1) if not self.down_sample else (2, 2),
                                      padding="same",
                                      use_bias=False,
                                      kernel_initializer=tf.keras.initializers.HeNormal)(out)
            out = keras.layers.BatchNormalization()(out)
            out = keras.layers.ReLU()(out)

            out = keras.layers.Conv2D(filters=self.filters,
                                      kernel_size=(3, 3),
                                      strides=(1, 1),
                                      padding="same",
                                      use_bias=False,
                                      kernel_initializer=tf.keras.initializers.HeNormal)(out)
            out = keras.layers.BatchNormalization()(out)

            if self.down_sample:
                residual = keras.layers.Conv2D(filters=self.filters, kernel_size=(1, 1), strides=(2, 2),
                                               padding="same",
                                               use_bias=False,
                                               kernel_initializer=tf.keras.initializers.HeNormal)(x)
                residual = tf.keras.layers.BatchNormalization()(residual)
            else:
                residual = x

            out = out + residual
            out = keras.layers.ReLU()(out)
            return out

    def __init__(self, args):
        inputs = keras.layers.Input(shape=(32, 32, 3), dtype=tf.float32)
        outputs = keras.layers.Conv2D(filters=16, kernel_size=(3, 3), strides=(1, 1), padding="same", use_bias=False,
                                      kernel_initializer=tf.keras.initializers.HeNormal)(
            inputs)
        outputs = keras.layers.BatchNormalization()(outputs)
        outputs = keras.layers.ReLU()(outputs)

        for _ in range(0, args.resnet_n):
            outputs = self.ResidualBlock(16, False)(outputs)

        outputs = self.ResidualBlock(32, True)(outputs)
        for _ in range(1, args.resnet_n):
            outputs = self.ResidualBlock(32, False)(outputs)

        outputs = self.ResidualBlock(64, True)(outputs)
        for _ in range(1, args.resnet_n):
            outputs = self.ResidualBlock(64, False)(outputs)

        outputs = keras.layers.GlobalAveragePooling2D()(outputs)
        outputs = keras.layers.Dense(10, activation=tf.nn.softmax)(outputs)
        super().__init__(inputs, outputs)

def main(args, tb_callback):
    ds_train,ds_test = tfds.load("cifar10",split=["train","test"],as_supervised=True)

    img_augmentation = keras.Sequential(
        [
            keras.layers.RandomFlip("horizontal"),
            keras.layers.RandomTranslation(height_factor=0.125, width_factor=0.125, fill_mode="constant",
                                           fill_value=0.5)
        ]
    )
    ds_train = ds_train.map(lambda img, label: (tf.cast(img, tf.float32) / 255.0, label))
    ds_test = ds_test.map(lambda img, label: (tf.cast(img, tf.float32) / 255.0, label))

    total_count, per_pixel_sum = ds_train.reduce((np.float32(0), tf.zeros((32, 32, 3))),
                                                 lambda prev, curr: (prev[0] + 1.0, prev[1] + curr[0]))
    per_pixel_mean = per_pixel_sum / total_count

    ds_train = ds_train.map(lambda img, label: (img_augmentation(img, training=True), tf.one_hot(label, 10)))
    ds_test = ds_test.map(lambda img, label: (img, tf.one_hot(label, 10)))

    ds_train = ds_train.map(lambda img, label: (img - per_pixel_mean, label))
    ds_test = ds_test.map(lambda img, label: (img - per_pixel_mean, label))

    ds_train = ds_train.shuffle(5000).batch(128, drop_remainder=True).prefetch(tf.data.AUTOTUNE)
    ds_test = ds_test.shuffle(5000).batch(128, drop_remainder=True).prefetch(tf.data.AUTOTUNE)

    model = ResNet(args)

    learning_rate = keras.optimizers.schedules.PiecewiseConstantDecay(
        [32000, 48000], [0.1, 0.01, 0.001]
    )
    weight_decay = keras.optimizers.schedules.PiecewiseConstantDecay(
        [32000, 48000], [1e-4, 1e-5, 1e-6]
    )

    model.compile(
        optimizer=tfa.optimizers.SGDW(weight_decay=weight_decay, learning_rate=learning_rate, momentum=0.9,
                                      nesterov=False),
        loss=tf.losses.CategoricalCrossentropy(),
        metrics=[tf.metrics.CategoricalAccuracy("accuracy")],
    )

    model.fit(x=ds_train, epochs=200, validation_data=ds_test, callbacks=[tb_callback], use_multiprocessing=True,
              workers=args.threads)

    model.save(args.logdir + '/model')
    print('OK')

if __name__ == "__main__":
    args = parser.parse_args([] if "__file__" not in globals() else None)

    # Fix random seeds and threads
    np.random.seed(args.seed)
    tf.random.set_seed(args.seed)
    tf.config.threading.set_inter_op_parallelism_threads(args.threads)
    tf.config.threading.set_intra_op_parallelism_threads(args.threads)

    # Create logdir name
    args.logdir = os.path.join("{}/{}".format("logs", os.path.basename(globals().get("__file__", "notebook"))),
                               "{}-{}".format(
                                   datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"),
                                   ",".join(("{}={}".format(re.sub("(.)[^_]*_?", r"\1", key), value) for key, value in
                                             sorted(vars(args).items())))
                               ))

    tb_callback = tf.keras.callbacks.TensorBoard(args.logdir, histogram_freq=1, update_freq=100, profile_batch=0)

    main(args, tb_callback)

</code>```

答:
I found what my problems were:

I didn't apply data augmentation correctly, changed img_augmentation(img) to img_augmentation(img, training=True)

Changed kernel initializer to HeNormal, what they used in the paper

Added per pixel mean substraction as a normalization

Disabling nesterov helped somehow (IDK why)

Body:
I was trying to implement Resnet56 in Tensorflow to classify the CIFAR10 images, but somehow I got a lower accuracy than the original creators.

I did everything exactly as described in the paper: same architecture, same data augmentation, same learning rate scheduling, same batch size...

But somehow my implementation produced an accuracy of only 91.84%, while in the original paper they reached 93.03% for the 56 layer Resnet.

Here is the link to the Resnet paper: https://arxiv.org/pdf/1512.03385.pdf

I found what my problem was (see answers if interested) and here you can find my (now correct) implementation, that can now reach the exact same accuracy:

import argparse
import datetime
import os
import re

import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow_addons as tfa
import tensorflow_datasets as tfds

os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")  # Report only TF errors and warnings by default

parser = argparse.ArgumentParser()
parser.add_argument("--resnet_n", default=9, type=int, help="n from Resnet paper.")
parser.add_argument("--seed", default=42, type=int, help="Random seed.")
parser.add_argument("--threads", default=1, type=int, help="Maximum number of threads to use.")

class ResNet(keras.Model):
    class ResidualBlock(tf.Module):
        def __init__(self, filters: int, down_sample: bool):
            super().__init__()
            self.filters = filters
            self.down_sample = down_sample

        def __call__(self, x):
            out = x

            out = keras.layers.Conv2D(filters=self.filters,
                                      kernel_size=(3, 3),
                                      strides=(1, 1) if not self.down_sample else (2, 2),
                                      padding="same",
                                      use_bias=False,
                                      kernel_initializer=tf.keras.initializers.HeNormal)(out)
            out = keras.layers.BatchNormalization()(out)
            out = keras.layers.ReLU()(out)

            out = keras.layers.Conv2D(filters=self.filters,
                                      kernel_size=(3, 3),
                                      strides=(1, 1),
                                      padding="same",
                                      use_bias=False,
                                      kernel_initializer=tf.keras.initializers.HeNormal)(out)
            out = keras.layers.BatchNormalization()(out)

            if self.down_sample:
                residual = keras.layers.Conv2D(filters=self.filters, kernel_size=(1, 1), strides=(2, 2),
                                               padding="same",
                                               use_bias=False,
                                               kernel_initializer=tf.keras.initializers.HeNormal)(x)
                residual = tf.keras.layers.BatchNormalization()(residual)
            else:
                residual = x

            out = out + residual
            out = keras.layers.ReLU()(out)
            return out

    def __init__(self, args):
        inputs = keras.layers.Input(shape=(32, 32, 3), dtype=tf.float32)
        outputs = keras.layers.Conv2D(filters=16, kernel_size=(3, 3), strides=(1, 1), padding="same", use_bias=False,
                                      kernel_initializer=tf.keras.initializers.HeNormal)(
            inputs)
        outputs = keras.layers.BatchNormalization()(outputs)
        outputs = keras.layers.ReLU()(outputs)

        for _ in range(0, args.resnet_n):
            outputs = self.ResidualBlock(16, False)(outputs)

        outputs = self.ResidualBlock(32, True)(outputs)
        for _ in range(1, args.resnet_n):
            outputs = self.ResidualBlock(32, False)(outputs)

        outputs = self.ResidualBlock(64, True)(outputs)
        for _ in range(1, args.resnet_n):
            outputs = self.ResidualBlock(64, False)(outputs)

        outputs = keras.layers.GlobalAveragePooling2D()(outputs)
        outputs = keras.layers.Dense(10, activation=tf.nn.softmax)(outputs)
        super().__init__(inputs, outputs)

def main(args, tb_callback):
    ds_train,ds_test = tfds.load("cifar10",split=["train","test"],as_supervised=True)

    img_augmentation = keras.Sequential(
        [
            keras.layers.RandomFlip("horizontal"),
            keras.layers.RandomTranslation(height_factor=0.125, width_factor=0.125, fill_mode="constant",
                                           fill_value=0.5)
        ]
    )
    ds_train = ds_train.map(lambda img, label: (tf.cast(img, tf.float32) / 255.0, label))
    ds_test = ds_test.map(lambda img, label: (tf.cast(img, tf.float32) / 255.0, label))

    total_count, per_pixel_sum = ds_train.reduce((np.float32(0), tf.zeros((32, 32, 3))),
                                                 lambda prev, curr: (prev[0] + 1.0, prev[1] + curr[0]))
    per_pixel_mean = per_pixel_sum / total_count

    ds_train = ds_train.map(lambda img, label: (img_augmentation(img, training=True), tf.one_hot(label, 10)))
    ds_test = ds_test.map(lambda img, label: (img, tf.one_hot(label, 10)))

    ds_train = ds_train.map(lambda img, label: (img - per_pixel_mean, label))
    ds_test = ds_test.map(lambda img, label: (img - per_pixel_mean, label))

    ds_train = ds_train.shuffle(5000).batch(128, drop_remainder=True).prefetch(tf.data.AUTOTUNE)
    ds_test = ds_test.shuffle(5000).batch(128, drop_remainder=True).prefetch(tf.data.AUTOTUNE)

    model = ResNet(args)

    learning_rate = keras.optimizers.schedules.PiecewiseConstantDecay(
        [32000, 48000], [0.1, 0.01, 0.001]
    )
    weight_decay = keras.optimizers.schedules.PiecewiseConstantDecay(
        [32000, 48000], [1e-4, 1e-5, 1e-6]
    )

    model.compile(
        optimizer=tfa.optimizers.SGDW(weight_decay=weight_decay, learning_rate=learning_rate, momentum=0.9,
                                      nesterov=False),
        loss=tf.losses.CategoricalCrossentropy(),
        metrics=[tf.metrics.CategoricalAccuracy("accuracy")],
    )

    model.fit(x=ds_train, epochs=200, validation_data=ds_test, callbacks=[tb_callback], use_multiprocessing=True,
              workers=args.threads)

    model.save(args.logdir + '/model')
    print('OK')

if __name__ == "__main__":
    args = parser.parse_args([] if "__file__" not in globals() else None)

    # Fix random seeds and threads
    np.random.seed(args.seed)
    tf.random.set_seed(args.seed)
    tf.config.threading.set_inter_op_parallelism_threads(args.threads)
    tf.config.threading.set_intra_op_parallelism_threads(args.threads)

    # Create logdir name
    args.logdir = os.path.join("{}/{}".format("logs", os.path.basename(globals().get("__file__", "notebook"))),
                               "{}-{}".format(
                                   datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"),
                                   ",".join(("{}={}".format(re.sub("(.)[^_]*_?", r"\1", key), value) for key, value in
                                             sorted(vars(args).items())))
                               ))

    tb_callback = tf.keras.callbacks.TensorBoard(args.logdir, histogram_freq=1, update_freq=100, profile_batch=0)

    main(args, tb_callback)


问:
Graph search with weight limit
I have a undirected, weighted graph with objects of an arbitrary type as nodes. The weight of an edge between two nodes A and B is the similarity of these two nodes in the interval (0, 1]. A similarity of 0 leads to no connection between to nodes, so the graph may be partitioned.

Given a target weight w and a start-node S,  which is an algorithm to find all nodes that have a weight > w. Subnodes (seen from S) should have the product of all weights on the path. I.e:

```<code>S --(0.9)-- N1 --(0.9)-- N2 --(0.6) -- N3
</code>```

Starting with S the nodes will have the following similarity values:

```<code>N1: 0.9
N2: 0.9 * 0.9 = 0.81
N3: 0.9 * 0.9 * 0.6 = 0.486
</code>```

So given S and the target weight 0.5 the search should return N1 and N3. Wheres a search starting from N2 would return S, N1 and N3.

Are their any algorithms that fit my needs?

答:
note the following:

log(p1 * p2) = log(p1) + log(p2)

if p1 < p2 then log(p1) < log(p2) and thus: -log(p1) > -log(p2)

Claim [based on the 1,2 mentioned above]: finding the most similar route from s to t, is actually finding the minimum path from s to t, where weights are -log of original.

I suggest the following algorithm, based on Dijkstra's algorithm and the above claim.

```<code>1. define for each edge e: w'(e) = -log(w(e)) //well defined because w(e) > 0
2. run Dijkstra's algorithm on the graph with the modified weights.
3. return all vertices v that their weight is dijkstra(v) < -log(needed)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Graph search with weight limit

Body:
I have a undirected, weighted graph with objects of an arbitrary type as nodes. The weight of an edge between two nodes A and B is the similarity of these two nodes in the interval (0, 1]. A similarity of 0 leads to no connection between to nodes, so the graph may be partitioned.

Given a target weight w and a start-node S,  which is an algorithm to find all nodes that have a weight > w. Subnodes (seen from S) should have the product of all weights on the path. I.e:

S --(0.9)-- N1 --(0.9)-- N2 --(0.6) -- N3

Starting with S the nodes will have the following similarity values:

N1: 0.9
N2: 0.9 * 0.9 = 0.81
N3: 0.9 * 0.9 * 0.6 = 0.486

So given S and the target weight 0.5 the search should return N1 and N3. Wheres a search starting from N2 would return S, N1 and N3.

Are their any algorithms that fit my needs?

Body:
note the following:

log(p1 * p2) = log(p1) + log(p2)

if p1 < p2 then log(p1) < log(p2) and thus: -log(p1) > -log(p2)

Claim [based on the 1,2 mentioned above]: finding the most similar route from s to t, is actually finding the minimum path from s to t, where weights are -log of original.

I suggest the following algorithm, based on Dijkstra's algorithm and the above claim.

1. define for each edge e: w'(e) = -log(w(e)) //well defined because w(e) > 0
2. run Dijkstra's algorithm on the graph with the modified weights.
3. return all vertices v that their weight is dijkstra(v) < -log(needed)


问:
C++ Linker Errors mulitple function defined
Have been stuck with multiple functions defined and linker errors while trying to compile the program, not too sure how I even defined everything properly in the header.

The purpose of the program is to check the validity of two entries from the main.cpp/test file. I made a program which checks the entries from the test file.

CarInventory.cpp

```<code>       #include <iostream>
       #include <string>
       #include <iomanip>
       #include <string.h>
       #include "CarInventory.h"
       using namespace std;
       using namespace sdds;
       void CarInventory::resetInfo()

      {

         m_type = nullptr;

         m_brand = nullptr;

         m_model = nullptr;

         m_year = 0;

         m_code = 0;

    m_price = 0;

}

CarInventory::CarInventory()

{

    resetInfo();

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    resetInfo();

    setInfo(type, brand, model, year, code, price);

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model)

{

    resetInfo();

    setInfo(type, brand, model, 2022, 100, 1);

}

CarInventory::~CarInventory()

{

    delete[] m_type;

    delete[] m_brand;

    delete[] m_model;

}

CarInventory& CarInventory::setInfo(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    if (type == nullptr || brand == nullptr || model == nullptr || year < 1990 || code < 100 || price < 0)

    {

        resetInfo();

    }

    else

    {

        delete[] m_type;

        delete[] m_brand;

        delete[] m_model;

        m_type = new char[strlen(type) + 1];

        strcpy_s(m_type, sizeof(type), type);

        m_brand = new char[strlen(brand) + 1];

        strcpy_s(m_brand, sizeof(brand),  brand);

        m_model = new char[strlen(model) + 1];

        strcpy_s(m_model, sizeof(m_model),  model);

        m_year = year;

        m_code = code;

        m_price = price;

    }

    return *this;

}

bool CarInventory::isValid() const

{

    return m_type != nullptr && m_brand != nullptr && m_model != nullptr && m_year >= 1990 && m_code >= 100 && m_price >= 0;

}

void CarInventory::printInfo() const

{

    std::cout << "|" << std::setw(12) << m_type << "|" << std::setw(18) << m_brand << "|" << std::setw(18) << m_model << "|" << std::setw(6) << m_year << "|" << std::setw(6) << m_code << "|" << std::setw(11) << m_price << "|" << std::endl;

}

bool CarInventory::isSimilarTo(const CarInventory& car) const

{

    return m_type == car.m_type && m_brand == car.m_brand && m_model == car.m_model && m_year == car.m_year;

}

namespace sdds {

    bool find_similar(CarInventory car[], const int num_cars)

    {

        for (int i = 0; i < num_cars; i++)

        {

            for (int j = i + 1; j < num_cars; j++)

            {

                if (car[i].isSimilarTo(car[j]))

                {

                    return true;

                }

            }

        }

        return false;

    }
}
</code>```

Header File

```<code>#ifndef CARINVENTORY_H
#define CARINVENTORY_H
#define _CRT_SECURE_NO_WARNINGS

namespace sdds {
class CarInventory {
    char* m_type;
    char* m_brand;
    char* m_model;
    int m_year;
    int m_code;
    double m_price;
    void resetInfo();
public:
    CarInventory();
    CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price);
    CarInventory(const char* type, const char* brand, const char* model);
    bool isSimilarTo(const CarInventory& car) const;
    ~CarInventory();
    CarInventory& setInfo(const char* type, const char* brand, const char* model, int year, int code, double price);
    void printInfo() const;
    bool isValid() const;
    bool find_similar(CarInventory car[], const int num_cars);

  };
 }
    #endif
</code>```

Test/main file

```<code>#include<iostream>
#include<iomanip>
#include "CarInventory.h"
#include "CarInventory.cpp"
using namespace std;
using namespace sdds;

 int main()
 {
const int num_cars = 6;
bool invalid_data = false;
CarInventory cars[num_cars] = {
    {},
    {"suv", "volvo", "xc90"},
    {"Truck", "Ford", "F 150", 2021, 105, 55000},
    {"Sedan", "BMW", "M550i", 2022, 101, 91000},
    {"Truck", "Tesla", "Cybertruck", 2021, 102, 65000},
    {"Sedan", "BMW", "M550i"}
};

if (cars[2].setInfo("SUV", "Volvo", "XC90", 2019, 109, 80000).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}
if (cars[1].setInfo("SUV", "Volvo", "XC90", 1234, 1, 1).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}

cout << setw(60) << "----- Car Inventory Information -----" << endl << endl;;
cout << "| Type       | Brand            | Model            | Year | Code |     Price |" << endl;
cout << "+------------+------------------+------------------+------+------+-----------+" << endl;
for (int i = 0; i < num_cars; i++) {
    if (cars[i].isValid())
        cars[i].printInfo();
    else
        invalid_data = true;
}

if (invalid_data) {
    cout << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
    cout << "*  WARNING: There are invalid data in the inventory!      *" << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
}
if (find_similar(cars, num_cars)) {
    cout << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
    cout << "+  WARNING: There are similar entries in the inventory!   +" << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
}
return 0;
  }
</code>```

Compiler Error I've been getting

答:
You need to remove #include "CarInventory.cpp" from your main.cpp file.  It does not belong there.

Your project is already compiling CarInventory.cpp into CarInventory.obj and then linking that .obj into the final .exe.  But you are asking the compiler to include all of CarInventory.cpp's code into main.cpp's code, which is compiled into main.obj.  You are getting errors about all of CarInventory's methods that are being duplicated in both .obj files.

Body:
Have been stuck with multiple functions defined and linker errors while trying to compile the program, not too sure how I even defined everything properly in the header.

The purpose of the program is to check the validity of two entries from the main.cpp/test file. I made a program which checks the entries from the test file.

CarInventory.cpp

       #include <iostream>
       #include <string>
       #include <iomanip>
       #include <string.h>
       #include "CarInventory.h"
       using namespace std;
       using namespace sdds;
       void CarInventory::resetInfo()

      {

         m_type = nullptr;

         m_brand = nullptr;

         m_model = nullptr;

         m_year = 0;

         m_code = 0;

    m_price = 0;

}

CarInventory::CarInventory()

{

    resetInfo();

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    resetInfo();

    setInfo(type, brand, model, year, code, price);

}

CarInventory::CarInventory(const char* type, const char* brand, const char* model)

{

    resetInfo();

    setInfo(type, brand, model, 2022, 100, 1);

}

CarInventory::~CarInventory()

{

    delete[] m_type;

    delete[] m_brand;

    delete[] m_model;

}

CarInventory& CarInventory::setInfo(const char* type, const char* brand, const char* model, int year, int code, double price)

{

    if (type == nullptr || brand == nullptr || model == nullptr || year < 1990 || code < 100 || price < 0)

    {

        resetInfo();

    }

    else

    {

        delete[] m_type;

        delete[] m_brand;

        delete[] m_model;

        m_type = new char[strlen(type) + 1];

        strcpy_s(m_type, sizeof(type), type);

        m_brand = new char[strlen(brand) + 1];

        strcpy_s(m_brand, sizeof(brand),  brand);

        m_model = new char[strlen(model) + 1];

        strcpy_s(m_model, sizeof(m_model),  model);

        m_year = year;

        m_code = code;

        m_price = price;

    }

    return *this;

}

bool CarInventory::isValid() const

{

    return m_type != nullptr && m_brand != nullptr && m_model != nullptr && m_year >= 1990 && m_code >= 100 && m_price >= 0;

}

void CarInventory::printInfo() const

{

    std::cout << "|" << std::setw(12) << m_type << "|" << std::setw(18) << m_brand << "|" << std::setw(18) << m_model << "|" << std::setw(6) << m_year << "|" << std::setw(6) << m_code << "|" << std::setw(11) << m_price << "|" << std::endl;

}

bool CarInventory::isSimilarTo(const CarInventory& car) const

{

    return m_type == car.m_type && m_brand == car.m_brand && m_model == car.m_model && m_year == car.m_year;

}

namespace sdds {

    bool find_similar(CarInventory car[], const int num_cars)

    {

        for (int i = 0; i < num_cars; i++)

        {

            for (int j = i + 1; j < num_cars; j++)

            {

                if (car[i].isSimilarTo(car[j]))

                {

                    return true;

                }

            }

        }

        return false;

    }
}

Header File

#ifndef CARINVENTORY_H
#define CARINVENTORY_H
#define _CRT_SECURE_NO_WARNINGS

namespace sdds {
class CarInventory {
    char* m_type;
    char* m_brand;
    char* m_model;
    int m_year;
    int m_code;
    double m_price;
    void resetInfo();
public:
    CarInventory();
    CarInventory(const char* type, const char* brand, const char* model, int year, int code, double price);
    CarInventory(const char* type, const char* brand, const char* model);
    bool isSimilarTo(const CarInventory& car) const;
    ~CarInventory();
    CarInventory& setInfo(const char* type, const char* brand, const char* model, int year, int code, double price);
    void printInfo() const;
    bool isValid() const;
    bool find_similar(CarInventory car[], const int num_cars);

  };
 }
    #endif

Test/main file

#include<iostream>
#include<iomanip>
#include "CarInventory.h"
#include "CarInventory.cpp"
using namespace std;
using namespace sdds;

 int main()
 {
const int num_cars = 6;
bool invalid_data = false;
CarInventory cars[num_cars] = {
    {},
    {"suv", "volvo", "xc90"},
    {"Truck", "Ford", "F 150", 2021, 105, 55000},
    {"Sedan", "BMW", "M550i", 2022, 101, 91000},
    {"Truck", "Tesla", "Cybertruck", 2021, 102, 65000},
    {"Sedan", "BMW", "M550i"}
};

if (cars[2].setInfo("SUV", "Volvo", "XC90", 2019, 109, 80000).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}
if (cars[1].setInfo("SUV", "Volvo", "XC90", 1234, 1, 1).isValid()) {
    cout << "Information was set correctly!" << endl;
}
else {
    cout << "Information was set incorrectly!" << endl;
}

cout << setw(60) << "----- Car Inventory Information -----" << endl << endl;;
cout << "| Type       | Brand            | Model            | Year | Code |     Price |" << endl;
cout << "+------------+------------------+------------------+------+------+-----------+" << endl;
for (int i = 0; i < num_cars; i++) {
    if (cars[i].isValid())
        cars[i].printInfo();
    else
        invalid_data = true;
}

if (invalid_data) {
    cout << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
    cout << "*  WARNING: There are invalid data in the inventory!      *" << endl;
    cout << setfill('*') << setw(60) << "*" << endl;
}
if (find_similar(cars, num_cars)) {
    cout << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
    cout << "+  WARNING: There are similar entries in the inventory!   +" << endl;
    cout << setfill('+') << setw(60) << "+" << endl;
}
return 0;
  }

Compiler Error I've been getting


问:
Custom Sort using Java 8
Consider the dto class below -

```<code>public class RoleDto {

  private String name;

  RoleDto(String name) {
    this.name = name;
  }
}
</code>```

Its instances would contain names like -

```<code>Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Business Practitioner
Developer
Developer - Professional
Business Practitioner - Professional
</code>```

I want to sort the instances such that the order is -

```<code>Business Practitioner - Expert
Business Practitioner - Master
Business Practitioner - Professional
Business Practitioner

Developer - Expert
Developer - Master
Developer - Professional
Developer
</code>```

I have used the code below -

```<code>ArrayList<RoleDto> roles = new ArrayList<>();
roles.add(new RoleDto("Business Practitioner - Expert"));
roles.add(new RoleDto("Developer - Expert"));
roles.add(new RoleDto("Developer - Master"));
roles.add(new RoleDto("Business Practitioner - Master"));
roles.add(new RoleDto("Business Practitioner"));
roles.add(new RoleDto("Developer"));
roles.add(new RoleDto("Developer - Professional"));
roles.add(new RoleDto("Business Practitioner - Professional"));

List<RoleDto> sorted = roles.stream().sorted(comparing(r -> r.getName(),
    comparing((String s) -> !s.contains("-")))).collect(toList());

for(RoleDto r : sorted)
System.out.println(r.getName());
</code>```

However the output is

```<code>Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Developer - Professional
Business Practitioner - Professional
Business Practitioner
Developer
</code>```

Can someone please help me achieve the expected result

答:
I would suggest changing your RoleDto to have two attributes: String role and String level

Now the code for sorting List would look like:

```<code>Comparator<RoleDto> compareByRoleAndLevel = Comparator
                    .comparing(RoleDto::getRole)
                    .thenComparing(RoleDto::getLevel);

List<RoleDto> sortedRoles = roles.stream()
                .sorted(compareByRoleAndLevel)
                .collect(Collectors.toList());
</code>```

Title: Custom Sort using Java 8

Body:
Consider the dto class below -

public class RoleDto {

  private String name;

  RoleDto(String name) {
    this.name = name;
  }
}

Its instances would contain names like -

Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Business Practitioner
Developer
Developer - Professional
Business Practitioner - Professional

I want to sort the instances such that the order is -

Business Practitioner - Expert
Business Practitioner - Master
Business Practitioner - Professional
Business Practitioner

Developer - Expert
Developer - Master
Developer - Professional
Developer

I have used the code below -

ArrayList<RoleDto> roles = new ArrayList<>();
roles.add(new RoleDto("Business Practitioner - Expert"));
roles.add(new RoleDto("Developer - Expert"));
roles.add(new RoleDto("Developer - Master"));
roles.add(new RoleDto("Business Practitioner - Master"));
roles.add(new RoleDto("Business Practitioner"));
roles.add(new RoleDto("Developer"));
roles.add(new RoleDto("Developer - Professional"));
roles.add(new RoleDto("Business Practitioner - Professional"));

List<RoleDto> sorted = roles.stream().sorted(comparing(r -> r.getName(),
    comparing((String s) -> !s.contains("-")))).collect(toList());

for(RoleDto r : sorted)
System.out.println(r.getName());

However the output is

Business Practitioner - Expert
Developer - Expert
Developer - Master
Business Practitioner - Master
Developer - Professional
Business Practitioner - Professional
Business Practitioner
Developer

Can someone please help me achieve the expected result

Body:
I would suggest changing your RoleDto to have two attributes: String role and String level

Now the code for sorting List would look like:

Comparator<RoleDto> compareByRoleAndLevel = Comparator
                    .comparing(RoleDto::getRole)
                    .thenComparing(RoleDto::getLevel);

List<RoleDto> sortedRoles = roles.stream()
                .sorted(compareByRoleAndLevel)
                .collect(Collectors.toList());


问:
Conditionally apply styles based on component's own width?
The top-level container on my site has a max-width to keep it a reasonable size on wide screens. I have a dynamically sized component which can potentially be wider than that max-width. Normally, the component overflows off the side of the screen with it's own independent scrollbar. But on wide screens, with the max-width, the component is cropped by the side margins and it doesn't look great.

I've got a set of styles which can effectively override the top-level max-width and instead left-justifies the component and makes it use the viewport width instead of the top level max-width. It's as follows:

```<code>.wide-content {
    width: fit-content;
    max-width: 100vh;
    position: relative;
    left: calc(-50vw + 50%);
}
</code>```

The problem now is that this class is unsuitable when the component isn't too wide. It's left justifying when the component would've fit just fine within the container. I only want those components which would be wider than the container to display this way.

Is there a way to conditionally apply this class, or at least just the left property, based on the components own width? Ie. Only apply that left style if the component is wider than top-max-width?

I'd rather avoid using JS for simplicity sake, but I am using scss if that makes it simpler. I'd take a JS solution if it's the only way, but that's a last resort.

Edit for clarification, here are some pictures of what I'm describing. The cream-colored boxes (labeled Main and Main #2) are the components which get the above styles:

What it looked like originally, without the above styles and with the cropping I don't like:

What it looks like with those styles applied unconditionally:

What I want, ie. the small box displays as it did originally but the large box gets the left-justification treatment:

答:
I'm not sure whether this is what you're looking for, but checkout this

* {
  margin: 0;
  padding: 0;
}

:root {
  --container-max: 300px;
}

.container {
  background: lightcoral;
  width: var(--container-max);
  margin: 0 auto;
}

.graph {
  background-color: yellowgreen;
  white-space: nowrap;
  overflow: visible;
  min-width: fit-content;
  transform: translate(calc((var(--container-max) - 100%) / 2), 0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>An H1 Heading</h1>
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit odio voluptatum minima architecto a omnis at iure sint officia neque sapiente quos cupiditate similique illum doloribus, accusantium natus enim! Et.
  </p>
  <div class="graph" contenteditable>Lorem ipsum dolor sit amet</div>
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit odio voluptatum minima architecto a omnis at iure sint officia neque sapiente quos cupiditate similique illum doloribus, accusantium natus enim! Et.
  </p>
</div></code>```

The green block is contenteditable, so start typing into it and you'll see its width eventually expands past the outer container, remaining centered in the screen.

Body:
The top-level container on my site has a max-width to keep it a reasonable size on wide screens. I have a dynamically sized component which can potentially be wider than that max-width. Normally, the component overflows off the side of the screen with it's own independent scrollbar. But on wide screens, with the max-width, the component is cropped by the side margins and it doesn't look great.

I've got a set of styles which can effectively override the top-level max-width and instead left-justifies the component and makes it use the viewport width instead of the top level max-width. It's as follows:

.wide-content {
    width: fit-content;
    max-width: 100vh;
    position: relative;
    left: calc(-50vw + 50%);
}

The problem now is that this class is unsuitable when the component isn't too wide. It's left justifying when the component would've fit just fine within the container. I only want those components which would be wider than the container to display this way.

Is there a way to conditionally apply this class, or at least just the left property, based on the components own width? Ie. Only apply that left style if the component is wider than top-max-width?

I'd rather avoid using JS for simplicity sake, but I am using scss if that makes it simpler. I'd take a JS solution if it's the only way, but that's a last resort.

Edit for clarification, here are some pictures of what I'm describing. The cream-colored boxes (labeled Main and Main #2) are the components which get the above styles:

What it looked like originally, without the above styles and with the cropping I don't like:

What it looks like with those styles applied unconditionally:

What I want, ie. the small box displays as it did originally but the large box gets the left-justification treatment:

Body:
I'm not sure whether this is what you're looking for, but checkout this

* {
  margin: 0;
  padding: 0;
}

:root {
  --container-max: 300px;
}

.container {
  background: lightcoral;
  width: var(--container-max);
  margin: 0 auto;
}

.graph {
  background-color: yellowgreen;
  white-space: nowrap;
  overflow: visible;
  min-width: fit-content;
  transform: translate(calc((var(--container-max) - 100%) / 2), 0);
}

<div class="container">
  <h1>An H1 Heading</h1>
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit odio voluptatum minima architecto a omnis at iure sint officia neque sapiente quos cupiditate similique illum doloribus, accusantium natus enim! Et.
  </p>
  <div class="graph" contenteditable>Lorem ipsum dolor sit amet</div>
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit odio voluptatum minima architecto a omnis at iure sint officia neque sapiente quos cupiditate similique illum doloribus, accusantium natus enim! Et.
  </p>
</div>

The green block is contenteditable, so start typing into it and you'll see its width eventually expands past the outer container, remaining centered in the screen.


问:
Generate a series of numbers that go up in two interweaving intervals
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

```<code>0,5,15,20,30,35,45,50,60,65,75,85,90,100
</code>```

I am aware of

```<code>seq 0 10 100
</code>```

but am looking to jump two different intervals intertwined.

答:
As bash is tagged: Use seq with a step size that covers a whole cycle (here 5+10 = 15). Then, for each line, print the missing steps.

seq 0 15 100 | while read -r n; do printf '%d\n' $n $((n+5)); done
```
```0
5
15
20
30
35
45
50
60
65
75
80
90
95
```
<p>If the intervals are more complex, calling <code>seq</code> that way could very well be nested again inside, like so for this example</p>
<pre class="lang-sh prettyprint-override"><code>seq 0 15 100 | while read -r n; do seq $n 5 $((n+5)); done
</code>```

Body:
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

0,5,15,20,30,35,45,50,60,65,75,85,90,100

I am aware of

seq 0 10 100

but am looking to jump two different intervals intertwined.

Body:
As bash is tagged: Use seq with a step size that covers a whole cycle (here 5+10 = 15). Then, for each line, print the missing steps.

seq 0 15 100 | while read -r n; do printf '%d\n' $n $((n+5)); done

0
5
15
20
30
35
45
50
60
65
75
80
90
95

If the intervals are more complex, calling seq that way could very well be nested again inside, like so for this example

seq 0 15 100 | while read -r n; do seq $n 5 $((n+5)); done


问:
How can I make a checkbox readonly? not disabled?
I have a form where I have to post form values to my action class. In this form I have a checkbox that needs to be readonly. I tried setting disabled="true" but that doesn't work when posting to the action class.

So please advice??

答:
Extract from https://stackoverflow.com/a/71086058/18183749

If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :

```<code>  addReadOnlyToFormElements = function (idElement) {

        // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
        $('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',true);

        // and, on the selected ones, to deactivate mouse/keyboard events and mimic readonly appearance
        $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');
    }
</code>```

And there's nothing easier than to remove these readonly

```<code>removeReadOnlyFromFormElements = function (idElement) {

     // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',false);

    // Restore mouse/keyboard events and remove readonly appearance on selected ones
    $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');
}
</code>```

Body:
Extract from https://stackoverflow.com/a/71086058/18183749

If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :

  addReadOnlyToFormElements = function (idElement) {

        // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
        $('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',true);

        // and, on the selected ones, to deactivate mouse/keyboard events and mimic readonly appearance
        $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');
    }

And there's nothing easier than to remove these readonly

removeReadOnlyFromFormElements = function (idElement) {

     // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',false);

    // Restore mouse/keyboard events and remove readonly appearance on selected ones
    $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');
}


问:
Get dominating elements in the prefix of an array
Given an array A of size N, for each element A[i], I want to find all j such that A[j] > A[i]. Currently, I cannot think of a method better than O(i)(Traverse all 0 <= j < i and check). Is there an algorithm that achieves better time complexity than above? Space Complexity can be O(N)

Update 1

We can assume the array has distinct elements

Update 2

Let us consider array A = [4 6 7 1 2 3 5]. Let dom(i) = {j | 0 < j  A[i] }

dom(0) = empty

dom(1) = empty

dom(2) = empty

dom(3) = {0, 1, 2}

dom(4) = {0, 1, 2}

dom(5) = {0, 1, 2}

dom(6) = {1, 2}

Also the space complexity of O(N) is meant to be per every iteration i

答:
Lower time complexity cannot be achieved, as, for example, if your array is all descending, all lists would have quadratic total length, so if your task is to get the lists, this is as fast as it can get. Your solution already achieves this O(N^2), so it already is optimal.

There are faster ways to calculate some things related to this, though. For example, if you are actually looking to get just the total count of all such pairs, it can be done in O(n ln n) time, see this post.


问:
Instantiate class from name in MATLAB
I'm trying to list classes I created in some folder in my Matlab folder - using only their name (class name)

as an example, I have a class called 'SimpleString' - and I'm aiming to instantiate an object from that class, if all I know is that its name is 'SimpleString'

So in realtime, I'd like to find out what classes are in a folder (done), then be able to instantiate any of those classes (my question)
Thanks

答:
Use str2func to get a function handle to the constructor. You can then call it with whatever arguments are appropriate.

```<code>>> m = str2func('containers.Map')
m =
    @containers.Map
>> x = m({'foo', 'bar'}, {0, 1})
x =
  containers.Map handle
  Package: containers

  Properties:
        Count: 2
      KeyType: 'char'
    ValueType: 'double'
  Methods, Events, Superclasses
</code>```

Title: Instantiate class from name in MATLAB

Body:
Use str2func to get a function handle to the constructor. You can then call it with whatever arguments are appropriate.

>> m = str2func('containers.Map')
m =
    @containers.Map
>> x = m({'foo', 'bar'}, {0, 1})
x =
  containers.Map handle
  Package: containers

  Properties:
        Count: 2
      KeyType: 'char'
    ValueType: 'double'
  Methods, Events, Superclasses


问:
How to schedule a chain task in celery
I want to run a complex task scheduled by beat. Let us assume the default add/mul tasks are defined.

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(
        crontab(),
        add.s(2,3) | mul.s(2)
    )
```

<p>But this will return an error in the worker:</p>

```NotImplementedError: chain is not a real task
```

How can I schedule a non trivial task with celery beat?

答:
for add chained periodic tasks you can use an @app.task when declare your chain and then, add this new task on add_periodic_task() method. Example:</p>
```<code>@app.on_after_finalize.connect ->i use this because it`s declared on task.py
def setup_periodic_tasks(sender, **kwargs):
   sender.add_periodic_task(timedelta(minutes=10), chian_st22.s(),name='test')

@app.task
def chian_st22(): -> i create the task with chain
    cadena = chain(st22.s(), mailer.s()).apply_async()

@app.task
def mailer(data):
    clase = CheckAlert()
    mail = clase.envio_mail(data)
    return mail

@app.task
def st22():
    clase = CheckAlert()
    st = clase.check_st22_dumps()
    return st
</code>```

Title: How to schedule a chain task in celery

Body:
I want to run a complex task scheduled by beat. Let us assume the default add/mul tasks are defined.

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(
        crontab(),
        add.s(2,3) | mul.s(2)
    )

But this will return an error in the worker:

NotImplementedError: chain is not a real task

How can I schedule a non trivial task with celery beat?

Body:
for add chained periodic tasks you can use an @app.task when declare your chain and then, add this new task on add_periodic_task() method. Example:

@app.on_after_finalize.connect ->i use this because it`s declared on task.py
def setup_periodic_tasks(sender, **kwargs):
   sender.add_periodic_task(timedelta(minutes=10), chian_st22.s(),name='test')

@app.task
def chian_st22(): -> i create the task with chain
    cadena = chain(st22.s(), mailer.s()).apply_async()

@app.task
def mailer(data):
    clase = CheckAlert()
    mail = clase.envio_mail(data)
    return mail

@app.task
def st22():
    clase = CheckAlert()
    st = clase.check_st22_dumps()
    return st


问:
Project training data onto PCA R
I'm a total beginner in ML, R, you name it and I'm using FactoMineR's PCA function on my training set to find the principal components of my data.

```<code>res_pca <- PCA(training, scale.unit=TRUE, graph=FALSE)
</code>```

Now I have to project my training data onto the space spanned by the vectors found by PCA. How do I do that?

This is what I've tried:

```<code># get_pca_var is from the factoextra package
var <- get_pca_var(res_pca)
# training_no_target is just the training dataset without the target variable, which is a factor
train_pca <- as.matrix(training_no_target) %*% var$coord
train_pca <- data.frame(train_pca)
</code>```

I think train_pca should now contain the final dataset onto which training my models... is this right?

答:
PCA is an unsupervised method that is used for descriptive modeling rather than predictive modeling. Therefore we don't usually think of projecting data with PCA as training per se. However it is possible to define a PCA space with one dataset and ask where new data falls into that same space. You were on the right track using the rotations (p$var$coord) to rotate the new data matrix with %*%.

Note you have to be careful to apply the same scaling and centering on your new data. This is also discussed here.

Here's an example with the iris dataset where we define a PCA projection with half the data and then project the other half into that PCA space by %*%ing by the rotation.

library(tidyverse)
library(FactoMineR)

# split data
set.seed(1)
splits <- sample(nrow(iris), nrow(iris)/2)
train <- iris[splits,]
test <- iris[-splits,]

# build PCA rotation based on 'training' data
p <- train[,-5] %>% PCA(graph = F)

# projection of training data
p$ind$coord %>%
  as.data.frame() %>%
  bind_cols(., Species = train[,5]) %>%
  ggplot(aes(Dim.1, Dim.2)) +
  ggtitle("original points") +
  geom_point(aes(color = Species))
```
<p><img src="https://i.imgur.com/SzqTslP.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code># scale and project 'test' data into original PCA space
test[,-5] %>%
  scale(center = p$call$centre, scale = p$call$scale.unit) %*% p$var$coord %>%
  as.data.frame() %>%
  bind_cols(., Species = test[,5]) %>%
  ggplot(aes(Dim.1, Dim.2)) +
  ggtitle("projection of new points into original space") +
  geom_point(aes(color = Species))
</code>```

Created on 2022-02-12 by the reprex package (v2.0.1)

Title: Project training data onto PCA R

Body:
I'm a total beginner in ML, R, you name it and I'm using FactoMineR's PCA function on my training set to find the principal components of my data.

res_pca <- PCA(training, scale.unit=TRUE, graph=FALSE)

Now I have to project my training data onto the space spanned by the vectors found by PCA. How do I do that?

This is what I've tried:

# get_pca_var is from the factoextra package
var <- get_pca_var(res_pca)
# training_no_target is just the training dataset without the target variable, which is a factor
train_pca <- as.matrix(training_no_target) %*% var$coord
train_pca <- data.frame(train_pca)

I think train_pca should now contain the final dataset onto which training my models... is this right?

Body:
PCA is an unsupervised method that is used for descriptive modeling rather than predictive modeling. Therefore we don't usually think of projecting data with PCA as training per se. However it is possible to define a PCA space with one dataset and ask where new data falls into that same space. You were on the right track using the rotations (p$var$coord) to rotate the new data matrix with %*%.

Note you have to be careful to apply the same scaling and centering on your new data. This is also discussed here.

Here's an example with the iris dataset where we define a PCA projection with half the data and then project the other half into that PCA space by %*%ing by the rotation.

library(tidyverse)
library(FactoMineR)

# split data
set.seed(1)
splits <- sample(nrow(iris), nrow(iris)/2)
train <- iris[splits,]
test <- iris[-splits,]

# build PCA rotation based on 'training' data
p <- train[,-5] %>% PCA(graph = F)

# projection of training data
p$ind$coord %>%
  as.data.frame() %>%
  bind_cols(., Species = train[,5]) %>%
  ggplot(aes(Dim.1, Dim.2)) +
  ggtitle("original points") +
  geom_point(aes(color = Species))

# scale and project 'test' data into original PCA space
test[,-5] %>%
  scale(center = p$call$centre, scale = p$call$scale.unit) %*% p$var$coord %>%
  as.data.frame() %>%
  bind_cols(., Species = test[,5]) %>%
  ggplot(aes(Dim.1, Dim.2)) +
  ggtitle("projection of new points into original space") +
  geom_point(aes(color = Species))

Created on 2022-02-12 by the reprex package (v2.0.1)


问:
How do I cancel processing in a deep call stack with messages?
My requirement is that the user will see localized messages at the end of the process. If the process failed, there will be at least one "external" message of type error. If the process was successfully executed, the user might see multiple "external" information messages.

Additionally, all messages (including internal) shall be logged by the application.

Now here comes the tricky part. Assume the following callstack:

controller.uploadImageHandler

imageService.createImageContainer

galleryService.loadForImage

galleryService.validateGalleryAttributes

Now validateGalleryAttributes will validate 3 attributes. 2 aren't matching, so the messages Attribute A must be X and Attribute B must not be empty of type External are generated and logged to the application log. The calls before added multiple information messages.

Now I need have to

abort processing

bubble the Messages up

Is the right approach to pass along a Message Collection (or add a collection to the logger) into every method, throw an Exception upon failure (even simple ones such as invalid attributes), extract the messages at the controller level and return them to the user? It's not enough to add them to the exception class, since info messages must also be possible and multiple methods might produce just messages.

But honestly it seems a bit weird to have a collection that is inspected upon success and exception. Is there a better language construct?

答:
Theres two alternative solutions that I could come up with.

If you are into monads at all you could move away from using exceptions to a custom LoggingEither<L, R> or LoggingResult<S, E> return type. They would carry the result/exception as well as all accumulated messages so far. You would just have to make sure to merge the messages of all methods you call into the object you return in the current method. For an idea of how these monad types could be implemented take a look at vavr.

If everything happens in the same Thread you could consider using ThreadLocal to keep track of all the log messages. This eliminates the need of passing a collection down the stacktrace. You will still need to take care of bundling messages and resetting the ThreadLocal, though.


问:
How can I set the IP address value from a URL onto an input field in HTML?
I am loading an 'index.html' page where the URL might be http://127.0.0.1:5000/?ip_address=192.168.2.36.

The variable ip_address can change when I get to index.html.

I have a form with a submit button that should send the value of ip_address to the controller. My goal is to, be default, set the input field box with the variable ip_address and leave it greyed out, so the user only hits the button.

Is there a way I can get that variable from the URL?

答:
Use:

```<code>@app.route("/")
def home():
    return "<h1> Hello World</h1>"

url_for("home" _external=True)
</code>```

The url_for with the option "_external" set to True will create the URL with the IP address.

Body:
Use:

@app.route("/")
def home():
    return "<h1> Hello World</h1>"

url_for("home" _external=True)

The url_for with the option "_external" set to True will create the URL with the IP address.


问:
Unable to programmatically open input selector dialog in Angular
I have an Angular app which has a stylized input box so I keep another actual  element which I call .click() on to open the dialog

This used to work great but for some reason stopped working recently? Anyway I can't make it work even though this all should be quite simple to do...

I've tried every way I can think to access my input and click it all to no avail

```<code>  <input type="file" id="fileInputRef">
  <button (click)="fileInputRef.click()">open</button>
</code>```

this produces the error "Cannot read properties of undefined (reading 'click')"

```<code>  <input type="file" #fileInputRef>
  <button (click)="fileInputRef.click()">open</button>
</code>```

this produces no effect at all, no error in console even

so I tried moving it to my component's code like so

```<code>  <input type="file" #fileInputRef>
  <button (click)="doClick()">open</button>
</code>```

and in my typescript

```<code>  @ViewChild('fileInputRef') fileInputRef: HTMLInputElement;

  public doClick() {
    this.fileInputRef.click();
  }
</code>```

but then this errors with "this.fileInputRef.click is not a function"

If I print out this.fileInputRef it looks like "ElementRef {nativeElement: input}"

So lastly I tried

```<code>  public doClick() {
    this.fileInputRef.nativeElement.click();
  }
</code>```

which produces no effect

I'm not sure why this feature used to be working and stopped but I'm sure I'm missing something basic

How can I programmatically fire of a click for a file input element in my html

答: No idea what happened but this was resolved after I updated and restarted Chrome :-\ everything started to work again normally</p>

Body:
I have an Angular app which has a stylized input box so I keep another actual  element which I call .click() on to open the dialog

This used to work great but for some reason stopped working recently? Anyway I can't make it work even though this all should be quite simple to do...

I've tried every way I can think to access my input and click it all to no avail

  <input type="file" id="fileInputRef">
  <button (click)="fileInputRef.click()">open</button>

this produces the error "Cannot read properties of undefined (reading 'click')"

  <input type="file" #fileInputRef>
  <button (click)="fileInputRef.click()">open</button>

this produces no effect at all, no error in console even

so I tried moving it to my component's code like so

  <input type="file" #fileInputRef>
  <button (click)="doClick()">open</button>

and in my typescript

  @ViewChild('fileInputRef') fileInputRef: HTMLInputElement;

  public doClick() {
    this.fileInputRef.click();
  }

but then this errors with "this.fileInputRef.click is not a function"

If I print out this.fileInputRef it looks like "ElementRef {nativeElement: input}"

So lastly I tried

  public doClick() {
    this.fileInputRef.nativeElement.click();
  }

which produces no effect

I'm not sure why this feature used to be working and stopped but I'm sure I'm missing something basic

How can I programmatically fire of a click for a file input element in my html


问:
how do you pass Environment Variables to tasks triggered by Spring Cloud Data Flow UI
I have a local setup for SCDF with docker-compose.
I'm trying to understand how can I pass environment variables to a triggered task.
I tried via the 'Deployer properties' but it doesn't seem to work.
Ideally I would have liked to be able to set LOG4J2_APPENDER=PatternAppender in the UI...
If its not possible via the UI, what other options do I have?

I tried to add under 'enviroment' in the docker-compose.yml (where there are other vars):

but it also didnt work:

```<code>dataflow-server:
    user: root
    image: springcloud/spring-cloud-dataflow-server:${DATAFLOW_VERSION:-2.9.1}${BP_JVM_VERSION:-}
    container_name: dataflow-server
    ports:
      - "9393:9393"
      - "1142:1142"
    environment:
      # Set CLOSECONTEXTENABLED=true to ensure that the CRT launcher is closed.
      - SPRING_CLOUD_DATAFLOW_APPLICATIONPROPERTIES_TASK_SPRING_CLOUD_TASK_CLOSECONTEXTENABLED=true
      - LOG4J2_APPENDER=PatternAppender
      - SPRING_DATASOURCE_URL=jdbc:mysql://mysql:3306/dataflow
      - SPRING_DATASOURCE_USERNAME=root
      - SPRING_DATASOURCE_PASSWORD=rootpw
      - SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.mariadb.jdbc.Driver
      # (Optionally) authenticate the default Docker Hub access for the App Metadata access.
      #- SPRING_CLOUD_DATAFLOW_CONTAINER_REGISTRY_CONFIGURATIONS_DEFAULT_USER=${METADATA_DEFAULT_DOCKERHUB_USER}
      #- SPRING_CLOUD_DATAFLOW_CONTAINER_REGISTRY_CONFIGURATIONS_DEFAULT_SECRET=${MET
</code>```

答:
In your snippet, you're passing the environment variable SPRING_CLOUD_TASK_CLOSECONTEXTENABLED with the value true to all tasks.

The same should work for LOG4J2_APPENDER, i.e. add the environment variable

```<code>SPRING_CLOUD_DATAFLOW_APPLICATIONPROPERTIES_TASK_LOG4J2_APPENDER=PatternAppender
</code>```

to the environment variables of the Dataflow server.

Setting the environment variable as an application property (not a deployer property) in the UI should have the same effect.

Body:
I have a local setup for SCDF with docker-compose.
I'm trying to understand how can I pass environment variables to a triggered task.
I tried via the 'Deployer properties' but it doesn't seem to work.
Ideally I would have liked to be able to set LOG4J2_APPENDER=PatternAppender in the UI...
If its not possible via the UI, what other options do I have?

I tried to add under 'enviroment' in the docker-compose.yml (where there are other vars):

but it also didnt work:

dataflow-server:
    user: root
    image: springcloud/spring-cloud-dataflow-server:${DATAFLOW_VERSION:-2.9.1}${BP_JVM_VERSION:-}
    container_name: dataflow-server
    ports:
      - "9393:9393"
      - "1142:1142"
    environment:
      # Set CLOSECONTEXTENABLED=true to ensure that the CRT launcher is closed.
      - SPRING_CLOUD_DATAFLOW_APPLICATIONPROPERTIES_TASK_SPRING_CLOUD_TASK_CLOSECONTEXTENABLED=true
      - LOG4J2_APPENDER=PatternAppender
      - SPRING_DATASOURCE_URL=jdbc:mysql://mysql:3306/dataflow
      - SPRING_DATASOURCE_USERNAME=root
      - SPRING_DATASOURCE_PASSWORD=rootpw
      - SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.mariadb.jdbc.Driver
      # (Optionally) authenticate the default Docker Hub access for the App Metadata access.
      #- SPRING_CLOUD_DATAFLOW_CONTAINER_REGISTRY_CONFIGURATIONS_DEFAULT_USER=${METADATA_DEFAULT_DOCKERHUB_USER}
      #- SPRING_CLOUD_DATAFLOW_CONTAINER_REGISTRY_CONFIGURATIONS_DEFAULT_SECRET=${MET

Body:
In your snippet, you're passing the environment variable SPRING_CLOUD_TASK_CLOSECONTEXTENABLED with the value true to all tasks.

The same should work for LOG4J2_APPENDER, i.e. add the environment variable

SPRING_CLOUD_DATAFLOW_APPLICATIONPROPERTIES_TASK_LOG4J2_APPENDER=PatternAppender

to the environment variables of the Dataflow server.

Setting the environment variable as an application property (not a deployer property) in the UI should have the same effect.


问:
React state change best practices: useEffect vs callback
I have a question regarding best practices when using useEffect and when to use it to handle state changes.

For example let's say I have a button that will send an email on the 5th click (pseudo code as I didn't really test to see if it works). What's better according to React best practices.

Here I am using useEffect to handle the count state change:

```<code>import React, { useState, useEffect } from 'react'
export default () => {
    const [count, setCount] = useState(0)
    useEffect(() => {
        if (count === 5) {
            sendEmail()
            setCount(0)
        }
    }, [count])

    return (
        <div>
            <input
                type="button"
                onClick={() => {
                    setCount((count) => count + 1)
                }}
            ></input>
        </div>
    )
}
</code>```

Here is the same functionality with a callback:

```<code>import React, { useState } from 'react'
export default () => {
    const [count, setCount] = useState(0)

    return (
        <div>
            <input
                type="button"
                onClick={() => {
                    if(count + 1 === 5) {
                        sendEmail()
                        setCount(0)
                        return
                    }
                    setCount(count=>count+1)
                }}
            ></input>
        </div>
    )
}
</code>```

The argument for using useEffect, at least as I see it, is to react to state changes. However if I want to check other state in that useEffect block or other dependencies, then I have to add it to the dependency array and it's in danger of re-running even though I'm only interested in running it in response to the count changing (one piece of state). In this example it isn't too egregious but in more advanced situations it seems that you have to add a bunch of conditionals in the useEffect block if you only want it to react to one piece of state change. if(x,y,z) {run count logic}

The argument for the callback is that it's readable and will only be called on the button being pressed however it is more imperative than declarative and not as REACTive as useEffect. Furthermore with the setCount being async it might create a race condition (not in this case but in more advanced cases).

Also I can use useEffect to run code when a component has first rendered but if it has logic that touches dependencies I have to add them to the dependency array according to my linter and Dan Abramov but then I run the chance of running it multiple times unless I add a bunch of conditionals in the body of useEffect (as I mentioned above). In short I may want to run the useEffect on one piece of state change and not when any of the dependencies change.

I hope that makes sense.

An example of the useEffect issue with conditionals is if I want to send the email if some localState variable === "whatever". Once I add the localState variable into the dep array, then it will run whenever it changes even if I only want to run it when specific state (count) changes. The only way around this I see is adding logic on the useEffect to exit early but it starts to get complicated and error prone.

答: I would go with option 1. If you want to run other effects off of some state you can have a separate useEffect block for that, so your count block only runs when the count state changes.</p>

Body:
I have a question regarding best practices when using useEffect and when to use it to handle state changes.

For example let's say I have a button that will send an email on the 5th click (pseudo code as I didn't really test to see if it works). What's better according to React best practices.

Here I am using useEffect to handle the count state change:

import React, { useState, useEffect } from 'react'
export default () => {
    const [count, setCount] = useState(0)
    useEffect(() => {
        if (count === 5) {
            sendEmail()
            setCount(0)
        }
    }, [count])

    return (

            <input
                type="button"
                onClick={() => {
                    setCount((count) => count + 1)
                }}
            ></input>

    )
}

Here is the same functionality with a callback:

import React, { useState } from 'react'
export default () => {
    const [count, setCount] = useState(0)

    return (

            <input
                type="button"
                onClick={() => {
                    if(count + 1 === 5) {
                        sendEmail()
                        setCount(0)
                        return
                    }
                    setCount(count=>count+1)
                }}
            ></input>

    )
}

The argument for using useEffect, at least as I see it, is to react to state changes. However if I want to check other state in that useEffect block or other dependencies, then I have to add it to the dependency array and it's in danger of re-running even though I'm only interested in running it in response to the count changing (one piece of state). In this example it isn't too egregious but in more advanced situations it seems that you have to add a bunch of conditionals in the useEffect block if you only want it to react to one piece of state change. if(x,y,z) {run count logic}

The argument for the callback is that it's readable and will only be called on the button being pressed however it is more imperative than declarative and not as REACTive as useEffect. Furthermore with the setCount being async it might create a race condition (not in this case but in more advanced cases).

Also I can use useEffect to run code when a component has first rendered but if it has logic that touches dependencies I have to add them to the dependency array according to my linter and Dan Abramov but then I run the chance of running it multiple times unless I add a bunch of conditionals in the body of useEffect (as I mentioned above). In short I may want to run the useEffect on one piece of state change and not when any of the dependencies change.

I hope that makes sense.

An example of the useEffect issue with conditionals is if I want to send the email if some localState variable === "whatever". Once I add the localState variable into the dep array, then it will run whenever it changes even if I only want to run it when specific state (count) changes. The only way around this I see is adding logic on the useEffect to exit early but it starts to get complicated and error prone.


问:
Why not sprite larger images that are page content?
The typical rule of thumb when it comes to using CSS sprites for images is that you should only do it for smaller images (like icons) and that actual image content should always be represented through  elements. My question is: why? Aren't the advantages of spriting worthwhile for content images as well?

One reason I have read is to enable the use of alt text, to be more syntactically correct and accessible to screen-readers. However, when that is a concern, couldn't you just as easily use a single tiny transparent image with all the syntactical sugar atop a sprite that presents the real visual content?

答: Sprites are used to reduce the amount of requests to a server. The impact of lots of small requests is slowing the server more than one bigger request. But if the image of sprites, I like to call it sprite-map, is too large, it will also slow down the performance. The other thing of importance is like you sad the possibility for each single picture to give some name, to manage and to index by search engine.</p>


问:
How do I switch the active window and automate GUI changes?
I am working on a program that automates some testing at my job using pyautogui. I will have 2 applications that will be open and closed if needed, and one that will run the entire time.

I need to be able to switch which application is my active window, make some gui changes, and then switch active application windows.

I think I'm looking for the right os library function to use.

答:
You need to give us some code or what you already tried for your solution.

But you could use pywinauto package to get and use the application you want by switching them from a list and use pyautogui if you want to do something. For more details please check the How does it work documentation.

You can get all applications open from Desktop function as:

```<code>from pywinauto import Desktop

windows = Desktop(backend="uia").windows()
window = [w.window_text() for w in windows]
</code>```

So if you print(window) you will have for example:

```<code>['Zoom', 'Dictations - OneNote']
</code>```

Body:
You need to give us some code or what you already tried for your solution.

But you could use pywinauto package to get and use the application you want by switching them from a list and use pyautogui if you want to do something. For more details please check the How does it work documentation.

You can get all applications open from Desktop function as:

from pywinauto import Desktop

windows = Desktop(backend="uia").windows()
window = [w.window_text() for w in windows]

So if you print(window) you will have for example:

['Zoom', 'Dictations - OneNote']


问:
Flutter Global Function update Stateful Widget State
I am writing a Flutter app that uses a Global Function to handle Pushy.me notifications. This function needs to update a stateful widget's state.

I have tried a Global Key to access the widgets current state but it did nothing. I have tried an Eventify emitter, the emit and the listener didnt seem to line up.

```<code>import 'package:eventify/eventify.dart';

EventEmitter emitter = new EventEmitter();
GlobalKey<_WrapperScreenState> _key = GlobalKey<_WrapperScreenState>();

void backgroundNotificationListener(Map<String, dynamic> data) {
  // Print notification payload data
  print('Received notification: $data');

  // Notification title
  String notificationTitle = 'MyApp';

  // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
  String notificationText = data['message'] ?? 'Hello World!';

  Pushy.notify(notificationTitle, notificationText, data);
  emitter.emit('updateList',null,"");
  try{
    print(_key.currentState.test);
  }
  catch(e){
    print(e);
  }
  // Clear iOS app badge number
  Pushy.clearBadge();
}
class WrapperScreen extends StatefulWidget {
  @override
  _WrapperScreenState createState() => _WrapperScreenState();
}
</code>```

答:
You can try using events for this, using a StreamController or the event bus package. Your stateful widget would listen on a global event bus, and you can fire an event with the necessary information for the widget itself to use to update the state.

Something like this (using the event bus package):

```<code>// main.dart

EventBus eventBus = EventBus();

class MyEvent {}

void somewhereGlobal() {
    // trigger widget state change from global location
    eventBus.fire(MyEvent());
}

void main() {

...

}

</code>```
```<code>// my_stateful_widget.dart
...

class _MyWidgetState extends State<MyWidget> {
  @override
  void initState() {
    super.initState();
    eventBus.on<MyEvent>().listen((event) {
      // update widget state
      print("update widget state");
    });
  }

...
</code>```

Body:
I am writing a Flutter app that uses a Global Function to handle Pushy.me notifications. This function needs to update a stateful widget's state.

I have tried a Global Key to access the widgets current state but it did nothing. I have tried an Eventify emitter, the emit and the listener didnt seem to line up.

import 'package:eventify/eventify.dart';

EventEmitter emitter = new EventEmitter();
GlobalKey<_WrapperScreenState> _key = GlobalKey<_WrapperScreenState>();

void backgroundNotificationListener(Map<String, dynamic> data) {
  // Print notification payload data
  print('Received notification: $data');

  // Notification title
  String notificationTitle = 'MyApp';

  // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
  String notificationText = data['message'] ?? 'Hello World!';

  Pushy.notify(notificationTitle, notificationText, data);
  emitter.emit('updateList',null,"");
  try{
    print(_key.currentState.test);
  }
  catch(e){
    print(e);
  }
  // Clear iOS app badge number
  Pushy.clearBadge();
}
class WrapperScreen extends StatefulWidget {
  @override
  _WrapperScreenState createState() => _WrapperScreenState();
}

Body:
You can try using events for this, using a StreamController or the event bus package. Your stateful widget would listen on a global event bus, and you can fire an event with the necessary information for the widget itself to use to update the state.

Something like this (using the event bus package):

// main.dart

EventBus eventBus = EventBus();

class MyEvent {}

void somewhereGlobal() {
    // trigger widget state change from global location
    eventBus.fire(MyEvent());
}

void main() {

...

}

// my_stateful_widget.dart
...

class _MyWidgetState extends State<MyWidget> {
  @override
  void initState() {
    super.initState();
    eventBus.on<MyEvent>().listen((event) {
      // update widget state
      print("update widget state");
    });
  }

...


问:
How could I run a remote command within a Gitlab CI Pipeline using sshpass and print the output/depend on the result of that command?
I want to run a script that is on a separate server within a Gitlab CI job and have the job print the output of that script and depend on the script's result.

I'm using sshpass to get around inputting a password like this:

```<code>- sshpass -p "password" ssh -o "StrictHostKeyChecking=no" user@SERVER 'command_to_run'
</code>```

and I've tried redirecting output just to at least try and see that the command is actually running:

```<code>- sshpass -p "password" ssh -o "StrictHostKeyChecking=no" user@SERVER 'command_to_run' > command_log.txt
- cat command_log.txt
</code>```

but regardless, all I get in the pipeline logs after it runs that line is:

```<code>Warning: Permanently added 'SERVER' (ECDSA) to the list of known hosts.
</code>```

and it isn't even waiting for command_to_run to complete before moving on.

Is there any way to get the command output logs and depend on the remote command_to_run within a pipeline job?

Would appreciate any advice. Thanks!

答:
Is there any way to get the command output logs

The output of the command should be shown in the Gitlab logs. Check the script if it using some form of redirection e.g. >

depend on the remote command_to_run within a pipeline job?

Assuming nothing goes wrong with ssh itself, its exit code is the exit code of the last command executed on the remote host. (If something does go wrong, its exit code is 255.)

So you could check $? which contains the exit code of the last command. And depend on it in order to impose a specific logic. E.g.

```<code>  - sshpass -p "password" ssh -o "StrictHostKeyChecking=no" user@SERVER 'command_to_run'
  - |
    if [ $? -eq 0 ];
    then
       ...All well case...
</code>```

Be aware that the exit code of a script would be the exit code of the last executed command in that scipt.

If your case is to fail the job, if even a single error was encoutered in the remote command.

Add set -e to the start of script, which would make the script fail at the first command error

Body:
I want to run a script that is on a separate server within a Gitlab CI job and have the job print the output of that script and depend on the script's result.

I'm using sshpass to get around inputting a password like this:

- sshpass -p "password" ssh -o "StrictHostKeyChecking=no" user@SERVER 'command_to_run'

and I've tried redirecting output just to at least try and see that the command is actually running:

- sshpass -p "password" ssh -o "StrictHostKeyChecking=no" user@SERVER 'command_to_run' > command_log.txt
- cat command_log.txt

but regardless, all I get in the pipeline logs after it runs that line is:

Warning: Permanently added 'SERVER' (ECDSA) to the list of known hosts.

and it isn't even waiting for command_to_run to complete before moving on.

Is there any way to get the command output logs and depend on the remote command_to_run within a pipeline job?

Would appreciate any advice. Thanks!

Body:
Is there any way to get the command output logs

The output of the command should be shown in the Gitlab logs. Check the script if it using some form of redirection e.g. >

depend on the remote command_to_run within a pipeline job?

Assuming nothing goes wrong with ssh itself, its exit code is the exit code of the last command executed on the remote host. (If something does go wrong, its exit code is 255.)

So you could check $? which contains the exit code of the last command. And depend on it in order to impose a specific logic. E.g.

  - sshpass -p "password" ssh -o "StrictHostKeyChecking=no" user@SERVER 'command_to_run'
  - |
    if [ $? -eq 0 ];
    then
       ...All well case...

Be aware that the exit code of a script would be the exit code of the last executed command in that scipt.

If your case is to fail the job, if even a single error was encoutered in the remote command.

Add set -e to the start of script, which would make the script fail at the first command error


问:
Can i use more than once $(document).ready() of jquery in a single html page?
i have one html page named "text.html"

```<code><html>
    <body>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="js/Photos.js"></script>
        <script type="text/javascript" src="js/Animations.js"></script>
    </body>
</html>
</code>```

Both Photos.js and Animations.js start with "$(document).ready()" like this

```<code>//Javascript File Photos.js
$(document).ready(function() {
    //My code here ....
});

//Javascript File Animations.js
$(document).ready(function() {
    //My code here ....
});
</code>```

Does it matter if i use multiple $(document).ready(function() { in a single html page??

Thanks, in advance

答:
No, it does not matter.

However, everything can be contained within the same one.

EDIT:

See my answer in this thread for a detailed explanation regarding your comment:

Will linking javascript files in the body rather than in the header cause a problem?

Body:
i have one html page named "text.html"

Both Photos.js and Animations.js start with "$(document).ready()" like this

//Javascript File Photos.js
$(document).ready(function() {
    //My code here ....
});

//Javascript File Animations.js
$(document).ready(function() {
    //My code here ....
});

Does it matter if i use multiple $(document).ready(function() { in a single html page??

Thanks, in advance


问:
TypeError: Cannot read property 'NormalModule' of undefined
I am working on a big project and I cannot run it anymore because of this error:

When I run npm run serve

```<code> ERROR  TypeError: Cannot read property 'NormalModule' of undefined
TypeError: Cannot read property 'NormalModule' of undefined
    at VueLoaderPlugin.apply (/Users/<user>/muso-ninjas/node_modules/vue-loader-v16/dist/pluginWebpack5.js:44:47)
    at webpack (/Users/<user>/muso-ninjas/node_modules/@vue/cli-service/node_modules/webpack/lib/webpack.js:51:13)
    at serve (/Users/<user>/muso-ninjas/node_modules/@vue/cli-service/lib/commands/serve.js:163:22)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
</code>```

Please help me because I am stuck and I would like to go with my project.

答:
As suggested in link from the first comment, I deleted node_modules, replaced the node-sass in package.json with "sass": "^1.26.5" and ran npm install but it didn't work.

Then I repeated the steps and removed package-lock.json as well.

This helped and the app was served properly

Body:
I am working on a big project and I cannot run it anymore because of this error:

When I run npm run serve

 ERROR  TypeError: Cannot read property 'NormalModule' of undefined
TypeError: Cannot read property 'NormalModule' of undefined
    at VueLoaderPlugin.apply (/Users/<user>/muso-ninjas/node_modules/vue-loader-v16/dist/pluginWebpack5.js:44:47)
    at webpack (/Users/<user>/muso-ninjas/node_modules/@vue/cli-service/node_modules/webpack/lib/webpack.js:51:13)
    at serve (/Users/<user>/muso-ninjas/node_modules/@vue/cli-service/lib/commands/serve.js:163:22)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Please help me because I am stuck and I would like to go with my project.