问:
Difflib.get_close_matches() like weighted match finder
My use case is something like a auto-correction. User enters a string and gets the corrected string. For example Hose -> House. However, user's input can be two words.

Therefore, I sometimes have the case that the user inputs something like Artificial looking for Artifical Intelligence, but receives Artifungal (just to make up an example).

I am looking for a function like difflib.get_close_matches() but that's trying to match against the parts of a string instead of matching against the whole string. I.e. matching a word in the string 0.9 and one 0 should be valued more than matching both strings 0.45 (simplified).

I attempted cutting the every possibility in possibilities to input length, but of course this doesn't work perfectly as it only helps if the second word is omitted by the user, but worsen results if the first word is omitted.


来源: stackexchange

问:
jsonDecode error in flutter | expected a value of type 'String', but got one of type '_JsonMap'
I am having an issue with decoding my api response, searched and tried different solutions but none worked.

```<code>Future<Artwork> getArtwork() async {

  const urlApi =
      'http://localhost:6060/getartwork?RequestID=t26ypmg55';

  var dio = Dio();
  var response = await dio.get(urlApi);

  if (response.statusCode == 200) {
    //final json = "[ ${response.data} ]";
    final map = jsonDecode(response.data)  as Map<String, dynamic>;
    return Artwork.fromJson(map);
  } else {
    log("Exception Section");
    throw Exception(response.data);
  }
}
</code>```

there is also factory code for the struct

```<code>factory Artwork.fromJson(Map<String, dynamic> json) {
    return Artwork(
      id: json['id'],
      imageUrl: json['imageUrl'],
....
</code>```

error:

```<code>Error: Expected a value of type 'String', but got one of type '_JsonMap'
</code>```

when I debug, this is what I see as the response.data

```<code>_JsonMap ({Id: 123456, ImageUrl: ohO0P8VXzfzDMCk6ZYJP6jAQEF9EEdkzQjKTeoPbttUHbrGQA/out-0.png, CampaignId: campaign155faghf, CreatedTime: 2022-12-04 20:36:11.335297 +0000 UTC, CompleteTime: 2022-12-04 20:36:23.934309 +0000 UTC, ImageList: [/ohO0P8VXzfzDMCk6ZYJP6jAQEF9EEdkzQjKTeoPbttUHbrGQA/out-0.png] })
</code>```

the error message is not clear;
https://github.com/dart-lang/sdk/issues/41174

None of the below worked;

using http.StreamedRequest

using request.sink

wrapping the json with [ ] as suggested by another post.

ContentLicense: CC BY-SA 4.0

Body:
I am having an issue with decoding my api response, searched and tried different solutions but none worked.

Future<Artwork> getArtwork() async {

  const urlApi =
      'http://localhost:6060/getartwork?RequestID=t26ypmg55';

  var dio = Dio();
  var response = await dio.get(urlApi);

  if (response.statusCode == 200) {
    //final json = "[ ${response.data} ]";
    final map = jsonDecode(response.data)  as Map<String, dynamic>;
    return Artwork.fromJson(map);
  } else {
    log("Exception Section");
    throw Exception(response.data);
  }
}

there is also factory code for the struct

