问:
App Tracking Transparency with webview | Flutter app
My flutter app has access to some webviews, each webview opens a different page of the same website that has the cookie banner. I tought that the cookie banner would be enough for apple because the app doesn't actually track users, it's the website that does that.

Apple rejected my App because of this so I'm trying to find a way to incorporate the App Tracking Transparency but I can't find what I should do in the case the user disables the tracking, what is the correct behaviour that the app should have?

If I give the user access to the web do I still need to implement App Tracking Transparency? If not, would giving the option on a corner of the webview be enough or should I make the user choose where to open the pages before the actual webview shows?

Thank you all in advance.

答:
Indeed.The only way I have found is to make your webview be displayed is to ask permissions for tracking
You can use this plugin to achieve it.

https://pub.dev/packages/app_tracking_transparency

But probably if you give the option to open the URL into an external web app that could work as well.


来源: stackexchange

问:
Redux devtools with redux toolkit not working
I am trying to implement redux toolkit in to my react native project. Well the integration was successfull, however i am unable to get the redux dev tools to work. I did a bit of research and couldnt find any article related to redux toolkit and react native in combination. If anyone knows how to use the dev tools with rtk and react native, would be a great help</p>

答:
Usually when the redux dev tool is inactive / grayed out in react application, can mean that the store is not been initialized(passed as a prop), this maybe also your case, but I haven't used yet in RN. Maybe better to add a codesanbox to better check.

In general could be that you have forgot the commented part :

```<code>import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
 value: number
}

const initialState: CounterState = {  //--> part you my have forgot to define
  value: 0,
}
</code>```

or you have maybe forgot to connect the store to the app:

```<code>...
...
import { Provider } from "react-redux"
import { store } from "./app/store"

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>  // --> connecting the store
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Usually when the redux dev tool is inactive / grayed out in react application, can mean that the store is not been initialized(passed as a prop), this maybe also your case, but I haven't used yet in RN. Maybe better to add a codesanbox to better check.

In general could be that you have forgot the commented part :

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
 value: number
}

const initialState: CounterState = {  //--> part you my have forgot to define
  value: 0,
}

or you have maybe forgot to connect the store to the app:

...
...
import { Provider } from "react-redux"
import { store } from "./app/store"

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>  // --> connecting the store
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);


问:
Chrome Extension - Invalid Package. Details:Can't unzip the extension
I worked on a chrome extension and uploaded it to chrome webstore and everything went well, I installed it on my Mac and on my Ubuntu machines in chrome it worked fine and installed. But when I try it on Windows machines, after download it popups a error message saying "Invalid Package, Can't unzip the extension".

Can any one tell me why or what might be the cause for this OS specific issue. Does it have anything to do with the permission or anything with respective folder name or content? The folder name or the extension name don't have any special characters and the previous version was fine.

Thanks in advance.

答:
I had problems with zipping with MacOS. There was a bunch of hidden files in the zip.

Using Windows solved it but probably taking not the default zipper in MacOS should do the same.

ContentLicense: CC BY-SA 3.0


问:
Azure Create App Service Managed Certificates - runs for ours and then fails
I want to create a free certificate by "Create App Service Managed Certificates" for an App Service. It works for all my websites except one. The differnce between the problem domain and the other domains is that we used a paid certificate for this domain in the past - also generated by Azure.

I also deleted and recreated App Service - no luck.

Activity log says:

10:11 Accepted - Add or Update Certificate

10:11 Started - Add or Update Certificate

12:27 Failed - Add or Update Certificate (it failed after two hours)

ErrorCode: ResourceOperationFailure

Message:
The resource operation completed with terminal provisioning state 'Failed'.

EDIT:

I found the Deployment error message: "The subscription is not registered with Azure Key Vault."

答:
Apologies for the delay on this, Lopuch.

Kindly check the complete/exact error message that you received to isolate issue.

Typically, you could receive an error something like:

'code': 'DeploymentFailed',
'message': 'At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.',
'details': [
{
'code': 'BadRequest',
'message': 'Pending managed certificate failed: Certificate creation was rejected by CA for canonical name “Your domain name”:  The domain or certificate request triggered a risky domain check.

The free App Service Managed Certificate (ASMC) comes with the following limitations, kindly review or validate for your domain:

•   Does not support wildcard certificates.

•   Does not support usage as a client certificate by using certificate thumbprint.

•   Does not support private DNS.

•   Only supports alphanumeric characters, dashes (-), and periods (.).

Also note that the free certificate is issued by DigiCert. For some top-level domains, you must explicitly allow DigiCert as a certificate issuer by creating a CAA domain record with the value: 0 issue digicert.com.


问:
What is causing the '403 Forbidden error' in my Apache2 server? And how can I fix it? The available fixes on the web are not working for me
A little bit of context to my problem... I'm trying to deploy my django application following a tutorial (https://www.youtube.com/watch?v=Sa_kQheCnds) which uses linode to setup a linux apache server, and after following the steps, it always results in the same error, 403 Forbidden: You don't have permission to access this resource. I've followed the steps in this guide roughly 6 times now and I've determined that I'm definitely not doing anything the guy didn't do.

Something worth mentioning is that in the tutorial, Ubuntu 18.10 is being used, however I don't have Ubuntu 18.10 available, so I've tried it using Ubuntu 18.04, 20.04 and 21.10.

In my sixth and latest attempt, I am using Ubuntu 21.10

I've also tried running the server with DEBUG=True to see if I can get a little more insight on the error, but it just displays the following:

The tutorial is very long so I've broken down every single step in this post.

The steps I had to follow are:

(everything done in the Windows Linux Bash shell)

Creating Linode and analizing Ip Address and SSH Credentials I got

Root Connection to the Server

ssh into the server for the first time

Installing Software Updates

Running the command sudo apt-get update && apt-get upgrade

Setting Host Name

hostnamectl set-hostname SERVER_NAME

Then checking if it was rightfully executed with hostname

Setting Host File

nano /etc/hosts and then adding the IP address and server name to the file.

Adding Limited User

The guy in the video said it's not good practice to use root user because it's easy to mess things up like that so we created a limited user with adduser USER_NAME and then gave it sudo permissions with adduser USER_NAME sudo

Setting Up SSH Key Based Authentication

In my local machine's bash shell:
ssh keygen -b 4096
And deposit that file into my home folder, after that I copy that file over to my server with
scp ~/.ssh/id_rsa.pub user@serverip:~/.ssh/authorized_keys
then lasty confirming it was done correcty in the server with
ls .ssh

Setting Permissions for SSH Directory

Attach certain permision like
sudo chmod 700 ~/.ssh/
and
sudo chmod 600 ~/.ssh/*

Forbiding Root Login & Password Authentication

sudo nano /etc/ssh/sshh_config
to forbit #PermitRootLogin and #PasswordAuthentification
and then restart with
sudo systemctl restart sshd

Setting Up a Firewall

First, I install Uncomplicated Firewall with
sudo apt-get install ufw
and then I do the following commands:
sudo ufw default allow outgoing , sudo ufw default deny incoming , sudo ufw allow ssh and sudo ufw allow 8000.
After that, I enable the firewall with sudo ufw enable

Generating requirements.txt File

Here I actually did it a bit different that in the video. I open my VSCODE environment for the project in question, and then I run a pip freeze in the terminal to see if the dependencies are correct, if they are I write the requirements with pip freeze > requirements.txt

Copying Django Application on to the Webserver

This step is pretty straightforward. Just scp -r /folder/ user@serverip:~/ and that way the folder project is copied into the web server.

Creating Virtual Environment on the Server

First run a sudo apt-get install python3-pip and then pip install sudo apt-get install python3-venv. Once that's done, to create my virtual environment I do python3 -m venv django_project/venv and lastly I activate it by cding into the project's folder and then source venv/bin/activate.

Installing Dependencies

With my virtual environment running I run a pip install -r requirements.txt

Changing Django Settings for Testing the Application on Django Server

Inside the project's folder: sudo nano django_project/settings.py and add my server's IP to the allowed hosts list, and add a STATIC_ROOT directory.

Collecting Static Files

python manage.py collectstatic
Which could collect about 120 static files, but my project is a somewhat different from the on in the video because I added way more features so it collects about 137 files (in case these details are needed)

Testing Application

python manage.py runserver 0.0.0.0:8000 and then test to see if there is any problems, there are not (minus some variables I forgot to add because they were in my PC's environment variables) so I move on to the next step.

Installing Apache & ModWSGI

sudo apt-get install apache2, sudo apt-get install libapache2-mod-wsgi-py3.

Configuring Apache Webserver

Then move into the apache configuration folder cd /etc/apache2/sites-available/ and create a new configuration file based off the default one with sudo cp 000-default.conf django_project.conf, and then I edit with sudo nano django_project.conf it and add the following things to it: https://github.com/CoreyMSchafer/code_snippets/blob/master/Django_Blog/snippets/django_project.conf

Enabling Site Through Apache

Run the following commands:
sudo a2ensite django_project , sudo a2dissite 000-default.conf

Setting Up File Permissions

Run the following commands:
sudo chown :www-date django_project/db.sqlite3 , sudo chmod 664 django_project/db.sqlite3 and sudo chown :www-data django_project/. Then sudo chown -R :www-data django_project/media/andsudo chmod -R django_project/media```

