问:
How can I create a pagination for this react app with jikan anime API?
How can I create a pagination to handle this api in React. I have tried but it does not work for me. I did not write any code. because I am not sure what to do anymore.

```<code>https://api.jikan.moe/v4/top/anime?page=${page}&limit=24
</code>```

```<code>const {
        data: manga = [],
        isLoading,
        isFetching,
        error,
    } = useGetAnimeQuery(1);

    //destructuring objects
    const { data, pagination } = manga;
    const top_anime = data;

    if (isLoading) {
        return <Spinner color_1={"#141e30"} color_2={"#243b55"} />;
    } else if (isFetching) {
        return <Spinner color_1={"#141e30"} color_2={"#243b55"} />;
    } else if (error) {
        console.log("ERROR =>", error.message);
    }

    return (
        <section className="bg-gradient-to-r from-[#141e30] to-[#243b55]">
            <div className="container font-poppins">
                <div className="grid grid-cols-4 gap-3 place-items-center px-20">
                    {top_anime &&
                        top_anime?.map((anime) => (
                            <TopAnime anime={anime} key={anime.mal_id} />
                        ))}
                </div>
                <div className="button text-yellow-500 flex items-center justify-center mt-2 pb-2">

                </div>
            </div>
        </section>
    );
};

</code>```

Body:
How can I create a pagination to handle this api in React. I have tried but it does not work for me. I did not write any code. because I am not sure what to do anymore.

https://api.jikan.moe/v4/top/anime?page=${page}&limit=24

const {
        data: manga = [],
        isLoading,
        isFetching,
        error,
    } = useGetAnimeQuery(1);

    //destructuring objects
    const { data, pagination } = manga;
    const top_anime = data;

    if (isLoading) {
        return <Spinner color_1={"#141e30"} color_2={"#243b55"} />;
    } else if (isFetching) {
        return <Spinner color_1={"#141e30"} color_2={"#243b55"} />;
    } else if (error) {
        console.log("ERROR =>", error.message);
    }

    return (

                    {top_anime &&
                        top_anime?.map((anime) => (
                            <TopAnime anime={anime} key={anime.mal_id} />
                        ))}

    );
};


来源: stackexchange

问:
How to require email and (username or nickname) in signup, and require only email in login in Amplify Auth(Cognito)
On signup, I will require email, password, and (nickname or username). I don't care nickname or username. nickname or username doesn't have to be unique.
On login, I will require only email and password.

I don't know how to achieve them in Amplify CLI. Any help?

ContentLicense: CC BY-SA 4.0


问:
Assertion error when running GSEApy: assert len(dat) > 1
I want to prepare a ".cls" file and feed it into the Gseapy software (source code: here). I get an assertion error "assert len(dat) > 1". However, my dataframe is >1 so I'm unsure how to rectify my error.

```<code>groups = subtype
with open("./kirp_deg_gene_exp.cls", "w") as cl:
    line = f"{len(groups)}\t2\t1\n#\tKIRP\tnormal\n"
    cl.write(line)
    cl.write("\t".join(groups) + "\t")

gene_sets = ["KEGG_2021_Human", "Reactome_2022", "BioCarta_2016", "WikiPathway_2021_Human", "Panther_2016"]
</code>```

Run GseaPy:

```<code>gs_res = gp.gsea(data=rcc_normal_deg, # or data='./P53_resampling_data.txt'
                 gene_sets=gene_sets, # or enrichr library names
                 cls= "./kirp_deg_gene_exp.cls", # cls=class_vector
                 # set permutation_type to phenotype if samples >=15
                 permutation_type='phenotype',
                 permutation_num=1000, # reduce number to speed up test
                 outdir=None,  # do not write output to disk
                 method='signal_to_noise',
                 threads=4, seed= 7)
</code>```

Traceback:

```<code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
/tmp/ipykernel_27/3071075505.py in <module>
      9                  outdir=None,  # do not write output to disk
     10                  method='signal_to_noise',
---> 11                  threads=4, seed= 7)

/opt/conda/lib/python3.7/site-packages/gseapy/__init__.py in gsea(data, gene_sets, cls, outdir, min_size, max_size, permutation_num, weighted_score_type, permutation_type, method, ascending, threads, figsize, format, graph_num, no_plot, seed, verbose, *arg, **kwarg)
    147         verbose,
    148     )
--> 149     gs.run()
    150
    151     return gs

/opt/conda/lib/python3.7/site-packages/gseapy/gsea.py in run(self)
    258         self.cls_dict = cls_dict
    259         # data frame must have length > 1
--> 260         assert len(dat) > 1
    261         # filtering out gene sets and build gene sets dictionary
    262         gmt = self.load_gmt(gene_list=dat.index.values, gmt=self.gene_sets)

AssertionError:
</code>```

Data:

rcc_normal_deg.iloc[-4:,-5:-1].to_dict()

```<code>{'TCGA-Y8-A8RY-01A': {'ZNF771': '131.6026',
  'ZNF775': '328.4314',
  'ZNF789': '568.6275',
  'subtype': 'KIRP'},
 'TCGA-Y8-A8RY-11A': {'ZNF771': '61.4095',
  'ZNF775': '107.5387',
  'ZNF789': '63.4277',
  'subtype': 'normal'},
 'TCGA-Y8-A8RZ-01A': {'ZNF771': '171.2236',
  'ZNF775': '96.9937',
  'ZNF789': '93.5296',
  'subtype': 'KIRP'},
 'TCGA-Y8-A8S0-01A': {'ZNF771': '107.6399',
  'ZNF775': '198.0431',
  'ZNF789': '249.7065',
  'subtype': 'KIRP'}}
</code>```

Body:
I want to prepare a ".cls" file and feed it into the Gseapy software (source code: here). I get an assertion error "assert len(dat) > 1". However, my dataframe is >1 so I'm unsure how to rectify my error.

groups = subtype
with open("./kirp_deg_gene_exp.cls", "w") as cl:
    line = f"{len(groups)}\t2\t1\n#\tKIRP\tnormal\n"
    cl.write(line)
    cl.write("\t".join(groups) + "\t")

gene_sets = ["KEGG_2021_Human", "Reactome_2022", "BioCarta_2016", "WikiPathway_2021_Human", "Panther_2016"]

Run GseaPy:

gs_res = gp.gsea(data=rcc_normal_deg, # or data='./P53_resampling_data.txt'
                 gene_sets=gene_sets, # or enrichr library names
                 cls= "./kirp_deg_gene_exp.cls", # cls=class_vector
                 # set permutation_type to phenotype if samples >=15
                 permutation_type='phenotype',
                 permutation_num=1000, # reduce number to speed up test
                 outdir=None,  # do not write output to disk
                 method='signal_to_noise',
                 threads=4, seed= 7)

Traceback:

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
/tmp/ipykernel_27/3071075505.py in <module>
      9                  outdir=None,  # do not write output to disk
     10                  method='signal_to_noise',
---> 11                  threads=4, seed= 7)

/opt/conda/lib/python3.7/site-packages/gseapy/__init__.py in gsea(data, gene_sets, cls, outdir, min_size, max_size, permutation_num, weighted_score_type, permutation_type, method, ascending, threads, figsize, format, graph_num, no_plot, seed, verbose, *arg, **kwarg)
    147         verbose,
    148     )
--> 149     gs.run()
    150
    151     return gs

/opt/conda/lib/python3.7/site-packages/gseapy/gsea.py in run(self)
    258         self.cls_dict = cls_dict
    259         # data frame must have length > 1
--> 260         assert len(dat) > 1
    261         # filtering out gene sets and build gene sets dictionary
    262         gmt = self.load_gmt(gene_list=dat.index.values, gmt=self.gene_sets)

AssertionError:

Data:

rcc_normal_deg.iloc[-4:,-5:-1].to_dict()

{'TCGA-Y8-A8RY-01A': {'ZNF771': '131.6026',
  'ZNF775': '328.4314',
  'ZNF789': '568.6275',
  'subtype': 'KIRP'},
 'TCGA-Y8-A8RY-11A': {'ZNF771': '61.4095',
  'ZNF775': '107.5387',
  'ZNF789': '63.4277',
  'subtype': 'normal'},
 'TCGA-Y8-A8RZ-01A': {'ZNF771': '171.2236',
  'ZNF775': '96.9937',
  'ZNF789': '93.5296',
  'subtype': 'KIRP'},
 'TCGA-Y8-A8S0-01A': {'ZNF771': '107.6399',
  'ZNF775': '198.0431',
  'ZNF789': '249.7065',
  'subtype': 'KIRP'}}


问:
How to make a transition animation in Aframe similar to Street View or Matterport?
I'm using an aframe-react library in a project, and I need to make the transitions between scenes similar to Street View and Matterport (https://matterport.com/discover/space/PPJGbzBA9JA).

In these examples cited, the transition happens as if one image were superimposed on another, and the previous one was disappearing and the new one taking shape.

Here is my current code:

<!DOCTYPE html>

        <a-entity id="cursor-visual" cursor="fuse:true;fuseTimeout:2000"
                  material="shader:flat;color:#09B4FF"
                  position="0 0 -1"
                  geometry="primitive: ring; radiusInner: 0.01; radiusOuter: 0.015;thetaLength:0"
                  animation__mouseenter="property: geometry.thetaLength; dir: alternate; dur: 2000;
                                easing: easeInSine; from:0;to: 360;startEvents:startFuse;pauseEvents:stopFuse;autoplay:false"

                  animation__mouseleave="property: geometry.thetaLength; dir: alternate; dur: 500;
                                easing: easeInSine; to: 0;startEvents:stopFuse;autoplay:false">