factory Artwork.fromJson(Map<String, dynamic> json) {
    return Artwork(
      id: json['id'],
      imageUrl: json['imageUrl'],
....

error:

Error: Expected a value of type 'String', but got one of type '_JsonMap'

when I debug, this is what I see as the response.data

_JsonMap ({Id: 123456, ImageUrl: ohO0P8VXzfzDMCk6ZYJP6jAQEF9EEdkzQjKTeoPbttUHbrGQA/out-0.png, CampaignId: campaign155faghf, CreatedTime: 2022-12-04 20:36:11.335297 +0000 UTC, CompleteTime: 2022-12-04 20:36:23.934309 +0000 UTC, ImageList: [/ohO0P8VXzfzDMCk6ZYJP6jAQEF9EEdkzQjKTeoPbttUHbrGQA/out-0.png] })

the error message is not clear;
https://github.com/dart-lang/sdk/issues/41174

None of the below worked;

using http.StreamedRequest

using request.sink

wrapping the json with [ ] as suggested by another post.


问:
python collectstatic commad is not ran in Docker compose and gitlab
I am trying to run python manage.py collectstatic , in docker but nothing works, my python project misses some icons, and this command will solve the issue, but I can't know where to place the command, I have read several questions here but no luck.

Below is my docker-compose.ci.stag.yml file:

version: "3.7"

```<code>services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.staging
      cache_from:
        - gingregisr*ty.azurecr.io/guio-tag:tag
    image: gingregisrty.azurecr.io/guio-tag:tag
    expose:
      - 7000
    env_file: .env
</code>```

Then my docker-compose.staging.yml file :

```<code>version: '3.5'
# sudo docker login -p <password> -u <username>
services:
  api:
    container_name: api
    image: gingregisrty.azurecr.io/guio-tag:tag
    ports:
      - 7000:7000
    restart: unless-stopped
    env_file:
      - .env
    networks:
      - app-network

  watchtower:
    image: containrrr/watchtower
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /root/.docker/config.json:/config.json
    command: --interval 30
    environment:
      - WATCHTOWER_CLEANUP=true
    networks:
      - app-network

  nginx-proxy:
    container_name: nginx-proxy
    image: jwilder/nginx-proxy:0.9
    restart: always
    ports:
      - 443:443
      - 90:90
    volumes:
      - certs:/etc/nginx/certs
      - html:/usr/share/nginx/html
      - vhost:/etc/nginx/vhost.d
      - /var/run/docker.sock:/tmp/docker.sock:ro
    depends_on:
      - api
    networks:
      - app-network

  nginx-proxy-letsencrypt:
    image: jrcs/letsencrypt-nginx-proxy-companion
    env_file:
      - .env.prod.proxy-companion
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - certs:/etc/nginx/certs
      - html:/usr/share/nginx/html
      - vhost:/etc/nginx/vhost.d
      - acme:/etc/acme.sh
    depends_on:
      - nginx-proxy
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  certs:
  html:
  vhost:
  acme:
</code>```

then my Docker.staging file :

```<code># ./django-docker/app/Dockerfile
FROM python:3.7.5-buster

# set work directory
WORKDIR /opt/app

# Add current directory code to working directory
ADD . /opt/app/

# set environment variables

# Prevents Python from writing pyc files to disc.
ENV PYTHONDONTWRITEBYTECODE 1
# Prevents Python from buffering stdout and stderr.
ENV PYTHONUNBUFFERED 1

# Copy firebase file
# COPY afro-mobile-test-firebase-adminsdk-cspoa.json

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    tzdata \
    python3-setuptools \
    python3-pip \
    python3-dev \
    python3-venv \
    git \
    && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# install environment dependencies
RUN pip3 install --upgrade pip

# Install project dependencies
RUN pip3 install -r requirements.txt

EXPOSE 7000

# copy project
COPY . /opt/app/

CMD ["bash", "start-app.sh"]

</code>```

then my start-app.sh file :

```<code>#Run migrations
python manage.py migrate

#run tests
# python manage.py test

# run collect statics
python manage.py collectstatic

echo 'COLLECT STAIIC DONE ********'

echo $PORT
# Start server
# python manage.py runserver 0.0.0.0:$PORT
gunicorn server.wsgi:application --bind 0.0.0.0:$PORT

</code>```

Am using gitlab ci to automate the pipeline, so here is my gitlab.yml build script:

```<code># Build and Deploy to Azure.
build-dev:
  stage: build
  before_script:
    - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME
  script:
    - apk add --no-cache bash
    - chmod +x ./setup_env.sh
    - bash ./setup_env.sh
    - docker login $AZ_REGISTRY_IMAGE -u $AZ_USERNAME_REGISTRY -p $AZ_PASSWORD_REGISTRY
    - docker pull $AZ_REGISTRY_IMAGE/guio-tag:tag || true
    - docker-compose -f docker-compose.ci.stag.yml build
    - docker push $AZ_REGISTRY_IMAGE/guio-tag:tag
  only:
    - develop
    - test-branch
</code>```

The build runs successfully, but am sure python manage.py collectstatic is not ran, how best can I do this ?

Body:
I am trying to run python manage.py collectstatic , in docker but nothing works, my python project misses some icons, and this command will solve the issue, but I can't know where to place the command, I have read several questions here but no luck.

Below is my docker-compose.ci.stag.yml file:

version: "3.7"

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.staging
      cache_from:
        - gingregisr*ty.azurecr.io/guio-tag:tag
    image: gingregisrty.azurecr.io/guio-tag:tag
    expose:
      - 7000
    env_file: .env

Then my docker-compose.staging.yml file :

version: '3.5'
# sudo docker login -p <password> -u <username>
services:
  api:
    container_name: api
    image: gingregisrty.azurecr.io/guio-tag:tag
    ports:
      - 7000:7000
    restart: unless-stopped
    env_file:
      - .env
    networks:
      - app-network

  watchtower:
    image: containrrr/watchtower
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /root/.docker/config.json:/config.json
    command: --interval 30
    environment:
      - WATCHTOWER_CLEANUP=true
    networks:
      - app-network

  nginx-proxy:
    container_name: nginx-proxy
    image: jwilder/nginx-proxy:0.9
    restart: always
    ports:
      - 443:443
      - 90:90
    volumes:
      - certs:/etc/nginx/certs
      - html:/usr/share/nginx/html
      - vhost:/etc/nginx/vhost.d
      - /var/run/docker.sock:/tmp/docker.sock:ro
    depends_on:
      - api
    networks:
      - app-network

  nginx-proxy-letsencrypt:
    image: jrcs/letsencrypt-nginx-proxy-companion
    env_file:
      - .env.prod.proxy-companion
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - certs:/etc/nginx/certs
      - html:/usr/share/nginx/html
      - vhost:/etc/nginx/vhost.d
      - acme:/etc/acme.sh
    depends_on:
      - nginx-proxy
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  certs:
  html:
  vhost:
  acme:

then my Docker.staging file :

# ./django-docker/app/Dockerfile
FROM python:3.7.5-buster

# set work directory
WORKDIR /opt/app

# Add current directory code to working directory
ADD . /opt/app/

# set environment variables

# Prevents Python from writing pyc files to disc.
ENV PYTHONDONTWRITEBYTECODE 1
# Prevents Python from buffering stdout and stderr.
ENV PYTHONUNBUFFERED 1

# Copy firebase file
# COPY afro-mobile-test-firebase-adminsdk-cspoa.json

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    tzdata \
    python3-setuptools \
    python3-pip \
    python3-dev \
    python3-venv \
    git \
    && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# install environment dependencies
RUN pip3 install --upgrade pip

# Install project dependencies
RUN pip3 install -r requirements.txt

EXPOSE 7000

# copy project
COPY . /opt/app/

CMD ["bash", "start-app.sh"]

then my start-app.sh file :

#Run migrations
python manage.py migrate

#run tests
# python manage.py test

# run collect statics
python manage.py collectstatic

echo 'COLLECT STAIIC DONE ********'

echo $PORT
# Start server
# python manage.py runserver 0.0.0.0:$PORT
gunicorn server.wsgi:application --bind 0.0.0.0:$PORT

Am using gitlab ci to automate the pipeline, so here is my gitlab.yml build script:

# Build and Deploy to Azure.
build-dev:
  stage: build
  before_script:
    - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME
  script:
    - apk add --no-cache bash
    - chmod +x ./setup_env.sh
    - bash ./setup_env.sh
    - docker login $AZ_REGISTRY_IMAGE -u $AZ_USERNAME_REGISTRY -p $AZ_PASSWORD_REGISTRY
    - docker pull $AZ_REGISTRY_IMAGE/guio-tag:tag || true
    - docker-compose -f docker-compose.ci.stag.yml build
    - docker push $AZ_REGISTRY_IMAGE/guio-tag:tag
  only:
    - develop
    - test-branch

The build runs successfully, but am sure python manage.py collectstatic is not ran, how best can I do this ?


问:
C# Embedd A Non-Winforms Application into a Winform Application
I want to embedd an application (Hikvision iVMS-4200) into my winform .net application. The application appears to use custom rendering for its GUI, and a loading screen appears before the main window is launched.

In more detail, I want the window of this app to be confined within the window area of my application in a locked position (user can't move the embedded window), and display other things in the same parent window (for example a picture).

I have tried solutions such as this. It worked perfectly, but only with notepad. This solution doesn't work with the application I want (the process is opened successfuly but it is in a completely independant window).

My guess is that the app (again, Hikvision iVMS-4200) uses OpenGL for a custom GUI or another type of non-native GUI library. As a though, shouldn't any application on windows have atleast a single main window? could I access and edit its position and parenting properties? Any solution would be highly appreciated.


问:
Why do I have different shell commands available to me in terminal vs xcode?
When I run swiftgen in Terminal the command is recognized. When a script in a xcode build runs swiftgen it says command not found. How are the two environments different, and how can I get them in sync?

I tried different shells in both and they always worked in Terminal but not in xcode.


问:
Error: "NameError: name 'self' is not defined" when using exec() to create several buttons in tkinter
I am trying to create a GUI for a cribbage program that I made a while back. I want to fan the cards out at the beginning so the player can select where they would like to cut the deck. To avoid individually declaring and packing 52 different frames and buttons manually, I used a for loop and the exec() method to create each button and frame and also pass an integer into the method in the command= parameter of the buttons. It works as intended to create all of the buttons, but when I click on one of the cards, the NameError is raised.

```<code>def cut(self, i):
    self.select_card_frame.place_forget()
    for k in range(52):
        exec(f'self.cut_frame_{k}.place_forget()')
    return i

def start_cut(self):
    global cut_image
    cut_image = self.resize_card('cards/back_of_card.png')
    self.select_card_frame = Frame(self.window)
    self.select_card_label = Label(self.select_card_frame, text='Select Card to Cut', font=20)
    self.select_card_label.pack()
    self.select_card_frame.place(x=450, y=50)
    for i in range(52):
        exec(f'self.cut_frame_{i} = Frame(self.window)')
        exec(f'self.cut_label_{i} = Button(self.cut_frame_{i}, image=cut_image, command=lambda: self.cut({i}))')
        exec(f"self.cut_label_{i}.pack(side='left')")
        exec(f'self.cut_frame_{i}.place(x={i*20}, y=100)')
</code>```

I have tried making a few of the card buttons individually and it worked as it should, so I suspect it is something that I am doing wrong with the exec() method. Any ideas on what I am doing wrong? or is there a better way to do this without using exec()? or do I just have to suck it up and type out the extra 300 lines of code? This is what the window looks like for a better picture of what I am trying to do.
Deck fanned out for cut

Body:
I am trying to create a GUI for a cribbage program that I made a while back. I want to fan the cards out at the beginning so the player can select where they would like to cut the deck. To avoid individually declaring and packing 52 different frames and buttons manually, I used a for loop and the exec() method to create each button and frame and also pass an integer into the method in the command= parameter of the buttons. It works as intended to create all of the buttons, but when I click on one of the cards, the NameError is raised.

def cut(self, i):
    self.select_card_frame.place_forget()
    for k in range(52):
        exec(f'self.cut_frame_{k}.place_forget()')
    return i

def start_cut(self):
    global cut_image
    cut_image = self.resize_card('cards/back_of_card.png')
    self.select_card_frame = Frame(self.window)
    self.select_card_label = Label(self.select_card_frame, text='Select Card to Cut', font=20)
    self.select_card_label.pack()
    self.select_card_frame.place(x=450, y=50)
    for i in range(52):
        exec(f'self.cut_frame_{i} = Frame(self.window)')
        exec(f'self.cut_label_{i} = Button(self.cut_frame_{i}, image=cut_image, command=lambda: self.cut({i}))')
        exec(f"self.cut_label_{i}.pack(side='left')")
        exec(f'self.cut_frame_{i}.place(x={i*20}, y=100)')

I have tried making a few of the card buttons individually and it worked as it should, so I suspect it is something that I am doing wrong with the exec() method. Any ideas on what I am doing wrong? or is there a better way to do this without using exec()? or do I just have to suck it up and type out the extra 300 lines of code? This is what the window looks like for a better picture of what I am trying to do.
Deck fanned out for cut


问:
How to upload custom emoji in bulk
I am testing a #Mastodon instance and want to upload a set of emojis.  Is there a way to do that?  Or do I have to do it one by one?

I understand I can copy the ones that appear on my federated feed, but I have a set of 110 custom emojis that I need to upload.  I haven't seen a Mastodon instance with the same emoji I want to use.  (Meesier Celestial Objects all 110 of them)

Title: How to upload custom emoji in bulk


问:
Error "rawError ... Invalid Form Body" and Discord bot doesn't run
I made this code for my Discord music bot and when I put my guild id in the handlers index.js file,

.get("1038150024145674320")
            .commands.set(arrayOfSlashCommands);
```
<p>and when I run it after that, I get this error:</p>
<pre class="lang-javascript prettyprint-override"><code>min_value: undefined,
            max_value: undefined,
            min_length: undefined,
            max_length: undefined
          }
        ],
        default_member_permissions: undefined,
        dm_permission: undefined
      }
    ]
  },
  rawError: {
    code: 50035,
    errors: {
      '0': { type: { _errors: [ [Object] ] } },
      '1': { options: { '0': { _errors: [Array] } } },
      '4': { options: { '0': { _errors: [Array] } } },
      '8': { options: { '0': { _errors: [Array] } } }
    },
    message: 'Invalid Form Body'
  },
  code: 50035,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v10/applications/792723109081513985/guilds/1038150024145674320/commands'
}
</code>```

How can I fix this? What would the fixed code be?

I tried reinstalling npm packages, but they didn't work.

Handler/index.js code:

const { glob } = require("glob");
const { promisify } = require("util");
const { Client } = require("discord.js");
const mongoose = require("mongoose");

const globPromise = promisify(glob);

/**
 * @param {Client} client
 */
module.exports = async (client) => {
    // Commands
    const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
    commandFiles.map((value) => {
        const file = require(value);
        const splitted = value.split("/");
        const directory = splitted[splitted.length - 2];

        if (file.name) {
            const properties = { directory, ...file };
            client.commands.set(file.name, properties);
        }
    });

    // Events
    const eventFiles = await globPromise(`${process.cwd()}/events/*.js`);
    eventFiles.map((value) => require(value));

    // Slash Commands
    const slashCommands = await globPromise(
        `${process.cwd()}/SlashCommands/*/*.js`
    );

    const arrayOfSlashCommands = [];
    slashCommands.map((value) => {
        const file = require(value);
        if (!file?.name)
            return;
        client.slashCommands.set(file.name, file);

        if (["MESSAGE", "USER"].includes(file.type))
            delete file.description;
        arrayOfSlashCommands.push(file);
    });
    client.on("ready", async () => {
        await client.guilds.cache
            .get("1038150024145674320")
            .commands.set(arrayOfSlashCommands);

      await client.application.commands.set(arrayOfSlashCommands);
    });

    // Mongoose
    const { mongooseConnectionString } = require("../config.json");
    if (!mongooseConnectionString)
        return;

    mongoose
        .connect(mongooseConnectionString)
        .then(() => console.log("Connected to MongoDB"));
};
```

Body:
I made this code for my Discord music bot and when I put my guild id in the handlers index.js file,

.get("1038150024145674320")
            .commands.set(arrayOfSlashCommands);

and when I run it after that, I get this error:

min_value: undefined,
            max_value: undefined,
            min_length: undefined,
            max_length: undefined
          }
        ],
        default_member_permissions: undefined,
        dm_permission: undefined
      }
    ]
  },
  rawError: {
    code: 50035,
    errors: {
      '0': { type: { _errors: [ [Object] ] } },
      '1': { options: { '0': { _errors: [Array] } } },
      '4': { options: { '0': { _errors: [Array] } } },
      '8': { options: { '0': { _errors: [Array] } } }
    },
    message: 'Invalid Form Body'
  },
  code: 50035,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v10/applications/792723109081513985/guilds/1038150024145674320/commands'
}

How can I fix this? What would the fixed code be?

I tried reinstalling npm packages, but they didn't work.

Handler/index.js code:

const { glob } = require("glob");
const { promisify } = require("util");
const { Client } = require("discord.js");
const mongoose = require("mongoose");

const globPromise = promisify(glob);

/**
 * @param {Client} client
 */
module.exports = async (client) => {
    // Commands
    const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
    commandFiles.map((value) => {
        const file = require(value);
        const splitted = value.split("/");
        const directory = splitted[splitted.length - 2];

        if (file.name) {
            const properties = { directory, ...file };
            client.commands.set(file.name, properties);
        }
    });

    // Events
    const eventFiles = await globPromise(`${process.cwd()}/events/*.js`);
    eventFiles.map((value) => require(value));

    // Slash Commands
    const slashCommands = await globPromise(
        `${process.cwd()}/SlashCommands/*/*.js`
    );

    const arrayOfSlashCommands = [];
    slashCommands.map((value) => {
        const file = require(value);
        if (!file?.name)
            return;
        client.slashCommands.set(file.name, file);

        if (["MESSAGE", "USER"].includes(file.type))
            delete file.description;
        arrayOfSlashCommands.push(file);
    });
    client.on("ready", async () => {
        await client.guilds.cache
            .get("1038150024145674320")
            .commands.set(arrayOfSlashCommands);

      await client.application.commands.set(arrayOfSlashCommands);
    });

    // Mongoose
    const { mongooseConnectionString } = require("../config.json");
    if (!mongooseConnectionString)
        return;

    mongoose
        .connect(mongooseConnectionString)
        .then(() => console.log("Connected to MongoDB"));
};


问:
Trying to create an AAB file for the Google Play Store with both Flutter and Unity asset packs
I have an app I'm building that uses Flutter plus Unity (using https://github.com/juicycleff/flutter-unity-view-widget to glue the two together).

The app's large-ish. Lots of videos in Flutter. Some large assets in Unity. Obviously I'm over the Play Store's 150MB limit. So I'm breaking the app into asset packs. The Flutter video asset packs see fine, but getting Unity to play nice is causing problems. Meaning, whatever I'm doing does not seem to be working and I'm pretty confused!

Any suggestions or experiences with this sort of problem?

Thank you!


问:
Azure AD Authentication, Next-Auth JWT and .NET Core Web API
I've set up a Next.js app to authenticate to Azure AD using Next-Auth, and this is successfully returning a JWT token.  I'd like to use this token for authentication in a .NET Core Web API project but I'm getting a 401 Unauthorized error with the WWW-Authenticate header returning Bearer error="invalid_token", error_description="The signature key was not found".  I'm using the same secret for the value of both the NEXTAUTH_SECRET and the IssuerSigningKey, as I assume this is the key that Next-Auth signs the JWT with, but I don't know if this is even correct or not.  If anyone knows a resource that shows the proper configuration for this or if they can spot a configuration error in my code it's appreciated.

[...nextauth].ts:

```<code>import NextAuth, { NextAuthOptions } from "next-auth"
import AzureADProvider from "next-auth/providers/azure-ad";

export const authOptions: NextAuthOptions = {
  providers: [
    AzureADProvider({
      clientId: process.env.AZURE_AD_CLIENT_ID!,
      clientSecret: process.env.AZURE_AD_CLIENT_SECRET!,
      tenantId: process.env.AZURE_AD_TENANT_ID,
      authorization: {
        params: {
          scope:
            `access_as_user api://${process.env.AZURE_AD_CLIENT_ID}/access_as_user`,
        },
      }
    }),
  ],
  theme: {
    colorScheme: "light",
  },
  callbacks: {
    async jwt({ token, user, account, profile, isNewUser }) {
      if (account) {
        token.access_token = account.access_token;
      }
      return token;
    },
    async session({ session, token }) {
      return { ...session };
    },
  },
}

export default NextAuth(authOptions)
</code>```

Program.cs:

```<code>using System.Text;

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
    o.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])), // Same as NEXTAUTH_SECRET
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        ValidIssuer = "localhost"
    };
}).AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"), "AzureAd");

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddCors(o => o.AddPolicy("default", builder =>
{
    builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
}));

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
</code>```

weather.ts:

```<code>import { getToken } from 'next-auth/jwt'
import type { NextApiRequest, NextApiResponse } from "next"

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET }) // get JWT token from request

  try {
    return new Promise(async (resolve, reject) => {
        var apiUrl = `${process.env.API_BASE_URL}/weatherForecast/get`;

        const response = await fetch(apiUrl, { // example URL
            method: "GET",
            credentials: "include",
            headers: {
              Authorization: `Bearer ${token?.access_token}`,  // <-- add token to request
              "Content-Type": "application/json",
            }
          });
          const json = await response.json();
          res.send(JSON.stringify(json, null, 2));
    });
} catch (e) {
    var error = e;
  }
}
</code>```

Body:
I've set up a Next.js app to authenticate to Azure AD using Next-Auth, and this is successfully returning a JWT token.  I'd like to use this token for authentication in a .NET Core Web API project but I'm getting a 401 Unauthorized error with the WWW-Authenticate header returning Bearer error="invalid_token", error_description="The signature key was not found".  I'm using the same secret for the value of both the NEXTAUTH_SECRET and the IssuerSigningKey, as I assume this is the key that Next-Auth signs the JWT with, but I don't know if this is even correct or not.  If anyone knows a resource that shows the proper configuration for this or if they can spot a configuration error in my code it's appreciated.

[...nextauth].ts:

import NextAuth, { NextAuthOptions } from "next-auth"
import AzureADProvider from "next-auth/providers/azure-ad";

export const authOptions: NextAuthOptions = {
  providers: [
    AzureADProvider({
      clientId: process.env.AZURE_AD_CLIENT_ID!,
      clientSecret: process.env.AZURE_AD_CLIENT_SECRET!,
      tenantId: process.env.AZURE_AD_TENANT_ID,
      authorization: {
        params: {
          scope:
            `access_as_user api://${process.env.AZURE_AD_CLIENT_ID}/access_as_user`,
        },
      }
    }),
  ],
  theme: {
    colorScheme: "light",
  },
  callbacks: {
    async jwt({ token, user, account, profile, isNewUser }) {
      if (account) {
        token.access_token = account.access_token;
      }
      return token;
    },
    async session({ session, token }) {
      return { ...session };
    },
  },
}