Creating Configuration File for Hiding Sensitive Information

I won't detail this process, I just make a .json file with some secret information like the SECRET_KEY and the email and password.

Updating Project Settings File

I delete the sentitive information from the settings.py of the project, and instead add those with the .json file (like if it were an environment variable).

Allowing http Traffic

Run the following commands:
sudo ufw delete allow 8000, and sudo ufw allow http/tcp.

Restarting the Server & Running the Site

sudo service apache2 restart

Please, I'd appreciate any kind of help. I have to fix this error for a school project and I can't find solutions that actually fix it. I've read in some forums that I just needed to change certain permissions again, I did that and still the same error. It's really driving me crazy.

答:
I've found a solution, for now at least. I ran a sudo chmod 777 on my home folder so that literally every single file is accessible. I heard that this solution was not recommendable, but for now it will do.

I still don't know why other solutions that were posted didn't work for me, because it was of my understanding that every file that was needed to fun the server was inside the django_project folder.

I will be looking into it a bit more though, because I don't know how secure it is to have everysingle file with permisions.


问:
NestJS | Using OAuth along with Session
I'm using NestJS as a Service then I've got this problem. I don't usually deal with sessions and tokens.

I've been able to implement the session via passport-local, but I'm having a problem regarding Facebook and Google OAuth login it's not saving the session in the database, while the local guard does.

Below are the codes for the strategies and guards.

File: local.strategy.ts

```<code>
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { AuthService } from '../auth.service';
import { VerifyUserDto } from 'src/user/dto/VerifyUser.dto';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'UserID',
      passwordField: 'UserPass',
    });
  }

  async validate(UserID: string, UserPass: string): Promise<any> {
    const ToBeVerified = new VerifyUserDto();
    ToBeVerified.UserID = UserID;
    ToBeVerified.UserPass = UserPass;
    return await this.authService.ValidateUser(ToBeVerified);
  }
}
</code>```

File: google.strategy.ts

```<code>import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor() {
    super({
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      callbackURL: '/api/v1/google/redirect',
      scope: ['email', 'profile'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: any,
    done: VerifyCallback,
  ): Promise<any> {
    const data = {
      accessToken,
      profile,
      // refreshToken,
    };
    done(null, data);
  }
}
</code>```

File: facebook.strategy.ts

```<code>import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-facebook';

@Injectable()
export class FacebookStrategy extends PassportStrategy(Strategy, 'facebook') {
  constructor() {
    super({
      clientID: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_SECRET,
      callbackURL: '/api/v1/facebook/redirect',
      scope: ['email', 'profile'],
      // profileFields: ['emails', 'name'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: Profile,
    done: (err: any, user: any, info?: any) => void,
  ): Promise<any> {
    const data = {
      accessToken,
      profile,
    };
    done(null, data);
  }
}
</code>```

File: Local Guard

```<code>import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalGuard extends AuthGuard('local') {
  async canActivate(context: ExecutionContext) {
    const result = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest();
    await super.logIn(request);
    return result;
  }
}

export class Authenticated implements CanActivate {
  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    return request.isAuthenticated();
  }
}
</code>```

File: Google Guard

```<code>import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class GoogleGuard extends AuthGuard('google') {
  async canActivate(context: ExecutionContext) {
    const result = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest();
    await super.logIn(request);
    return result;
  }
}

export class Authenticated implements CanActivate {
  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    return request.isAuthenticated();
  }
}
</code>```

File: Facebook Guard

```<code>import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class FacebookGuard extends AuthGuard('facebook') {
  async canActivate(context: ExecutionContext) {
    const result = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest();
    await super.logIn(request);
    return result;
  }
}

export class Authenticated implements CanActivate {
  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    return request.isAuthenticated();
  }
}
</code>```

答:
I will share with You my code for google autorization