```

I would like a transition between images/scenes similar to the examples cited above (Google Street View and Matterport).

Does anyone have any ideas?

Body:
I'm using an aframe-react library in a project, and I need to make the transitions between scenes similar to Street View and Matterport (https://matterport.com/discover/space/PPJGbzBA9JA).

In these examples cited, the transition happens as if one image were superimposed on another, and the previous one was disappearing and the new one taking shape.

Here is my current code:

<!DOCTYPE html>

        <a-entity id="cursor-visual" cursor="fuse:true;fuseTimeout:2000"
                  material="shader:flat;color:#09B4FF"
                  position="0 0 -1"
                  geometry="primitive: ring; radiusInner: 0.01; radiusOuter: 0.015;thetaLength:0"
                  animation__mouseenter="property: geometry.thetaLength; dir: alternate; dur: 2000;
                                easing: easeInSine; from:0;to: 360;startEvents:startFuse;pauseEvents:stopFuse;autoplay:false"

                  animation__mouseleave="property: geometry.thetaLength; dir: alternate; dur: 500;
                                easing: easeInSine; to: 0;startEvents:stopFuse;autoplay:false">

I would like a transition between images/scenes similar to the examples cited above (Google Street View and Matterport).

Does anyone have any ideas?


问:
WireMock for Mocking TCP Calls
Does WireMock support mocking TCP (Java Socket API) calls or can that be achieved via WireMock? Thanks

We are using WireMock already for mocking HTTP calls

Title: WireMock for Mocking TCP Calls


问:
Rails in docker error when try to start server in Windows WSL2 Docker Desktop Engine(docker compose), but working correctly in a Debian system
This error message appears to 3 images in composed docker container.

exec /usr/bin/entrypoint.sh: no such file or directory

All images related to Ruby execution of services
Sidekiq, Webpack runned by Ruby executable and Web(rails) services
I have tried change every execution to run loading de Gemfile environment using bundle exec, but nothing worked.

Dockerfile

```<code>FROM ruby:2.6.6
RUN apt-get update -qq \
&& apt-get install -y curl build-essential libpq-dev postgresql \
 nodejs postgresql-client &&\
  curl -sL https://deb.nodesource.com/setup_14.x | bash - && \
  curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
  echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
  apt-get update && apt-get install -y nodejs yarn
ADD . /app
WORKDIR /app
RUN gem install bundler:2.3.22
RUN bundle install
RUN yarn install --check-files
RUN gem install foreman
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 80
CMD ["bash"]
</code>```

docker-compose.yml

```<code>version: '3.3'
services:
  db:
    image: postgres
    ports:
      - 5423:5432
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: *****
  redis:
    image: redis
    ports:
      - "6379:6379"
    volumes:
      - 'redis:/data'
    depends_on:
      - db
  webpack:
    build: .
    command: sh -c 'rm -rf public/packs/* || true && bin/webpack-dev-server --host 0.0.0.0 --port 3035 -w'
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - "3035:3035"
    depends_on:
      - db
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && rails s -b 0.0.0.0 -p 80"
    volumes:
      - .:/app
    ports:
      - "80:80"
    depends_on:
      - db
      - redis
      - webpack
      - chrome
    env_file: .env_docker
    environment:
      RAILS_ENV: development
      RAILS_MAX_THREADS: 5
  sidekiq:
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - .:/app
    depends_on:
      - db
      - redis
    env_file: .env_docker
    environment:
      RAILS_MAX_THREADS: 5
  chrome:
    image: selenium/standalone-chrome
    ports:
      - "4444:4444"
    volumes:
      - /dev/shm:/dev/shm
    depends_on:
      - db
      - redis
      - webpack
      - sidekiq
volumes:
  redis:
  postgres:

</code>```

Equal to entrypoint.sh exec: @: not found but not resolved

I really want to change my Debian development OS to Windows and work only with containers, not looking to Linux or WSL alternatives

Body:
This error message appears to 3 images in composed docker container.

exec /usr/bin/entrypoint.sh: no such file or directory

All images related to Ruby execution of services
Sidekiq, Webpack runned by Ruby executable and Web(rails) services
I have tried change every execution to run loading de Gemfile environment using bundle exec, but nothing worked.

Dockerfile

FROM ruby:2.6.6
RUN apt-get update -qq \
&& apt-get install -y curl build-essential libpq-dev postgresql \
 nodejs postgresql-client &&\
  curl -sL https://deb.nodesource.com/setup_14.x | bash - && \
  curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
  echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
  apt-get update && apt-get install -y nodejs yarn
ADD . /app
WORKDIR /app
RUN gem install bundler:2.3.22
RUN bundle install
RUN yarn install --check-files
RUN gem install foreman
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 80
CMD ["bash"]

docker-compose.yml

version: '3.3'
services:
  db:
    image: postgres
    ports:
      - 5423:5432
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: *****
  redis:
    image: redis
    ports:
      - "6379:6379"
    volumes:
      - 'redis:/data'
    depends_on:
      - db
  webpack:
    build: .
    command: sh -c 'rm -rf public/packs/* || true && bin/webpack-dev-server --host 0.0.0.0 --port 3035 -w'
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - "3035:3035"
    depends_on:
      - db
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && rails s -b 0.0.0.0 -p 80"
    volumes:
      - .:/app
    ports:
      - "80:80"
    depends_on:
      - db
      - redis
      - webpack
      - chrome
    env_file: .env_docker
    environment:
      RAILS_ENV: development
      RAILS_MAX_THREADS: 5
  sidekiq:
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - .:/app
    depends_on:
      - db
      - redis
    env_file: .env_docker
    environment:
      RAILS_MAX_THREADS: 5
  chrome:
    image: selenium/standalone-chrome
    ports:
      - "4444:4444"
    volumes:
      - /dev/shm:/dev/shm
    depends_on:
      - db
      - redis
      - webpack
      - sidekiq
volumes:
  redis:
  postgres:

Equal to entrypoint.sh exec: @: not found but not resolved

I really want to change my Debian development OS to Windows and work only with containers, not looking to Linux or WSL alternatives


问:
What happens under the hood when I iterate a tf.data.Dataset?
When I create a tf.data.Dataset from, for example, a TFRecord file that is on disk, what happens under the hood when I iterate over the dataset itself?
And what happens when I iterate when I do the model training with keras/tensorflow? Like here

For example:

```<code>dataset_train = tf.data.TFRecordDataset(PATH_TFRECORD)
dataset_train = dataset_train.map(decode_function)
dataset_train = dataset_train.batch(64)
for (X_batch, y_batch) in dataset_train:
    model(X_batch, y_batch, training=True)
</code>```

What happens here, if the training is done on GPU is that a for each batch, you read from disk until you get to RAM, decode the batch via "decode_function" and then send the batch from CPU RAM to GPU memory?
Or what happens is to read from disk all the TFRecord and load it into CPU RAM, decode all the elements via map, make the batches and then send the batches from CPU RAM to GPU memory?
What happens when there is a new epoch instead? Do I re-read the data from disk as TFRecord or do I already start from the data that is on RAM?
For each epoch do you copy the data then from CPU RAM to GPU memory even though the data is the same and the dataset fits there in memory?
Thanks in advance

Body:
When I create a tf.data.Dataset from, for example, a TFRecord file that is on disk, what happens under the hood when I iterate over the dataset itself?
And what happens when I iterate when I do the model training with keras/tensorflow? Like here

For example:

dataset_train = tf.data.TFRecordDataset(PATH_TFRECORD)
dataset_train = dataset_train.map(decode_function)
dataset_train = dataset_train.batch(64)
for (X_batch, y_batch) in dataset_train:
    model(X_batch, y_batch, training=True)

What happens here, if the training is done on GPU is that a for each batch, you read from disk until you get to RAM, decode the batch via "decode_function" and then send the batch from CPU RAM to GPU memory?
Or what happens is to read from disk all the TFRecord and load it into CPU RAM, decode all the elements via map, make the batches and then send the batches from CPU RAM to GPU memory?
What happens when there is a new epoch instead? Do I re-read the data from disk as TFRecord or do I already start from the data that is on RAM?
For each epoch do you copy the data then from CPU RAM to GPU memory even though the data is the same and the dataset fits there in memory?
Thanks in advance


问:
Cannot use Qt6 libraries in android studio ndk
I want to use Qt6 Core library in my android studio ndk project. Despite of many attempts I have failed. Please guide me how to use Qt6 libraries in android studio ndk project.

```<code>Qt6 installation directory: "C:\Qt"
</code>```

And the path "C:\Qt\6.4.1" directory contains the following files and folders:

```<code>14.12.2022  18:32    <DIR>          .
14.12.2022  18:32    <DIR>          ..
10.11.2022  18:12    <DIR>          android_arm64_v8a
10.11.2022  18:16    <DIR>          android_armv7
10.11.2022  18:19    <DIR>          android_x86
10.11.2022  18:21    <DIR>          android_x86_64
10.11.2022  17:47    <DIR>          Logs
10.11.2022  16:04    <DIR>          mingw_64
10.11.2022  16:33    <DIR>          msvc2019_64
10.11.2022  17:11    <DIR>          msvc2019_arm64
14.12.2022  18:32                 0 output.txt
10.11.2022  17:47             2.084 sha1s.txt
10.11.2022  17:47    <DIR>          Src
10.11.2022  18:25    <DIR>          wasm_32
               2 File(s)          2.084 bytes
              12 Dir(s)  230.990.303.232 bytes free
</code>```

Please note that it doesn't contain CMakeLists.txt.

I tried the following steps and failed at all.

Step1:

```<code># CMakeLists.txt
cmake_minimum_required(VERSION 3.21.1)
project(test)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

list(APPEND CMAKE_PREFIX_PATH "C:/Qt/6.4.1")
list(APPEND CMAKE_PREFIX_PATH "C:/Qt/6.4.1/mingw_64/")

find_packgggage(Qt6 REQUIRED COMPONENTS Core)

add_library(test-lib SHARED native-lib.cpp)
target_link_libraries(test-lib Qt6::Core)
</code>```

Step2:

```<code># CMakeLists.txt
cmake_minimum_required(VERSION 3.21.1)
project(test)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_library(test-lib SHARED native-lib.cpp)

include_directories(test-lib "C:/Qt/6.4.1/mingw_64/include")

target_link_libraries(test-lib
        "C:/Qt/6.4.1/mingw_64/lib/libQt6Core.a"
        )