export default NextAuth(authOptions)

Program.cs:

using System.Text;

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
    o.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])), // Same as NEXTAUTH_SECRET
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        ValidIssuer = "localhost"
    };
}).AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"), "AzureAd");

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddCors(o => o.AddPolicy("default", builder =>
{
    builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
}));

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

weather.ts:

import { getToken } from 'next-auth/jwt'
import type { NextApiRequest, NextApiResponse } from "next"

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET }) // get JWT token from request

  try {
    return new Promise(async (resolve, reject) => {
        var apiUrl = `${process.env.API_BASE_URL}/weatherForecast/get`;

        const response = await fetch(apiUrl, { // example URL
            method: "GET",
            credentials: "include",
            headers: {
              Authorization: `Bearer ${token?.access_token}`,  // <-- add token to request
              "Content-Type": "application/json",
            }
          });
          const json = await response.json();
          res.send(JSON.stringify(json, null, 2));
    });
} catch (e) {
    var error = e;
  }
}


问:
Algorithm for finding grid(s) formed by a list of points
Problem: Given a list of points on a 2D plane, find all largest grids formed by these points.

A grid, in my definition, is a set of points that "fill a rectangle". Also, there's no need to consider rotated grids in my case.

For example, the points { A, B, C, ... , I } form a grid below:

```<code>A B C
D E F
G H I
</code>```

But if we remove point E, it's no longer a grid because there's a hole:

```<code>A B C
D   F
G H I
</code>```

By largest I mean in the following case:

```<code>A B C
D E F
</code>```

Although the points { A, B, C, D } form a grid, the output should be { A, B, C, D, E, F } because it forms a larger grid.

Finally, grids can overlap, so in this case:

```<code>A B
C D E
  F G
</code>```

The points {A, B, C, D} and {D, E, F, G} each form a grid.

Context: I want to create a Figma plugin that detects if there are repeated elements, in order to turn them into reusable components. For example in this Figma design, we can turn each column into a component. This grid problem is a part of the algorithm I'm trying to write.

What I've tried:

I first ran the DBSCAN algorithm on the points' x-coordinates and y-coordiantes to find a list of points that align with each other vertically and horizontally respectively, because it allowed for a margin of error when points are not perfectly aligned.

Then I was kind of stuck.

Maybe a way is to loop through each point, treat it as the top-left corner of a potential grid, then search for all possible grid sizes? That sounds pretty inefficient.

Any suggestions are welcome. Thanks a lot!

Body:
Problem: Given a list of points on a 2D plane, find all largest grids formed by these points.

A grid, in my definition, is a set of points that "fill a rectangle". Also, there's no need to consider rotated grids in my case.

For example, the points { A, B, C, ... , I } form a grid below:

A B C
D E F
G H I

But if we remove point E, it's no longer a grid because there's a hole:

A B C
D   F
G H I

By largest I mean in the following case:

A B C
D E F

Although the points { A, B, C, D } form a grid, the output should be { A, B, C, D, E, F } because it forms a larger grid.

Finally, grids can overlap, so in this case:

A B
C D E
  F G

The points {A, B, C, D} and {D, E, F, G} each form a grid.

Context: I want to create a Figma plugin that detects if there are repeated elements, in order to turn them into reusable components. For example in this Figma design, we can turn each column into a component. This grid problem is a part of the algorithm I'm trying to write.