```<code>import { Injectable }               from '@nestjs/common';
import { ModuleRef }                from '@nestjs/core';
import { PassportStrategy }         from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { AuthService }              from '../services/auth.service';

export interface StrategyProfile<STRATEGY extends string> {
  id: string;
  displayName: string;
  name: {
    familyName: string; givenName: string;
  };
  emails: { value: string; verified: boolean; }[];
  photos: { value: string; }[];
  provider: STRATEGY;
}

export interface UserExternalAuthorization {
  providerId: string;
  providerName: string;

  eMail: string;
  name: string;
  avatar: string;
}

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private authService: AuthService, private moduleRef: ModuleRef) {
    super({
      clientID: process.env.GOOGLE_CLIENT_ID || '',
      clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
      callbackURL: 'http://localhost:3000/auth/redirect/google',
      scope: [ 'email', 'profile', ],
      // scope: [ 'email', 'profile', 'https://www.googleapis.com/auth/user.birthday.read' ], // not reading the date
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: StrategyProfile<'google'>,
    done: VerifyCallback,
  ): Promise<any> {
    const email = profile.emails.find((x) => x.verified);
    if (!email) {
      throw new Error('No verified email returned from Google Authorization!');
    }

    const user: UserExternalAuthorization = {
      providerId: profile.id,
      providerName: profile.provider,

      eMail: email.value,
      name: profile.displayName,
      avatar: profile?.photos[0]?.value,
    };

    const u = await this.authService.externalUser(user);

    done(null, u);
  }
}
</code>```

Function return await this.authService.ValidateUser(ToBeVerified); from local strategy, check against password (if its correct) and then returns user object im using for jwt (userId, loginType(google, local etc), userType(admin or not) and some other simple data - not many).

Function await this.authService.externalUser(user); from google-strategy returns same object, but also

creates user in the database (by email) if there was no such user before

do not check password (just is user was already there and was removed/banned)

So in every part of the system tokens im using have the same structure and i dont care from where user came).

As for Guard, im using one for each user (as i dont want to distinguish them on this level yet). AuthService is service for logging users and for changing password (even if you are not from local, your account is created and you would be able to log in using password unless you check different option in settings)

```<code>import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard }                    from '@nestjs/passport';
import { Observable }                   from 'rxjs';
import { AuthService }                  from '../services/auth.service';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {

  constructor(
    protected readonly dbService: AuthService,
  ) {super();}

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const can = super.canActivate(context);

    if (can instanceof Promise) {
      return new Promise(async (resolve, reject) => {
        can.then((c) => {
          // c !== true -> log notLogged
          resolve(c);
        }).catch((e) => {
          // logged denied, e.message
          reject(e);
        });
      });
    } else {
      return can;
    }
  }
}
</code>```

Also i made decorator for using in controllers

```<code>import { applyDecorators, UseGuards }             from '@nestjs/common';
import { ApiBearerAuth, ApiUnauthorizedResponse } from '@nestjs/swagger';
import { JwtAuthGuard }                           from '../guards/jwt-auth.guard';

export function IsLogged() {
  return applyDecorators(
    UseGuards(JwtAuthGuard),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({description: 'Unauthorized'}),
  );
}
</code>```

So in controllers you can have something like that

everything in controller locked for logged users

```<code>@IsLogged()
@Controller()
export class name {}
</code>```

just end point locked only for logged users

```<code>@Controller()
export class name {

  @IsLogged()
  @Get('/')
  async fName() {}
}
</code>```

I wish this helps and leverage some overburden of using many AuthGuard types

Title: NestJS | Using OAuth along with Session

Body:
I'm using NestJS as a Service then I've got this problem. I don't usually deal with sessions and tokens.

I've been able to implement the session via passport-local, but I'm having a problem regarding Facebook and Google OAuth login it's not saving the session in the database, while the local guard does.

Below are the codes for the strategies and guards.

File: local.strategy.ts

import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { AuthService } from '../auth.service';
import { VerifyUserDto } from 'src/user/dto/VerifyUser.dto';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'UserID',
      passwordField: 'UserPass',
    });
  }

  async validate(UserID: string, UserPass: string): Promise<any> {
    const ToBeVerified = new VerifyUserDto();
    ToBeVerified.UserID = UserID;
    ToBeVerified.UserPass = UserPass;
    return await this.authService.ValidateUser(ToBeVerified);
  }
}

File: google.strategy.ts

import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor() {
    super({
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      callbackURL: '/api/v1/google/redirect',
      scope: ['email', 'profile'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: any,
    done: VerifyCallback,
  ): Promise<any> {
    const data = {
      accessToken,
      profile,
      // refreshToken,
    };
    done(null, data);
  }
}

File: facebook.strategy.ts

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-facebook';

@Injectable()
export class FacebookStrategy extends PassportStrategy(Strategy, 'facebook') {
  constructor() {
    super({
      clientID: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_SECRET,
      callbackURL: '/api/v1/facebook/redirect',
      scope: ['email', 'profile'],
      // profileFields: ['emails', 'name'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: Profile,
    done: (err: any, user: any, info?: any) => void,
  ): Promise<any> {
    const data = {
      accessToken,
      profile,
    };
    done(null, data);
  }
}

File: Local Guard

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalGuard extends AuthGuard('local') {
  async canActivate(context: ExecutionContext) {
    const result = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest();
    await super.logIn(request);
    return result;
  }
}

export class Authenticated implements CanActivate {
  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    return request.isAuthenticated();
  }
}

File: Google Guard

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class GoogleGuard extends AuthGuard('google') {
  async canActivate(context: ExecutionContext) {
    const result = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest();
    await super.logIn(request);
    return result;
  }
}

export class Authenticated implements CanActivate {
  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    return request.isAuthenticated();
  }
}

File: Facebook Guard

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class FacebookGuard extends AuthGuard('facebook') {
  async canActivate(context: ExecutionContext) {
    const result = (await super.canActivate(context)) as boolean;
    const request = context.switchToHttp().getRequest();
    await super.logIn(request);
    return result;
  }
}

export class Authenticated implements CanActivate {
  async canActivate(context: ExecutionContext) {
    const request = context.switchToHttp().getRequest();
    return request.isAuthenticated();
  }
}

Body:
I will share with You my code for google autorization

import { Injectable }               from '@nestjs/common';
import { ModuleRef }                from '@nestjs/core';
import { PassportStrategy }         from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { AuthService }              from '../services/auth.service';

export interface StrategyProfile<STRATEGY extends string> {
  id: string;
  displayName: string;
  name: {
    familyName: string; givenName: string;
  };
  emails: { value: string; verified: boolean; }[];
  photos: { value: string; }[];
  provider: STRATEGY;
}

export interface UserExternalAuthorization {
  providerId: string;
  providerName: string;

  eMail: string;
  name: string;
  avatar: string;
}

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private authService: AuthService, private moduleRef: ModuleRef) {
    super({
      clientID: process.env.GOOGLE_CLIENT_ID || '',
      clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
      callbackURL: 'http://localhost:3000/auth/redirect/google',
      scope: [ 'email', 'profile', ],
      // scope: [ 'email', 'profile', 'https://www.googleapis.com/auth/user.birthday.read' ], // not reading the date
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: StrategyProfile<'google'>,
    done: VerifyCallback,
  ): Promise<any> {
    const email = profile.emails.find((x) => x.verified);
    if (!email) {
      throw new Error('No verified email returned from Google Authorization!');
    }

    const user: UserExternalAuthorization = {
      providerId: profile.id,
      providerName: profile.provider,

      eMail: email.value,
      name: profile.displayName,
      avatar: profile?.photos[0]?.value,
    };

    const u = await this.authService.externalUser(user);

    done(null, u);
  }
}

Function return await this.authService.ValidateUser(ToBeVerified); from local strategy, check against password (if its correct) and then returns user object im using for jwt (userId, loginType(google, local etc), userType(admin or not) and some other simple data - not many).

Function await this.authService.externalUser(user); from google-strategy returns same object, but also

creates user in the database (by email) if there was no such user before

do not check password (just is user was already there and was removed/banned)

So in every part of the system tokens im using have the same structure and i dont care from where user came).

As for Guard, im using one for each user (as i dont want to distinguish them on this level yet). AuthService is service for logging users and for changing password (even if you are not from local, your account is created and you would be able to log in using password unless you check different option in settings)

import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard }                    from '@nestjs/passport';
import { Observable }                   from 'rxjs';
import { AuthService }                  from '../services/auth.service';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {

  constructor(
    protected readonly dbService: AuthService,
  ) {super();}

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const can = super.canActivate(context);

    if (can instanceof Promise) {
      return new Promise(async (resolve, reject) => {
        can.then((c) => {
          // c !== true -> log notLogged
          resolve(c);
        }).catch((e) => {
          // logged denied, e.message
          reject(e);
        });
      });
    } else {
      return can;
    }
  }
}

