问:
Spring security always giving 403
I configured Spring security with a customer filter to authenticate using JWT.
Here's my config:

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf()
                .disable()
                .authorizeHttpRequests()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider())
                .addFilterBefore(new JwtAuthFilter(jwtManager, customerCredentialsDao), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
```
<p>Filter:</p>
<pre class="lang-java prettyprint-override"><code>package catsit.config;

import catsit.authentication.CustomerContext;
import catsit.authentication.CustomerCredentialsDao;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtManager jwtManager;

    private final CustomerCredentialsDao customerCredentialsDao;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        final String authorizationHeader = request.getHeader(AUTHORIZATION);
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer")) {
            filterChain.doFilter(request, response);
            return;
        }

        String jwt = authorizationHeader.substring(7);
        if (jwtManager.isTokenValid(jwt)) {
            CustomerContext userDetails = customerCredentialsDao.findCredentialsAndIdByEmail(jwtManager.extractEmail(jwt));

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities()
            );

            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
</code>```

It's working as expected but for some reason when I send a request to a random endpoint it returns 403. What I'm expecting is 404 but I can't seem to figure out why it's returning 403.
The requests to random endpoints are sent with a token so they are authenticated.

Title: Spring security always giving 403

Body:
I configured Spring security with a customer filter to authenticate using JWT.
Here's my config:

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf()
                .disable()
                .authorizeHttpRequests()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider())
                .addFilterBefore(new JwtAuthFilter(jwtManager, customerCredentialsDao), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

Filter:

package catsit.config;

import catsit.authentication.CustomerContext;
import catsit.authentication.CustomerCredentialsDao;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtManager jwtManager;

    private final CustomerCredentialsDao customerCredentialsDao;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        final String authorizationHeader = request.getHeader(AUTHORIZATION);
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer")) {
            filterChain.doFilter(request, response);
            return;
        }

        String jwt = authorizationHeader.substring(7);
        if (jwtManager.isTokenValid(jwt)) {
            CustomerContext userDetails = customerCredentialsDao.findCredentialsAndIdByEmail(jwtManager.extractEmail(jwt));

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities()
            );

            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}

It's working as expected but for some reason when I send a request to a random endpoint it returns 403. What I'm expecting is 404 but I can't seem to figure out why it's returning 403.
The requests to random endpoints are sent with a token so they are authenticated.


来源: stackexchange

问:
How do I pull website information (class within class within div within class within div) through google sheets?
I'm creating a spreadsheet that pulls basic information from a website for an upcoming bicycle tour that I'm doing. In short, I'm trying to gather community names, locations, and contact information. I'm very new to this (as in a few hours) and can't seem to find specific formulas for access information under many different umbrellas of coding.

The source code reads:

```<code><div class="clearfix"><div class="float-left"><h1 class="mb-1">Sustainable Ecovillage</h1><h2><small>Gasquet, California, United States</small></h2></div><ul class="text-right small text-muted float-right list-unstyled"><li><b>Updated on: </b>Oct 19, 2022 (about 1 month ago)</li><li><b>Created on: </b>Dec 26, 2008 (almost 14 years ago)</li></ul></div>

</code>```

I'm trying to gather the community name (h1) in one cell, and location (h2) in another.

I'd also like to grab the website link if it exists:

```<code><li><b>Website:</b> <a href="https://sustainableecovillage.com/" target="_blank">https://sustainableecovillage.com/</a></li>
</code>```

As well as the Contact Name, Phone, and Address:

```<code>
<ul class="card-body list-unstyled listing-status mb-0"><li><b>Status:</b> <span class="">Established (4+ adults, 2+ years)</span></li><li><b>Started Planning:</b> 2007</li><li><b>Started Living Together:</b> 2008</li><li><b>Visitors Accepted:</b> <span class="text-success">Yes</span></li><li><b>Open to New Members:</b> <span class="text-success">Yes</span></li><li class="text-center mt-2 mb-3"><small class="text-muted">Please read the details in <a href="#Membership">Membership</a> below before contacting this community.</small><a class="my-1 btn btn-block btn-warning" href="/directory/contact-a-community/?cmty=38947">Send Message</a></li><li>**<b>Website:</b> <a href="https://sustainableecovillage.com/" target="_blank">https://sustainableecovillage.com/</a>**</li><li><b>Business, Project, or Organization:</b> <a href="https://sustainableecovillage.com/" target="_blank">https://sustainableecovillage.com/</a></li><li><b>Contact Name:</b> Dan</li><li><b>Phone:</b> 707-954-7743</li><li><b>Community Address:</b><address>P O Box 246<br>Gasquet, California 95543<br>United States</address></li><li><h3 class="text-center"><a href="/community-bookstore/product/fic-membership/" target="_blank">FIC Membership</a></h3><div class="text-center mb-3"><a href="/community-bookstore/product/fic-membership/" target="_blank"><img id="fic-membership-badge" title="FIC Membership Badge" src="/wp-content/themes/fic-theme/img/membership-badge.png?v=1" alt="This Community is an FIC Member" class="img-fluid"></a></div></li><li><h3 class="text-center">Location</h3><img src="/wp-content/themes/fic-theme/img/directory-map-placeholder.png?v=1" alt="Directory Map Placeholder" class="img-fluid"></li></ul>

</code>```

From my reaserch, it seems I should be able to simply put

=IMPORTXML("https://www.ic.org/directory/sustainable-ecovillage/","//h1")

However, it returns content is empty.

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a spreadsheet that pulls basic information from a website for an upcoming bicycle tour that I'm doing. In short, I'm trying to gather community names, locations, and contact information. I'm very new to this (as in a few hours) and can't seem to find specific formulas for access information under many different umbrellas of coding.

The source code reads:

Sustainable Ecovillage

Gasquet, California, United States

Updated on: Oct 19, 2022 (about 1 month ago)

Created on: Dec 26, 2008 (almost 14 years ago)

I'm trying to gather the community name (h1) in one cell, and location (h2) in another.

I'd also like to grab the website link if it exists:

Website: https://sustainableecovillage.com/

As well as the Contact Name, Phone, and Address:

Status: Established (4+ adults, 2+ years)

Started Planning: 2007

Started Living Together: 2008

Visitors Accepted: Yes

Open to New Members: Yes

Please read the details in Membership below before contacting this community.Send Message

**Website: https://sustainableecovillage.com/**

Business, Project, or Organization: https://sustainableecovillage.com/

Contact Name: Dan

Phone: 707-954-7743

Community Address:<address>P O Box 246
Gasquet, California 95543
United States</address>

FIC Membership

Location

From my reaserch, it seems I should be able to simply put

=IMPORTXML("https://www.ic.org/directory/sustainable-ecovillage/","//h1")

However, it returns content is empty.


问:
How do I group bars in a single trace of a plotly bar chart
I am trying to plot a bar chart in plotly with grouped bars for data points with the same x-value, but the barmode is being ignored. How can I do this for the following sample data:

```<code>x = [3,2,4,5,6,7,4,3,2,3,7]
y = [10,20,24,13,14,20,21,20,12,13,7]
</code>```

For this data, I want three bars next to each other at x=3, two bars at x=2 and two bars at x=7

I have tried the following, updating the layout to group and setting base to 0, but the bars are still being stacked.

```<code>fig = go.Figure()
fig.add_trace(go.Bar(x=self.x, y=self.y,
                     base=0
))
fig.update_layout(barmode='group')
fig.show()
</code>```

Thanks.

Body:
I am trying to plot a bar chart in plotly with grouped bars for data points with the same x-value, but the barmode is being ignored. How can I do this for the following sample data:

x = [3,2,4,5,6,7,4,3,2,3,7]
y = [10,20,24,13,14,20,21,20,12,13,7]

For this data, I want three bars next to each other at x=3, two bars at x=2 and two bars at x=7

I have tried the following, updating the layout to group and setting base to 0, but the bars are still being stacked.

fig = go.Figure()
fig.add_trace(go.Bar(x=self.x, y=self.y,
                     base=0
))
fig.update_layout(barmode='group')
fig.show()

Thanks.


问:
Java+Spring @Digits annotation allows String from JSON Request - I don't want them
It's my first question on Stackoverflow so Hello everybody :)

I'm new to Spring and I want to use @Digits annotation to valid input from request to be only digits before  putting them to ArrayList but I don't know why an array like [1,2,3,"g",5] is treated like OK ?

Here's my code:

```<code>public class PostRequest {

    private ArrayList<@Digits(integer = 100, fraction = 0, message = "Only integers please") BigDecimal> numbers;

    public ArrayList<BigDecimal> getNumbers() {
        if (numbers==null) return null;
        return numbers;
    }

    public void setNumbers(ArrayList<BigDecimal> numbers) {
        this.numbers = numbers;
    }

}
</code>```

And here's my Controller:

```<code>@RestController
public class MyController {

    @PostMapping("/test")
    public void test(@Valid @RequestBody PostRequest postRequest){

        System.out.println(postRequest.getNumbers());
    }

}
</code>```

Here's JSON code:

```<code>{
    "numbers":[1,2,3,"g",5]
}
</code>```

Writing 10.2 triggers MethodArgumentNotValidException but writing letters not

I have tried this:

```<code>private ArrayList<@Pattern(regexp = "^[0-9]*$", message = "Only integers please") BigDecimal> numbers;
</code>```

but I got this error:

jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.Pattern' validating type 'java.math.BigDecimal'. Check configuration for 'numbers[0].'

Thanks in advance!

Body:
It's my first question on Stackoverflow so Hello everybody :)

I'm new to Spring and I want to use @Digits annotation to valid input from request to be only digits before  putting them to ArrayList but I don't know why an array like [1,2,3,"g",5] is treated like OK ?

Here's my code:

public class PostRequest {

    private ArrayList<@Digits(integer = 100, fraction = 0, message = "Only integers please") BigDecimal> numbers;

    public ArrayList<BigDecimal> getNumbers() {
        if (numbers==null) return null;
        return numbers;
    }

    public void setNumbers(ArrayList<BigDecimal> numbers) {
        this.numbers = numbers;
    }

}

And here's my Controller:

@RestController
public class MyController {

    @PostMapping("/test")
    public void test(@Valid @RequestBody PostRequest postRequest){

        System.out.println(postRequest.getNumbers());
    }

}

Here's JSON code:

{
    "numbers":[1,2,3,"g",5]
}

Writing 10.2 triggers MethodArgumentNotValidException but writing letters not

I have tried this:

private ArrayList<@Pattern(regexp = "^[0-9]*$", message = "Only integers please") BigDecimal> numbers;

but I got this error:

jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.Pattern' validating type 'java.math.BigDecimal'. Check configuration for 'numbers[0].'