What I've tried:

I first ran the DBSCAN algorithm on the points' x-coordinates and y-coordiantes to find a list of points that align with each other vertically and horizontally respectively, because it allowed for a margin of error when points are not perfectly aligned.

Then I was kind of stuck.

Maybe a way is to loop through each point, treat it as the top-left corner of a potential grid, then search for all possible grid sizes? That sounds pretty inefficient.

Any suggestions are welcome. Thanks a lot!


问:
Stretch Function C++ Stack Based Implementation
I am working on a stack based implementation function that "stretches" the given input by a k value. For example for a string "abc" stretched by 2, the output would be abc, aabc, abbc, abcc, aabbc, aabcc, abbcc, aabbcc. So far the code I have is producing the output cc bb aa but I am not sure where my logic has an error that is causing this incorrect output.

My Code:

```<code>class Node
{
    public:
        string word; // stores the word in the node
        Node *next;
        Node(); //default constructor (never used)
        Node(string); // Constructor creates Node with word
        Node(string, int, int);
};

Node :: Node()
{
    word = "";
    next = NULL;
}

// Constructor with string input sets word and freq to 1
Node :: Node(string s)
{
    word = s;
    next = NULL;
}

class List
{
    public:
        Node *head; // Stores head of linked list
        List();
        string print();
}

List :: List()
{
    head = NULL;
}

string List :: print()
{
    Node *curr = head; // curr is ths current node as it progresses through the linked list. Initialized to head to start at the head of the list
    string output = ""; // output string
    while(curr!=NULL){ // loop over list
        output = output + " " + curr->word; //append current word onto output string
        curr = curr->next; // proceed to next node
    }
    return output;
}

List stretch(string input_str, int val) {
    List final_output;
    int length = input_str.length();

    for (int i = 0; i < length; i++) {
        string insert = "";
        for (int j = 0; j < val; j++) {
            insert.push_back(input_str[i]);
        }
        final_output.insert(insert);
    }
    return final_output;
}

int main(int argc, char** argv)
{
    List myList2 = stretch("abc", 2);
    cout << "Stretch: " << myList2.print() << endl;
}

</code>```

Body:
I am working on a stack based implementation function that "stretches" the given input by a k value. For example for a string "abc" stretched by 2, the output would be abc, aabc, abbc, abcc, aabbc, aabcc, abbcc, aabbcc. So far the code I have is producing the output cc bb aa but I am not sure where my logic has an error that is causing this incorrect output.

My Code:

class Node
{
    public:
        string word; // stores the word in the node
        Node *next;
        Node(); //default constructor (never used)
        Node(string); // Constructor creates Node with word
        Node(string, int, int);
};

Node :: Node()
{
    word = "";
    next = NULL;
}

// Constructor with string input sets word and freq to 1
Node :: Node(string s)
{
    word = s;
    next = NULL;
}

class List
{
    public:
        Node *head; // Stores head of linked list
        List();
        string print();
}

List :: List()
{
    head = NULL;
}

string List :: print()
{
    Node *curr = head; // curr is ths current node as it progresses through the linked list. Initialized to head to start at the head of the list
    string output = ""; // output string
    while(curr!=NULL){ // loop over list
        output = output + " " + curr->word; //append current word onto output string
        curr = curr->next; // proceed to next node
    }
    return output;
}

List stretch(string input_str, int val) {
    List final_output;
    int length = input_str.length();

    for (int i = 0; i < length; i++) {
        string insert = "";
        for (int j = 0; j < val; j++) {
            insert.push_back(input_str[i]);
        }
        final_output.insert(insert);
    }
    return final_output;
}

int main(int argc, char** argv)
{
    List myList2 = stretch("abc", 2);
    cout << "Stretch: " << myList2.print() << endl;
}


问:
Problem with Android License in Command Prompt
Need help with this. Every time I run flutter doctor, I get the message "Error: could not open `C:\Program Files\Android\Android Studio\jre\lib\jvm.cfg'".

I've tried to watch videos on this, clicking on the link provided in the command prompt. I also tried reading other stacked overflow forums on this as well as referring to reddit but none of them resolve my problem. I tried going into the "lib" directory but there's no such folder called "jvm.cfg".


问:
Validate JWT token in Keycloak server without login page
I want to use Keycloak server with Spring Gateway. In my case I have a API to API communication (Server to Server) communication which I would like to protect using JWT token.

The question is how I can use Keycloak Authorization server to generate and validate JWT token having in mind that I don't have a login page. I need to:

Generate JWT using Keycloak API because I want to generate the JWT token from a customer portal page and put some custom data into JWT token payload.

When API request is send to Spring Gateway I want to validate the JWT token into Keycloak server.

Is this functionality possible with Spring gateway and Keycloak server?


问:
android studio Native C++ template project [CXX1405] error when building with cmake using CMakeLists.txt: C++ build system [configure] failed
I have an error message when I try build grandle Native C++ template project on android studio, I've not modified anything in the files, it's just a simple template project.

Console log:

```<code>> Task :prepareKotlinBuildScriptModel UP-TO-DATE
[CXX1405] error when building with cmake using C:\Users\both\AndroidStudioProjects\MyApplication\app\src\main\cpp\CMakeLists.txt: C++ build system [configure] failed while executing:
    @echo off
    "C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\cmake\\3.18.1\\bin\\cmake.exe" ^
      "-HC:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\src\\main\\cpp" ^
      "-DCMAKE_SYSTEM_NAME=Android" ^
      "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON" ^
      "-DCMAKE_SYSTEM_VERSION=29" ^
      "-DANDROID_PLATFORM=android-29" ^
      "-DANDROID_ABI=x86" ^
      "-DCMAKE_ANDROID_ARCH_ABI=x86" ^
      "-DANDROID_NDK=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620" ^
      "-DCMAKE_ANDROID_NDK=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620" ^
      "-DCMAKE_TOOLCHAIN_FILE=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620\\build\\cmake\\android.toolchain.cmake" ^
      "-DCMAKE_MAKE_PROGRAM=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\cmake\\3.18.1\\bin\\ninja.exe" ^
      "-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\build\\intermediates\\cxx\\Debug\\6n168485\\obj\\x86" ^
      "-DCMAKE_RUNTIME_OUTPUT_DIRECTORY=C:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\build\\intermediates\\cxx\\Debug\\6n168485\\obj\\x86" ^
      "-DCMAKE_BUILD_TYPE=Debug" ^
      "-BC:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\.cxx\\Debug\\6n168485\\x86" ^
      -GNinja
  from C:\Users\both\AndroidStudioProjects\MyApplication\app

BUILD SUCCESSFUL in 1m 7s

</code>```

Body:
I have an error message when I try build grandle Native C++ template project on android studio, I've not modified anything in the files, it's just a simple template project.

Console log:

> Task :prepareKotlinBuildScriptModel UP-TO-DATE
[CXX1405] error when building with cmake using C:\Users\both\AndroidStudioProjects\MyApplication\app\src\main\cpp\CMakeLists.txt: C++ build system [configure] failed while executing:
    @echo off
    "C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\cmake\\3.18.1\\bin\\cmake.exe" ^
      "-HC:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\src\\main\\cpp" ^
      "-DCMAKE_SYSTEM_NAME=Android" ^
      "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON" ^
      "-DCMAKE_SYSTEM_VERSION=29" ^
      "-DANDROID_PLATFORM=android-29" ^
      "-DANDROID_ABI=x86" ^
      "-DCMAKE_ANDROID_ARCH_ABI=x86" ^
      "-DANDROID_NDK=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620" ^
      "-DCMAKE_ANDROID_NDK=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620" ^
      "-DCMAKE_TOOLCHAIN_FILE=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620\\build\\cmake\\android.toolchain.cmake" ^
      "-DCMAKE_MAKE_PROGRAM=C:\\Users\\both\\AppData\\Local\\Android\\Sdk\\cmake\\3.18.1\\bin\\ninja.exe" ^
      "-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\build\\intermediates\\cxx\\Debug\\6n168485\\obj\\x86" ^
      "-DCMAKE_RUNTIME_OUTPUT_DIRECTORY=C:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\build\\intermediates\\cxx\\Debug\\6n168485\\obj\\x86" ^
      "-DCMAKE_BUILD_TYPE=Debug" ^
      "-BC:\\Users\\both\\AndroidStudioProjects\\MyApplication\\app\\.cxx\\Debug\\6n168485\\x86" ^
      -GNinja
  from C:\Users\both\AndroidStudioProjects\MyApplication\app

BUILD SUCCESSFUL in 1m 7s


问:
how to show row index in datagrid in react js?
I want to add a list of numbers to the top left side, but there is no index in my API response, so I don't know how to do so. I noticed that there are numbers in datagrid pagination; is there any way to use it here?


问:
Could not auto-determine entry point from rollupOptions?
I am trying to host an app on Heroku (React + Vite), but after the build succeeds the hosting fails because:

"Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."

What does this mean and how can I go about resolving this? Do I need to have something specific in my vite.config.js?

package.json:

```<code>{
  "name": "portfolio-website",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "start": "node main.jsx"
  },
  "dependencies": {
    "@glidejs/glide": "3.5.2",
    "@types/react": "^18.0.20",
    "@types/react-dom": "^18.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.0",
    "react-scripts": "^5.0.1",
    "rollup": "^2.79.1",
    "sass": "^1.54.9"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^2.1.0",
    "vite": "^3.1.0"
  },
  "engines": {
    "node": "16.17.1"
  }
}
</code>```

Procfile:

```<code>web: npm run dev --port $PORT
</code>```

static.json:

```<code>{
    "routes": {
      "/**": "index.html"
    }
  }
</code>```

vite.config.js:

```<code>import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()]
})
</code>```

Body:
I am trying to host an app on Heroku (React + Vite), but after the build succeeds the hosting fails because:

"Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."