</code>```

All the steps above failed. How to overcome this? Any helps would be very appreciated.

Body:
I want to use Qt6 Core library in my android studio ndk project. Despite of many attempts I have failed. Please guide me how to use Qt6 libraries in android studio ndk project.

Qt6 installation directory: "C:\Qt"

And the path "C:\Qt\6.4.1" directory contains the following files and folders:

14.12.2022  18:32    <DIR>          .
14.12.2022  18:32    <DIR>          ..
10.11.2022  18:12    <DIR>          android_arm64_v8a
10.11.2022  18:16    <DIR>          android_armv7
10.11.2022  18:19    <DIR>          android_x86
10.11.2022  18:21    <DIR>          android_x86_64
10.11.2022  17:47    <DIR>          Logs
10.11.2022  16:04    <DIR>          mingw_64
10.11.2022  16:33    <DIR>          msvc2019_64
10.11.2022  17:11    <DIR>          msvc2019_arm64
14.12.2022  18:32                 0 output.txt
10.11.2022  17:47             2.084 sha1s.txt
10.11.2022  17:47    <DIR>          Src
10.11.2022  18:25    <DIR>          wasm_32
               2 File(s)          2.084 bytes
              12 Dir(s)  230.990.303.232 bytes free

Please note that it doesn't contain CMakeLists.txt.

I tried the following steps and failed at all.

Step1:

# CMakeLists.txt
cmake_minimum_required(VERSION 3.21.1)
project(test)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

list(APPEND CMAKE_PREFIX_PATH "C:/Qt/6.4.1")
list(APPEND CMAKE_PREFIX_PATH "C:/Qt/6.4.1/mingw_64/")

find_packgggage(Qt6 REQUIRED COMPONENTS Core)

add_library(test-lib SHARED native-lib.cpp)
target_link_libraries(test-lib Qt6::Core)

Step2:

# CMakeLists.txt
cmake_minimum_required(VERSION 3.21.1)
project(test)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_library(test-lib SHARED native-lib.cpp)

include_directories(test-lib "C:/Qt/6.4.1/mingw_64/include")

target_link_libraries(test-lib
        "C:/Qt/6.4.1/mingw_64/lib/libQt6Core.a"
        )

All the steps above failed. How to overcome this? Any helps would be very appreciated.


问:
Typescript recognizes conditional function parameter as union type
I'm trying to create a function with conditional parameters. Where, based on the first parameter, the second parameter will be changed. But typescript isn't asserting the correct type automatically inside a conditional block. How can I do that?

Typescript playground

Here is my code:

type User = {
  name: string
}

type Animal = {
  species: string
}

function get<T extends 'user' | 'animal'>(modelType: T, model: T extends 'user' ? User : Animal) {
  if (modelType === 'user') {
    model.name // Property 'name' does not exist on type 'User | Animal'.
  } else {
    model.species // Property 'species' does not exist on type 'User | Animal'.
  }
}

```

If check if type is 'user', typescript should recognize that the model is User, according conditional type

Body:
I'm trying to create a function with conditional parameters. Where, based on the first parameter, the second parameter will be changed. But typescript isn't asserting the correct type automatically inside a conditional block. How can I do that?

Typescript playground

Here is my code:

type User = {
  name: string
}

type Animal = {
  species: string
}

function get<T extends 'user' | 'animal'>(modelType: T, model: T extends 'user' ? User : Animal) {
  if (modelType === 'user') {
    model.name // Property 'name' does not exist on type 'User | Animal'.
  } else {
    model.species // Property 'species' does not exist on type 'User | Animal'.
  }
}

If check if type is 'user', typescript should recognize that the model is User, according conditional type


问:
How to connect firebase-auth to firebase real time database
A have got a project in react-native with rest api auntification in firebase like:

```<code> const hanldeLogin = () => {
    setIsLoading(true)
    axios({
      method: 'POST',
      url: 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword',
      params: {
        key: '....',
      },
      data: {
        email,
        password,
      }
    }).then(res => {
      setUser(res.data)
    })
    .catch(e => {})
    .finally(() => {
      setIsLoading(false)
    })
</code>```

I need to connect my users data like token to firebase real time db. To upload the data. For exapmle, i need to connect the statistic for each oher user. When antoher user will log in, statistic will be upload from db

Body:
A have got a project in react-native with rest api auntification in firebase like:

 const hanldeLogin = () => {
    setIsLoading(true)
    axios({
      method: 'POST',
      url: 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword',
      params: {
        key: '....',
      },
      data: {
        email,
        password,
      }
    }).then(res => {
      setUser(res.data)
    })
    .catch(e => {})
    .finally(() => {
      setIsLoading(false)
    })

I need to connect my users data like token to firebase real time db. To upload the data. For exapmle, i need to connect the statistic for each oher user. When antoher user will log in, statistic will be upload from db


问:
Get version number from play store xamarin android
i've tried all the solution with HtmlAgilityPack

```<code>            newVersion = doc.DocumentNode.SelectNodes("//div[@itemprop='softwareVersion']")
                              .Select(p => p.InnerText)
                              .ToList()
                              .First()
                              .Trim();

</code>```

also i've tried this dcsoup

```<code> var doc = client.GetAsync("https://play.google.com/store/apps/details?id=" + AppInfo.PackageName + "&hl=en_CA").Result.Parse();
                    var versionElement = doc.Select("div:containsOwn(Current Version)");
</code>```

all the method return empty string
i noticed there is a changes of page play store and does not show the version number

Body:
i've tried all the solution with HtmlAgilityPack

            newVersion = doc.DocumentNode.SelectNodes("//div[@itemprop='softwareVersion']")
                              .Select(p => p.InnerText)
                              .ToList()
                              .First()
                              .Trim();

also i've tried this dcsoup

 var doc = client.GetAsync("https://play.google.com/store/apps/details?id=" + AppInfo.PackageName + "&hl=en_CA").Result.Parse();
                    var versionElement = doc.Select("div:containsOwn(Current Version)");

all the method return empty string
i noticed there is a changes of page play store and does not show the version number


问:
How to link Github account to another system account using Oauth
I am trying to use Github Oauth App for authorization purpose. No Authentication, no sign in with github.

I would like a user (having an account on my app) to link their GitHub account to my app's account. I understand the github web flow. Let the user authorize Oauth app for the first time. Get the authorization code. Fetch an access token using the code. And use that token to do git operations on user's behalf.

Now the thing I am unsure about is, what if the user logs out of my app and logs back in again?

Not a good practise to ask them to link accounts for each login.

Should I automatically do the Oauth flow again and generate a new access token for each login? If that is, why does Github Oauth App have an access token that won't expire? And why does Oauth app store multiple tokens for the same user, same scope? Why not remove the previous token and store the new one only? Because of this move by Github, I believe this is not the correct way to go. I don't know.

Or, should I store their initial token in the database, and use the same token forever? Is that a good practise? And if that is, how do I verify the scopes initially defined for that token is still the same? I couldn't understand this bit, reading through the Github documentation.

I hope I was clear enough. I couldn't understand this account linking thing.


问:
How to reference a .kv page inside python
how can I code a function in python which opens the next window in a .kv file?

Since the buttons are created dynamically I want to add the button function (to go to the next page) inside the python code. I just do not get how to "reference" the page from the .kv file in my python code.

So the python function should do the same as:

```<code>Button:
        size_hint_y: .05
        size_hint_x: .25
        background_color: 0,0,0,0
        pos_hint:{"center_y":0.04, "x": 0.71}
        on_press: root.manager.current = 'EditPage'  <------
</code>```

Body:
how can I code a function in python which opens the next window in a .kv file?

Since the buttons are created dynamically I want to add the button function (to go to the next page) inside the python code. I just do not get how to "reference" the page from the .kv file in my python code.

So the python function should do the same as:

Button:
        size_hint_y: .05
        size_hint_x: .25
        background_color: 0,0,0,0
        pos_hint:{"center_y":0.04, "x": 0.71}
        on_press: root.manager.current = 'EditPage'  <------


问:
function like in a select statement
I need to implement a function-like functionality in a select statement.
I need to do something like this:

```<code>select ID, OwnerName(ManagerID), OwnerName(ManagerID2) from Table1;
</code>```

Should OwnerName be a function or a Stored procedure. I know Stored Procedures can't be called in a Select Statement. Any suggestions How can I do that?

Title: function like in a select statement

Body:
I need to implement a function-like functionality in a select statement.
I need to do something like this:

select ID, OwnerName(ManagerID), OwnerName(ManagerID2) from Table1;

Should OwnerName be a function or a Stored procedure. I know Stored Procedures can't be called in a Select Statement. Any suggestions How can I do that?


问:
unity uvs are interpolated and dont work for textures
i have made a script for 3D voxel terrain in unity and it works. i have made a triplanar texturing shader in the universal render pipeline,  i set the mesh uvs in my script and the shader uses the uvs to get an index from a texture2d array. my problem is that uvs are interpolated and between every vertex it shows numerous other textures. is there maybe another way to pass vertey wise data through meshes that is not interpolated between vertices or can i get the uv coordinate at the nearest vertex in shader graph somehow?

i tried using vertex colors but they are interpolated too.


问:
Empty movie file when combining videos in Swift
I'm new to Swift.
I'm trying to combine several mp4 files into a single movie, but my code ends up writing an empty video file.

This is the code I wrote:

```<code>import Foundation
import AVFoundation

var folderURL = URL(fileURLWithPath: "/")
var outputMovieURL = URL(fileURLWithPath:"/test.mov")

var mp4URLs = try! FileManager
    .default
    .contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])
    .filter { forMP4(url:$0) }

func forMP4(url: URL) -> Bool {
    return url.pathExtension == "mp4"
}

let movie = AVMutableComposition()
let videoTrack = movie.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)

for url in mp4URLs {
    if #available(macOS 12.0, *) {
        do {
                let videoAsset = AVAsset(url: url)
                let firstVideoTrack = try await videoAsset.loadTracks(withMediaType: .video).first
                let range = CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration)
                try videoTrack?.insertTimeRange(range, of: firstVideoTrack!, at: CMTime.zero)
            } catch {
                print("Failed to insert video data from URL: \(url)")
                print("Error: \(error.localizedDescription)")
            }
        print(movie.duration)
    } else {
        // Fallback on earlier versions
    }
}

let exporter = AVAssetExportSession(asset: movie,
                               presetName: AVAssetExportPresetHighestQuality)
exporter?.outputURL = outputMovieURL
exporter?.outputFileType = .mov
//export!
exporter?.exportAsynchronously(completionHandler: { [weak exporter] in
  DispatchQueue.main.async {
    if let error = exporter?.error {
      print("failed \(error.localizedDescription)")
    } else {
      print("movie has been exported to \(outputMovieURL)")
    }
  }
})

</code>```

What is odd is that the duration of it increments as I include videos. This is the output of the code's print(movie.duration) command.

```<code>CMTime(value: 1135671, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)
CMTime(value: 1153202, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)
CMTime(value: 1801843, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)
CMTime(value: 1944314, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)
</code>```

Body:
I'm new to Swift.
I'm trying to combine several mp4 files into a single movie, but my code ends up writing an empty video file.

This is the code I wrote:

import Foundation
import AVFoundation

var folderURL = URL(fileURLWithPath: "/")
var outputMovieURL = URL(fileURLWithPath:"/test.mov")

var mp4URLs = try! FileManager
    .default
    .contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])
    .filter { forMP4(url:$0) }

func forMP4(url: URL) -> Bool {
    return url.pathExtension == "mp4"
}

let movie = AVMutableComposition()
let videoTrack = movie.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)