Also i made decorator for using in controllers

import { applyDecorators, UseGuards }             from '@nestjs/common';
import { ApiBearerAuth, ApiUnauthorizedResponse } from '@nestjs/swagger';
import { JwtAuthGuard }                           from '../guards/jwt-auth.guard';

export function IsLogged() {
  return applyDecorators(
    UseGuards(JwtAuthGuard),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({description: 'Unauthorized'}),
  );
}

So in controllers you can have something like that

everything in controller locked for logged users

@IsLogged()
@Controller()
export class name {}

just end point locked only for logged users

@Controller()
export class name {

  @IsLogged()
  @Get('/')
  async fName() {}
}

I wish this helps and leverage some overburden of using many AuthGuard types


问:
unable to find timezone in django

What I am doing.

I am working on a very basic django project.

what is my problem.

When I am loading my webpage (locally) it is showing following error on webpage.

```<code>A server error occurred.  Please contact the administrator
</code>```

and error that I saw on terminal is

```<code>zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key utc'
</code>```

答:
Running the command below in the terminal should fix the issue:

pip3 install tzdata

or

pip install tzdata

Title: unable to find timezone in django

Body:
What I am doing.

I am working on a very basic django project.

what is my problem.

When I am loading my webpage (locally) it is showing following error on webpage.

A server error occurred.  Please contact the administrator

and error that I saw on terminal is

zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key utc'


问:
Display Google Map API in Python Tkinter window
Hi I am working on Google Map API in Python. I am using the source code which can be found at this website

This code when compiled produces a 'htm' file showing a Google Map with the markers placed on the map.

So I have created a Window Frame shown below:

```<code>from Tkinter import *  # order seems to matter: import Tkinter first
import Image, ImageTk  # then import ImageTk
class MyFrame(Frame):
    def __init__(self, master, im):
        Frame.__init__(self, master)
        self.caption = Label(self, text="Some text about the map")
        self.caption.grid()
        self.image = ImageTk.PhotoImage(im) # <--- results of PhotoImage() must be stored
        self.image_label = Label(self, image=self.image, bd=0) # <--- will not work if 'image = ImageTk.PhotoImage(im)'
    self.image_label.grid()
    self.grid()

im = Image.open("test.html") # read map from disk

# or you could use the PIL image you created directly via option 2 from the URL request ...
mainw = Tk()
mainw.frame = MyFrame(mainw, im)
mainw.mainloop()
</code>```

And with that Window Frame I want to display the 'htm' image of the Google Map in that Window Frame.

答:
If somebody wants to have an interactive Google-Maps widget inside their Tkinter application like in the example above, I wrote a small library that displays tile based maps. The standard server is OpenStreetMap but you can change it to Google-Maps if you want. But note that the Google-Maps tile server is deprecated and will probably don't work at some point in the future.

Documentation: https://github.com/TomSchimansky/TkinterMapView

Install: pip3 install tkintermapview

With the following code you get a fully working Google-Maps widget inside a Tkinter window:

import tkinter
from tkintermapview import TkinterMapView

root_tk = tkinter.Tk()
root_tk.geometry(f"{600}x{400}")
root_tk.title("map_view_simple_example.py")

# create map widget
map_widget = TkinterMapView(root_tk, width=600, height=400, corner_radius=0)
map_widget.pack(fill="both", expand=True)

# google normal tile server
self.map_widget.set_tile_server("https://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22)

map_widget.set_address("Berlin Germany", marker=True)

root_tk.mainloop()
```

Body:
Hi I am working on Google Map API in Python. I am using the source code which can be found at this website

This code when compiled produces a 'htm' file showing a Google Map with the markers placed on the map.

So I have created a Window Frame shown below:

from Tkinter import *  # order seems to matter: import Tkinter first
import Image, ImageTk  # then import ImageTk
class MyFrame(Frame):
    def __init__(self, master, im):
        Frame.__init__(self, master)
        self.caption = Label(self, text="Some text about the map")
        self.caption.grid()
        self.image = ImageTk.PhotoImage(im) # <--- results of PhotoImage() must be stored
        self.image_label = Label(self, image=self.image, bd=0) # <--- will not work if 'image = ImageTk.PhotoImage(im)'
    self.image_label.grid()
    self.grid()

im = Image.open("test.html") # read map from disk

# or you could use the PIL image you created directly via option 2 from the URL request ...
mainw = Tk()
mainw.frame = MyFrame(mainw, im)
mainw.mainloop()

And with that Window Frame I want to display the 'htm' image of the Google Map in that Window Frame.


问:
ToolTip is not closing with Select2
I am using jQuery UI ToolTip with Select2. My code is like below.

```<code>$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('<span class="tooltip" title="' + data_format.title + '">' + data_format.text + '</span>');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('<span class="tooltip" title="' + state.title + '">' + state.text + '('+ state.text1 +')</span>');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '<table> \
                        <tr> \
                        <td>Organisation</td> \
                        <td>'+text[2][1]+'</td> \
                        </tr> \
                        <tr> \
                        <td>Age</td> \
                        <td>'+ text[2][0]+'</td> \
                        </tr> \
                    </table>';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("<div>")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});