What does this mean and how can I go about resolving this? Do I need to have something specific in my vite.config.js?

package.json:

{
  "name": "portfolio-website",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "start": "node main.jsx"
  },
  "dependencies": {
    "@glidejs/glide": "3.5.2",
    "@types/react": "^18.0.20",
    "@types/react-dom": "^18.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.0",
    "react-scripts": "^5.0.1",
    "rollup": "^2.79.1",
    "sass": "^1.54.9"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^2.1.0",
    "vite": "^3.1.0"
  },
  "engines": {
    "node": "16.17.1"
  }
}

Procfile:

web: npm run dev --port $PORT

static.json:

{
    "routes": {
      "/**": "index.html"
    }
  }

vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()]
})


问:
API or Package to handle address fields of form
I'm looking for an API or a package that gives info about address's fields to be completed according to a specific country.

Why? Because countries don't handle address info in the same way.

Let me give you an example:

FIRST EXAMPLE

You chouse United State as your country

Then this "package/api" let you know about the address's field according to United State, eg. fields=[street, numberStreet, state, zipcode]

With this info the form, with a .map, going to create fields. Field Street, Field Number Street, Field State, Field Zipocode.

SECOND EXAMPLE

You chouse Argentina as your country

Then this "package/api" let you know about the address's field according to Argentina, eg. fields=[street, numberStreet, departament, province, zipcode]. Look the difference with United State.

With this info the form, with a .map, going to create fields. Field Street, Field Number Street, Field Departament, Field Province, Field Zipocode.

Any idea? Thanks

If there exists any package or API that let you know about which address fields are used according to each country in the world.


问:
Session data in Thymeleaf (+ Spring Boot)
I decided to design my own e-shop app in order to practice my knowledge of Spring framework. Now I try to get my shopping cart functionality working. I have java class itself:

```<code>public class Cart implements Serializable{

    private Map<Product, Integer> mapProductAmount = new HashMap<Product, Integer>();

    public Cart() {

    }

    public void addToCart(Product product, Integer amount) {
        mapProductAmount.put(product, amount);
    }

    public Map<Product, Integer> getMapProductAmount() {
        return mapProductAmount;
    }

    public void setMapProductAmount(Map<Product, Integer> mapProductAmount) {
        this.mapProductAmount = mapProductAmount;
    }

}
</code>```

In my Thymeleaf template I have shopping cart icon, after clicking on it it will show Javascript dialog with the cart content (Cart as object is saved in session). That's the idea. I did some research and it looks like it will be a problem to do this using only JS, since I can't imagine passing Cart object to javascript. The other way could be to send data into model and then use it in template. But thymeleaf isn't good at showing dialogs so I guess this is dead-end for me too. It could be doable in .jsp file, but not sure about my thymeleaf situation. What is the best possible approach to do that?

Body:
I decided to design my own e-shop app in order to practice my knowledge of Spring framework. Now I try to get my shopping cart functionality working. I have java class itself:

public class Cart implements Serializable{

    private Map<Product, Integer> mapProductAmount = new HashMap<Product, Integer>();

    public Cart() {

    }

    public void addToCart(Product product, Integer amount) {
        mapProductAmount.put(product, amount);
    }

    public Map<Product, Integer> getMapProductAmount() {
        return mapProductAmount;
    }

    public void setMapProductAmount(Map<Product, Integer> mapProductAmount) {
        this.mapProductAmount = mapProductAmount;
    }

}

In my Thymeleaf template I have shopping cart icon, after clicking on it it will show Javascript dialog with the cart content (Cart as object is saved in session). That's the idea. I did some research and it looks like it will be a problem to do this using only JS, since I can't imagine passing Cart object to javascript. The other way could be to send data into model and then use it in template. But thymeleaf isn't good at showing dialogs so I guess this is dead-end for me too. It could be doable in .jsp file, but not sure about my thymeleaf situation. What is the best possible approach to do that?


问:
Python - Easy 3D rendering scene guidance
I am doing a robotics project in Python and I want to add a real-time 3D visualiser. I have the CAD files (from SOLIDWORKS, they could be STL, STEP or probably converted tomost 3D formats) and I want to animate them. What I mean by that  is that:

I hardcode or define in a file: the name of each file, their position relative to each other and parent/child relationships.

In my code, I have some function calls like motor1.setPosition(X).
Instead of sending data to my microcontroller, if we are in the vizualization, I want to be able to control the rotation/position of one of my object.

The rendering should not be blocking code (as I need to run my control code at the same time) or run in another thread but then I need to be able to communicate in real time btween the rendering thread and the contorl one and I am not sure how to do this. Ideally I would prefer a Render() function that I owuld call often.

If possible I would like to have some kind of camera control with the mouse.

I have tried vtk and vpython but none seem to suit my purposes. (vpython does not seem to support well 3D objects and vtk's execution blocks the code)

I have used previously OpenGL in C++ and while I could do that, I don't want to go as low level and really want to do this in Python (even if the eprformance are not great).

Any suggestions?


问:
Docker private registry login deployed by k8s pod: Connection refused
I have deployed a docker private registry on Centos-7 using k8s pod deployment. I have used self signed certificate and htpasswd for authentication. I have created a folder with the name of hostname:nodeport in /etc/deocker/certs.d/ and copied ca.crt here for all docker host. Also copy the .crt certificate to

/etc/pki/ca-trust/source/anchors/ folder.

Interesting thing is when I deploy as docker container with both TLS and auth, then I can login to the registry. But when I deploy the registry container using k8s deployment and connect with NodePort service, I am having below error:

docker login ktmaster:30310 -u user -p password
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get “https://ktmaster:30310/v2/”: dial tcp 192.168.0.160:30310: connect: connection refused

I have followed the docker documentation (https://docs.docker.com/registry/deploying/). But still no luck. Did I miss something?  Your thoughts are much appriciated.

Deployment file and service (NodePort) file are below:

Pod config file:

apiVersion: apps/v1
kind: Deployment
metadata:
name: private-repository
labels:
app: private-repository
spec:
replicas: 1
selector:
matchLabels:
app: private-repository
template:
metadata:
labels:
app: private-repository
spec:
volumes:
- name: certs-vol
hostPath:
path: /opt/certs
type: Directory
- name: registry-vol
hostPath:
path: /opt/registry
type: Directory
- name: auth-vol
secret:
secretName: auth-secret
containers:
- image: registry:2.6.2
name: private-repository
args:
- sleep
- "300"
env:
- name: REGISTRY_AUTH
value: "htpasswd"
- name: REGISTRY_AUTH_HTPASSWD_REALM
value: "Registry Realm"
- name: REGISTRY_AUTH_HTPASSWD_PATH
value: "/auth/htpasswd"
- name: REGISTRY_HTTP_TLS_CERTIFICATE
value: "/certs/registry.crt"
- name: REGISTRY_HTTP_TLS_KEY
value: "/certs/registry.key"
volumeMounts:
- name: certs-vol
mountPath: /certs
readOnly: true
- name: registry-vol
mountPath: /var/lib/registry
readOnly: true
- name: auth-vol
mountPath: "/auth"
readOnly: true
ports:
- containerPort: 5000

Service config file

apiVersion: v1
kind: Service
metadata:
labels:
app: private-repository
name: private-repository-service
spec:
ports:

port: 5000
nodePort: 30310
protocol: TCP
targetPort: 5000
selector:
app: private-repository
type: NodePort

I have tried all possible workaround as described. But every time the connections was refused.


问:
Set a JSDoc comment to generate API documentation without adding a TypeScript declaration to the .d.ts file
I'm writing in JS, and I use JSDoc comments to generate both my API documentation and my TypeScript declaration files. However, I have a couple of functions that I'd like to keep out of my TS code -- but I still want to include them in my API reference docs. Is this possible? Is there any sort of tag that tells JSDoc, "document this function but leave it out of the .d.ts file"?


问:
LSTM model with multiple inputs and outputs
I'm building a machine learning model to predict stock prices. The input is a multidimensional array with the last 60 days of price, high, low, volume, and adjusted price. The output should be an array with all the predicted prices, so that the results can be plotted and confronted. The goal is to predict the price in function of the variables I just mentioned.

The code is the following:

```<code>#importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#importing training set
dataset_train = pd.read_csv('GE.csv')
dataset_train["Tomorrow"]= dataset_train["Close"].shift(-1)

dataset_train["Target"] = (dataset_train["Tomorrow"]>dataset_train["Close"]).astype(int)
del dataset_train['Tomorrow']
#print(dataset_train)
training_set = dataset_train.iloc[:,1:7].values
#print(training_set)
#feature scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range=(0,1))
training_set_scaled = sc.fit_transform(training_set)
Train_cap=(int(0.7*len(dataset_train)+60))
#creating a data structure with 60 timesteps and 1 output
X_train = []
y_train = []
High_train = []
Low_train = []
Close_train = []
Adj_Close_train = []
Volume_train = []
for i in range(60,Train_cap):
    X_train.append(training_set_scaled[i-60:i,0])
    y_train.append(training_set_scaled[i,0])
    High_train.append(training_set_scaled[i,1])
    Low_train.append(training_set_scaled[i,2])
    Close_train.append(training_set_scaled[i,3])
    Adj_Close_train.append(training_set_scaled[i,4])
    Volume_train.append(training_set_scaled[i,5])
X_train,y_train, High_train,Low_train,Close_train,Adj_Close_train,Volume_train =\
    np.array(X_train),np.array(y_train),np.array(High_train),np.array(Low_train),np.array(Close_train),np.array(Adj_Close_train),np.array(Volume_train)
#reshaping
X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))
#print(X_train)
#building the RNN
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
import tensorflow as tf

#initialising the RNN
regressor = Sequential()

#adding the first LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True,input_shape=(X_train.shape[1],1)))
regressor.add(Dropout(0.2))

#adding a second LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True))
regressor.add(Dropout(0.2))

#adding a third LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True))
regressor.add(Dropout(0.2))

#adding a fourth LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50))
regressor.add(Dropout(0.2))

#adding the output layer
regressor.add(Dense(units=1))

#compiling the RNN
regressor.compile(optimizer='adam',loss='mean_squared_error')
#fitting the RNN to the training set
X_train=tf.data.Dataset.from_tensors(X_train,y_train, High_train,Low_train,Close_train,Adj_Close_train,Volume_train)
regressor.fit(X_train,y_train,epochs=1,batch_size=32)
#making the predictions and visualising the results

#getting the real stock price of 2017
dataset_test = pd.read_csv('GE.csv')
real_stock_price = dataset_test.iloc[:,1:2].values

#getting the predicted stock price of 2017
dataset_total = pd.concat((dataset_train['Open'],dataset_test['Open']),axis=0)
inputs = dataset_total[len(dataset_total)-len(dataset_test)-60:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
X_test = []
for i in range(60,len(dataset_train['Open'])+60):
    X_test.append(inputs[i-60:i,0])
X_test = np.array(X_test)
X_test = np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)

#visualising the results
plt.plot(real_stock_price,color='red',label='Real Price')
plt.plot(predicted_stock_price,color='blue',label='Predicted Price')
plt.title('Price Prediction')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()
plt.show()

from sklearn.metrics import mean_squared_error
rmse = mean_squared_error.sqrt((real_stock_price,predicted_stock_price))
print(rmse)
</code>```

I have tried multiple solutions to input this multidimensional array but I don't understand how to do it.

Body:
I'm building a machine learning model to predict stock prices. The input is a multidimensional array with the last 60 days of price, high, low, volume, and adjusted price. The output should be an array with all the predicted prices, so that the results can be plotted and confronted. The goal is to predict the price in function of the variables I just mentioned.

The code is the following:

#importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#importing training set
dataset_train = pd.read_csv('GE.csv')
dataset_train["Tomorrow"]= dataset_train["Close"].shift(-1)

dataset_train["Target"] = (dataset_train["Tomorrow"]>dataset_train["Close"]).astype(int)
del dataset_train['Tomorrow']
#print(dataset_train)
training_set = dataset_train.iloc[:,1:7].values
#print(training_set)
#feature scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range=(0,1))
training_set_scaled = sc.fit_transform(training_set)
Train_cap=(int(0.7*len(dataset_train)+60))
#creating a data structure with 60 timesteps and 1 output
X_train = []
y_train = []
High_train = []
Low_train = []
Close_train = []
Adj_Close_train = []
Volume_train = []
for i in range(60,Train_cap):
    X_train.append(training_set_scaled[i-60:i,0])
    y_train.append(training_set_scaled[i,0])
    High_train.append(training_set_scaled[i,1])
    Low_train.append(training_set_scaled[i,2])
    Close_train.append(training_set_scaled[i,3])
    Adj_Close_train.append(training_set_scaled[i,4])
    Volume_train.append(training_set_scaled[i,5])
X_train,y_train, High_train,Low_train,Close_train,Adj_Close_train,Volume_train =\
    np.array(X_train),np.array(y_train),np.array(High_train),np.array(Low_train),np.array(Close_train),np.array(Adj_Close_train),np.array(Volume_train)
#reshaping
X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))
#print(X_train)
#building the RNN
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
import tensorflow as tf