Thanks in advance!


问:
Unexpected string literal "@hotwired/turbo-rails" in browser console

error ...

in the browser console (Safari), it display the error:

SyntaxError: Unexpected string literal "@hotwired/turbo-rails". import
call expects one or two arguments.

This error points to application.js.

Is this yet another rails error than can be safely ignored, is it an indication my set-up is not quite right?  Is it a bug?

gemfile includes...

```<code>gem "cssbundling-rails", "~> 1.1"

gem 'turbo-rails'

gem 'importmap-rails'
</code>```

importmap.rb

```<code>pin "application", preload: true

pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true

pin "popper", to: 'popper.js', preload: true

pin "bootstrap", to: 'bootstrap.min.js', preload: true

pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true

pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true

pin "trix"

pin "@rails/actiontext", to: "actiontext.js"

pin "stimulus-autocomplete", to: "https://ga.jspm.io/npm:stimulus-autocomplete@3.0.2/src/autocomplete.js"

pin "choices" # @10.2.0

pin_all_from "app/javascript/controllers", under: "controllers"
</code>```

application.js

```<code>import "@hotwired/turbo-rails"

import "popper"

import "bootstrap"

import "controllers"

import * as bootstrap from "bootstrap"
</code>```

package.json

```<code>{
  "name": "flightrecord",
  "private": "true",
  "dependencies": {
    "@fortawesome/fontawesome-free": "^6.2.0",
    "@hotwired/stimulus": "^3.2.1",
    "@hotwired/turbo-rails": "7.2.4",
    "@popperjs/core": "^2.11.6",
    "@rails/actioncable": "^7.0.3-1",
    "@rails/actiontext": "^7.0.4",
    "@rails/activestorage": "^7.0.3-1",
    "@rails/webpacker": "5.4.3",
    "bootstrap": "^5.2.3",
    "bootstrap-icons": "^1.10.2",
    "choices.js": "^10.2.0",
    "currency.js": "^2.0.3",
    "dropzone": "^5.9.2",
    "sass": "^1.56.2",
    "sortablejs": "^1.14.0",
    "stimulus-autocomplete": "^3.0.0-rc.2",
    "tributejs": "^5.1.3",
    "trix": "^2.0.3"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3"
  },
  "engines": {
    "node": "19.2.0",
    "yarn": "1.22.19",
    "npm": "6.14.9"
  },
  "scripts": {
    "build:css": "sass ./app/assets/stylesheets/application.bootstrap.scss:./app/assets/builds/application.css --no-source-map --load-path=node_modules"
  }
}
</code>```

Body:
error ...

in the browser console (Safari), it display the error:

SyntaxError: Unexpected string literal "@hotwired/turbo-rails". import
call expects one or two arguments.

This error points to application.js.

Is this yet another rails error than can be safely ignored, is it an indication my set-up is not quite right?  Is it a bug?

gemfile includes...

gem "cssbundling-rails", "~> 1.1"

gem 'turbo-rails'

gem 'importmap-rails'

importmap.rb

pin "application", preload: true

pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true

pin "popper", to: 'popper.js', preload: true

pin "bootstrap", to: 'bootstrap.min.js', preload: true

pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true

pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true

pin "trix"

pin "@rails/actiontext", to: "actiontext.js"

pin "stimulus-autocomplete", to: "https://ga.jspm.io/npm:stimulus-autocomplete@3.0.2/src/autocomplete.js"

pin "choices" # @10.2.0

pin_all_from "app/javascript/controllers", under: "controllers"

application.js

import "@hotwired/turbo-rails"

import "popper"

import "bootstrap"

import "controllers"

import * as bootstrap from "bootstrap"

package.json

{
  "name": "flightrecord",
  "private": "true",
  "dependencies": {
    "@fortawesome/fontawesome-free": "^6.2.0",
    "@hotwired/stimulus": "^3.2.1",
    "@hotwired/turbo-rails": "7.2.4",
    "@popperjs/core": "^2.11.6",
    "@rails/actioncable": "^7.0.3-1",
    "@rails/actiontext": "^7.0.4",
    "@rails/activestorage": "^7.0.3-1",
    "@rails/webpacker": "5.4.3",
    "bootstrap": "^5.2.3",
    "bootstrap-icons": "^1.10.2",
    "choices.js": "^10.2.0",
    "currency.js": "^2.0.3",
    "dropzone": "^5.9.2",
    "sass": "^1.56.2",
    "sortablejs": "^1.14.0",
    "stimulus-autocomplete": "^3.0.0-rc.2",
    "tributejs": "^5.1.3",
    "trix": "^2.0.3"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3"
  },
  "engines": {
    "node": "19.2.0",
    "yarn": "1.22.19",
    "npm": "6.14.9"
  },
  "scripts": {
    "build:css": "sass ./app/assets/stylesheets/application.bootstrap.scss:./app/assets/builds/application.css --no-source-map --load-path=node_modules"
  }
}


问:
.NET 6 impersonation in a background job
I'm having trouble impersonating user in a background job (Hangfire).

Workflow:
User sends a request which will last for 10+ minutes so instead of processing synchronously I enqueue a background job using Hangfire framework. The API is authenticated using Windows authentication.
Job has to call a WCF service using user's credentials.
This works when the request is synchronous.

When request is synchronous I get SafeAccessTokenHandle from HttpConext like this:

```<code>var handle = (HttpContext.User.Identity as WindowsIdentity).AccessToken
WindowsIdentity.RunImpersonatedAsync(handle, () => ....)
</code>```

Note: the code above is simplified

What have I tried:

When enqueueing the job I pass the handle (SafeAccessTokenHandle) as a parameter to the job.
It does not work and handle.IsInvalid returns true.

I've tried passing the WindowsIdentity.Token (its of type IntPtr) as parameter and instantiating the handle. It does not work.

I've tried passing Identity guid to the job and using the code below:

```<code>PrincipalContext context = new(ContextType.Domain);
var userPrincipal = UserPrincipal.FindByIdentity(
                context,
                IdentityType.Guid,
                request.Guid.ToString());
var upn = userPrincipal.UserPrincipalName;
var identity = new WindowsIdentity(upn);

// Use WindowsIndentity.RunImpersonatedAsync(identity.AccessToken, () => ...)
</code>```

I've also noticed that identity.ImpersonationLevel is Identification which I guess is the main reason why 3. doesn't work.

I would appreciate any kind of help. Thanks.

UPDATE 1:
I have deployed the 3rd solution to IIS server and I've noticed that I get ImpersonationLevel = Impersonation there, while in visual studio it's Identification.
Everything looks pretty much identical now as synchronous way but still no progress.

Body:
I'm having trouble impersonating user in a background job (Hangfire).

Workflow:
User sends a request which will last for 10+ minutes so instead of processing synchronously I enqueue a background job using Hangfire framework. The API is authenticated using Windows authentication.
Job has to call a WCF service using user's credentials.
This works when the request is synchronous.

When request is synchronous I get SafeAccessTokenHandle from HttpConext like this:

var handle = (HttpContext.User.Identity as WindowsIdentity).AccessToken
WindowsIdentity.RunImpersonatedAsync(handle, () => ....)

Note: the code above is simplified

What have I tried:

When enqueueing the job I pass the handle (SafeAccessTokenHandle) as a parameter to the job.
It does not work and handle.IsInvalid returns true.

I've tried passing the WindowsIdentity.Token (its of type IntPtr) as parameter and instantiating the handle. It does not work.

I've tried passing Identity guid to the job and using the code below:

PrincipalContext context = new(ContextType.Domain);
var userPrincipal = UserPrincipal.FindByIdentity(
                context,
                IdentityType.Guid,
                request.Guid.ToString());
var upn = userPrincipal.UserPrincipalName;
var identity = new WindowsIdentity(upn);

// Use WindowsIndentity.RunImpersonatedAsync(identity.AccessToken, () => ...)

I've also noticed that identity.ImpersonationLevel is Identification which I guess is the main reason why 3. doesn't work.

I would appreciate any kind of help. Thanks.

UPDATE 1:
I have deployed the 3rd solution to IIS server and I've noticed that I get ImpersonationLevel = Impersonation there, while in visual studio it's Identification.
Everything looks pretty much identical now as synchronous way but still no progress.


问:
Trouble implementing ml-agents in a Unity snooker game
I'm trying to implement a Reinforcement Learning snooker player and I want to train it using ml-agents in Unity. The thing is that I am not used to this library and I am not sure how should I do it. So when I try to train it, the agent does nothing. Could you check what am I doing wrong and how can I solve it? Thanks so much.
This is the main code:

```<code>
using System;
using Unity.MLAgents;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Actuators;
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public struct Player
{
    public int score;
    public bool isNPC;
}

public class Snooker2D : Agent
{
    public GameObject cueBall;
    public Transform stick;
    public Transform ball;
    public Transform selectionFx;
    public Slider slider;

    int currentPlayer = 1;
    int nPlayers = 2;
    Player[] players = new Player[2];
    bool follow = true;
    bool doubleShot = false;
    float ballRadius = 0;
    LayerMask layerMaskBalls = 1 << 9;
    LayerMask layerMaskBallsAndWalls = 1 << 9 | 1 << 10;
    LayerMask layerMaskWalls = 1 << 10;

    RaycastHit2D hit;
    float dist = 0;
    float minDist = 0;
    float maxDist = -3;
    float forceMultiplier = 2.5f;

    Vector3 whiteBallPos = new Vector3(-4.3111f, 0, 0);

    public override void OnEpisodeBegin()
    {
        // Reset the environment
        Application.LoadLevel(Application.loadedLevel);
    }

    public override void CollectObservations(VectorSensor sensor)
    {
        // Target and Agent positions
        sensor.AddObservation(ball.position);
        // sensor.AddObservation(stick.position);

        // All balls positions
        foreach (GameObject ball in GameObject.FindGameObjectsWithTag("Ball"))
        {
            sensor.AddObservation(ball.transform.position);
        }
    }

    public override void OnActionReceived(ActionBuffers actionBuffers)
    {
        // Actions, size = 3, the force vector
        var action = actionBuffers.ContinuousActions;
        Vector3 force = new Vector3(action[0], action[1], action[2]);

        // Apply the force vector to the game environment, for example by adding it to the velocity of the cue ball
        Shoot(force);
    }

    public override void Heuristic(in ActionBuffers actionsOut)
    {
        var continuousActionsOut = actionsOut.ContinuousActions;

        // Set the force vector using keyboard or gamepad inputs, each action is between -1 and 1
        // Each action is an axis of the force vector
        continuousActionsOut[0] = Input.GetAxis("Horizontal");
        continuousActionsOut[1] = Input.GetAxis("Vertical");
        continuousActionsOut[2] = Input.GetAxis("Jump");
    }

    void Start()
    {
        players[1].isNPC = true;

        ballRadius = ball.GetComponent<CircleCollider2D>().radius;
        minDist = -(ballRadius + ballRadius / 2);
        dist = Mathf.Clamp(maxDist / 2, maxDist, minDist);

        slider.maxValue = -maxDist;
        slider.minValue = -minDist;
        slider.value = dist + -maxDist - minDist;

        selectionFx.GetComponent<Fader>().StartFade();
    }

    void Update()
    {
        if (Input.GetKeyDown("r")) Application.LoadLevel(Application.loadedLevel);

        // PLAYER TURN
        if (follow)
        {
            Vector3 forceDir = Vector3.zero;
            // Analog Player
            if (!players[currentPlayer].isNPC)
            {
                // MOUSE: Get mouse position
                Vector3 mPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
                PowerAdjust();
                RotateStickAroundBall(mPos);
                ProjectTrajectory();
                forceDir = (ball.position - stick.position).normalized * -(dist - minDist - 0.02f) * forceMultiplier;
                if (Input.GetMouseButtonUp(0)) Shoot(forceDir); // && hit.collider != null)
            }
            // AI Player
            else
            {
                // TODO: Here will be the AI
                // Reward the model if there are less balls on the table
                // Apply the action to the ball
                //forceDir = new Vector3(1, 1, 1);
                //Shoot(forceDir);
                var continuousActionsOut = new ActionBuffers();
                Heuristic(continuousActionsOut);
                SetReward(1.0f / GameObject.FindGameObjectsWithTag("Ball").Length);
                if (GameObject.FindGameObjectsWithTag("Ball").Length == 1)
                {
                    // End the episode if there is only one ball left
                    EndEpisode();
                }
            }
        }

        // start following
        if (!follow)
        {
            if (AllBallsStopped() && ball.GetComponent<Rigidbody2D>().velocity.sqrMagnitude == 0.0f)
            {
                // Update player score
                // players[currentPlayer].score = UpdateScore(currentPlayer);
                // currentPlayer = (currentPlayer + 1) % nPlayers;
                follow = true;
                if (cueBall.activeSelf == false)
                {
                    SetReward(-0.1f);
                    RespawnBall();
                }
                selectionFx.GetComponent<Fader>().StartFade();
                Invoke("HideShowStick", 0.2f);
            }
        }

    } // update()
}
</code>```

I tried reading about this, but I couldn't find much information.

Body:
I'm trying to implement a Reinforcement Learning snooker player and I want to train it using ml-agents in Unity. The thing is that I am not used to this library and I am not sure how should I do it. So when I try to train it, the agent does nothing. Could you check what am I doing wrong and how can I solve it? Thanks so much.
This is the main code:

using System;
using Unity.MLAgents;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Actuators;
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public struct Player
{
    public int score;
    public bool isNPC;
}

public class Snooker2D : Agent
{
    public GameObject cueBall;
    public Transform stick;
    public Transform ball;
    public Transform selectionFx;
    public Slider slider;

    int currentPlayer = 1;
    int nPlayers = 2;
    Player[] players = new Player[2];
    bool follow = true;
    bool doubleShot = false;
    float ballRadius = 0;
    LayerMask layerMaskBalls = 1 << 9;
    LayerMask layerMaskBallsAndWalls = 1 << 9 | 1 << 10;
    LayerMask layerMaskWalls = 1 << 10;

    RaycastHit2D hit;
    float dist = 0;
    float minDist = 0;
    float maxDist = -3;
    float forceMultiplier = 2.5f;

    Vector3 whiteBallPos = new Vector3(-4.3111f, 0, 0);

    public override void OnEpisodeBegin()
    {
        // Reset the environment
        Application.LoadLevel(Application.loadedLevel);
    }

    public override void CollectObservations(VectorSensor sensor)
    {
        // Target and Agent positions
        sensor.AddObservation(ball.position);
        // sensor.AddObservation(stick.position);

        // All balls positions
        foreach (GameObject ball in GameObject.FindGameObjectsWithTag("Ball"))
        {
            sensor.AddObservation(ball.transform.position);
        }
    }

    public override void OnActionReceived(ActionBuffers actionBuffers)
    {
        // Actions, size = 3, the force vector
        var action = actionBuffers.ContinuousActions;
        Vector3 force = new Vector3(action[0], action[1], action[2]);

        // Apply the force vector to the game environment, for example by adding it to the velocity of the cue ball
        Shoot(force);
    }

    public override void Heuristic(in ActionBuffers actionsOut)
    {
        var continuousActionsOut = actionsOut.ContinuousActions;

        // Set the force vector using keyboard or gamepad inputs, each action is between -1 and 1
        // Each action is an axis of the force vector
        continuousActionsOut[0] = Input.GetAxis("Horizontal");
        continuousActionsOut[1] = Input.GetAxis("Vertical");
        continuousActionsOut[2] = Input.GetAxis("Jump");
    }

    void Start()
    {
        players[1].isNPC = true;

        ballRadius = ball.GetComponent<CircleCollider2D>().radius;
        minDist = -(ballRadius + ballRadius / 2);
        dist = Mathf.Clamp(maxDist / 2, maxDist, minDist);

        slider.maxValue = -maxDist;
        slider.minValue = -minDist;
        slider.value = dist + -maxDist - minDist;

        selectionFx.GetComponent<Fader>().StartFade();
    }

    void Update()
    {
        if (Input.GetKeyDown("r")) Application.LoadLevel(Application.loadedLevel);

        // PLAYER TURN
        if (follow)
        {
            Vector3 forceDir = Vector3.zero;
            // Analog Player
            if (!players[currentPlayer].isNPC)
            {
                // MOUSE: Get mouse position
                Vector3 mPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
                PowerAdjust();
                RotateStickAroundBall(mPos);
                ProjectTrajectory();
                forceDir = (ball.position - stick.position).normalized * -(dist - minDist - 0.02f) * forceMultiplier;
                if (Input.GetMouseButtonUp(0)) Shoot(forceDir); // && hit.collider != null)
            }
            // AI Player
            else
            {
                // TODO: Here will be the AI
                // Reward the model if there are less balls on the table
                // Apply the action to the ball
                //forceDir = new Vector3(1, 1, 1);
                //Shoot(forceDir);
                var continuousActionsOut = new ActionBuffers();
                Heuristic(continuousActionsOut);
                SetReward(1.0f / GameObject.FindGameObjectsWithTag("Ball").Length);
                if (GameObject.FindGameObjectsWithTag("Ball").Length == 1)
                {
                    // End the episode if there is only one ball left
                    EndEpisode();
                }
            }
        }

        // start following
        if (!follow)
        {
            if (AllBallsStopped() && ball.GetComponent<Rigidbody2D>().velocity.sqrMagnitude == 0.0f)
            {
                // Update player score
                // players[currentPlayer].score = UpdateScore(currentPlayer);
                // currentPlayer = (currentPlayer + 1) % nPlayers;
                follow = true;
                if (cueBall.activeSelf == false)
                {
                    SetReward(-0.1f);
                    RespawnBall();
                }
                selectionFx.GetComponent<Fader>().StartFade();
                Invoke("HideShowStick", 0.2f);
            }
        }

    } // update()
}

I tried reading about this, but I couldn't find much information.


问:
Woocommerce add extra fee on checkout page
I am using this code in WooCommerce to display additional paid options. The option in the block is activated by a tick in the checkbox. After that, in the drop-down list, you can select options for this option with different prices. After choosing an option, the order amount, excluding shipping costs, automatically increases on the screen. The code calculates the amount as a percentage of the order amount. After confirming the order, the data appears in Woocommerce - Orders.

Question:

How to make it so that in the drop-down list the cost of variations is fixed (NOT as a percentage) and one of the options is with the ability to manually enter the amount of the donation type. And after entering the amount, the total amount of the order, excluding shipping costs, also changed automatically on the screen.

How to make several such blocks several paid options. For example 3.
enter image description here

Code source - https://gist.github.com/psaikali/728be703ac016235bf587051882521c5

Description: https://saika.li/woocommerce-customize-checkout/