</code>```

After selection of a value ToolTip is not closing.

I am getting below error message in console.

$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('' + data_format.text + '');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('' + state.text + '('+ state.text1 +')');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '
 \

 \
                        Organisation	 \
                        '+text[2][1]+'	 \

 \

 \
                        Age	 \
                        '+ text[2][0]+'	 \

 \

';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("
")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>

<table style="text-align:left;min-width:800px;margin-top: 0 !important;">
                    <tbody><tr>
                    <th style="min-width:100px">Task +</th>
                    <th style="min-width:150px">Time</th>
                    <th style="min-width:180px">volunteers</th>
                    <th style="width:50%">Comment</th></tr><tr>
                    <td>test 1</td>
                    <td>09:00 - 12:00</td>
                    <td class="volunteer" id="1485"></td>
                    <td><p>hello</p>
</td>
                    </tr><tr>
                    <td>test2</td>
                    <td>09:00 - 12:00</td>
                    <td class="volunteer" id="1486"></td>
                    <td><p>test</p>
</td>
                    </tr></tbody></table></code>```

Three state of the issue.

First state when I click on td and select2 drop down is displaying.

Second state when I hove over a value of select2 drop down and ToolTip is displaying.

Third state when I click on a value of select2 and that value is selected but Tooltip still displaying. I need to close, remove or destroy the ToolTip. I can see an error message in console also.

I am trying to replicate my issue here. But I am not so expert about jsfiddle that's why I couldn't do it properly.

答:
```<code> <script>
        $(function() {
            $('[data-toggle="tooltip"]').tooltip()
        });
    </script>
</code>```

Try this script. It may help you.

Title: ToolTip is not closing with Select2

Body:
I am using jQuery UI ToolTip with Select2. My code is like below.

$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('' + data_format.text + '');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('' + state.text + '('+ state.text1 +')');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '
 \

 \
                        Organisation	 \
                        '+text[2][1]+'	 \

 \

 \
                        Age	 \
                        '+ text[2][0]+'	 \

 \

';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("
")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});

After selection of a value ToolTip is not closing.

I am getting below error message in console.

$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('' + data_format.text + '');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('' + state.text + '('+ state.text1 +')');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '
 \

 \
                        Organisation	 \
                        '+text[2][1]+'	 \

 \

 \
                        Age	 \
                        '+ text[2][0]+'	 \

 \

';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("
")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});

                    Task +
                    Time
                    volunteers
                    Comment

                    test 1
                    09:00 - 12:00

hello

                    test2
                    09:00 - 12:00

test

Three state of the issue.

First state when I click on td and select2 drop down is displaying.

Second state when I hove over a value of select2 drop down and ToolTip is displaying.

Third state when I click on a value of select2 and that value is selected but Tooltip still displaying. I need to close, remove or destroy the ToolTip. I can see an error message in console also.

I am trying to replicate my issue here. But I am not so expert about jsfiddle that's why I couldn't do it properly.

Body:
 <script>
        $(function() {
            $('[data-toggle="tooltip"]').tooltip()
        });
    </script>

Try this script. It may help you.


问:
How to make a simple Python Text Server
I'm trying to make a webserver that serves string. Yes, that's it, just string, no variables, no CSS. The problem has been the refresh. Assume that the string changes every second, stored in a Python variable. The problem is serving to the client, I want to make it so that the client doesn't have to request the page again, rather, the server sends the new string every time it's updated.

I tried Cherrypy but the method used is a return one, which exits a loop. How can I make this "simple" web server? Really new to sockets programming too.. Just heard the term yesterday..
Edit : I think it should be served by HTML.. I want it to be able to be opened via browsers
Edit: I think the pseudocode should be like this

```<code>def loopingfunction:
    do things
    return var
def server:
    while True:
         displayed_text=loopingfunction()
         send_displayed_text_to_client()
</code>```

答:
Solved! Using https://github.com/ChrisKnott/Eel/tree/master/eel , this is achievable.

Basically, initalize a web server that exposes python functions, and then refresh the page and change the contents using javascript, receiving variables from python.

Title: How to make a simple Python Text Server

Body:
I'm trying to make a webserver that serves string. Yes, that's it, just string, no variables, no CSS. The problem has been the refresh. Assume that the string changes every second, stored in a Python variable. The problem is serving to the client, I want to make it so that the client doesn't have to request the page again, rather, the server sends the new string every time it's updated.

I tried Cherrypy but the method used is a return one, which exits a loop. How can I make this "simple" web server? Really new to sockets programming too.. Just heard the term yesterday..
Edit : I think it should be served by HTML.. I want it to be able to be opened via browsers
Edit: I think the pseudocode should be like this

def loopingfunction:
    do things
    return var
def server:
    while True:
         displayed_text=loopingfunction()
         send_displayed_text_to_client()


问:
How to output formated text but with added values - Python
I am new to Python and I can´t find any way to execute this code.

I am using JSON generator and need to print formated code and add some changes to it. I have variables that have some values and I need to insert them into my code. So the final code will have exact formating but with added values.

hp = 50;
cp = 100;
wp = 40;

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "<hp (value of hp here)>",
        "Combat Power": "<cp (value of cp here)>",
        "Working Power": "<wp (value of wp here)>",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }```
</div>
</div>
</p>
<p>Final output (I want to generate 100 of this same code with exact formating but with different hp wp and cp values.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "50",
        "Combat Power": "100",
        "Working Power": "40",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }</code>```

答:
```<code># you don't need semi colon after variable
hp = 50
cp = 100
wp = 40
# use variable name directly without quotes
"Health Points": hp,
"Combat Power": cb,
"Working Power": wp,
</code>```

Body:
I am new to Python and I can´t find any way to execute this code.

I am using JSON generator and need to print formated code and add some changes to it. I have variables that have some values and I need to insert them into my code. So the final code will have exact formating but with added values.