#initialising the RNN
regressor = Sequential()

#adding the first LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True,input_shape=(X_train.shape[1],1)))
regressor.add(Dropout(0.2))

#adding a second LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True))
regressor.add(Dropout(0.2))

#adding a third LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences=True))
regressor.add(Dropout(0.2))

#adding a fourth LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50))
regressor.add(Dropout(0.2))

#adding the output layer
regressor.add(Dense(units=1))

#compiling the RNN
regressor.compile(optimizer='adam',loss='mean_squared_error')
#fitting the RNN to the training set
X_train=tf.data.Dataset.from_tensors(X_train,y_train, High_train,Low_train,Close_train,Adj_Close_train,Volume_train)
regressor.fit(X_train,y_train,epochs=1,batch_size=32)
#making the predictions and visualising the results

#getting the real stock price of 2017
dataset_test = pd.read_csv('GE.csv')
real_stock_price = dataset_test.iloc[:,1:2].values

#getting the predicted stock price of 2017
dataset_total = pd.concat((dataset_train['Open'],dataset_test['Open']),axis=0)
inputs = dataset_total[len(dataset_total)-len(dataset_test)-60:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
X_test = []
for i in range(60,len(dataset_train['Open'])+60):
    X_test.append(inputs[i-60:i,0])
X_test = np.array(X_test)
X_test = np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)

#visualising the results
plt.plot(real_stock_price,color='red',label='Real Price')
plt.plot(predicted_stock_price,color='blue',label='Predicted Price')
plt.title('Price Prediction')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()
plt.show()

from sklearn.metrics import mean_squared_error
rmse = mean_squared_error.sqrt((real_stock_price,predicted_stock_price))
print(rmse)

I have tried multiple solutions to input this multidimensional array but I don't understand how to do it.


问:
Using EventSource with Ajax
I am trying to work out how EventSource might help solve an update problem with a web applications.

I would like to be able to notify visitors to a web page when one or another visitor has performed an update. The idea is:

One visitor makes some changes to a text area and submits.

The data is submitted using Ajax.

At the server, the changes are saved.

I would like the server to send a notification that changes have been made

I would like all other visitors to get this notification.

On the server in PHP, I have something like this:

if(isset($_POST['save'])) {
    //  process changes

    $data = sprintf('data: {"time": "%s","type": "save"}',$date);

    header("Cache-Control: no-store");
    header("Content-Type: text/event-stream");
    print "event: ping\n$data\n\n";
    ob_flush();
    flush();

    exit;
}
```
<p>In JavaScript I have something like this:</p>
<pre class="lang-js prettyprint-override"><code>var eventSource = new EventSource("https://example.net/ajax.php", { withCredentials: true } );
eventSource.addEventListener("ping", (event) => {
    const time = JSON.parse(event.data).time;
    const type = JSON.parse(event.data).type;
    console.log(`Ping at ${time} for ${type}`);
});
</code>```

That doesn’t do the job at all. At the client end I get get an error message about the wrong headers (I think that it’s because there’s no save yet, so the PHP falls through to an empty string).

All the samples I have seen include a while(true) loop in the PHP, but non have a one-off event.

Is this possible to implement, and, if so, how?

Title: Using EventSource with Ajax

Body:
I am trying to work out how EventSource might help solve an update problem with a web applications.

I would like to be able to notify visitors to a web page when one or another visitor has performed an update. The idea is:

One visitor makes some changes to a text area and submits.

The data is submitted using Ajax.

At the server, the changes are saved.

I would like the server to send a notification that changes have been made

I would like all other visitors to get this notification.

On the server in PHP, I have something like this:

if(isset($_POST['save'])) {
    //  process changes

    $data = sprintf('data: {"time": "%s","type": "save"}',$date);

    header("Cache-Control: no-store");
    header("Content-Type: text/event-stream");
    print "event: ping\n$data\n\n";
    ob_flush();
    flush();

    exit;
}

In JavaScript I have something like this:

var eventSource = new EventSource("https://example.net/ajax.php", { withCredentials: true } );
eventSource.addEventListener("ping", (event) => {
    const time = JSON.parse(event.data).time;
    const type = JSON.parse(event.data).type;
    console.log(`Ping at ${time} for ${type}`);
});

That doesn’t do the job at all. At the client end I get get an error message about the wrong headers (I think that it’s because there’s no save yet, so the PHP falls through to an empty string).

All the samples I have seen include a while(true) loop in the PHP, but non have a one-off event.

Is this possible to implement, and, if so, how?


问:
Laravel relation with custom join condition
I received quite strange database to work with and I'm trying to create relation on model Invoice like below:

```<code>public function order()
{
    return $this->hasOneThrough(Order::class, Shipment::class,
        'id',
        'id',
        DB::raw('-order_id'),
        Shipment::COL_ORDER_ID
    );
}
</code>```

but it gives me the error array_key_exists(): Argument #1 ($key) must be a valid array offset type.
Of course the problem is in the DB::raw part... As you may have guessed I'm trying to create join condition like -Invoice.order_id = Shipment.id or ABS(Invoice.order_id) = Shpment.id will be fine too because only order_id on the Invoice needs to be converted into positive number.

Any ideas to get it to work with minimal additional code as possible? Any help will be appreciated :)

Body:
I received quite strange database to work with and I'm trying to create relation on model Invoice like below:

public function order()
{
    return $this->hasOneThrough(Order::class, Shipment::class,
        'id',
        'id',
        DB::raw('-order_id'),
        Shipment::COL_ORDER_ID
    );
}

but it gives me the error array_key_exists(): Argument #1 ($key) must be a valid array offset type.
Of course the problem is in the DB::raw part... As you may have guessed I'm trying to create join condition like -Invoice.order_id = Shipment.id or ABS(Invoice.order_id) = Shpment.id will be fine too because only order_id on the Invoice needs to be converted into positive number.

Any ideas to get it to work with minimal additional code as possible? Any help will be appreciated :)


问:
Proper Fault-tolerant/HA setup for KeyDB/Redis in Kubernetes
Sorry for a long post, but I hope it would relieve us from some of clarifying questions. I also added some diagrams to split the wall of text, hope you'll like those.