```<code><?php
/**
 * Plugin Name: WooCommerce Custom Checkout Fields
 * Description: Add some custom "emergency level" extra fields on the WooCommerce Checkout page. Save this custom data in each order metadata.
 * Author: Pierre Saïkali
 * Author URI: https://saika.li
 * Text Domain: wc_ccf
 * Domain Path: /languages/
 * Version: 1.0.0
 * Full Tutorial: https://mosaika.fr/personnaliser-tunnel-commande-woocommerce/
 */

namespace WC_CCF;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

//========================================
//
//  ##   ##  ######  ##  ##       ####
//  ##   ##    ##    ##  ##      ##
//  ##   ##    ##    ##  ##       ###
//  ##   ##    ##    ##  ##         ##
//   #####     ##    ##  ######  ####
//
//========================================

/**
 * Get form posted data from WooCommerce: in some cases, it's serialized in a "post_data" key.
 *
 * @return array
 */
function get_wc_posted_data() {
    $form_data = $_POST;

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $form_data );
    }

    return $form_data;
}

//==========================================================
//
//  ####    ##   ####  #####   ##        ###    ##    ##
//  ##  ##  ##  ##     ##  ##  ##       ## ##    ##  ##
//  ##  ##  ##   ###   #####   ##      ##   ##    ####
//  ##  ##  ##     ##  ##      ##      #######     ##
//  ####    ##  ####   ##      ######  ##   ##     ##
//
//==========================================================

/**
 * Display our custom extra fields: a checkbox and a select dropdown.
 *
 * @return void
 */
function display_custom_shipping_methods() {
    ?>
    <fieldset class="extra-fields">
        <legend><?php _e( 'Emergency', 'wc_ccf' ); ?></legend>

        <p>
            <label for="msk-urgent-order">
                <input type="checkbox" name="msk-urgent-order" id="msk-urgent-order" value="on" class="msk-custom-field" />
                <span><?php esc_html_e( 'This is an emergency, send me my order ASAP!', 'wc_ccf' ); ?></span>
            </label>
        </p>

        <p>
            <label for="msk-urgency-level">
                <span><?php esc_html_e( 'When do you want this shipped?', 'wc_ccf' ); ?></span>
                <select name="msk-urgency-level" id="msk-urgency-level" class="msk-custom-field">
                    <option value="_null"><?php esc_attr_e( '— Select an option', 'wc_ccf' ); ?></option>
                    <option value="next_hour"><?php esc_attr_e( 'In the next hour', 'wc_ccf' ); ?></option>
                    <option value="next_6hours"><?php esc_attr_e( 'In the next 6 hours', 'wc_ccf' ); ?></option>
                    <option value="next_12hours"><?php esc_attr_e( 'In the next 12 hours', 'wc_ccf' ); ?></option>
                    <option value="tomorrow"><?php esc_attr_e( 'By tomorrow', 'wc_ccf' ); ?></option>
                </select>
            </label>
        </p>
    </fieldset>

    <script>
        // When one of our custom field value changes, tell WC to update the checkout data (AJAX request to the back-end).
        jQuery(document).ready(function($) {
            $('form.checkout').on('change', '.msk-custom-field', function() {
                $('body').trigger('update_checkout');
            });
        });
    </script>
    <?php
}
add_action( 'woocommerce_checkout_billing', __NAMESPACE__ . '\\display_custom_shipping_methods', 10 );

//==================================================================
//
//  ##   ##    ###    ##      ##  ####      ###    ######  #####
//  ##   ##   ## ##   ##      ##  ##  ##   ## ##     ##    ##
//  ##   ##  ##   ##  ##      ##  ##  ##  ##   ##    ##    #####
//   ## ##   #######  ##      ##  ##  ##  #######    ##    ##
//    ###    ##   ##  ######  ##  ####    ##   ##    ##    #####
//
//==================================================================

/**
 * Validate checkout fields before processing the WooCommerce "order"
 *
 * @return void
 */
function validate_all_checkout_fields() {
    $errors = [];

    if ( isset( $_POST['msk-urgent-order'] ) && $_POST['msk-urgent-order'] === 'on' ) {
        if ( ! isset( $_POST['msk-urgency-level'] ) || $_POST['msk-urgency-level'] === '_null' ) {
            $errors[] = __( 'Please tell us the <strong>level of emergency</strong>.', 'wc_ccf' );
        }

        elseif ( isset( $_POST['msk-urgency-level'] ) && ! in_array( $_POST['msk-urgency-level'], [ 'next_hour', 'next_6hours', 'next_12hours', 'tomorrow' ], true ) ) {
            $errors[] = __( 'This <strong>level of emergency</strong> is invalid.', 'wc_ccf' );
        }
    }

    /**
     * If we have errors,
     */
    if ( ! empty( $errors ) ) {
        foreach ( $errors as $error ) {
            wc_add_notice( $error, 'error' );
        }
    }
}
add_action( 'woocommerce_checkout_process', __NAMESPACE__ . '\\validate_all_checkout_fields' );

//==============================================================================
//
//   ####    ###    #####    ######        #####   #####    ##   ####  #####
//  ##      ## ##   ##  ##     ##          ##  ##  ##  ##   ##  ##     ##
//  ##     ##   ##  #####      ##          #####   #####    ##  ##     #####
//  ##     #######  ##  ##     ##          ##      ##  ##   ##  ##     ##
//   ####  ##   ##  ##   ##    ##          ##      ##   ##  ##   ####  #####
//
//==============================================================================

/**
 * Add emergency fee depending on the emergency level selected.
 *
 * @param WC_Cart $cart_object
 * @return void
 */
function add_emergency_fee( $cart_object ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) || ! is_checkout() ) {
        return;
    }

    // Only trigger this logic once.
    if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 ) {
        return;
    }

    $form_data = get_wc_posted_data();

    // Do not calculate anything if we do not have our emergency field checked or no emergency level is provided.
    if ( ! isset( $form_data['msk-urgent-order'], $form_data['msk-urgency-level'] ) || $form_data['msk-urgent-order'] !== 'on' ) {
        return;
    }

    // Store a mutiplier/coefficient to calculate the emergency fee.
    $multipliers = [
        'next_hour'    => 2,
        'next_6hours'  => 1.5,
        'next_12hours' => 1.25,
        'tomorrow'     => 1.1,
    ];

    if ( ! array_key_exists( $form_data['msk-urgency-level'], $multipliers ) ) {
        return;
    }

    // Add the extra fee to the user cart.
    WC()->cart->add_fee(
        __( 'Emergency processing fee', 'wc_ccf' ),
        WC()->cart->subtotal * $multipliers[ $form_data['msk-urgency-level'] ],
        false
    );
}
add_action( 'woocommerce_cart_calculate_fees', __NAMESPACE__ . '\\add_emergency_fee' );

//========================================================================================
//
//  #####    #####    ####  ######             #####   #####    ####    #####  #####
//  ##  ##  ##   ##  ##       ##              ##   ##  ##  ##   ##  ##  ##     ##  ##
//  #####   ##   ##   ###     ##    ########  ##   ##  #####    ##  ##  #####  #####
//  ##      ##   ##     ##    ##              ##   ##  ##  ##   ##  ##  ##     ##  ##
//  ##       #####   ####     ##               #####   ##   ##  ####    #####  ##   ##
//
//========================================================================================

/**
 * For tutorial sake, enable the order process without payment.
 *
 * @param boolean $needed
 * @return boolean
 */
function woocommerce_order_needs_payment( $needed ) {
    return false;
}
add_filter( 'woocommerce_cart_needs_payment', __NAMESPACE__ . '\\woocommerce_order_needs_payment' );

/**
 * Allow our custom checkout data (emergency checkbox & level) to be included in order data array.
 *
 * @param array $data
 * @return array
 */
function add_custom_checkout_data_to_order_data_array( $data ) {
    $custom_keys = [
        'msk-urgent-order',
        'msk-urgency-level',
    ];

    foreach ( $custom_keys as $key ) {
        if ( isset( $_POST[ $key ] ) ) {
            $data[ $key ] = sanitize_text_field( $_POST[ $key ] );
        }
    }

    return $data;
}
add_filter( 'woocommerce_checkout_posted_data', __NAMESPACE__ . '\\add_custom_checkout_data_to_order_data_array', 10, 2 );

/**
 * Save our custom checkout data on the order metadata.
 *
 * @param integer $order_id
 * @param array $data Posted data.
 * @return void
 */
function save_custom_checkout_data_in_order_metadata( $order_id, $data ) {
    $custom_keys = [
        'msk-urgent-order',
        'msk-urgency-level',
    ];

    $order = wc_get_order( $order_id );

    foreach ( $custom_keys as $key ) {
        if ( isset( $data[ $key ] ) ) {
            $order->add_meta_data( $key, $data[ $key ] );
        }
    }

    $order->save();
}
add_action( 'woocommerce_checkout_update_order_meta', __NAMESPACE__ . '\\save_custom_checkout_data_in_order_metadata', 10, 2 );
</code>```

Body:
I am using this code in WooCommerce to display additional paid options. The option in the block is activated by a tick in the checkbox. After that, in the drop-down list, you can select options for this option with different prices. After choosing an option, the order amount, excluding shipping costs, automatically increases on the screen. The code calculates the amount as a percentage of the order amount. After confirming the order, the data appears in Woocommerce - Orders.

Question:

How to make it so that in the drop-down list the cost of variations is fixed (NOT as a percentage) and one of the options is with the ability to manually enter the amount of the donation type. And after entering the amount, the total amount of the order, excluding shipping costs, also changed automatically on the screen.

How to make several such blocks several paid options. For example 3.
enter image description here

Code source - https://gist.github.com/psaikali/728be703ac016235bf587051882521c5

Description: https://saika.li/woocommerce-customize-checkout/

<?php
/**
 * Plugin Name: WooCommerce Custom Checkout Fields
 * Description: Add some custom "emergency level" extra fields on the WooCommerce Checkout page. Save this custom data in each order metadata.
 * Author: Pierre Saïkali
 * Author URI: https://saika.li
 * Text Domain: wc_ccf
 * Domain Path: /languages/
 * Version: 1.0.0
 * Full Tutorial: https://mosaika.fr/personnaliser-tunnel-commande-woocommerce/
 */

namespace WC_CCF;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

//========================================
//
//  ##   ##  ######  ##  ##       ####
//  ##   ##    ##    ##  ##      ##
//  ##   ##    ##    ##  ##       ###
//  ##   ##    ##    ##  ##         ##
//   #####     ##    ##  ######  ####
//
//========================================

/**
 * Get form posted data from WooCommerce: in some cases, it's serialized in a "post_data" key.
 *
 * @return array
 */
function get_wc_posted_data() {
    $form_data = $_POST;

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $form_data );
    }

    return $form_data;
}

//==========================================================
//
//  ####    ##   ####  #####   ##        ###    ##    ##
//  ##  ##  ##  ##     ##  ##  ##       ## ##    ##  ##
//  ##  ##  ##   ###   #####   ##      ##   ##    ####
//  ##  ##  ##     ##  ##      ##      #######     ##
//  ####    ##  ####   ##      ######  ##   ##     ##
//
//==========================================================

/**
 * Display our custom extra fields: a checkbox and a select dropdown.
 *
 * @return void
 */
function display_custom_shipping_methods() {
    ?>
    <fieldset class="extra-fields">
        <legend><?php _e( 'Emergency', 'wc_ccf' ); ?></legend>

                <input type="checkbox" name="msk-urgent-order" id="msk-urgent-order" value="on" class="msk-custom-field" />
                <?php esc_html_e( 'This is an emergency, send me my order ASAP!', 'wc_ccf' ); ?>

                <?php esc_html_e( 'When do you want this shipped?', 'wc_ccf' ); ?>
                <select name="msk-urgency-level" id="msk-urgency-level" class="msk-custom-field">
                    <option value="_null"><?php esc_attr_e( '— Select an option', 'wc_ccf' ); ?></option>
                    <option value="next_hour"><?php esc_attr_e( 'In the next hour', 'wc_ccf' ); ?></option>
                    <option value="next_6hours"><?php esc_attr_e( 'In the next 6 hours', 'wc_ccf' ); ?></option>
                    <option value="next_12hours"><?php esc_attr_e( 'In the next 12 hours', 'wc_ccf' ); ?></option>
                    <option value="tomorrow"><?php esc_attr_e( 'By tomorrow', 'wc_ccf' ); ?></option>
                </select>

    </fieldset>

    <?php
}
add_action( 'woocommerce_checkout_billing', __NAMESPACE__ . '\\display_custom_shipping_methods', 10 );

//==================================================================
//
//  ##   ##    ###    ##      ##  ####      ###    ######  #####
//  ##   ##   ## ##   ##      ##  ##  ##   ## ##     ##    ##
//  ##   ##  ##   ##  ##      ##  ##  ##  ##   ##    ##    #####
//   ## ##   #######  ##      ##  ##  ##  #######    ##    ##
//    ###    ##   ##  ######  ##  ####    ##   ##    ##    #####
//
//==================================================================

/**
 * Validate checkout fields before processing the WooCommerce "order"
 *
 * @return void
 */