hp = 50;
cp = 100;
wp = 40;

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "<hp (value of hp here)>",
        "Combat Power": "<cp (value of cp here)>",
        "Working Power": "<wp (value of wp here)>",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }

Final output (I want to generate 100 of this same code with exact formating but with different hp wp and cp values.

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "50",
        "Combat Power": "100",
        "Working Power": "40",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }


问:
Compare 2-dimensional data sets based on a specified second level value
I have an array containing rows of associative data.

```<code>$array1 = array(
    array('ITEM' => 1),
    array('ITEM' => 2),
    array('ITEM' => 3),
);
</code>```

I have a second array, also containing rows of associative data, that I would like to filter using the first array.

```<code>$array2 = array(
    array('ITEM' => 2),
    array('ITEM' => 3),
    array('ITEM' => 1),
    array('ITEM' => 4),
);
</code>```

This feels like a job for array_diff(), but how can I compare the rows exclusively on the deeper ITEM values?

How can I filter the second array and get the following result?

```<code>array(3 => array('ITEM' => 4))
</code>```

答:
Trust that the maintainers of PHP have optimized array_udiff() to outperform all other techniques which could do the same.

With respect to your scenario, you are seeking a filtering array_diff() that evaluates data within the first level's "value" (the row of data).  Within the custom function, the specific column must be isolated for comparison.  For a list of all native array_diff() function variations, see this answer.

To use the first array to filter the second array (and output the retained data from the second array), you must write $array2 as the first parameter and $array1 as the second parameter.

array_diff() and array_intersect() functions that leverage (contain u in their function name) expect an integer as their return value.  That value is used to preliminary sort the data before actually performing the evaluations -- this is a performance optimization.  There may be scenarios where if you only return 0 or 1 (not a three-way comparison), then the results may be unexpected.  To ensure a stable result, always provide a comparison function that can return a negative, a positive, and a zero integer.

When comparing integer values, subtraction ($a - $b) will give reliable return values.  For greater utility when comparing float values or non-numeric data, you can use the spaceship operator when your PHP version makes it available.

Codes: (Demo)

PHP7.4+ (arrow functions)

```<code>var_export(
    array_udiff($array2, $array1, fn($a, $b) => $a['ITEM'] <=> $b['ITEM'])
);
</code>```

PHP7+ (spaceship operator)

```<code>var_export(
    array_udiff(
        $array2,
        $array1,
        function($a, $b) {
            return $a['ITEM'] <=> $b['ITEM'];
        }
    )
);
</code>```

PHP5.3+ (anonymous functions)

```<code>var_export(
    array_udiff(
        $array2,
        $array1,
        function($a, $b) {
            return $a['ITEM'] === $b['ITEM']
                ? 0
                : ($a['ITEM'] > $b['ITEM'] ? 1 : -1);
        }
    )
);
</code>```

Output for all version above:

```<code>array (
  3 =>
  array (
    'ITEM' => 4,
  ),
)
</code>```

When working with object arrays, the technique is the same; only the syntax to access a property is different from accessing an array element ($a['ITEM'] would be $a->ITEM).

For scenarios where the element being isolated from one array does not exist in the other array, you will need to coalesce both $a and $b data to the opposite fallback column because the data from the first array and the second arrays will be represented in both arguments of the callback.

Code: (Demo)

```<code>$array1 = array(
    array('ITEM' => 1),
    array('ITEM' => 2),
    array('ITEM' => 3),
);

$array2 = array(
    array('ITEMID' => 2),
    array('ITEMID' => 3),
    array('ITEMID' => 1),
    array('ITEMID' => 4),
);

// PHP7.4+ (arrow functions)
var_export(
    array_udiff(
        $array2,
        $array1,
        fn($a, $b) => ($a['ITEM'] ?? $a['ITEMID']) <=> ($b['ITEM'] ?? $b['ITEMID'])
    )
);
</code>```

Body:
I have an array containing rows of associative data.

$array1 = array(
    array('ITEM' => 1),
    array('ITEM' => 2),
    array('ITEM' => 3),
);

I have a second array, also containing rows of associative data, that I would like to filter using the first array.

$array2 = array(
    array('ITEM' => 2),
    array('ITEM' => 3),
    array('ITEM' => 1),
    array('ITEM' => 4),
);

This feels like a job for array_diff(), but how can I compare the rows exclusively on the deeper ITEM values?

How can I filter the second array and get the following result?

array(3 => array('ITEM' => 4))

Body:
Trust that the maintainers of PHP have optimized array_udiff() to outperform all other techniques which could do the same.

With respect to your scenario, you are seeking a filtering array_diff() that evaluates data within the first level's "value" (the row of data).  Within the custom function, the specific column must be isolated for comparison.  For a list of all native array_diff() function variations, see this answer.

To use the first array to filter the second array (and output the retained data from the second array), you must write $array2 as the first parameter and $array1 as the second parameter.

array_diff() and array_intersect() functions that leverage (contain u in their function name) expect an integer as their return value.  That value is used to preliminary sort the data before actually performing the evaluations -- this is a performance optimization.  There may be scenarios where if you only return 0 or 1 (not a three-way comparison), then the results may be unexpected.  To ensure a stable result, always provide a comparison function that can return a negative, a positive, and a zero integer.

When comparing integer values, subtraction ($a - $b) will give reliable return values.  For greater utility when comparing float values or non-numeric data, you can use the spaceship operator when your PHP version makes it available.

Codes: (Demo)

PHP7.4+ (arrow functions)

var_export(
    array_udiff($array2, $array1, fn($a, $b) => $a['ITEM'] <=> $b['ITEM'])
);

PHP7+ (spaceship operator)

var_export(
    array_udiff(
        $array2,
        $array1,
        function($a, $b) {
            return $a['ITEM'] <=> $b['ITEM'];
        }
    )
);

PHP5.3+ (anonymous functions)

var_export(
    array_udiff(
        $array2,
        $array1,
        function($a, $b) {
            return $a['ITEM'] === $b['ITEM']
                ? 0
                : ($a['ITEM'] > $b['ITEM'] ? 1 : -1);
        }
    )
);

Output for all version above:

array (
  3 =>
  array (
    'ITEM' => 4,
  ),
)

When working with object arrays, the technique is the same; only the syntax to access a property is different from accessing an array element ($a['ITEM'] would be $a->ITEM).

For scenarios where the element being isolated from one array does not exist in the other array, you will need to coalesce both $a and $b data to the opposite fallback column because the data from the first array and the second arrays will be represented in both arguments of the callback.

Code: (Demo)