for url in mp4URLs {
    if #available(macOS 12.0, *) {
        do {
                let videoAsset = AVAsset(url: url)
                let firstVideoTrack = try await videoAsset.loadTracks(withMediaType: .video).first
                let range = CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration)
                try videoTrack?.insertTimeRange(range, of: firstVideoTrack!, at: CMTime.zero)
            } catch {
                print("Failed to insert video data from URL: \(url)")
                print("Error: \(error.localizedDescription)")
            }
        print(movie.duration)
    } else {
        // Fallback on earlier versions
    }
}

let exporter = AVAssetExportSession(asset: movie,
                               presetName: AVAssetExportPresetHighestQuality)
exporter?.outputURL = outputMovieURL
exporter?.outputFileType = .mov
//export!
exporter?.exportAsynchronously(completionHandler: { [weak exporter] in
  DispatchQueue.main.async {
    if let error = exporter?.error {
      print("failed \(error.localizedDescription)")
    } else {
      print("movie has been exported to \(outputMovieURL)")
    }
  }
})

What is odd is that the duration of it increments as I include videos. This is the output of the code's print(movie.duration) command.

CMTime(value: 1135671, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)
CMTime(value: 1153202, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)
CMTime(value: 1801843, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)
CMTime(value: 1944314, timescale: 1000, flags: __C.CMTimeFlags(rawValue: 1), epoch: 0)


问:
Test management tool that support cucumber scenario with multiple example tables
Does exists any test management tool that can be integrated with Jira and supports cucumber scenario outline multiple example tables?

I try to use this cucumber feature with xray cloud but it looks that xray does not support this yet. Is there any similar tool that could be integrated with Jira and supports multiple example tables like in below example?

Example cucumber code:

```<code>Feature: Log in to the application
  As user I want to be able to successfully log in to the application

  @XrayTicketId-5000
  Scenario Outline: Log in to the application
    Given Log in page is opened
    When User with <User Role> logs in
    Then User should be logged in
    And Overview page should be opened

    @smoke
    Examples:
      | User Role     |
      | Administrator |
      | Customer      |
      | Supplier      |

    @critical
    Examples:
      | User Role         |
      | Technical Support |
      | Analyst           |
</code>```

Body:
Does exists any test management tool that can be integrated with Jira and supports cucumber scenario outline multiple example tables?

I try to use this cucumber feature with xray cloud but it looks that xray does not support this yet. Is there any similar tool that could be integrated with Jira and supports multiple example tables like in below example?

Example cucumber code:

Feature: Log in to the application
  As user I want to be able to successfully log in to the application

  @XrayTicketId-5000
  Scenario Outline: Log in to the application
    Given Log in page is opened
    When User with <User Role> logs in
    Then User should be logged in
    And Overview page should be opened

    @smoke
    Examples:
      | User Role     |
      | Administrator |
      | Customer      |
      | Supplier      |

    @critical
    Examples:
      | User Role         |
      | Technical Support |
      | Analyst           |


问:
pyspark - java.sql.BatchUpdateException
Is it possible to check the (not null) constraints ion the target database table before writing the data into the target database table?

Is there anyway to handle the below exception in pyspark?

java.sql.BatchUpdateException: Batch entry 4 INSERT INTO public.empl ("id","name") VALUES (5,NULL) was aborted: ERROR: null value in column "name" of relation "empl" violates not-null constraint

I want to write data into a table via pyspark. But, I'm getting not null constraint error. I need to handle it without termination

Title: pyspark - java.sql.BatchUpdateException


问:
Angular Child Component Not Detecting Changes
I have a simple Angular component which includes an Angular Material ProgressBar, this component is a child of a 'Container' component. An Observable stream of data from the NgRx Store into the container component is updating, but the child component which is passed the data does not detect the changes. A new object is being created every time the data changes and I enforce immutability in my Store. I am implementing ChangeDetectionStrategy.OnPush (though when removed makes no difference to this problem).

The container's only responsibility is to subscribe to an Observable stream of data from the NgRx Store and pass it to the child component as follows:

```<code>  public progressBarData$: Observable<ProgressBarData | null>;

  constructor(
    private store: Store<AppState>
  ) {

    this.progressBarData$ = this.store.pipe(
      select(fromCoreSelectors.programSelectors.selectProgressBarDeterminateData),
      tap(data => {
        console.log(`selectProgressBarDeterminateData: `, data);
      })
    );

  }
</code>```

An async pipe manages the subscription for me as the data is passed into the child as follows:

```<code><app-progress-bar-determinate [progressBarData]="progressBarData$ | async"></app-progress-bar-determinate>
</code>```

The child component is nice and simple as follows:

```<code>export class ProgressBarDeterminateComponent implements OnInit {

  @Input() progressBarData: ProgressBarData | null = null;

  constructor() { }

  ngOnInit(): void {
  };

  ngOnChanges(changes: SimpleChanges) {
    console.log(`ngOnChanges`, changes);
  };

}
</code>```

I included ngOnChanges so I could see what changes the child detects.

The child component's template is as follows:

```<code><div *ngIf="progressBarData?.show === true" fxLayout="column" fxLayoutAlign="center center" style="width: 100%; height: 100%; position: absolute; left: 0; top: 0;">
  <div fxFlex="nogrow" class="mat-elevation-z4" style="width: 320px; height: 64px; background-color: white; z-index: 4;">

    <div fxLayout="column" fxLayoutAlign="center center" style="width: 100%; height: 100%;">

      <div fxFlex="nogrow" *ngIf="progressBarData?.message">
        <p>{{progressBarData?.message}}</p>
      </div>

      <mat-progress-bar mode="determinate" [value]="progressBarData?.value" color="accent" style="width: 240px;"></mat-progress-bar>

    </div>

  </div>
</div>
</code>```

To display the ProgressBar I dispatch an Action which creates a new object in the Reducer which causes the Selector to emit a new object. A different Action hides the ProgressBar. All fine.

In my application I have a very processor intensive routine (which lasts approximately 10 seconds) which I want to display the ProgressBar throughout and then hide it when everything is complete. This intensive routine starts when a button is clicked and the button function dispatches two Actions; Display the ProgressBar and start the routine. When the application is launched I can see the initial values from the Store being passed into the ProgressBar child component as the ngOnChanges console logs out the default ProgressBarData values.

When the Start button is clicked I know both Actions are being dispatched. I can see the Reducer updating the Store with a new ProgressBarData object and the container component console logs out that it received the new object and that the show property is true along with the correct message string. However, the child component doesn't appear to receive the new object at its @Input(). ngOnChanges does not detect anything, the ProgressBar remains resolutely hidden. I also created a setter on the @Input() to log out if a new value was received, but nothing was received even though I could see the parent container had received a new object in it's subscription.

As a sanity check I temporarily placed a second button on the screen but this button only dispatches the Action to display the ProgressBar. When clicked the ProgressBar displays instantly and if I then click the original button the routine runs and after the routine the Action is dispatched to hide the ProgressBar and it hides, as expected.

After nearly two days on this I am starting to go around in circles so I thought I would ask for a fresh pair of eyes, as it were. It is as if change detection pauses while the routine is running and then when complete resumes again.

Any thoughts, suggestions or questions are very welcome.

Update 01

The intensive routine is trigerred by dispatching an NgRx Action and immediately before this I dispatch another Action to display the ProgressBar as follows:

```<code>        // Dispatch an Action to show the Progress Bar.
        this.store.dispatch(fromCoreActions.ProgramActions.showProgressBarDeterminateFromTaskGeneratorEffects(
          { message: "Calculating Tasks, please wait..." }
        ));

        // Dispatch an Action to generate the Tasks.
        this.store.dispatch(fromAppPlanActions.TasksGeneratorActions.generateTasks());
</code>```

I have found, almost by accident, that if I wrap the second Action within a setTimeout() function everything works! as follows:

```<code>// Dispatch an Action to show the Progress Bar.
this.store.dispatch(fromCoreActions.ProgramActions.showProgressBarDeterminateFromTaskGeneratorEffects(
  { message: "Calculating Tasks, please wait..." }
));

// Use setTimeout to force the ProgressBar to display before the Action is dispatched to generate Tasks.
setTimeout(() => {

  // Dispatch an Action to generate the Tasks.
  this.store.dispatch(fromAppPlanActions.TasksGeneratorActions.generateTasks());

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

That wasn't the end of it. I then faced the same problem when trying to update the ProgressBar's value property by dispatching Actions incrementally through the intensive process. Again the child component initially just ignored the changing data being passed to it from its parent container using an async pipe. Wrapping the dispatch of the Action to update the NgRx Store within a setTimeout() again forced the issue (somehow).

Many thanks for those who suggested ideas and to Chris for setting up the StackBlitz. Please share any thoughts as it's an opportunity to learn and improve.

Body:
I have a simple Angular component which includes an Angular Material ProgressBar, this component is a child of a 'Container' component. An Observable stream of data from the NgRx Store into the container component is updating, but the child component which is passed the data does not detect the changes. A new object is being created every time the data changes and I enforce immutability in my Store. I am implementing ChangeDetectionStrategy.OnPush (though when removed makes no difference to this problem).

The container's only responsibility is to subscribe to an Observable stream of data from the NgRx Store and pass it to the child component as follows:

  public progressBarData$: Observable<ProgressBarData | null>;

  constructor(
    private store: Store<AppState>
  ) {

    this.progressBarData$ = this.store.pipe(
      select(fromCoreSelectors.programSelectors.selectProgressBarDeterminateData),
      tap(data => {
        console.log(`selectProgressBarDeterminateData: `, data);
      })
    );

  }

An async pipe manages the subscription for me as the data is passed into the child as follows:

<app-progress-bar-determinate [progressBarData]="progressBarData$ | async"></app-progress-bar-determinate>

The child component is nice and simple as follows:

export class ProgressBarDeterminateComponent implements OnInit {

  @Input() progressBarData: ProgressBarData | null = null;

  constructor() { }

  ngOnInit(): void {
  };

  ngOnChanges(changes: SimpleChanges) {
    console.log(`ngOnChanges`, changes);
  };

}

I included ngOnChanges so I could see what changes the child detects.

The child component's template is as follows:

{{progressBarData?.message}}

      <mat-progress-bar mode="determinate" [value]="progressBarData?.value" color="accent" style="width: 240px;"></mat-progress-bar>

To display the ProgressBar I dispatch an Action which creates a new object in the Reducer which causes the Selector to emit a new object. A different Action hides the ProgressBar. All fine.

In my application I have a very processor intensive routine (which lasts approximately 10 seconds) which I want to display the ProgressBar throughout and then hide it when everything is complete. This intensive routine starts when a button is clicked and the button function dispatches two Actions; Display the ProgressBar and start the routine. When the application is launched I can see the initial values from the Store being passed into the ProgressBar child component as the ngOnChanges console logs out the default ProgressBarData values.

When the Start button is clicked I know both Actions are being dispatched. I can see the Reducer updating the Store with a new ProgressBarData object and the container component console logs out that it received the new object and that the show property is true along with the correct message string. However, the child component doesn't appear to receive the new object at its @Input(). ngOnChanges does not detect anything, the ProgressBar remains resolutely hidden. I also created a setter on the @Input() to log out if a new value was received, but nothing was received even though I could see the parent container had received a new object in it's subscription.

As a sanity check I temporarily placed a second button on the screen but this button only dispatches the Action to display the ProgressBar. When clicked the ProgressBar displays instantly and if I then click the original button the routine runs and after the routine the Action is dispatched to hide the ProgressBar and it hides, as expected.

After nearly two days on this I am starting to go around in circles so I thought I would ask for a fresh pair of eyes, as it were. It is as if change detection pauses while the routine is running and then when complete resumes again.

Any thoughts, suggestions or questions are very welcome.

Update 01

The intensive routine is trigerred by dispatching an NgRx Action and immediately before this I dispatch another Action to display the ProgressBar as follows:

        // Dispatch an Action to show the Progress Bar.
        this.store.dispatch(fromCoreActions.ProgramActions.showProgressBarDeterminateFromTaskGeneratorEffects(
          { message: "Calculating Tasks, please wait..." }
        ));

        // Dispatch an Action to generate the Tasks.
        this.store.dispatch(fromAppPlanActions.TasksGeneratorActions.generateTasks());

I have found, almost by accident, that if I wrap the second Action within a setTimeout() function everything works! as follows:

// Dispatch an Action to show the Progress Bar.
this.store.dispatch(fromCoreActions.ProgramActions.showProgressBarDeterminateFromTaskGeneratorEffects(
  { message: "Calculating Tasks, please wait..." }
));

// Use setTimeout to force the ProgressBar to display before the Action is dispatched to generate Tasks.
setTimeout(() => {

  // Dispatch an Action to generate the Tasks.
  this.store.dispatch(fromAppPlanActions.TasksGeneratorActions.generateTasks());

}, 0);

That wasn't the end of it. I then faced the same problem when trying to update the ProgressBar's value property by dispatching Actions incrementally through the intensive process. Again the child component initially just ignored the changing data being passed to it from its parent container using an async pipe. Wrapping the dispatch of the Action to update the NgRx Store within a setTimeout() again forced the issue (somehow).

Many thanks for those who suggested ideas and to Chris for setting up the StackBlitz. Please share any thoughts as it's an opportunity to learn and improve.


问:
How do I get data from the Google Analytics API by filtering on a specific URL
Good afternoon, I'm developing an application in Node.js, this application returns the total views of my projects in JSON.

My question is: how do I get the total views of a specific page or URL. Bearing in mind that this will become an attribute for my function later.

```<code>async function getTopPosts(customUrl) {  /* I need the Custom URL to be used as a filter */

    try {
        await jwt.authorize();

        const response = await google.analytics("v3").data.ga.get({
            auth: jwt,
            ids: "ga:" + VIEW_ID,
            "start-date": "2019-01-01",
            "end-date": "today",
            dimensions: "ga:pagePath,ga:pageTitle",
            metrics: "ga:pageviews",
            sort: "-ga:pageviews",
            "max-results": "10",
            filters: "ga:medium==organic",
        });

        let data = response.data
        console.log(data)

    } catch (err) {
        console.log(err);
    }
};
</code>```

I tried to see the GA-API documentations GA-API but I was not successful.

I hope it returns a JSON containing only the total views of a specific page or URL of my Google Analytics project.

Body:
Good afternoon, I'm developing an application in Node.js, this application returns the total views of my projects in JSON.

My question is: how do I get the total views of a specific page or URL. Bearing in mind that this will become an attribute for my function later.

async function getTopPosts(customUrl) {  /* I need the Custom URL to be used as a filter */

    try {
        await jwt.authorize();

        const response = await google.analytics("v3").data.ga.get({
            auth: jwt,
            ids: "ga:" + VIEW_ID,
            "start-date": "2019-01-01",
            "end-date": "today",
            dimensions: "ga:pagePath,ga:pageTitle",
            metrics: "ga:pageviews",
            sort: "-ga:pageviews",
            "max-results": "10",
            filters: "ga:medium==organic",
        });

        let data = response.data
        console.log(data)

    } catch (err) {
        console.log(err);
    }
};

I tried to see the GA-API documentations GA-API but I was not successful.

I hope it returns a JSON containing only the total views of a specific page or URL of my Google Analytics project.


问:
Generating metrics for Prometheus from Spring Boot application
I am exposing two counter metrics from my spring boot application. The metrics are getting generated and the counters increase by 1 when the requests succeed. I am facing 2 issues - 1) The name of the counter is getting appended by "_total" even though I did not add that and I don't want it to be added, 2) The last label ends with an open ','. I want to remove this last ','.
Here is my code:

```<code>public class PrometheusUtility {

    private PrometheusUtility(){

    }

    static CollectorRegistry registry = CollectorRegistry.defaultRegistry;

    static final Counter counter = Counter.build().name("http_request").help("help").labelNames("method","status","api", "component").register(registry);
    static final Counter dsCounter = Counter.build().name("http_downstream_request").help("Records the downstream request count").labelNames("method","status","api", "component", "downstream").register(registry);

    public static void incrementCounter(String method, String status, String apiName, String component){
        counter.labels(method,status,apiName,component).inc();
    }

    public static void incrementDownstreamCounter(String method, String status, String apiName, String component, String downstream){
        dsCounter.labels(method,status,apiName,component, downstream).inc();
    }

}
</code>```

I am calling these functions from the business class:

```<code>PrometheusUtility.incrementCounter("Post", String.valueOf(HttpStatus.SC_OK), "newMail", "mx");
PrometheusUtility.incrementDownstreamCounter("Post", String.valueOf(HttpStatus.SC_OK), "newMail", "mx", "mwi");
</code>```

The pom.xml has this dependency added

```<code>       <dependency>
          <groupId>io.prometheus</groupId>
          <artifactId>simpleclient_spring_boot</artifactId>
          <version>0.16.0</version>
        </dependency>
</code>```

The output I am checking in the browser where my application is up and running (not in Prometheus):

```<code>http_request_total{method="Post",status="200",api="newMail",component="mx",} 1.0
http_downstream_request_total{method="Post",status="200",api="newMail",component="mx",downstream="mwi",} 1.0
</code>```

Issue:

Both metric names are getting an additional "_total" appended to it. I don't want this to be added by default. It should be same as the name I have put in the Utility class.

Both metrics have an open ',' or comma at the end. Ideally this should not be there. A metric does not have an open comma at the end. Not sure why it's adding this comma. I have specified the correct number of labels at the creation time of the counter and populating the labels correctly for incrementing. Not sure where this comma is coming from.

Please let me know how I could fix these issues.

Body:
I am exposing two counter metrics from my spring boot application. The metrics are getting generated and the counters increase by 1 when the requests succeed. I am facing 2 issues - 1) The name of the counter is getting appended by "_total" even though I did not add that and I don't want it to be added, 2) The last label ends with an open ','. I want to remove this last ','.
Here is my code:

public class PrometheusUtility {

    private PrometheusUtility(){

    }

    static CollectorRegistry registry = CollectorRegistry.defaultRegistry;

    static final Counter counter = Counter.build().name("http_request").help("help").labelNames("method","status","api", "component").register(registry);
    static final Counter dsCounter = Counter.build().name("http_downstream_request").help("Records the downstream request count").labelNames("method","status","api", "component", "downstream").register(registry);

    public static void incrementCounter(String method, String status, String apiName, String component){
        counter.labels(method,status,apiName,component).inc();
    }

    public static void incrementDownstreamCounter(String method, String status, String apiName, String component, String downstream){
        dsCounter.labels(method,status,apiName,component, downstream).inc();
    }

}

I am calling these functions from the business class:

PrometheusUtility.incrementCounter("Post", String.valueOf(HttpStatus.SC_OK), "newMail", "mx");
PrometheusUtility.incrementDownstreamCounter("Post", String.valueOf(HttpStatus.SC_OK), "newMail", "mx", "mwi");

The pom.xml has this dependency added

       <dependency>
          <groupId>io.prometheus</groupId>
          <artifactId>simpleclient_spring_boot</artifactId>
          <version>0.16.0</version>
        </dependency>

The output I am checking in the browser where my application is up and running (not in Prometheus):

http_request_total{method="Post",status="200",api="newMail",component="mx",} 1.0
http_downstream_request_total{method="Post",status="200",api="newMail",component="mx",downstream="mwi",} 1.0

Issue:

Both metric names are getting an additional "_total" appended to it. I don't want this to be added by default. It should be same as the name I have put in the Utility class.

Both metrics have an open ',' or comma at the end. Ideally this should not be there. A metric does not have an open comma at the end. Not sure why it's adding this comma. I have specified the correct number of labels at the creation time of the counter and populating the labels correctly for incrementing. Not sure where this comma is coming from.

Please let me know how I could fix these issues.


问:
Could not load custom control library
I created a brand new Custom Control Library (WPF), and am trying to use it from another class library (not a WPF project). I get this error:

System.Windows.Markup.XamlParseException: 'Could not load file or
assembly 'CustomControls, PublicKeyToken=null' or one of its
dependencies. The system cannot find the file specified.'

From the XAML that is referencing the custom control library:

```<code><Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:myNamespace="clr-namespace:CustomControls;assembly=CustomControls"
    x:Class="MyCommandWindow.Ui"
    mc:Ignorable="d"
    Title="My Command" Height="710" Width="960" WindowStartupLocation="CenterScreen"
    Background="White"
    Foreground="Gray"
    FontSize="12"
    Name="CommandWindow" Loaded="CommandWindow_Loaded">
</code>```

The custom control library reference is added to the class library.
Am I missing any steps?

Title: Could not load custom control library

Body:
I created a brand new Custom Control Library (WPF), and am trying to use it from another class library (not a WPF project). I get this error:

System.Windows.Markup.XamlParseException: 'Could not load file or
assembly 'CustomControls, PublicKeyToken=null' or one of its
dependencies. The system cannot find the file specified.'

From the XAML that is referencing the custom control library:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:myNamespace="clr-namespace:CustomControls;assembly=CustomControls"
    x:Class="MyCommandWindow.Ui"
    mc:Ignorable="d"
    Title="My Command" Height="710" Width="960" WindowStartupLocation="CenterScreen"
    Background="White"
    Foreground="Gray"
    FontSize="12"
    Name="CommandWindow" Loaded="CommandWindow_Loaded">

The custom control library reference is added to the class library.
Am I missing any steps?


问:
HighCharts xAxis labels render incorrect format on wide screens, displaying date, Month format instead of Months
I believe HighCharts' default approach is to format the xAxis labels based on the available space. However, it causes the erroneous format to be rendered, displaying days and months instead of months. Is it possible to change this behavior?

I tried tickIntervals and afterSetExtremes to set tick intervals based on zoom in, but it still doesn't work.

My chart shows essentially a year's worth of hourly data. When the page loads, it should display months labels in the xAxis, then zoom in to see day and month labels, and then zoom out to see hours, day, and month format. This is how I defined my dateTimeFormat label.

```<code> dateTimeLabelFormats: {
        month: "%B",
        day: '%e %b',
        hour: '%H %e %b',

      }