We are in the process of moving our current solution to local Kubernetes infrastructure, and the current thing we investigate is the proper way to setup a KV-store (we've been using Redis for this) in the K8s.

One of the main use-cases for the store is providing processes with exclusive ownership for resources via a simple version of a Distibuted lock pattern, as in (discouraged) pattern here. (More on why we are not using Redlock below).

And once again, we are looking for a way to set it in the K8s, so that details of HA setup are opaque to clients. Ideally, the setup would look like this:

So what is the proper way to setup Redis for this? Here are the options that we considered:

First of all, we discarded Redis cluster, because we don't need sharding of keyspace. Our keyspace is rather small.

Next, we discarded Redis Sentinel setup, because with sentinels clients are expected to be able to connect to chosen Redis node, so we would have to expose all nodes. And also will have to provide some identity for each node (like distinct ports, etc) which contradicts with idea of a K8s Service. And even worse, we'll have to check that all (heterogeneous) clients do support Sentinel protocol and properly implement all that fiddling.

Somewhere around here we got out of options for the first time. We thought about using regular Redis replication, but without Sentinel it's unclear how to set things up for fault-tolerance in case of master failure — there seem to be no auto-promotion for replicas, and no (easy) way to tell K8s that master has been changed — except maybe for inventing a custom K8s operator, but we are not that desperate (yet).

So, here we came to idea that Redis may be not very cloud-friendly, and started looking for alternatives. And so we found KeyDB, which has promising additional modes. That's besides impressing performance boost while having 100% compatible API — very impressive!

So here are the options that we considered with KeyDB:

Active replication with just two nodes. This would look like this:

This setup looks very promising at first — simple, clear, and even official KeyDB docs recommend this as a preferred HA setup, superior to Sentinel setup.

But there's a caveat. While the docs advocate this setup to be tolerant to split-brains (because the nodes would catch up one to another after connectivity is re-established), this would ruin our use-case, because two clients would be able to lock same resource id:

And there's no way to tell K8s that one node is OK, and another is unhealthy, because both nodes have lost their replicas.

Well, it's clear that it's impossible to make an even-node setup to be split-brain-tolerant, so next thing we considered was KeyDB 3-node multi-master, which allows each node to be an (active) replica of multiple masters:

Ok, things got more complicated, but it seems that the setup is brain-split proof:

Note that we had to add more stuff here:

health check — to consider a node that lost all its replicas as unhealthy, so K8s load balancer would not route new clients to this node

WAIT 1 command for SET/EXPIRE — to ensure that we are writing to a healthy split (preventing case when client connects to unhealthy node before load balancer learns it's ill).

And this is when a sudden thought struck: what's about consistency?? Both these setups with multiple writable nodes provide no guard against two clients both locking same key on different nodes!

Redis and KeyDB both have asynchronous replication, so there seem to be no warranty that if an (exclusive) SET succeeds as a command, it would not get overwritten by another SET with same key issued on another master a split-second later.

Adding WAITs does not help here, because it only covers spreading information from master to replicas, and seem to have no affect on these overlapping waves of overwrites spreading from multiple masters.

Okay now, this is actually the Distributed Lock problem, and both Redis and KeyDB provide the same answer — use the Redlock algorithm. But it seem to be quite too complex:

It requires client to communicate with multiple nodes explicitly (and we'd like to not do that)

These nodes are to be independent. Which is rather bad, because we are using Redis/KeyDB not only for this locking case, and we'd still like to have a reasonably fault-tolerant setup, not 5 separate nodes.

So, what options do we have? Both Redlock explanations do start from a single-node version, which is OK, if the node will never die and is always available. And while it's surely not the case, but we are willing to accept the problems that are explained in the section "Why failover-based implementations are not enough" — because we believe failovers would be quite rare, and we think that we fall under this clause:

Sometimes it is perfectly fine that under special circumstances, like during a failure, multiple clients can hold the lock at the same time. If this is the case, you can use your replication based solution.

So, having said all of this, let me finally get to the question: how do I setup a fault-tolerant "replication-based solution" of KeyDB to work in Kubernetes, and having a single write node most of the time?

If it's a regular 'single master, multiple replicas' setup (without 'auto'), what mechanism would assure promoting replica in case of master failure, and what mechanism would tell Kubernetes that master node has changed? And how? By re-assigning labels on pods?

Also, what would restore a previously dead master node in such a way that it would not become a master again, but a replica of a substitute master?

Do we need some K8s operator for this? (Those that I found were not smart enough to do this).

Or if it's multi-master active replication from KeyDB (like in my last picture above), I'd still need to use something instead of LoadBalanced K8s Service, to route all clients to a single node at time, and then again — to use some mechanism to switch this 'actual master' role in case of failure.

And this is where I'd like to ask for your help!

I've found frustratingly little info on the topic. And it does not seem that many people have such problems that we face. What are we doing wrong? How do you cope with Redis in the cloud?


问:
Detecting Numbers in Image using pytesseract
I have this image:

I would like to detect the numbers within the image, mainly 2261 using Tesseract (pytesseract). I have tried various processing techniques with opencv, and I haven't been able to get tesseract to detect anything.

This is my current code:

def get_grayscale(image):
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

img1 = cv2.imread('runs/detect/exp/crops/Gauge/image0.jpg')

scale_percent = 220 # percent of original size
width = int(img1.shape[1] * scale_percent / 100)
height = int(img1.shape[0] * scale_percent / 100)
dim = (width, height)

resized = cv2.resize(img1, dim, interpolation = cv2.INTER_AREA)

resized = get_grayscale(resized)

thr = cv2.threshold(src=resized, thresh=0, maxval=255, type=cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)[1]

txt = pytesseract.image_to_string(thr, config='digits')
print(txt)

cv2.imshow("",thr)
cv2.waitKey(0)
```

This produces the following image:

As stated earlier, tesseract is unable to detect anything, and I'm unsure why, as the numbers are quite visible in this image. Am I missing something, or are there certain config options I need to include?

Body:
I have this image:

I would like to detect the numbers within the image, mainly 2261 using Tesseract (pytesseract). I have tried various processing techniques with opencv, and I haven't been able to get tesseract to detect anything.

This is my current code:

def get_grayscale(image):
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

img1 = cv2.imread('runs/detect/exp/crops/Gauge/image0.jpg')

scale_percent = 220 # percent of original size
width = int(img1.shape[1] * scale_percent / 100)
height = int(img1.shape[0] * scale_percent / 100)
dim = (width, height)

resized = cv2.resize(img1, dim, interpolation = cv2.INTER_AREA)

resized = get_grayscale(resized)

thr = cv2.threshold(src=resized, thresh=0, maxval=255, type=cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)[1]

txt = pytesseract.image_to_string(thr, config='digits')
print(txt)

cv2.imshow("",thr)
cv2.waitKey(0)

This produces the following image:

As stated earlier, tesseract is unable to detect anything, and I'm unsure why, as the numbers are quite visible in this image. Am I missing something, or are there certain config options I need to include?


问:
Why this error occurs while updating kotlin version Execution failed for task ':app:kaptDebugKotlin'
I am implementing SDK which requires kotlin version 1.6.10 but right now my project kotlin version is 1.4.10.When i changed the version Gradle gives me this error .
Execution failed for task ':app:kaptDebugKotlin'.

What is the meaning of this error?

i am trying to implement sdk but its not working on my project current kotlin version 1.4.10.
//Expected
How to update kotlin version of project?


问:
How to replace variables for certain observations in R?
So I have a list of countries in my survey with their specific spellings. I have another dataframe which has a score for each country, but the name of some of the countries are spelled differently than those in my survey (e.g. it is "Republic of Korea" in my survey and "South Korea" in that dataframe). When I merge these two dataframes, the score for those countries turn NA since they don't match.

I decided to build a dataframe of rows with the two different spellings being the two variables: should go about it?

```<code>                           correct_names                    incorrect
1                 BOSNIA AND HERZEGOVINA           BOSNIA HERZEGOVINA
2  CONGO- THE DEMOCRATIC REPUBLIC OF THE DEMOCRATIC REPUBLIC OF CONGO
3              IRAN- ISLAMIC REPUBLIC OF                         IRAN
4                     KOREA- REPUBLIC OF                  SOUTH KOREA
5                 LIBYAN ARAB JAMAHIRIYA                        LIBYA
6                               MALDIVES                         NONE
7                             MARTINIQUE                         NONE
8                                MAYOTTE                         NONE
9                   MOLDOVA- REPUBLIC OF                      MOLDOVA
10                    RUSSIAN FEDERATION                       RUSSIA
11                  SYRIAN ARAB REPUBLIC                        SYRIA
12             TAIWAN- PROVINCE OF CHINA                       TAIWAN
13          TANZANIA- UNITED REPUBLIC OF                     TANZANIA
14                  UNITED ARAB EMIRATES                         NONE
15                              VIET NAM                      VIETNAM
</code>```

Now I want R to replace the "incorrect" names in the dataframe with my "correct" names. Anyone has any idea how I should go about it?

Body:
So I have a list of countries in my survey with their specific spellings. I have another dataframe which has a score for each country, but the name of some of the countries are spelled differently than those in my survey (e.g. it is "Republic of Korea" in my survey and "South Korea" in that dataframe). When I merge these two dataframes, the score for those countries turn NA since they don't match.

I decided to build a dataframe of rows with the two different spellings being the two variables: should go about it?

                           correct_names                    incorrect
1                 BOSNIA AND HERZEGOVINA           BOSNIA HERZEGOVINA
2  CONGO- THE DEMOCRATIC REPUBLIC OF THE DEMOCRATIC REPUBLIC OF CONGO
3              IRAN- ISLAMIC REPUBLIC OF                         IRAN
4                     KOREA- REPUBLIC OF                  SOUTH KOREA
5                 LIBYAN ARAB JAMAHIRIYA                        LIBYA
6                               MALDIVES                         NONE
7                             MARTINIQUE                         NONE
8                                MAYOTTE                         NONE
9                   MOLDOVA- REPUBLIC OF                      MOLDOVA
10                    RUSSIAN FEDERATION                       RUSSIA
11                  SYRIAN ARAB REPUBLIC                        SYRIA
12             TAIWAN- PROVINCE OF CHINA                       TAIWAN
13          TANZANIA- UNITED REPUBLIC OF                     TANZANIA
14                  UNITED ARAB EMIRATES                         NONE
15                              VIET NAM                      VIETNAM

Now I want R to replace the "incorrect" names in the dataframe with my "correct" names. Anyone has any idea how I should go about it?


问:
Thymeleaf couldn't resolve a specific template only when running in a Docker container
In my spring-boot application i have a simple controller like this:

```<code>public Class MyController(){

    @GetMapping("/gioca")
    public String viewQuiz(Model model){
        //stuff
        return "gioca";
    }
}
</code>```

The template, gioca.html, is under resources/templates/, like the others.

No error shows while executing the app from IDE or command line (I've tried both mvn exec:java and java -jar app.jar after creating the jar file).

All seems fine, but when I create a Docker container that specific template stop working, giving me the following exception:

```<code> ERROR 1 --- [io-8080-exec-10] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-10] Exception processing template "gioca": Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers
...
ERROR 1 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers
</code>```

while all the other templates work just fine.

Here's my Dockerfile:

```<code>FROM openjdk:18-jdk-alpine
RUN addgroup -S spring && adduser -S spring -G spring
USER spring:spring
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
EXPOSE 8080
</code>```

Can anyone help me with this issue?

I tried to re-creating both the jar file and the container, rename the template, change the path but nothing worked.

Body:
In my spring-boot application i have a simple controller like this:

public Class MyController(){

    @GetMapping("/gioca")
    public String viewQuiz(Model model){
        //stuff
        return "gioca";
    }
}

The template, gioca.html, is under resources/templates/, like the others.

No error shows while executing the app from IDE or command line (I've tried both mvn exec:java and java -jar app.jar after creating the jar file).

All seems fine, but when I create a Docker container that specific template stop working, giving me the following exception:

 ERROR 1 --- [io-8080-exec-10] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-10] Exception processing template "gioca": Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers
...
ERROR 1 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [gioca], template might not exist or might not be accessible by any of the configured Template Resolvers

while all the other templates work just fine.

Here's my Dockerfile:

FROM openjdk:18-jdk-alpine
RUN addgroup -S spring && adduser -S spring -G spring
USER spring:spring
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
EXPOSE 8080

Can anyone help me with this issue?

I tried to re-creating both the jar file and the container, rename the template, change the path but nothing worked.


问:
What way of using $model in Vuelidate is more performant and stable?
I'm refactoring a validation for a complex object and I see that some of the code is written like that:
this.v$.object.$model.param.setting.value = someValue

And the rest is
this.v$.object.param.setting.value.$model = someValue

According to the docs $model is the reference to the exact value, which means for me that if I want to refer to a value I should use ...value.$model. But both ways work correctly. So I'm wondering is it a matter of code style or there could be performance issue when instead of referring to object.param.setting.value you changing whole object object.param.setting.value?


问:
ESP WiFi in AP mode with Flutter?
I want to connect my ESP8266 in AP mode with a Flutter aplication. The idea is the user, first can discover networks and next to connect it for connect to an ESP web server.
I tryied https://pub.dev/packages/wifi_scan and https://pub.dev/packages/wifi_iot but i got no results. And other package, however many are discontinued or with low support.
Do you have any ideas?</p>

Title: ESP WiFi in AP mode with Flutter?


问:
Two issue in my java code, incompatible types: possible lossy conversion from double to int and boolean cannot be converted to int
```<code>public class Applicants {
    //data fields
    private String name; //to hold the name
    private int[] academicData; //to hold the grades from 6 core CS courses

    //constructors
    public Applicants(){
        //default constructor
    }
    public Applicants(String name, int[] academicData){
        setName(name);
        setAcademicData(academicData);
    }
    public Applicants(String name){
        setName(name);
    }

    //getters and setters
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public int[] getAcademicData(){
        return academicData;
    }
    public void setAcademicData(int[] academicData){
        this.academicData = academicData;
    }

    //methods to analyze applications
    public boolean averageAbove85(){
        int sum = 0;
        for (int grade : academicData){
            sum += grade;
        }
        double average = sum / academicData.length;
        return average > 85;
    }
    public boolean noGradeBelow65(){
        for (int grade : academicData){
            if (grade < 65){
                return false;
            }
        }
        return true;
    }
    public boolean atleastFour85(){
        int count = 0;
        for (int grade : academicData){
            if (grade > 85){
                count++;
            }
        }
        return count >= 4;
    }
    public boolean upperLevelAbove85(){
        int sum = 0;
        for (int i = academicData.length - 4; i < academicData.length; i++){
            sum += academicData[i];
        }
        double average = sum / 4;
        return average > 85;
    }
    public boolean customFilter(int[] data){
        int sum = 0;
        int count = 0;
        for (int i = 0; i < data.length; i++){
            if (i < 6){
                sum += data[i];
            }
            else if (i >=6 && data[i] > 3.5){
                count++;
            }
        }
        double average = sum / 6;
        return (average > 70 && count > 0);
    }

}
</code>```
```<code>public class TestApplicants {
    public static void main(String[] args){
        Applicants applicant1 = new Applicants("John Doe", new int[]{90, 95, 80, 100, 75, 95});
        System.out.println(applicant1.averageAbove85()); //true
        System.out.println(applicant1.noGradeBelow65()); //true
        System.out.println(applicant1.atleastFour85()); //false
        System.out.println(applicant1.upperLevelAbove85()); //true
        System.out.println(applicant1.customFilter(new int[]{90, 95, 80, 100, 75, 95, 4.0, true, 3})); //true

        Applicants applicant2 = new Applicants("Jane Doe", new int[]{60, 70, 80, 85, 95, 100});
        System.out.println(applicant2.averageAbove85()); //true
        System.out.println(applicant2.noGradeBelow65()); //false
        System.out.println(applicant2.atleastFour85()); //true
        System.out.println(applicant2.upperLevelAbove85()); //true
        System.out.println(applicant2.customFilter(new int[]{60, 70, 80, 85, 95, 100, 3.2, false, 1})); //false
    }
}
</code>```

help! with fixing these two issues (incompatible types: boolean cannot be converted to int and possible lossy conversion from double to int), i tried replacing int with double but that didn't work, and i was thinking maybe boolean is the issue here but if someone can please take a look. these are two java files one is  Applicants and the other TestApplicants that work hand in hand!

Body:
public class Applicants {
    //data fields
    private String name; //to hold the name
    private int[] academicData; //to hold the grades from 6 core CS courses

    //constructors
    public Applicants(){
        //default constructor
    }
    public Applicants(String name, int[] academicData){
        setName(name);
        setAcademicData(academicData);
    }
    public Applicants(String name){
        setName(name);
    }

    //getters and setters
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public int[] getAcademicData(){
        return academicData;
    }
    public void setAcademicData(int[] academicData){
        this.academicData = academicData;
    }

    //methods to analyze applications
    public boolean averageAbove85(){
        int sum = 0;
        for (int grade : academicData){
            sum += grade;
        }
        double average = sum / academicData.length;
        return average > 85;
    }
    public boolean noGradeBelow65(){
        for (int grade : academicData){
            if (grade < 65){
                return false;
            }
        }
        return true;
    }
    public boolean atleastFour85(){
        int count = 0;
        for (int grade : academicData){
            if (grade > 85){
                count++;
            }
        }
        return count >= 4;
    }
    public boolean upperLevelAbove85(){
        int sum = 0;
        for (int i = academicData.length - 4; i < academicData.length; i++){
            sum += academicData[i];
        }
        double average = sum / 4;
        return average > 85;
    }
    public boolean customFilter(int[] data){
        int sum = 0;
        int count = 0;
        for (int i = 0; i < data.length; i++){
            if (i < 6){
                sum += data[i];
            }
            else if (i >=6 && data[i] > 3.5){
                count++;
            }
        }
        double average = sum / 6;
        return (average > 70 && count > 0);
    }

}

public class TestApplicants {
    public static void main(String[] args){
        Applicants applicant1 = new Applicants("John Doe", new int[]{90, 95, 80, 100, 75, 95});
        System.out.println(applicant1.averageAbove85()); //true
        System.out.println(applicant1.noGradeBelow65()); //true
        System.out.println(applicant1.atleastFour85()); //false
        System.out.println(applicant1.upperLevelAbove85()); //true
        System.out.println(applicant1.customFilter(new int[]{90, 95, 80, 100, 75, 95, 4.0, true, 3})); //true

        Applicants applicant2 = new Applicants("Jane Doe", new int[]{60, 70, 80, 85, 95, 100});
        System.out.println(applicant2.averageAbove85()); //true
        System.out.println(applicant2.noGradeBelow65()); //false
        System.out.println(applicant2.atleastFour85()); //true
        System.out.println(applicant2.upperLevelAbove85()); //true
        System.out.println(applicant2.customFilter(new int[]{60, 70, 80, 85, 95, 100, 3.2, false, 1})); //false
    }
}

help! with fixing these two issues (incompatible types: boolean cannot be converted to int and possible lossy conversion from double to int), i tried replacing int with double but that didn't work, and i was thinking maybe boolean is the issue here but if someone can please take a look. these are two java files one is  Applicants and the other TestApplicants that work hand in hand!


问:
Compare route with parameters
Compare a route with parameters wrote by user and a route allowed by system.

I am creating a PHP routing system and I need compare two routes.

The following route is allowed by the system, setting the parameter name between {}:

```<code>name/{var}/{var2}/edit
</code>```

And the following route is wrote by user, setting the parameter value between each /:

```<code>name/val/val2/edit
</code>```

Thanks for your help!

Title: Compare route with parameters

Body:
Compare a route with parameters wrote by user and a route allowed by system.

I am creating a PHP routing system and I need compare two routes.

The following route is allowed by the system, setting the parameter name between {}:

name/{var}/{var2}/edit

And the following route is wrote by user, setting the parameter value between each /:

name/val/val2/edit

Thanks for your help!


问:
How to optimize the game's sound effects
As various sound effects of the game were added, the sound effects naturally increased. However, I would like to ask you a problem that can solve this problem because the more music you add, the more you worry about optimizing the game.

I tried to reduce the sound effects of the game, but the sound effects were different, so I couldn't easily reduce them. If I know how to optimize, my game will go smoother.