$array1 = array(
    array('ITEM' => 1),
    array('ITEM' => 2),
    array('ITEM' => 3),
);

$array2 = array(
    array('ITEMID' => 2),
    array('ITEMID' => 3),
    array('ITEMID' => 1),
    array('ITEMID' => 4),
);

// PHP7.4+ (arrow functions)
var_export(
    array_udiff(
        $array2,
        $array1,
        fn($a, $b) => ($a['ITEM'] ?? $a['ITEMID']) <=> ($b['ITEM'] ?? $b['ITEMID'])
    )
);


问:
remark-prism doesn't convert to HTML with classnames
I wanted to convert markdown to syntax highlighted HTML with remark and remark-prism. But it doesn't work.

code:

import {remark} from "remark";
import prism from "remark-prism";
import html from "remark-html";

const text = '```javascript\nconsole.log("Hello, world");\n```';
remark()
  .use(prism)
  .use(html)
  .process(text, (_, {value}) => console.log(value));
```
<p>result:</p>
<pre class="lang-html prettyprint-override"><code><div>
  ```

      console
      .
      log
      (
      "Hello, world"
      )
      ;

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

It looks good. But it doesn't contain classnames.

I wanted just like:

      console
      .
      log
      (
      "Hello World"
      )
      ;

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

答:
According this site, change just like below code, the code correctory work.

const content = await remark()
  .use(prism)
  .use(html, { sanitize: false })
  .process(markdown);
```

Body:
I wanted to convert markdown to syntax highlighted HTML with remark and remark-prism. But it doesn't work.

code:

import {remark} from "remark";
import prism from "remark-prism";
import html from "remark-html";

const text = '```javascript\nconsole.log("Hello, world");\n```';
remark()
  .use(prism)
  .use(html)
  .process(text, (_, {value}) => console.log(value));

result:

      console
      .
      log
      (
      "Hello, world"
      )
      ;

It looks good. But it doesn't contain classnames.

I wanted just like:

      console
      .
      log
      (
      "Hello World"
      )
      ;


问:
Show records ordering by status value
I have a table called communications in laravel and in it I have the status column, where status can be approved, error, pending, canceled. What I need is to bring all the records in order by status, where I define which one should appear first, for example:

all records that have error status

all records that have pending status

all records with approved status

答:
Answer:</p>
```<code>$query = "CASE WHEN status = 'error' THEN 1 ";
$query .= "WHEN status = 'pending' THEN 2 ";
$query .= "WHEN status = 'approved' THEN 3 ";
$query .= "ELSE 4 END ASC";
return $this->communication->query()->orderByRaw($query)->paginate($perPage);
</code>```

Title: Show records ordering by status value

Body:
Answer:

$query = "CASE WHEN status = 'error' THEN 1 ";
$query .= "WHEN status = 'pending' THEN 2 ";
$query .= "WHEN status = 'approved' THEN 3 ";
$query .= "ELSE 4 END ASC";
return $this->communication->query()->orderByRaw($query)->paginate($perPage);


问:
Checking for last entity position to move the entity randomly to somewhere else
I am trying to make a game like grindshot in aimlab using ursina engine. I need to move the targets each time you click on them. They should move somewhere where already isn´t any target. This part works but they ocassionally don´t change the position because they are randomly moved to the same position as they were before I think. (It sometimes takes 2 clicks to move the target)

I tried to create a new variable (previousposition) in which I stored the previous position but it didn´t work and the program froze. I think its because the variable changes with the new position and then it goes to an endless loop. Please help.

```<code>import random

from ursina.prefabs.first_person_controller import FirstPersonController

class Cube(Entity):
   def __init__(self, position = (0,0,0)):
       super().__init__(
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.white,
           collider= 'box')

class Target(Button):
   def __init__(self, position = (0,0,0), scale = (0.7, 0.7, 0.7)):
       super().__init__(
           parent = scene,
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.red,
           highlight_color = rgb(255, 88, 74),
           scale = scale)

   def input(self, key):
       if self.hovered:
           if key == "left mouse down":
               mouse.hovered_entity.x = random.randint(-2,2)
               mouse.hovered_entity.y = random.randint(1, 4)
               while target1.position == target2.position or target1.position == target3.position or target2.position == target3.position:
                   mouse.hovered_entity.x = random.randint(-2, 2)
                   mouse.hovered_entity.y = random.randint(1, 4)

app = Ursina()

target1 = Target(position = (0,3, 5))
target2 = Target(position = (1,4, 5))
target3 = Target(position = (2,2, 5))

for x in range(9):
   for z in range(9):
       floor = Cube(position = (x-4,0,z-4))

player = FirstPersonController()

app.run()
__________________________________________________________________________________________________
#Not Working

from ursina import *
import random

from ursina.prefabs.first_person_controller import FirstPersonController

class Cube(Entity):
   def __init__(self, position = (0,0,0)):
       super().__init__(
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.white,
           highlight_color = color.red,
           collider= 'box')

class Target(Button):
   def __init__(self, previousposition, position = (0,0,0), scale = (0.7, 0.7, 0.7)):
       super().__init__(
           parent = scene,
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.red,
           highlight_color = color.red,
           scale = scale)
       self.previousposition = previousposition

   def input(self, key):
       if self.hovered:
           if key == "left mouse down":
               mouse.hovered_entity.position = self.previousposition
               mouse.hovered_entity.x = random.randint(-2,2)
               mouse.hovered_entity.y = random.randint(1, 4)
               while target1.position == target2.position or target1.position == target3.position or target2.position == target3.position:
                   mouse.hovered_entity.x = random.randint(-2, 2)
                   mouse.hovered_entity.y = random.randint(1, 4)
               while self.previousposition == target1.position or target2.position or target3.position:
                   mouse.hovered_entity.x = random.randint(-2, 2)
                   mouse.hovered_entity.y = random.randint(1, 4)

app = Ursina()

target1 = Target((0,0,0), position = (0,3, 5))
target2 = Target((0,0,0), position = (1,4, 5))
target3 = Target((0,0,0), position = (2,2, 5))

for x in range(9):
   for z in range(9):
       floor = Cube(position = (x-4,0,z-4))

player = FirstPersonController()