</code>```

Body:
I believe HighCharts' default approach is to format the xAxis labels based on the available space. However, it causes the erroneous format to be rendered, displaying days and months instead of months. Is it possible to change this behavior?

I tried tickIntervals and afterSetExtremes to set tick intervals based on zoom in, but it still doesn't work.

My chart shows essentially a year's worth of hourly data. When the page loads, it should display months labels in the xAxis, then zoom in to see day and month labels, and then zoom out to see hours, day, and month format. This is how I defined my dateTimeFormat label.

 dateTimeLabelFormats: {
        month: "%B",
        day: '%e %b',
        hour: '%H %e %b',

      }


问:
Loading large JS object working in NodeJS but not in NextJS
In one NodeJS app I have a function that simply imports a large (140MB+) object from a JavaScript file, as so:

```<code>import bigObject from '../../../seeds/bigObject.js';

export default async function importObject() {

  // Get structural files (deep copy otherwise data persists)
  let seed = bigObject;
  let object = JSON.parse(JSON.stringify(seed));

   /* Process and modify object */

  return object
}
</code>```

This function is called seamlessly all over the backend with the following statements, without any error:

let object = await importObject()

However, in another app, from a NextJS backend, if I try to load this same object as such:

File 1:

```<code>import bigObject from "./bigObject"

export default async function importObject() {
    let seed = bigObject
    return seed
}
</code>```

File 2 (in /api folder):

```<code>import importObject from '../../objects/importObject'

export default async function handler(req, res) {
    const session = await getSession({ req });

    try {
        let object = await importObject()

        return res.status(200).json({ status: 'Successfully fetched object'})
    }
    catch{
        return res.status(401).json({ status: 'Error fetching object' })
    }
}
</code>```

The app just crashes and I get the following error:

<--- Last few GCs --->

[6450:0x5363870]   754725 ms: Mark-sweep (reduce) 2044.8 (2068.3) ->
2044.6 (2066.3) MB, 423.1 / 0.0 ms  (+ 15.2 ms in 8 steps since start of marking, biggest step 14.8 ms, walltime since start of marking 440
ms) (average mu = 0.231, current mu = 0.123) f[6450:0x5363870]

755180 ms: Mark-sweep 2045.8 (2066.3) -> 2045.5 (2070.3) MB, 452.5 /
0.0 ms  (average mu = 0.130, current mu = 0.004) allocation failure scavenge might not succeed

<--- JS stacktrace --->

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap
out of memory  1: 0xb09980 node::Abort() [node]  2: 0xa1c235
node::FatalError(char const*, char const*) [node]  3: 0xcf77be
v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool)
[node]  4: 0xcf7b37
v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char
const*, bool) [node]  5: 0xeaf3d5  [node]  6: 0xebf09d
v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace,
v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]  7:
0xec1d9e v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int,
v8::internal::AllocationType, v8::internal::AllocationOrigin,
v8::internal::AllocationAlignment) [node]  8: 0xe832da
v8::internal::Factory::NewFillerObject(int, bool,
v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]
9: 0x11fc026 v8::internal::Runtime_AllocateInYoungGeneration(int,
unsigned long*, v8::internal::Isolate*) [node] 10: 0x15f0a99  [node]
Aborted (core dumped)

At first I thought I was possibly loading this file into the client side, but considering the file placement in the project structure that wouldn't make sense.

Also, the object inside the file is a massive json array like this:

```<code>let JSONObj = [
    {
        /*Data*/
    }
]
export default JSONObj
</code>```

Body:
In one NodeJS app I have a function that simply imports a large (140MB+) object from a JavaScript file, as so:

import bigObject from '../../../seeds/bigObject.js';

export default async function importObject() {

  // Get structural files (deep copy otherwise data persists)
  let seed = bigObject;
  let object = JSON.parse(JSON.stringify(seed));

   /* Process and modify object */

  return object
}

This function is called seamlessly all over the backend with the following statements, without any error:

let object = await importObject()

However, in another app, from a NextJS backend, if I try to load this same object as such:

File 1:

import bigObject from "./bigObject"

export default async function importObject() {
    let seed = bigObject
    return seed
}

File 2 (in /api folder):

import importObject from '../../objects/importObject'

export default async function handler(req, res) {
    const session = await getSession({ req });

    try {
        let object = await importObject()

        return res.status(200).json({ status: 'Successfully fetched object'})
    }
    catch{
        return res.status(401).json({ status: 'Error fetching object' })
    }
}

The app just crashes and I get the following error:

<--- Last few GCs --->

[6450:0x5363870]   754725 ms: Mark-sweep (reduce) 2044.8 (2068.3) ->
2044.6 (2066.3) MB, 423.1 / 0.0 ms  (+ 15.2 ms in 8 steps since start of marking, biggest step 14.8 ms, walltime since start of marking 440
ms) (average mu = 0.231, current mu = 0.123) f[6450:0x5363870]

755180 ms: Mark-sweep 2045.8 (2066.3) -> 2045.5 (2070.3) MB, 452.5 /
0.0 ms  (average mu = 0.130, current mu = 0.004) allocation failure scavenge might not succeed

<--- JS stacktrace --->

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap
out of memory  1: 0xb09980 node::Abort() [node]  2: 0xa1c235
node::FatalError(char const*, char const*) [node]  3: 0xcf77be
v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool)
[node]  4: 0xcf7b37
v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char
const*, bool) [node]  5: 0xeaf3d5  [node]  6: 0xebf09d
v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace,
v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]  7:
0xec1d9e v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int,
v8::internal::AllocationType, v8::internal::AllocationOrigin,
v8::internal::AllocationAlignment) [node]  8: 0xe832da
v8::internal::Factory::NewFillerObject(int, bool,
v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]
9: 0x11fc026 v8::internal::Runtime_AllocateInYoungGeneration(int,
unsigned long*, v8::internal::Isolate*) [node] 10: 0x15f0a99  [node]
Aborted (core dumped)

At first I thought I was possibly loading this file into the client side, but considering the file placement in the project structure that wouldn't make sense.

Also, the object inside the file is a massive json array like this:

let JSONObj = [
    {
        /*Data*/
    }
]
export default JSONObj


问:
Python - how to slice a string with a fixed start index and a varying end index
These are the strings I'm slicing.

In the solution to this exercise, the programmer used positive and negative indices for slicing. I'd just like clarification about how the -26 index works in the solution (shared below).

Thank you!

```<code>counter_dict = {}
with open('Training_01.txt') as f:
    line = f.readline()
    while line:
        line = line[3:-26]
        if line in counter_dict:
            counter_dict[line] += 1
        else:
            counter_dict[line] = 1
        line = f.readline()

print(counter_dict)
</code>```

After seeing the solution, I modified my answer, but instead of complete categories, my solution gave me incomplete categories.

```<code>with open('Training_01.txt', 'r') as open_file:
    text = open_file.read()

new_page = text.split('\n')
categories = []
for category in new_page:
    category = category[3:-26]
    categories.append(category)
categories = set(categories)
print(len(categories))
for category in categories:
    print(category)
</code>```

Body:
These are the strings I'm slicing.

In the solution to this exercise, the programmer used positive and negative indices for slicing. I'd just like clarification about how the -26 index works in the solution (shared below).

Thank you!

counter_dict = {}
with open('Training_01.txt') as f:
    line = f.readline()
    while line:
        line = line[3:-26]
        if line in counter_dict:
            counter_dict[line] += 1
        else:
            counter_dict[line] = 1
        line = f.readline()

print(counter_dict)

After seeing the solution, I modified my answer, but instead of complete categories, my solution gave me incomplete categories.

with open('Training_01.txt', 'r') as open_file:
    text = open_file.read()

new_page = text.split('\n')
categories = []
for category in new_page:
    category = category[3:-26]
    categories.append(category)
categories = set(categories)
print(len(categories))
for category in categories:
    print(category)


问:
Dataset for weighted graph (Adjacency matrix) in the form of csv
Is there any python library / standard website where I can get a dataset of graphs which are stored in the form of adjacency matrix. For example, the columns of the csv sheet are in the form AA, AB, AC, AD, AE, .... , BA, BB, BC, BD, .... where the values in the AB columns denotes the weight of the edge AB in the graph.</p>


问:
Mapstruct only load lazy field if I need
I using GraphQL with Spring Boot and mapstruct.

The problem if when I do the DTO, MapStruct map all fields, including lazy fields that maybe I don't need because with GraphQL I don't request them.

They are any way to ignore field in runtime with Mapstruct?

Anything that:

fun toDto(user: User, fieldsToMap: List<String>): UserDTO
```


问:
Duplicate local variable driver error in eclipse
```<code>System.setProperty("webdriver.gecko.driver","C:\\Users\\Masooma\\Documents\\geckodriver-v0.32.0-win32.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://rahulshettyacademy.com/");
        System.out.println(driver.getTitle());
        System.out.println(driver.getCurrentUrl());
        driver.close();

</code>```

Why it's showing me an error WebDriver driver = new FirefoxDriver(); in this line

I do not know how to change the variable and run the script.

Body:
System.setProperty("webdriver.gecko.driver","C:\\Users\\Masooma\\Documents\\geckodriver-v0.32.0-win32.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://rahulshettyacademy.com/");
        System.out.println(driver.getTitle());
        System.out.println(driver.getCurrentUrl());
        driver.close();

Why it's showing me an error WebDriver driver = new FirefoxDriver(); in this line

I do not know how to change the variable and run the script.


问:
Execution "QueryAsync<T>" method by reflection in C#
Is there a possibility to call the "QueryAsync" method by reflection? As ?

I Have.