function validate_all_checkout_fields() {
    $errors = [];

    if ( isset( $_POST['msk-urgent-order'] ) && $_POST['msk-urgent-order'] === 'on' ) {
        if ( ! isset( $_POST['msk-urgency-level'] ) || $_POST['msk-urgency-level'] === '_null' ) {
            $errors[] = __( 'Please tell us the level of emergency.', 'wc_ccf' );
        }

        elseif ( isset( $_POST['msk-urgency-level'] ) && ! in_array( $_POST['msk-urgency-level'], [ 'next_hour', 'next_6hours', 'next_12hours', 'tomorrow' ], true ) ) {
            $errors[] = __( 'This level of emergency is invalid.', 'wc_ccf' );
        }
    }

    /**
     * If we have errors,
     */
    if ( ! empty( $errors ) ) {
        foreach ( $errors as $error ) {
            wc_add_notice( $error, 'error' );
        }
    }
}
add_action( 'woocommerce_checkout_process', __NAMESPACE__ . '\\validate_all_checkout_fields' );

//==============================================================================
//
//   ####    ###    #####    ######        #####   #####    ##   ####  #####
//  ##      ## ##   ##  ##     ##          ##  ##  ##  ##   ##  ##     ##
//  ##     ##   ##  #####      ##          #####   #####    ##  ##     #####
//  ##     #######  ##  ##     ##          ##      ##  ##   ##  ##     ##
//   ####  ##   ##  ##   ##    ##          ##      ##   ##  ##   ####  #####
//
//==============================================================================

/**
 * Add emergency fee depending on the emergency level selected.
 *
 * @param WC_Cart $cart_object
 * @return void
 */
function add_emergency_fee( $cart_object ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) || ! is_checkout() ) {
        return;
    }

    // Only trigger this logic once.
    if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 ) {
        return;
    }

    $form_data = get_wc_posted_data();

    // Do not calculate anything if we do not have our emergency field checked or no emergency level is provided.
    if ( ! isset( $form_data['msk-urgent-order'], $form_data['msk-urgency-level'] ) || $form_data['msk-urgent-order'] !== 'on' ) {
        return;
    }

    // Store a mutiplier/coefficient to calculate the emergency fee.
    $multipliers = [
        'next_hour'    => 2,
        'next_6hours'  => 1.5,
        'next_12hours' => 1.25,
        'tomorrow'     => 1.1,
    ];

    if ( ! array_key_exists( $form_data['msk-urgency-level'], $multipliers ) ) {
        return;
    }

    // Add the extra fee to the user cart.
    WC()->cart->add_fee(
        __( 'Emergency processing fee', 'wc_ccf' ),
        WC()->cart->subtotal * $multipliers[ $form_data['msk-urgency-level'] ],
        false
    );
}
add_action( 'woocommerce_cart_calculate_fees', __NAMESPACE__ . '\\add_emergency_fee' );

//========================================================================================
//
//  #####    #####    ####  ######             #####   #####    ####    #####  #####
//  ##  ##  ##   ##  ##       ##              ##   ##  ##  ##   ##  ##  ##     ##  ##
//  #####   ##   ##   ###     ##    ########  ##   ##  #####    ##  ##  #####  #####
//  ##      ##   ##     ##    ##              ##   ##  ##  ##   ##  ##  ##     ##  ##
//  ##       #####   ####     ##               #####   ##   ##  ####    #####  ##   ##
//
//========================================================================================

/**
 * For tutorial sake, enable the order process without payment.
 *
 * @param boolean $needed
 * @return boolean
 */
function woocommerce_order_needs_payment( $needed ) {
    return false;
}
add_filter( 'woocommerce_cart_needs_payment', __NAMESPACE__ . '\\woocommerce_order_needs_payment' );

/**
 * Allow our custom checkout data (emergency checkbox & level) to be included in order data array.
 *
 * @param array $data
 * @return array
 */
function add_custom_checkout_data_to_order_data_array( $data ) {
    $custom_keys = [
        'msk-urgent-order',
        'msk-urgency-level',
    ];

    foreach ( $custom_keys as $key ) {
        if ( isset( $_POST[ $key ] ) ) {
            $data[ $key ] = sanitize_text_field( $_POST[ $key ] );
        }
    }

    return $data;
}
add_filter( 'woocommerce_checkout_posted_data', __NAMESPACE__ . '\\add_custom_checkout_data_to_order_data_array', 10, 2 );

/**
 * Save our custom checkout data on the order metadata.
 *
 * @param integer $order_id
 * @param array $data Posted data.
 * @return void
 */
function save_custom_checkout_data_in_order_metadata( $order_id, $data ) {
    $custom_keys = [
        'msk-urgent-order',
        'msk-urgency-level',
    ];

    $order = wc_get_order( $order_id );

    foreach ( $custom_keys as $key ) {
        if ( isset( $data[ $key ] ) ) {
            $order->add_meta_data( $key, $data[ $key ] );
        }
    }

    $order->save();
}
add_action( 'woocommerce_checkout_update_order_meta', __NAMESPACE__ . '\\save_custom_checkout_data_in_order_metadata', 10, 2 );


问:
How to customize height of scrollbar and scroll thumb?
I was wondering if there is a way to change top part starting position of scrollbar and to make custome thumb size in this case height of it,not width since its auto scale with scrollbar.enter image description here

I tried using top property on scrollbar since i just wanted to change top part so i tried to move it down but it doesn't work.Actually there is a space for arrows and that is way I found to move thumb of scrollbar but it is not affecting its height.So we have two problems:TOP of scrollbar doesn't start where I want it yet it automatically gets fixed on top;Second problem is that height value of thumb cannot be adjusted .

```<code>::-webkit-scrollbar {

    transform: scale(20px, 100px);
    top:30px;
}

  ::-webkit-scrollbar-track {
    background: #0D2350;
  }

  ::-webkit-scrollbar-thumb {
    background: rgb(255, 255, 255);

  }

  ::-webkit-scrollbar-thumb:hover {
    background: rgb(54, 54, 54);
  }

  ::-webkit-scrollbar-button{
    background: #0D2350;
    height: 45px;
  }
</code>```

Body:
I was wondering if there is a way to change top part starting position of scrollbar and to make custome thumb size in this case height of it,not width since its auto scale with scrollbar.enter image description here

I tried using top property on scrollbar since i just wanted to change top part so i tried to move it down but it doesn't work.Actually there is a space for arrows and that is way I found to move thumb of scrollbar but it is not affecting its height.So we have two problems:TOP of scrollbar doesn't start where I want it yet it automatically gets fixed on top;Second problem is that height value of thumb cannot be adjusted .

::-webkit-scrollbar {

    transform: scale(20px, 100px);
    top:30px;
}

  ::-webkit-scrollbar-track {
    background: #0D2350;
  }

  ::-webkit-scrollbar-thumb {
    background: rgb(255, 255, 255);

  }

  ::-webkit-scrollbar-thumb:hover {
    background: rgb(54, 54, 54);
  }

  ::-webkit-scrollbar-button{
    background: #0D2350;
    height: 45px;
  }


问:
Skip based on a custom Condition over destination property fails always in Model Mapper
Hi am using model mapper 3.1.1. I want to skip the value assignment of destination property only if it is not null. But when I provide the condition is not getting added in the property condition.

```<code>@Configuration
public class ModelMapperInitializer {

    @Bean
    public ModelMapper modelMapper() {

        Condition<SourceObject, DestinationObject> isNotNull = context -> context.getDestination().getDestProperty() != null;

        ModelMapper modelMapper = new ModelMapper();

        modelMapper.typeMap(SourceObject.class, DestinationObject.class).addMappings(mapper ->
             mapper.when(isNotNull).skip(SourceObject::getDestProperty, DestinationObject::setDestProperty));

        return modelMapper;
    }
}
</code>```

Controller:

```<code>@Autowired
private ModelMapper modelMapper;
modelMapper.map(sourceObj, destObj);
</code>```

Could anyone please help in fixing the issue.

Body:
Hi am using model mapper 3.1.1. I want to skip the value assignment of destination property only if it is not null. But when I provide the condition is not getting added in the property condition.

@Configuration
public class ModelMapperInitializer {

    @Bean
    public ModelMapper modelMapper() {

        Condition<SourceObject, DestinationObject> isNotNull = context -> context.getDestination().getDestProperty() != null;

        ModelMapper modelMapper = new ModelMapper();

        modelMapper.typeMap(SourceObject.class, DestinationObject.class).addMappings(mapper ->
             mapper.when(isNotNull).skip(SourceObject::getDestProperty, DestinationObject::setDestProperty));

        return modelMapper;
    }
}

Controller:

@Autowired
private ModelMapper modelMapper;
modelMapper.map(sourceObj, destObj);

Could anyone please help in fixing the issue.


问:
VS2022 Publish to Azure Container Registry fails on Docker build
I'm working on an Azure Function in C#.

I can start the process and launch Docker with a debug build and everything runs as expected.

However, a release build fails building the container and does not launch reporting the following error.

```<code> => ERROR [build 5/9] COPY [AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj, AzureFunction-Service  0.0s
------
 > [build 5/9] COPY [AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj, AzureFunction-ServiceBus-01/]:
------
failed to compute cache key: "/AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj" not found: not found
</code>```

Publishing to the Azure Container Registry fails with with the same error as above.

```<code>2>------
2> > [build 5/9] COPY [AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj, AzureFunction-ServiceBus-01/]:
2>------
2>failed to compute cache key: "/AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj" not found: not found
</code>```

Running procmon.exe from www.sysinternals.com I was able to isolate command lines from each of the Docker container build actions used.

Start -> Docker [Debug] (Succeeds)

```<code>"docker" build -f "C:\AzurePlayground\AzureFunction-ServiceBus-01\Dockerfile" --force-rm -t funcservicebus01:dev --target base  --label "com.microsoft.created-by=visual-studio" --label "com.microsoft.visual-studio.project-name=Func-ServiceBus-01" "C:\AzurePlayground"
</code>```

Start -> Docker [Release] (Fails)

```<code>"docker" build -f "C:\AzurePlayground\AzureFunction-ServiceBus-01\Dockerfile" --force-rm -t funcservicebus01  --label "com.microsoft.created-by=visual-studio" --label "com.microsoft.visual-studio.project-name=Func-ServiceBus-01" "C:\AzurePlayground"
</code>```

Publish -> Docker Container Registry -> Azure Container Registry [Release] (Fails)

```<code>"C:\Program Files\Docker\Docker\resources\bin\com.docker.cli.exe" build -f C:\AzurePlayground\AzureFunction-ServiceBus-01\Dockerfile --force-rm -t funcservicebus01 --label com.microsoft.created-by=visual-studio --label com.microsoft.visual-studio.project-name=Func-ServiceBus-01 C:\AzurePlayground
</code>```