app.run()
</code>```

答:
Instead of generating a position and checking it it's not the same, avoid that position in the first place:

Generate a list of possible positions. You can change the range for different values. This will make a list like this: [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]

import itertools
possible_positions = [[(x,y) for y in range(4)] for x in range(3)]
possible_positions = list(itertools.chain(*possible_positions)) # flatten list
```
<p>Use list comprehension to remove the current position from possible positions and choose a random element from the new list:</p>
<pre class="lang-py prettyprint-override"><code>entity.position = random.choice([coordinate for coordinate in possible_positions if coordinate != (int(entity.x), int(entity.y))])
</code>```

Body:
I am trying to make a game like grindshot in aimlab using ursina engine. I need to move the targets each time you click on them. They should move somewhere where already isn´t any target. This part works but they ocassionally don´t change the position because they are randomly moved to the same position as they were before I think. (It sometimes takes 2 clicks to move the target)

I tried to create a new variable (previousposition) in which I stored the previous position but it didn´t work and the program froze. I think its because the variable changes with the new position and then it goes to an endless loop. Please help.

import random

from ursina.prefabs.first_person_controller import FirstPersonController

class Cube(Entity):
   def __init__(self, position = (0,0,0)):
       super().__init__(
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.white,
           collider= 'box')

class Target(Button):
   def __init__(self, position = (0,0,0), scale = (0.7, 0.7, 0.7)):
       super().__init__(
           parent = scene,
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.red,
           highlight_color = rgb(255, 88, 74),
           scale = scale)

   def input(self, key):
       if self.hovered:
           if key == "left mouse down":
               mouse.hovered_entity.x = random.randint(-2,2)
               mouse.hovered_entity.y = random.randint(1, 4)
               while target1.position == target2.position or target1.position == target3.position or target2.position == target3.position:
                   mouse.hovered_entity.x = random.randint(-2, 2)
                   mouse.hovered_entity.y = random.randint(1, 4)

app = Ursina()

target1 = Target(position = (0,3, 5))
target2 = Target(position = (1,4, 5))
target3 = Target(position = (2,2, 5))

for x in range(9):
   for z in range(9):
       floor = Cube(position = (x-4,0,z-4))

player = FirstPersonController()

app.run()
__________________________________________________________________________________________________
#Not Working

from ursina import *
import random

from ursina.prefabs.first_person_controller import FirstPersonController

class Cube(Entity):
   def __init__(self, position = (0,0,0)):
       super().__init__(
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.white,
           highlight_color = color.red,
           collider= 'box')

class Target(Button):
   def __init__(self, previousposition, position = (0,0,0), scale = (0.7, 0.7, 0.7)):
       super().__init__(
           parent = scene,
           position = position,
           model = "cube",
           origin_y = 0.5,
           texture = "white_cube",
           color = color.red,
           highlight_color = color.red,
           scale = scale)
       self.previousposition = previousposition

   def input(self, key):
       if self.hovered:
           if key == "left mouse down":
               mouse.hovered_entity.position = self.previousposition
               mouse.hovered_entity.x = random.randint(-2,2)
               mouse.hovered_entity.y = random.randint(1, 4)
               while target1.position == target2.position or target1.position == target3.position or target2.position == target3.position:
                   mouse.hovered_entity.x = random.randint(-2, 2)
                   mouse.hovered_entity.y = random.randint(1, 4)
               while self.previousposition == target1.position or target2.position or target3.position:
                   mouse.hovered_entity.x = random.randint(-2, 2)
                   mouse.hovered_entity.y = random.randint(1, 4)

app = Ursina()

target1 = Target((0,0,0), position = (0,3, 5))
target2 = Target((0,0,0), position = (1,4, 5))
target3 = Target((0,0,0), position = (2,2, 5))

for x in range(9):
   for z in range(9):
       floor = Cube(position = (x-4,0,z-4))

player = FirstPersonController()

app.run()

Body:
Instead of generating a position and checking it it's not the same, avoid that position in the first place:

Generate a list of possible positions. You can change the range for different values. This will make a list like this: [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]

import itertools
possible_positions = [[(x,y) for y in range(4)] for x in range(3)]
possible_positions = list(itertools.chain(*possible_positions)) # flatten list

Use list comprehension to remove the current position from possible positions and choose a random element from the new list:

entity.position = random.choice([coordinate for coordinate in possible_positions if coordinate != (int(entity.x), int(entity.y))])


问:
MEL to DataWeave conversion
We are migrating Mule 3 app to Mule 4 where we have encountered below MEL. Any inputs on how to convert it to DataWeave.</p>
```<code>mel:prevProperties.get(payload.get("A1 - Roll Number")) == null ? prevProperties.put(payload.get("A1 - Roll Number"), payload.get("M7 - Detailed status")) : duplicateRecords.put(payload.get("A1 - Roll Number"),": Duplicate Name Found By ID")
</code>```

答:
So this script can not be migrated as is to mule 4 as it uses side effects something that is not allowed in DW.

```<code>prevProperties.get(payload.get("A1 - Roll Number")) == null ?
        prevProperties.put(payload.get("A1 - Roll Number"), payload.get("M7 - Detailed status")) :
        duplicateRecords.put(payload.get("A1 - Roll Number"),": Duplicate Name Found By ID")
</code>```

So in order to map this semantically we need to get more context on your flow. To map syntactically the parts that can be mapped will be something like

```<code>if(prevProperties[payload["A1 - Roll Number"]] == null)
    prevProperties ++ {(payload["A1 - Roll Number"]): payload["M7 - Detailed status"]}
else duplicateRecords ++ {(payload["A1 - Roll Number"]) : ": Duplicate Name Found By ID"}
</code>```

And again this is not exactly the same as ++ doesn't modify but rather create a new instance.

Title: MEL to DataWeave conversion

Body:
We are migrating Mule 3 app to Mule 4 where we have encountered below MEL. Any inputs on how to convert it to DataWeave.

mel:prevProperties.get(payload.get("A1 - Roll Number")) == null ? prevProperties.put(payload.get("A1 - Roll Number"), payload.get("M7 - Detailed status")) : duplicateRecords.put(payload.get("A1 - Roll Number"),": Duplicate Name Found By ID")

Body:
So this script can not be migrated as is to mule 4 as it uses side effects something that is not allowed in DW.

prevProperties.get(payload.get("A1 - Roll Number")) == null ?
        prevProperties.put(payload.get("A1 - Roll Number"), payload.get("M7 - Detailed status")) :
        duplicateRecords.put(payload.get("A1 - Roll Number"),": Duplicate Name Found By ID")

So in order to map this semantically we need to get more context on your flow. To map syntactically the parts that can be mapped will be something like

if(prevProperties[payload["A1 - Roll Number"]] == null)
    prevProperties ++ {(payload["A1 - Roll Number"]): payload["M7 - Detailed status"]}
else duplicateRecords ++ {(payload["A1 - Roll Number"]) : ": Duplicate Name Found By ID"}

And again this is not exactly the same as ++ doesn't modify but rather create a new instance.