```<code>        {

            var query = string.Format(query, domain.GetColumns(), domain.GetTableName()); // here return "SELECT Columns from TableName"

            var command = new CommandDefinition(commandText: query,
                                                commandTimeout: TimeSpan.FromSeconds(5).Seconds,
                                                commandType: CommandType.Text,
                                                flags: CommandFlags.None,
                                                cancellationToken: cancellationToken);

            var response = await connection.QueryAsync<TModel>(command).ConfigureAwait(false); // Return IEnumerable<DapperRow> and not IEnumerable<TModel>

            return response;
        } ```

Can someone help me?

```

Body:
Is there a possibility to call the "QueryAsync" method by reflection? As ?

I Have.

        {

            var query = string.Format(query, domain.GetColumns(), domain.GetTableName()); // here return "SELECT Columns from TableName"

            var command = new CommandDefinition(commandText: query,
                                                commandTimeout: TimeSpan.FromSeconds(5).Seconds,
                                                commandType: CommandType.Text,
                                                flags: CommandFlags.None,
                                                cancellationToken: cancellationToken);

            var response = await connection.QueryAsync<TModel>(command).ConfigureAwait(false); // Return IEnumerable<DapperRow> and not IEnumerable<TModel>

            return response;
        } ```

Can someone help me?


问:
How to manually authenticate keycloack user when execute a scheduled job in springboot application
I have a REST API springboot application that uses keycloack as authentication.
All work fine with authentication and autorization.

Now I have to schedule some jobs that will have to use resource services. The execution of these services is bound by the fact that there is an authenticated keycloack user and that he has an 'admin' role.

This is how I check if user is authorized:

```<code>Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
KeycloakPrincipal<?> userDetails = (KeycloakPrincipal<?>) authentication.getPrincipal();
AccessToken accessToken = userDetails.getKeycloakSecurityContext().getToken();
AccessToken.Access resourceAccess = accessToken.getResourceAccess(env.getProperty("keycloak.resource"));
roles = resourceAccess.getRoles();
boolean isAuthorized = userRoles.contains('admin')
</code>```

How can I set my admin user in the SecurityContextHolder?

Body:
I have a REST API springboot application that uses keycloack as authentication.
All work fine with authentication and autorization.

Now I have to schedule some jobs that will have to use resource services. The execution of these services is bound by the fact that there is an authenticated keycloack user and that he has an 'admin' role.

This is how I check if user is authorized:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
KeycloakPrincipal<?> userDetails = (KeycloakPrincipal<?>) authentication.getPrincipal();
AccessToken accessToken = userDetails.getKeycloakSecurityContext().getToken();
AccessToken.Access resourceAccess = accessToken.getResourceAccess(env.getProperty("keycloak.resource"));
roles = resourceAccess.getRoles();
boolean isAuthorized = userRoles.contains('admin')

How can I set my admin user in the SecurityContextHolder?


问:
TF model downloaded from kaggle not working properly in local machine
I am training this neural network on a kaggle notebook (limiting the epochs to 40 for memory issues).

The callback

```<code>callbacks = [
    keras.callbacks.ModelCheckpoint("oxford_segmentation.keras",
                                    save_best_only=True)
]

history = model.fit(train_input_imgs, train_targets,
                    epochs=50,
                    callbacks=callbacks,
                    batch_size=64,
                    validation_data=(val_input_imgs, val_targets))
</code>```

saves the best model to file.

After training, if I load the model back on the kaggle notebook with:

```<code>loaded_model = keras.models.load_model("oxford_segmentation.keras")
</code>```

everything works fine. However, if the notebook is restarted for some reason, the model is not saved and I have to train again from scratch and, as far as I know of, there is no straightforward method to download the file from the kaggle notebook to my local machine.

I came across this method to download it a file from kaggle:

```<code>from IPython.display import FileLink
FileLink("oxford_segmentation.keras")
</code>```

which generates a link for downloading.

However, after downloading the file to my local machine, when I load it back in my local jupyter notebook, the model does not seem to work: the evaluation on validation data gives a loss of 5, while the reloaded model on kaggle I get around 0.4, which is comparable to the training val_loss.

Furthermore, when plotting a prediction with the following code:

```<code>from tensorflow.keras.utils import array_to_img
# if the above is not working use
#from keras.preprocessing.image import array_to_img

model = keras.models.load_model("oxford_segmentation.keras")
model.evaluate(val_input_imgs, val_targets)

i = 25
test_image = val_input_imgs[i]
plt.axis("off")
plt.imshow(array_to_img(test_image))

mask = model.predict(np.expand_dims(test_image, 0))[0]

def display_mask(pred):
    #print(pred.size, pred)
    mask = np.argmax(pred, axis=-1)
    mask *= 127
    plt.axis("off")
    print(mask, mask.size)
    plt.imshow(mask)

display_mask(mask)
</code>```

in kaggle I get a reasonable mask image, in my local notebook I get only a black mask.

Can I use FileLink to download keras models? If not I can I download the model to my local machine?
When downdloading the model history, everything worked fine.

Body:
I am training this neural network on a kaggle notebook (limiting the epochs to 40 for memory issues).

The callback

callbacks = [
    keras.callbacks.ModelCheckpoint("oxford_segmentation.keras",
                                    save_best_only=True)
]

history = model.fit(train_input_imgs, train_targets,
                    epochs=50,
                    callbacks=callbacks,
                    batch_size=64,
                    validation_data=(val_input_imgs, val_targets))

saves the best model to file.

After training, if I load the model back on the kaggle notebook with:

loaded_model = keras.models.load_model("oxford_segmentation.keras")

everything works fine. However, if the notebook is restarted for some reason, the model is not saved and I have to train again from scratch and, as far as I know of, there is no straightforward method to download the file from the kaggle notebook to my local machine.

I came across this method to download it a file from kaggle:

from IPython.display import FileLink
FileLink("oxford_segmentation.keras")

which generates a link for downloading.

However, after downloading the file to my local machine, when I load it back in my local jupyter notebook, the model does not seem to work: the evaluation on validation data gives a loss of 5, while the reloaded model on kaggle I get around 0.4, which is comparable to the training val_loss.

Furthermore, when plotting a prediction with the following code:

from tensorflow.keras.utils import array_to_img
# if the above is not working use
#from keras.preprocessing.image import array_to_img

model = keras.models.load_model("oxford_segmentation.keras")
model.evaluate(val_input_imgs, val_targets)

i = 25
test_image = val_input_imgs[i]
plt.axis("off")
plt.imshow(array_to_img(test_image))

mask = model.predict(np.expand_dims(test_image, 0))[0]

def display_mask(pred):
    #print(pred.size, pred)
    mask = np.argmax(pred, axis=-1)
    mask *= 127
    plt.axis("off")
    print(mask, mask.size)
    plt.imshow(mask)

display_mask(mask)

in kaggle I get a reasonable mask image, in my local notebook I get only a black mask.

Can I use FileLink to download keras models? If not I can I download the model to my local machine?
When downdloading the model history, everything worked fine.


问:
my code is only drawing a straight line no matter how many sides i input in the pSides JTextFields
When I input a digit in the JTextfields it should pass through my actionListener to store all the values (ID, number of sides, length of sides and color) into an arraylist. It should then be used in my polygonContainer class that goes through a for loop and a polygon formula, then prints it out. However what comes out all the time is a straight line.

This is the code i tried:

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class ContainerFrame extends JFrame{

    ArrayList<PolygonContainer> polygons = new ArrayList<>();

    // JTextFields for the number of sides, side length, color, and ID
    public JTextField pSides, pSidesLengths, pColor, pID;

    // Button for submission
    public JButton submitButton;

    public void createComponents() {

        // Initialize the JTextFields
        pSides = new JTextField();
        pSidesLengths = new JTextField();
        pColor = new JTextField();
        pID = new JTextField();

        submitButton = new JButton("Submit");
        submitButton.addActionListener(new ContainerButtonHandler(this));

        JPanel textFieldsPanel = new JPanel();

        // uses a gridlayout to organise the textfields then sets it as north
        textFieldsPanel.setLayout(new GridLayout(5, 2));
        textFieldsPanel.add(new JLabel("Sides:"));
        textFieldsPanel.add(pSides);
        textFieldsPanel.add(new JLabel("Sides Length:"));
        textFieldsPanel.add(pSidesLengths);
        textFieldsPanel.add(new JLabel("Color:"));
        textFieldsPanel.add(pColor);
        textFieldsPanel.add(new JLabel("ID:"));
        textFieldsPanel.add(pID);
        add(textFieldsPanel, BorderLayout.NORTH);

        add(submitButton, BorderLayout.SOUTH);

        JPanel drawPanel = new ContainerPanel(this);
        add(drawPanel, BorderLayout.CENTER);

        setSize(1600, 900);
        setVisible(true);
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );  // Close action.
    }

    public static void main(String[] args) {

        ContainerFrame cFrame = new ContainerFrame();
        cFrame.createComponents();

    }

}