Running these command lines directly reproduces the results seen in VS2022. The one for Debug builds work and the rest fail.

Adding --target base to command lines that failed will make them succeed.

While I could be missing some obscure setting to make this all work, I'm inclined to believe this is a defect in Visual Studio as Debug builds get the correct Docker command line but Release builds do not.

Any thoughts or insight on this? My ability to Google an answer to this has failed me.

Body:
I'm working on an Azure Function in C#.

I can start the process and launch Docker with a debug build and everything runs as expected.

However, a release build fails building the container and does not launch reporting the following error.

 => ERROR [build 5/9] COPY [AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj, AzureFunction-Service  0.0s
------
 > [build 5/9] COPY [AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj, AzureFunction-ServiceBus-01/]:
------
failed to compute cache key: "/AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj" not found: not found

Publishing to the Azure Container Registry fails with with the same error as above.

2>------
2> > [build 5/9] COPY [AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj, AzureFunction-ServiceBus-01/]:
2>------
2>failed to compute cache key: "/AzureFunction-ServiceBus-01/AzureFunction-ServiceBus-01.csproj" not found: not found

Running procmon.exe from www.sysinternals.com I was able to isolate command lines from each of the Docker container build actions used.

Start -> Docker [Debug] (Succeeds)

"docker" build -f "C:\AzurePlayground\AzureFunction-ServiceBus-01\Dockerfile" --force-rm -t funcservicebus01:dev --target base  --label "com.microsoft.created-by=visual-studio" --label "com.microsoft.visual-studio.project-name=Func-ServiceBus-01" "C:\AzurePlayground"

Start -> Docker [Release] (Fails)

"docker" build -f "C:\AzurePlayground\AzureFunction-ServiceBus-01\Dockerfile" --force-rm -t funcservicebus01  --label "com.microsoft.created-by=visual-studio" --label "com.microsoft.visual-studio.project-name=Func-ServiceBus-01" "C:\AzurePlayground"

Publish -> Docker Container Registry -> Azure Container Registry [Release] (Fails)

"C:\Program Files\Docker\Docker\resources\bin\com.docker.cli.exe" build -f C:\AzurePlayground\AzureFunction-ServiceBus-01\Dockerfile --force-rm -t funcservicebus01 --label com.microsoft.created-by=visual-studio --label com.microsoft.visual-studio.project-name=Func-ServiceBus-01 C:\AzurePlayground

Running these command lines directly reproduces the results seen in VS2022. The one for Debug builds work and the rest fail.

Adding --target base to command lines that failed will make them succeed.

While I could be missing some obscure setting to make this all work, I'm inclined to believe this is a defect in Visual Studio as Debug builds get the correct Docker command line but Release builds do not.

Any thoughts or insight on this? My ability to Google an answer to this has failed me.


问:
How to access same data from Api in Reactjs by multiple routes
I have React.js project.Now currently i have designed the routes like this :

```<code>:/userStoreName for home

:/userStoreName/about for about page
</code>```

//Accessing data from Api

```<code>`Const params=useParms();

const data=getdata(params.userStoreName);
</code>```

//Now i want to design my routes like this

```<code>`/ for home

/about for about page`
</code>```

Body:
I have React.js project.Now currently i have designed the routes like this :

:/userStoreName for home

:/userStoreName/about for about page

//Accessing data from Api

`Const params=useParms();

const data=getdata(params.userStoreName);

//Now i want to design my routes like this

`/ for home

/about for about page`


问:
Images showing up tiny in tkinter
I'm using customtkinter (have tried with standard tkinter as well to rule it out) and having issues with displaying photos. I've tried global-ing the photo, I've tried self.-ing the photo, and I've tried appending the photo to a global list as well. Nothing so far has worked. The image appears in the pop-up window, but it's a few pixels wide and a few pixels tall. I've tried fooling with the image.resize((width,height)) line, I've tried adjusting the size of the frame, I've tried not even using the frame at all. I cannot for the life of me scale this image to the proper size. Code is below.

```<code>import sys, os
import customtkinter as tk
import tkinter.ttk as ttk
#
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
#
def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
#
def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None
#
def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = tk.CTk()
    top = crc_main_window (root)
    init(root, top)
    root.mainloop()
#
w = None
def create_crc_main_window(rt, *args, **kwargs):
    '''Starting point when module is imported by another module.
       Correct form of call: 'create_crc_main_window(root, *args, **kwargs)' .'''
    global w, w_win, root
    #rt = root
    root = rt
    w = tk.CTkToplevel (root)
    top = crc_main_window (w)
    init(w, top, *args, **kwargs)
    return (w, top)
#
def destroy_crc_main_window():
    global w
    w.destroy()
    w = None
#
class crc_main_window:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        # setting geometry and locking it in, as well as the title
        top.geometry("392x300+607+367")
        top.minsize(120, 1)
        top.maxsize(3604, 1061)
        top.resizable(0,  0)
        top.title("test window")
        top.configure(background="#d9d9d9")
        # these were added later, and provides functionality to open additional windows to show reference information
        def max_power():
            self.max_power_top = tk.CTkToplevel(root)
            self.max_power_top.title("Max Power Transmission")
            self.max_power_top.geometry("372x351+607+367")
            self.max_power_top.resizable(0, 0)
            #
            self.max_frame = tk.CTkFrame(self.max_power_top)
            self.max_frame.place(x=3,y=3,height=345,width=366)
            #
            from PIL import ImageTk, Image
            self.image1 = Image.open(os.path.join(currentdir,'max_power_trans.PNG'))
            self.image1 = self.image1.resize((322, 301))
            self.image = tk.CTkImage(self.image1)
            self.label1 = tk.CTkLabel(self.max_frame,image=self.image)
            self.label1.place(x=0,y=0,width=322,height=301)
            self.label1.configure(text="")
        from tkinter import Menu
        menubar = Menu(top)
        top.config(menu=menubar)
        file_menu = Menu(menubar,tearoff=False)
        file_menu.add_command(label='Max Power Reference',command=max_power)
        file_menu.add_command(label='Exit',command=root.destroy)
        menubar.add_cascade(label="File",menu=file_menu,underline=0)
#
if __name__ == '__main__':
    vp_start_gui()
</code>```

Title: Images showing up tiny in tkinter

Body:
I'm using customtkinter (have tried with standard tkinter as well to rule it out) and having issues with displaying photos. I've tried global-ing the photo, I've tried self.-ing the photo, and I've tried appending the photo to a global list as well. Nothing so far has worked. The image appears in the pop-up window, but it's a few pixels wide and a few pixels tall. I've tried fooling with the image.resize((width,height)) line, I've tried adjusting the size of the frame, I've tried not even using the frame at all. I cannot for the life of me scale this image to the proper size. Code is below.

import sys, os
import customtkinter as tk
import tkinter.ttk as ttk
#
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
#
def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
#
def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None
#
def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = tk.CTk()
    top = crc_main_window (root)
    init(root, top)
    root.mainloop()
#
w = None
def create_crc_main_window(rt, *args, **kwargs):
    '''Starting point when module is imported by another module.
       Correct form of call: 'create_crc_main_window(root, *args, **kwargs)' .'''
    global w, w_win, root
    #rt = root
    root = rt
    w = tk.CTkToplevel (root)
    top = crc_main_window (w)
    init(w, top, *args, **kwargs)
    return (w, top)
#
def destroy_crc_main_window():
    global w
    w.destroy()
    w = None
#
class crc_main_window:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        # setting geometry and locking it in, as well as the title
        top.geometry("392x300+607+367")
        top.minsize(120, 1)
        top.maxsize(3604, 1061)
        top.resizable(0,  0)
        top.title("test window")
        top.configure(background="#d9d9d9")
        # these were added later, and provides functionality to open additional windows to show reference information
        def max_power():
            self.max_power_top = tk.CTkToplevel(root)
            self.max_power_top.title("Max Power Transmission")
            self.max_power_top.geometry("372x351+607+367")
            self.max_power_top.resizable(0, 0)
            #
            self.max_frame = tk.CTkFrame(self.max_power_top)
            self.max_frame.place(x=3,y=3,height=345,width=366)
            #
            from PIL import ImageTk, Image
            self.image1 = Image.open(os.path.join(currentdir,'max_power_trans.PNG'))
            self.image1 = self.image1.resize((322, 301))
            self.image = tk.CTkImage(self.image1)
            self.label1 = tk.CTkLabel(self.max_frame,image=self.image)
            self.label1.place(x=0,y=0,width=322,height=301)
            self.label1.configure(text="")
        from tkinter import Menu
        menubar = Menu(top)
        top.config(menu=menubar)
        file_menu = Menu(menubar,tearoff=False)
        file_menu.add_command(label='Max Power Reference',command=max_power)
        file_menu.add_command(label='Exit',command=root.destroy)
        menubar.add_cascade(label="File",menu=file_menu,underline=0)
#
if __name__ == '__main__':
    vp_start_gui()


问:
Add a Click listener to "save pdf" button in android print manager
I am working on saving a webview as a pdf in compose android .
Have this function that launches the android print manager which works for me .
I am looking to add a functionality where i can automatically pop the backstack  to the previous screen after the webview has been successfully saved . Is it possible to add a click listener to the save pdf button on the print manager screen to track if it was successful and go back ?
This is my code

fun saveAsPdf(
     webView: WebView,
     context: Context?,
     printJobName: String = printJobDescription,

 ) {
     (context?.getSystemService(Context.PRINT_SERVICE) as PrintManager).let { printManager ->

         val printAdapter = webView.createPrintDocumentAdapter(printJobName)

         printManager.print(
             printJobName,
             printAdapter,
             PrintAttributes
                 .Builder()
                 .setMediaSize(
                     PrintAttributes.MediaSize.ISO_A4
                 )
                 .build()
         )
     }
}
```
<p>I tried tracking the state of the printjob with</p>
```printJob.isSuccessful
```
<p>and</p>
```printJob.isFailed
```

but those are not working for me.
Any help would be appreciated

Body:
I am working on saving a webview as a pdf in compose android .
Have this function that launches the android print manager which works for me .
I am looking to add a functionality where i can automatically pop the backstack  to the previous screen after the webview has been successfully saved . Is it possible to add a click listener to the save pdf button on the print manager screen to track if it was successful and go back ?
This is my code

fun saveAsPdf(
     webView: WebView,
     context: Context?,
     printJobName: String = printJobDescription,

 ) {
     (context?.getSystemService(Context.PRINT_SERVICE) as PrintManager).let { printManager ->

         val printAdapter = webView.createPrintDocumentAdapter(printJobName)

         printManager.print(
             printJobName,
             printAdapter,
             PrintAttributes
                 .Builder()
                 .setMediaSize(
                     PrintAttributes.MediaSize.ISO_A4
                 )
                 .build()
         )
     }
}

I tried tracking the state of the printjob with

printJob.isSuccessful

and

printJob.isFailed

but those are not working for me.
Any help would be appreciated


问:
ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
This is my error, I donot know whats wrong, I am upgrading my project from node 10 to node 18 and I upgraded packages and everything and now I am stuck here for a while  now

```<code>webpack://fas-backend/./src/express/routes/products/product.model.js?:3
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
                                         ^

ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
    at Module.default (webpack://fas-backend/./src/express/routes/products/product.model.js?:3:42)
    at eval (webpack://fas-backend/./src/express/routes/projectProducts/projectProducts.model.js?:38:66)
    at ./src/express/routes/projectProducts/projectProducts.model.js (C:\Excersys\FASAPI3\dist\server.js:2059:1)
    at __webpack_require__ (C:\Excersys\FASAPI3\dist\server.js:2963:41)
    at eval (webpack://fas-backend/./src/express/routes/products/product.model.js?:30:97)
    at ./src/express/routes/products/product.model.js (C:\Excersys\FASAPI3\dist\server.js:1549:1)
    at __webpack_require__ (C:\Excersys\FASAPI3\dist\server.js:2963:41)
    at eval (webpack://fas-backend/./src/express/routes/operation/operation.helper.js?:7:81)
    at ./src/express/routes/operation/operation.helper.js (C:\Excersys\FASAPI3\dist\server.js:1239:1)
    at __webpack_require__ (C:\Excersys\FASAPI3\dist\server.js:2963:41)

Node.js v18.12.1
</code>```

this is packege.json file

```<code>{
  "name": "******",
  "version": "******",
  "description": "*********",
  "main": "index.js",
  "scripts": {
    "start": "set NODE_OPTIONS=--openssl-legacy-provider && node dist/server.js",
    "buildDev": "set NODE_OPTIONS=--openssl-legacy-provider && webpack --mode development --config webpack.dev.config.js --watch",
    "devBuild": "set NODE_OPTIONS=--openssl-legacy-provider && webpack --mode development --config webpack.dev.config.js",
    "buildProd": "webpack --mode production --config webpack.prod.config.js",
    "deploy-fas": "cp .fas.env .env && npm run buildProd && gcloud config set project faslive-51622 && gcloud app deploy",
    "deploy-mexmax": "cp .mexmax.env .env && npm run buildProd && gcloud config set project mexmax-backend && gcloud app deploy",
    "deploy-westgate": "cp .westgate.env .env && npm run buildProd && gcloud config set project westgate-1504085677899 && gcloud app deploy",
    "deploy-westgate-dev": "cp .westgate.dev.env .env && npm run devBuild && gcloud config set project westgatedash-dev && gcloud app deploy",
    "deploy-nova": "cp .fwd.env .env && npm run buildProd && gcloud config set project fwd-api-286114 && gcloud app deploy"
  },
  "nodemonConfig": {
    "ignore": [
      "src",
      "node_modules"
    ],
    "delay": "2500"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@elastic/elasticsearch": "~8.5.0",
    "@google-cloud/tasks": "^3.0.5",
    "@google/maps": "^1.1.0",
    "@sendgrid/mail": "^7.7.0",
    "amazon-mws": "0.0.30",
    "axios": "^1.2.1",
    "body-parser": "^1.18.3",
    "circular-dependency-plugin": "^5.2.2",
    "cors": "^2.8.4",
    "cross-env": "^7.0.3",
    "dotenv-webpack": "^8.0.1",
    "ebay-api": "^7.1.3",
    "express": "4.18.2",
    "express-validation": "^1.0.2",
    "faker": "^6.6.6",
    "firebase": "^9.15.0",
    "form-data": "^4.0.0",
    "http-status": "^1.3.2",
    "https": "^1.0.0",
    "icontact-api": "^0.3.0",
    "joi": "^14.3.1",
    "json-2-csv": "^3.7.8",
    "jsonwebtoken": "^8.5.1",
    "jwt-decode": "^3.1.2",
    "lodash": "^4.17.20",
    "luxon": "^3.0.1",
    "magento-api-rest": "^2.0.3",
    "morgan": "^1.9.1",
    "mysql2": "^2.3.3",
    "node-async-loop": "^1.2.2",
    "node-constantcontact": "^2.0.0",
    "oauth-1.0a": "^2.2.6",
    "parse-url": "^8.1.0",
    "payload-validator": "^1.0.4",
    "randomstring": "^1.2.2",
    "request": "^2.88.0",
    "request-promise": "^4.2.4",
    "sass-loader": "13.2.0",
    "sequelize": "^6.27.0",
    "streamifier": "^0.1.1",
    "throttled-queue": "^2.1.4",
    "uuid": "^9.0.0",
    "xhr2": "^0.2.0",
    "xml-js": "^1.6.11",
    "xml2js": "^0.4.23",
    "xmlbuilder": "^15.1.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.6.2",
    "@babel/core": "^7.5.5",
    "@babel/preset-env": "^7.6.2",
    "babel-core": "^6.26.3",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^9.1.0",
    "eslint": "^8.29.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-loader": "^4.0.2",
    "eslint-plugin-import": "^2.18.2",
    "nodemon": "^2.0.20",
    "nodemon-webpack-plugin": "^4.3.1",
    "terser-webpack-plugin": "^5.3.6",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-node-externals": "^3.0.0"
  }
}

</code>```

this is webpack config file

```<code>const path = require('path');
const Dotenv = require('dotenv-webpack');
const webpack = require('webpack'); // eslint-disable-line no-unused-vars
const nodeExternals = require('webpack-node-externals');
const NodemonPlugin = require('nodemon-webpack-plugin');

module.exports = (env, argv) => ({
  entry: {
    server: './src/index.js',
  },
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].js',
  },
  mode: argv.mode,
  target: 'node',
  node: {
    __dirname: false,
    __filename: false,
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
  plugins: [
    new NodemonPlugin(),
    new Dotenv(),
  ],
});

</code>```

I need to upgrade my project to react 18 from node 10 and upgraded my packages and everything and solved many issues and everything and I am stuck at this one for quite a while now tried everything, Need help.

Body:
This is my error, I donot know whats wrong, I am upgrading my project from node 10 to node 18 and I upgraded packages and everything and now I am stuck here for a while  now

webpack://fas-backend/./src/express/routes/products/product.model.js?:3
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
                                         ^

ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
    at Module.default (webpack://fas-backend/./src/express/routes/products/product.model.js?:3:42)
    at eval (webpack://fas-backend/./src/express/routes/projectProducts/projectProducts.model.js?:38:66)
    at ./src/express/routes/projectProducts/projectProducts.model.js (C:\Excersys\FASAPI3\dist\server.js:2059:1)
    at __webpack_require__ (C:\Excersys\FASAPI3\dist\server.js:2963:41)
    at eval (webpack://fas-backend/./src/express/routes/products/product.model.js?:30:97)
    at ./src/express/routes/products/product.model.js (C:\Excersys\FASAPI3\dist\server.js:1549:1)
    at __webpack_require__ (C:\Excersys\FASAPI3\dist\server.js:2963:41)
    at eval (webpack://fas-backend/./src/express/routes/operation/operation.helper.js?:7:81)
    at ./src/express/routes/operation/operation.helper.js (C:\Excersys\FASAPI3\dist\server.js:1239:1)
    at __webpack_require__ (C:\Excersys\FASAPI3\dist\server.js:2963:41)

Node.js v18.12.1

this is packege.json file

{
  "name": "******",
  "version": "******",
  "description": "*********",
  "main": "index.js",
  "scripts": {
    "start": "set NODE_OPTIONS=--openssl-legacy-provider && node dist/server.js",
    "buildDev": "set NODE_OPTIONS=--openssl-legacy-provider && webpack --mode development --config webpack.dev.config.js --watch",
    "devBuild": "set NODE_OPTIONS=--openssl-legacy-provider && webpack --mode development --config webpack.dev.config.js",
    "buildProd": "webpack --mode production --config webpack.prod.config.js",
    "deploy-fas": "cp .fas.env .env && npm run buildProd && gcloud config set project faslive-51622 && gcloud app deploy",
    "deploy-mexmax": "cp .mexmax.env .env && npm run buildProd && gcloud config set project mexmax-backend && gcloud app deploy",
    "deploy-westgate": "cp .westgate.env .env && npm run buildProd && gcloud config set project westgate-1504085677899 && gcloud app deploy",
    "deploy-westgate-dev": "cp .westgate.dev.env .env && npm run devBuild && gcloud config set project westgatedash-dev && gcloud app deploy",
    "deploy-nova": "cp .fwd.env .env && npm run buildProd && gcloud config set project fwd-api-286114 && gcloud app deploy"
  },
  "nodemonConfig": {
    "ignore": [
      "src",
      "node_modules"
    ],
    "delay": "2500"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@elastic/elasticsearch": "~8.5.0",
    "@google-cloud/tasks": "^3.0.5",
    "@google/maps": "^1.1.0",
    "@sendgrid/mail": "^7.7.0",
    "amazon-mws": "0.0.30",
    "axios": "^1.2.1",
    "body-parser": "^1.18.3",
    "circular-dependency-plugin": "^5.2.2",
    "cors": "^2.8.4",
    "cross-env": "^7.0.3",
    "dotenv-webpack": "^8.0.1",
    "ebay-api": "^7.1.3",
    "express": "4.18.2",
    "express-validation": "^1.0.2",
    "faker": "^6.6.6",
    "firebase": "^9.15.0",
    "form-data": "^4.0.0",
    "http-status": "^1.3.2",
    "https": "^1.0.0",
    "icontact-api": "^0.3.0",
    "joi": "^14.3.1",
    "json-2-csv": "^3.7.8",
    "jsonwebtoken": "^8.5.1",
    "jwt-decode": "^3.1.2",
    "lodash": "^4.17.20",
    "luxon": "^3.0.1",
    "magento-api-rest": "^2.0.3",
    "morgan": "^1.9.1",
    "mysql2": "^2.3.3",
    "node-async-loop": "^1.2.2",
    "node-constantcontact": "^2.0.0",
    "oauth-1.0a": "^2.2.6",
    "parse-url": "^8.1.0",
    "payload-validator": "^1.0.4",
    "randomstring": "^1.2.2",
    "request": "^2.88.0",
    "request-promise": "^4.2.4",
    "sass-loader": "13.2.0",
    "sequelize": "^6.27.0",
    "streamifier": "^0.1.1",
    "throttled-queue": "^2.1.4",
    "uuid": "^9.0.0",
    "xhr2": "^0.2.0",
    "xml-js": "^1.6.11",
    "xml2js": "^0.4.23",
    "xmlbuilder": "^15.1.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.6.2",
    "@babel/core": "^7.5.5",
    "@babel/preset-env": "^7.6.2",
    "babel-core": "^6.26.3",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^9.1.0",
    "eslint": "^8.29.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-loader": "^4.0.2",
    "eslint-plugin-import": "^2.18.2",
    "nodemon": "^2.0.20",
    "nodemon-webpack-plugin": "^4.3.1",
    "terser-webpack-plugin": "^5.3.6",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-node-externals": "^3.0.0"
  }
}

this is webpack config file

const path = require('path');
const Dotenv = require('dotenv-webpack');
const webpack = require('webpack'); // eslint-disable-line no-unused-vars
const nodeExternals = require('webpack-node-externals');
const NodemonPlugin = require('nodemon-webpack-plugin');

module.exports = (env, argv) => ({
  entry: {
    server: './src/index.js',
  },
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].js',
  },
  mode: argv.mode,
  target: 'node',
  node: {
    __dirname: false,
    __filename: false,
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
  plugins: [
    new NodemonPlugin(),
    new Dotenv(),
  ],
});

I need to upgrade my project to react 18 from node 10 and upgraded my packages and everything and solved many issues and everything and I am stuck at this one for quite a while now tried everything, Need help.


问:
Pytesseract/tesseract doesnt recognize individual characters from image. Also fails to recognize special characters
I have an image, with characters that where once contained into boxes. I needed to separate and read these characters after treating the image with opencv, in a way that i could retain the previous positions of each letter.

Like this:

full word: LOVES

segment 1: OES

segment 2: L

segment 3: V

Now, the "_" on each missing letter were draw by me with opencv, and i attempted to do the same with '0's, dots, '-', '/' and nothing works much better. I even tried drawing an "X" but tesseract seems to struggle really bad with repeated letters, or maybe spaces... special characters... honestly i do not know what is that makes it harder to recognize.

I further tweak each image before calling tesseract as follows:
(I used PIL instead of opencv because i had previously found slightly better results with the Smooth Filter from PIL, but even that seems to not work anymore)

```<code>def getLetters(img):
    text = ''

    cv2.imwrite("foo.png", img)
    pillImage = Image.open("foo.png")

    thresh = 100
    fn = lambda x : 255 if x > thresh else 0
    r = pillImage.convert('L').point(fn, mode='1')
    r = PIL.ImageOps.invert(r)
    #r = r.filter(ImageFilter.SMOOTH)
    r.save('foo.png')

    letters = cv2.imread("foo.PNG")
    cv2.imshow('all',letters)
    cv2.waitKey()
    cv2.destroyAllWindows()

    text = tess.image_to_string(r, lang='eng', config='--psm 10 --oem 3 -c tessedit_char_whitelist=_-/\AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzº.0')

    text = text.replace(" ", "")
    text = text.replace("\n", "")

    print(text)
    return text

OES= getLetters(resultFail)
L = getLetters(resultYellow)
V = getLetters(resultGreen)

</code>```

The last OUTPUT i got from calling this function, where these (followed by an example of the temp file treated with PIL):

```<code>_O_Es
a
---_-V-uR-
</code>```

foo image = segment 3 (V)

What am i doing wrong?

I have tried:

Multiple --psm settings for tesseract, 10 is really what works best yet i still not fully understand these parameters.

Using, not using and tweaking the char_whitelist

thresholding the image with opencv instead of PIL (it was worse)

The results i was expecting were something much more like the first i got. All 5 letters in lenght:

```<code>_O_ES
L_ _ _ _
_ _ V _ _
</code>```

Suggestions to get to this result in a different way would be immensely appreciated

I probably dont understand fully the library that im using, and im sorry if theres something missing on the explanations... Its my first post here.

Body:
I have an image, with characters that where once contained into boxes. I needed to separate and read these characters after treating the image with opencv, in a way that i could retain the previous positions of each letter.

Like this:

full word: LOVES

segment 1: OES

segment 2: L

segment 3: V

Now, the "_" on each missing letter were draw by me with opencv, and i attempted to do the same with '0's, dots, '-', '/' and nothing works much better. I even tried drawing an "X" but tesseract seems to struggle really bad with repeated letters, or maybe spaces... special characters... honestly i do not know what is that makes it harder to recognize.

I further tweak each image before calling tesseract as follows:
(I used PIL instead of opencv because i had previously found slightly better results with the Smooth Filter from PIL, but even that seems to not work anymore)

def getLetters(img):
    text = ''

    cv2.imwrite("foo.png", img)
    pillImage = Image.open("foo.png")

    thresh = 100
    fn = lambda x : 255 if x > thresh else 0
    r = pillImage.convert('L').point(fn, mode='1')
    r = PIL.ImageOps.invert(r)
    #r = r.filter(ImageFilter.SMOOTH)
    r.save('foo.png')

    letters = cv2.imread("foo.PNG")
    cv2.imshow('all',letters)
    cv2.waitKey()
    cv2.destroyAllWindows()

    text = tess.image_to_string(r, lang='eng', config='--psm 10 --oem 3 -c tessedit_char_whitelist=_-/\AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzº.0')

    text = text.replace(" ", "")
    text = text.replace("\n", "")

    print(text)
    return text

OES= getLetters(resultFail)
L = getLetters(resultYellow)
V = getLetters(resultGreen)

The last OUTPUT i got from calling this function, where these (followed by an example of the temp file treated with PIL):

_O_Es
a
---_-V-uR-

foo image = segment 3 (V)

What am i doing wrong?

I have tried:

Multiple --psm settings for tesseract, 10 is really what works best yet i still not fully understand these parameters.

Using, not using and tweaking the char_whitelist

thresholding the image with opencv instead of PIL (it was worse)

The results i was expecting were something much more like the first i got. All 5 letters in lenght:

_O_ES
L_ _ _ _
_ _ V _ _

Suggestions to get to this result in a different way would be immensely appreciated

I probably dont understand fully the library that im using, and im sorry if theres something missing on the explanations... Its my first post here.


问:
Getting google sheets cell references to change when I move cells
Edit:  So I think if kind of answered my own question.  Sheets is updating formulas but my problem is forumlas where I used to have =C2 for example, it has a problem with these since technically I am replacing C2 with F2.  I may have to manually delete all thos 'REF' errors

If you look at attached picture, I have red section and a blue section.

In red sections, I do not use columns B,C,D anymore.  I want to remove these.  But I can not just delete the columns because they are used in the blue section.

I tried to copy and paste everything in the red section from column E1 to P25 and paste that starting in column B1.  But when I did that, all my formulas got messed up.

So for example, if I had a cell that had =F2-E2, I would expect it to see because I moved all my cells over 3 columns, that F2 is C2 and E2 is B2.  So the new forumula should be =C2-B2

Is there anyway I can get sheets to do this automatically???

I tried copying and pasting, but cell refences did not update.


问:
Error in unique.default(x, nmax = nmax) : unique() applies only to vectors
I use neural network method for prediction for binary classification data
and I try to make a confusion matrix.

The code is

```<code>train.x_keras.ori<-train%>% select(-stroke) %>% scale() %>% as.matrix()
train.y_keras.ori<-to_categorical(train[,"stroke"])
test.x_keras<-test%>% select(-stroke) %>% scale() %>% as.matrix()
test.y_keras<-test[,"stroke"]
train.x_keras.ori<-array_reshape(train.x_keras.ori,dim=dim(train.x_keras.ori))
test.x_keras<-array_reshape(test.x_keras,dim=dim(test.x_keras))

prop.table(table(train[,"stroke"]))

initializer <- initializer_random_normal(seed = 100)
model2 <- keras_model_sequential()
model2 %>%
  layer_dense(input_shape = ncol(train.x_keras.ori), # input
              units = 56, activation = "relu", name = "hidden_1") %>%  # hidden layer 1
  layer_dense(units = 28, activation = "relu", name = "hidden_2") %>% # hidden layer 2
  layer_dense(units = 2, activation = "sigmoid", name = "output")
model2 %>%
  compile(loss = "binary_crossentropy",
          optimizer = optimizer_adam(lr = 0.001),
          metric = "accuracy")

history2 <- model2 %>%
  keras::fit(train.x_keras.ori,
             train.y_keras.ori,
             epoch = 50,
             batch_size = 50,verbose=T,
             class_weight = list("0"= 0.04775574 ,"1"=0.95224426))

prediction2 <- model2 %>% predict(test.x_keras) %>% `>`(0.5) %>% k_cast("int32")

confusionMatrix(as.factor(prediction2), as.factor(test.y_keras))

# Error in unique.default(x, nmax = nmax) : unique() applies only to vectors

</code>```

But I got such an Error message, what can I do for this??

I want to solve that error and make the confusion matrix clearly.

Body:
I use neural network method for prediction for binary classification data
and I try to make a confusion matrix.

The code is

train.x_keras.ori<-train%>% select(-stroke) %>% scale() %>% as.matrix()
train.y_keras.ori<-to_categorical(train[,"stroke"])
test.x_keras<-test%>% select(-stroke) %>% scale() %>% as.matrix()
test.y_keras<-test[,"stroke"]
train.x_keras.ori<-array_reshape(train.x_keras.ori,dim=dim(train.x_keras.ori))
test.x_keras<-array_reshape(test.x_keras,dim=dim(test.x_keras))

prop.table(table(train[,"stroke"]))

initializer <- initializer_random_normal(seed = 100)
model2 <- keras_model_sequential()
model2 %>%
  layer_dense(input_shape = ncol(train.x_keras.ori), # input
              units = 56, activation = "relu", name = "hidden_1") %>%  # hidden layer 1
  layer_dense(units = 28, activation = "relu", name = "hidden_2") %>% # hidden layer 2
  layer_dense(units = 2, activation = "sigmoid", name = "output")
model2 %>%
  compile(loss = "binary_crossentropy",
          optimizer = optimizer_adam(lr = 0.001),
          metric = "accuracy")

history2 <- model2 %>%
  keras::fit(train.x_keras.ori,
             train.y_keras.ori,
             epoch = 50,
             batch_size = 50,verbose=T,
             class_weight = list("0"= 0.04775574 ,"1"=0.95224426))

prediction2 <- model2 %>% predict(test.x_keras) %>% `>`(0.5) %>% k_cast("int32")

confusionMatrix(as.factor(prediction2), as.factor(test.y_keras))

# Error in unique.default(x, nmax = nmax) : unique() applies only to vectors

But I got such an Error message, what can I do for this??

I want to solve that error and make the confusion matrix clearly.