```
<pre class="lang-java prettyprint-override"><code>import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

class ContainerButtonHandler implements ActionListener {
    ContainerFrame theApp;   // Reference to ContainerFrame object

    // ButtonHandler constructor
    ContainerButtonHandler(ContainerFrame app) {
        theApp = app;
    }

    public void actionPerformed(ActionEvent e) {
        // Get the text from the JTextFields using the getText method
        String sides = theApp.pSides.getText();
        String sidesLengths = theApp.pSidesLengths.getText();
        String id = theApp.pID.getText();

        //parse the values as integers
        int intSides = Integer.parseInt(sides);
        int intSidesLength = Integer.parseInt(sidesLengths);
        int intId = Integer.parseInt(id);

        //does the input validation where sides, sides length and id needs to be positive integers
        if (intId >= 100000 && intId <= 999999 && intSides >= 0 && intSidesLength >= 0) {

            // The inputs are valid
            String color = theApp.pColor.getText();

            // Store the values in an arraylist or other data structure
            ArrayList<String> polygonArray = new ArrayList<String>();
            polygonArray.add(sides);
            polygonArray.add(sidesLengths);
            polygonArray.add(color);
            polygonArray.add(id);

            PolygonContainer polygon = new PolygonContainer(polygonArray);

            theApp.polygons.add(polygon);

            theApp.repaint();

            JOptionPane.showMessageDialog(theApp, "Polygon" + id + "was added to the list.", "Success", JOptionPane.INFORMATION_MESSAGE);

        } else {
            JOptionPane.showMessageDialog(theApp, "The Polygon" + id + "was not added to the list as a valid Id was not provided.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}

</code>```

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class PolygonContainer implements Comparable<PolygonContainer>{

    Color pColor = Color.BLACK; // Colour of the polygon, set to a Colour object, default set to black
    int pId = 000000;    // Polygon ID should be a six digit non-negative integer
    int pSides;         // Number of sides of the polygon, should be non-negative value
    int pSideLengths;   // Length of each side in pixels of the polygon, should be non-negative value
    int polyCenX;    // x value of centre point (pixel) of polygon when drawn on the panel
    int polyCenY;    // y value of centre point (pixel of polygon when drawn on the panel
    int [] pointsX;  // int array containing x values of each vertex (corner point) of the polygon
    int [] pointsY;  // int array containing y values of each vertex (corner point) of the polygon

    // Constructor currently set the number of sides and the equal length of each side of the Polygon

    //Constructor that takes the values from the array
    public PolygonContainer(ArrayList<String> values){
        this.pSides = Integer.parseInt(values.get(0));
        this.pSideLengths = Integer.parseInt(values.get(1));
        this.pColor = Color.getColor(values.get(2));
        this.pId = Integer.parseInt(values.get(3));

        pointsX = new int[pSides];
        pointsY = new int[pSides];
    }

    // Used to populate the points array with the vertices corners (points) and construct a polygon with the
    // number of sides defined by pSides and the length of each side defined by pSideLength.
    // Dimension object that is passed in as an argument is used to get the width and height of the ContainerPanel
    // and used to determine the x and y values of its centre point that will be used to position the drawn Polygon.
    public Polygon getPolygonPoints(Dimension dim) {

        polyCenX = dim.width / 2;          // x value of centre point of the polygon
        polyCenY = dim.height / 2;         // y value of centre point of the polygon

        Polygon p = new Polygon();

        for (int i = 0; i < pSides; i++) {
            // Calculate the x and y coordinates of the ith point of the polygon
            int x = polyCenX + pSideLengths * (int) Math.cos(2.0 * Math.PI * i / pSides);
            int y = polyCenY + pSideLengths * (int) Math.sin(2.0 * Math.PI * i / pSides);

            // Add the x and y coordinates to the pointsX and pointsY arrays
            pointsX[i] = x;
            pointsY[i] = y;

            // Add the point to the polygon object using the addPoint method
            p.addPoint(x, y);

        }

        return p;
    }

    // You will need to modify this method to set the colour of the Polygon to be drawn
    // Remember that Graphics2D has a setColor() method available for this purpose
    public void drawPolygon(Graphics2D g, Dimension d) {

        //Set color of polygon
        g.setColor(pColor);

        Polygon p = getPolygonPoints(d);

        g.draw(p);

        //this creates a bounding box around the polygon
        Rectangle2D bounds = p.getBounds2D();
        g.draw(bounds);

    }

    // gets a stored ID
    public int getID() {
        return pId;
    }

    @Override
    // method used for comparing PolygonContainer objects based on stored ids, you need to complete the method
    public int compareTo(PolygonContainer o) {

        return 0;
    }

    // outputs a string representation of the PolygonContainer object, you need to complete this to use for testing
    public String toString()
    {
        return "";
    }
}

```
<pre class="lang-java prettyprint-override"><code>import javax.swing.JPanel;
import java.awt.*;

public class ContainerPanel extends JPanel{

    ContainerFrame conFrame;

    public ContainerPanel(ContainerFrame cf) {

        conFrame = cf;   // reference to ContainerFrame object

    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D comp = (Graphics2D)g;   // You will need to use a Graphics2D objects for this
        Dimension size = getSize();        // You will need to use this Dimension object to get
                                           // the width / height of the JPanel in which the
                                           // Polygon is going to be drawn

        for (PolygonContainer polygon : conFrame.polygons) {
            polygon.drawPolygon(comp, size);
        }

    }

}

</code>```

JFrame

Body:
When I input a digit in the JTextfields it should pass through my actionListener to store all the values (ID, number of sides, length of sides and color) into an arraylist. It should then be used in my polygonContainer class that goes through a for loop and a polygon formula, then prints it out. However what comes out all the time is a straight line.

This is the code i tried:

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class ContainerFrame extends JFrame{

    ArrayList<PolygonContainer> polygons = new ArrayList<>();

    // JTextFields for the number of sides, side length, color, and ID
    public JTextField pSides, pSidesLengths, pColor, pID;

    // Button for submission
    public JButton submitButton;

    public void createComponents() {

        // Initialize the JTextFields
        pSides = new JTextField();
        pSidesLengths = new JTextField();
        pColor = new JTextField();
        pID = new JTextField();

        submitButton = new JButton("Submit");
        submitButton.addActionListener(new ContainerButtonHandler(this));

        JPanel textFieldsPanel = new JPanel();

        // uses a gridlayout to organise the textfields then sets it as north
        textFieldsPanel.setLayout(new GridLayout(5, 2));
        textFieldsPanel.add(new JLabel("Sides:"));
        textFieldsPanel.add(pSides);
        textFieldsPanel.add(new JLabel("Sides Length:"));
        textFieldsPanel.add(pSidesLengths);
        textFieldsPanel.add(new JLabel("Color:"));
        textFieldsPanel.add(pColor);
        textFieldsPanel.add(new JLabel("ID:"));
        textFieldsPanel.add(pID);
        add(textFieldsPanel, BorderLayout.NORTH);

        add(submitButton, BorderLayout.SOUTH);

        JPanel drawPanel = new ContainerPanel(this);
        add(drawPanel, BorderLayout.CENTER);

        setSize(1600, 900);
        setVisible(true);
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );  // Close action.
    }

    public static void main(String[] args) {

        ContainerFrame cFrame = new ContainerFrame();
        cFrame.createComponents();

    }

}

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

class ContainerButtonHandler implements ActionListener {
    ContainerFrame theApp;   // Reference to ContainerFrame object

    // ButtonHandler constructor
    ContainerButtonHandler(ContainerFrame app) {
        theApp = app;
    }

    public void actionPerformed(ActionEvent e) {
        // Get the text from the JTextFields using the getText method
        String sides = theApp.pSides.getText();
        String sidesLengths = theApp.pSidesLengths.getText();
        String id = theApp.pID.getText();

        //parse the values as integers
        int intSides = Integer.parseInt(sides);
        int intSidesLength = Integer.parseInt(sidesLengths);
        int intId = Integer.parseInt(id);

        //does the input validation where sides, sides length and id needs to be positive integers
        if (intId >= 100000 && intId <= 999999 && intSides >= 0 && intSidesLength >= 0) {

            // The inputs are valid
            String color = theApp.pColor.getText();

            // Store the values in an arraylist or other data structure
            ArrayList<String> polygonArray = new ArrayList<String>();
            polygonArray.add(sides);
            polygonArray.add(sidesLengths);
            polygonArray.add(color);
            polygonArray.add(id);

            PolygonContainer polygon = new PolygonContainer(polygonArray);

            theApp.polygons.add(polygon);

            theApp.repaint();

            JOptionPane.showMessageDialog(theApp, "Polygon" + id + "was added to the list.", "Success", JOptionPane.INFORMATION_MESSAGE);

        } else {
            JOptionPane.showMessageDialog(theApp, "The Polygon" + id + "was not added to the list as a valid Id was not provided.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class PolygonContainer implements Comparable<PolygonContainer>{

    Color pColor = Color.BLACK; // Colour of the polygon, set to a Colour object, default set to black
    int pId = 000000;    // Polygon ID should be a six digit non-negative integer
    int pSides;         // Number of sides of the polygon, should be non-negative value
    int pSideLengths;   // Length of each side in pixels of the polygon, should be non-negative value
    int polyCenX;    // x value of centre point (pixel) of polygon when drawn on the panel
    int polyCenY;    // y value of centre point (pixel of polygon when drawn on the panel
    int [] pointsX;  // int array containing x values of each vertex (corner point) of the polygon
    int [] pointsY;  // int array containing y values of each vertex (corner point) of the polygon

    // Constructor currently set the number of sides and the equal length of each side of the Polygon

    //Constructor that takes the values from the array
    public PolygonContainer(ArrayList<String> values){
        this.pSides = Integer.parseInt(values.get(0));
        this.pSideLengths = Integer.parseInt(values.get(1));
        this.pColor = Color.getColor(values.get(2));
        this.pId = Integer.parseInt(values.get(3));

        pointsX = new int[pSides];
        pointsY = new int[pSides];
    }

    // Used to populate the points array with the vertices corners (points) and construct a polygon with the
    // number of sides defined by pSides and the length of each side defined by pSideLength.
    // Dimension object that is passed in as an argument is used to get the width and height of the ContainerPanel
    // and used to determine the x and y values of its centre point that will be used to position the drawn Polygon.
    public Polygon getPolygonPoints(Dimension dim) {

        polyCenX = dim.width / 2;          // x value of centre point of the polygon
        polyCenY = dim.height / 2;         // y value of centre point of the polygon

        Polygon p = new Polygon();

        for (int i = 0; i < pSides; i++) {
            // Calculate the x and y coordinates of the ith point of the polygon
            int x = polyCenX + pSideLengths * (int) Math.cos(2.0 * Math.PI * i / pSides);
            int y = polyCenY + pSideLengths * (int) Math.sin(2.0 * Math.PI * i / pSides);

            // Add the x and y coordinates to the pointsX and pointsY arrays
            pointsX[i] = x;
            pointsY[i] = y;

            // Add the point to the polygon object using the addPoint method
            p.addPoint(x, y);

        }

        return p;
    }

    // You will need to modify this method to set the colour of the Polygon to be drawn
    // Remember that Graphics2D has a setColor() method available for this purpose
    public void drawPolygon(Graphics2D g, Dimension d) {

        //Set color of polygon
        g.setColor(pColor);

        Polygon p = getPolygonPoints(d);

        g.draw(p);

        //this creates a bounding box around the polygon
        Rectangle2D bounds = p.getBounds2D();
        g.draw(bounds);

    }

    // gets a stored ID
    public int getID() {
        return pId;
    }

    @Override
    // method used for comparing PolygonContainer objects based on stored ids, you need to complete the method
    public int compareTo(PolygonContainer o) {

        return 0;
    }

    // outputs a string representation of the PolygonContainer object, you need to complete this to use for testing
    public String toString()
    {
        return "";
    }
}

import javax.swing.JPanel;
import java.awt.*;

public class ContainerPanel extends JPanel{

    ContainerFrame conFrame;

    public ContainerPanel(ContainerFrame cf) {

        conFrame = cf;   // reference to ContainerFrame object

    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D comp = (Graphics2D)g;   // You will need to use a Graphics2D objects for this
        Dimension size = getSize();        // You will need to use this Dimension object to get
                                           // the width / height of the JPanel in which the
                                           // Polygon is going to be drawn

        for (PolygonContainer polygon : conFrame.polygons) {
            polygon.drawPolygon(comp, size);
        }

    }

}

JFrame