问:
Spring cloud gateway does not redirect on local addresses
I have been struggling for hours now on a problem related to an architecture based on Spring cloud gateway and Netflix Eureka.

Here's my Gateway code:

```<code>@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(p -> p
                        .path("/")
                        .uri("http://google.com"))
                .route(p -> p
                        .path("/auth-service")
                        .uri("http://10.0.2.15:8100"))
                .route(p -> p
                        .path("/concert-service")
                        .uri("lb://concert-service"))
                .build();
    }

}
</code>```

Its application.properties:

```<code>server.port=8762

spring.application.name=api-gateway
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.instance.prefer-ip-address=true
</code>```

The first path redirects well to google homepage but both others return an error 404. When I  request them directly on their host address, I get the content of the page.

By example:

this get request on Postman works well: http://10.0.2.15:8100/

but not this one: http://10.0.2.15:8762/auth-service/

nor this one: http://10.0.2.15:8762/concert-service/

Here's the code for the Auth service:

```<code>@SpringBootApplication
@EnableDiscoveryClient
public class AuthApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthApplication.class, args);
    }

    @RestController
    class ServiceInstanceRestController {

        @Autowired
        private DiscoveryClient discoveryClient;

        @GetMapping("/")
        public String welcome() {
            return "Welcome on Auth microservice api.";
        }

        @RequestMapping("/service-instances/{applicationName}")
        public List<ServiceInstance> serviceInstancesByApplicationName(
                @PathVariable String applicationName) {
            return this.discoveryClient.getInstances(applicationName);
        }
    }
}
</code>```

Its application.properties:

```<code>server.port=8100

spring.application.name=auth-service
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.instance.preferIpAddress=true
</code>```

Code for Concert service:

```<code>@SpringBootApplication
@EnableDiscoveryClient
public class ConcertApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConcertApplication.class, args);
    }

    @RestController
    class ServiceInstanceRestController {

        @Autowired
        private DiscoveryClient discoveryClient;

        @GetMapping("/")
        public String welcome() {
            return "Welcome on Concert microservice api.";
        }

        @RequestMapping("/service-instances/{applicationName}")
        public List<ServiceInstance> serviceInstancesByApplicationName(
                @PathVariable String applicationName) {
            return this.discoveryClient.getInstances(applicationName);
        }
    }
}

</code>```

Its application.properties:

```<code>server.port=8101

spring.application.name=concert-service
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.instance.preferIpAddress=true
</code>```

They are all well registered on Eureka server

```<code>@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }

}
</code>```

application.properties

```<code>server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

logging.level.com.netflix.eureka=DEBUG
logging.level.com.netflix.discovery=DEBUG
</code>```

Body:
I have been struggling for hours now on a problem related to an architecture based on Spring cloud gateway and Netflix Eureka.

Here's my Gateway code:

@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(p -> p
                        .path("/")
                        .uri("http://google.com"))
                .route(p -> p
                        .path("/auth-service")
                        .uri("http://10.0.2.15:8100"))
                .route(p -> p
                        .path("/concert-service")
                        .uri("lb://concert-service"))
                .build();
    }

}

Its application.properties:

server.port=8762

spring.application.name=api-gateway
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.instance.prefer-ip-address=true

The first path redirects well to google homepage but both others return an error 404. When I  request them directly on their host address, I get the content of the page.

By example:

this get request on Postman works well: http://10.0.2.15:8100/

but not this one: http://10.0.2.15:8762/auth-service/

nor this one: http://10.0.2.15:8762/concert-service/

Here's the code for the Auth service:

@SpringBootApplication
@EnableDiscoveryClient
public class AuthApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthApplication.class, args);
    }

    @RestController
    class ServiceInstanceRestController {

        @Autowired
        private DiscoveryClient discoveryClient;

        @GetMapping("/")
        public String welcome() {
            return "Welcome on Auth microservice api.";
        }

        @RequestMapping("/service-instances/{applicationName}")
        public List<ServiceInstance> serviceInstancesByApplicationName(
                @PathVariable String applicationName) {
            return this.discoveryClient.getInstances(applicationName);
        }
    }
}

Its application.properties:

server.port=8100

spring.application.name=auth-service
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.instance.preferIpAddress=true

Code for Concert service:

@SpringBootApplication
@EnableDiscoveryClient
public class ConcertApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConcertApplication.class, args);
    }

    @RestController
    class ServiceInstanceRestController {

        @Autowired
        private DiscoveryClient discoveryClient;

        @GetMapping("/")
        public String welcome() {
            return "Welcome on Concert microservice api.";
        }

        @RequestMapping("/service-instances/{applicationName}")
        public List<ServiceInstance> serviceInstancesByApplicationName(
                @PathVariable String applicationName) {
            return this.discoveryClient.getInstances(applicationName);
        }
    }
}

Its application.properties:

server.port=8101

spring.application.name=concert-service
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.instance.preferIpAddress=true

They are all well registered on Eureka server

@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }

}

application.properties

server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

logging.level.com.netflix.eureka=DEBUG
logging.level.com.netflix.discovery=DEBUG


来源: stackexchange

问:
Keep .nav-item>.nav-link css hover effect while hovering over its dropdown-item [Dropdown - Bootstrap 5]
Can anyone tell me how can I keep the nav-link's hover css while I hover over its dropdown menu?
The parent is .nav-item which is also a dropdown. It's immediate child is the nav-link then the dropdown-menu and its items.
Here is the code:

HTML

```<code><li class="nav-item dropdown">
    <a class="nav-link" data-bs-toggle="dropdown" href="#">About Us</a>
    <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Option 1</a></li>
        <li><a class="dropdown-item" href="#">Option 2</a></li>
        <li><a class="dropdown-item" href="#">Option 3</a></li>
    </ul>
</li>
</code>```

Here is a sample image also where the nav-link keeps its red color while I hover over its dropdown
Please ignore the dropdown background hover effect as I am only concerned with the nav-link hoover effect.

I haven't copied the whole Bootstrap 5 navbar code as it is irrelevant here.
Please do let me know if anyone knows how to achieve this within CSS or JS.

Thank You!

ContentLicense: CC BY-SA 4.0

Body:
Can anyone tell me how can I keep the nav-link's hover css while I hover over its dropdown menu?
The parent is .nav-item which is also a dropdown. It's immediate child is the nav-link then the dropdown-menu and its items.
Here is the code:

HTML

    About Us

Option 1

Option 2

Option 3

Here is a sample image also where the nav-link keeps its red color while I hover over its dropdown
Please ignore the dropdown background hover effect as I am only concerned with the nav-link hoover effect.

I haven't copied the whole Bootstrap 5 navbar code as it is irrelevant here.
Please do let me know if anyone knows how to achieve this within CSS or JS.

Thank You!


问:
Java Firefox Selenium Headless Screenshot
for my project i have managed to et each of the individual elements to work. a screenshot in firefox and firefox webdriver working in headless mode, however combing them has caused issues i cant seem to fix. I have enabled headless mode in Firefox webdriver and am using selenium's TakeScreenshot library but that only seems to work in gui modes. I cant find any selenium options that would fix this problem.

Does anyone have any suggestions of things that might fix this.


问:
The margins at the bottom and start of new pages do not appear when a pdf is split into multiple pages using JSPDF in Angular
Using jsPDF, I am able to save table contents in PDF format in Angular 12, but the bottom margin cannot be added to the page, and the new page starts from the top.

Preview At Page Break

```<code>`savePDF(): void {
    const htmlContent: any = document.getElementById('htmlData');
    html2canvas(htmlContent).then(canvas => {
      const fileURI = canvas.toDataURL('image/png');
      const fileWidth = 285;
      const pageHeight = 210;
      const imgHeight = (canvas.height * fileWidth) / canvas.width;
      let heightLeft = imgHeight;
      const pdf = new jsPDF('l', 'mm', 'a4');
      let position = 0;
      pdf.addImage(fileURI, 'PNG', 0, position, fileWidth, imgHeight);
      heightLeft -= pageHeight;
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage('a4', 'l');
        pdf.addImage(fileURI, 'PNG', 0, position, fileWidth, imgHeight);
        heightLeft -= pageHeight;
      }
      pdf.save('road-test-details.pdf');
    });
  }`
</code>```

Body:
Using jsPDF, I am able to save table contents in PDF format in Angular 12, but the bottom margin cannot be added to the page, and the new page starts from the top.

Preview At Page Break

`savePDF(): void {
    const htmlContent: any = document.getElementById('htmlData');
    html2canvas(htmlContent).then(canvas => {
      const fileURI = canvas.toDataURL('image/png');
      const fileWidth = 285;
      const pageHeight = 210;
      const imgHeight = (canvas.height * fileWidth) / canvas.width;
      let heightLeft = imgHeight;
      const pdf = new jsPDF('l', 'mm', 'a4');
      let position = 0;
      pdf.addImage(fileURI, 'PNG', 0, position, fileWidth, imgHeight);
      heightLeft -= pageHeight;
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage('a4', 'l');
        pdf.addImage(fileURI, 'PNG', 0, position, fileWidth, imgHeight);
        heightLeft -= pageHeight;
      }
      pdf.save('road-test-details.pdf');
    });
  }`


问:
VS Extension: how to handle OnAfterOpenFolder event
My extension currently supports solutions, but I'd like to make it also work with folders. Following the same approach I'm using for solutions, I've added a handler for the SolutionEvents.OnAfterOpenFolder event. But when I open a folder, this event doesn't fire. I wonder if it's firing before the handler is wired up. Can anyone shed some light here? Thanks a lot for any ideas.

Here is my package class (irrelevant stuff removed):

```<code>[ProvideAutoLoad(VSConstants.UICONTEXT.FolderOpened_string, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class MyExtensionPackage : AsyncPackage
{
    protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
    {
        SolutionEvents.OnAfterOpenFolder += this.SolutionEvents_OnAfterOpenFolder;
    }

    private void SolutionEvents_OnAfterOpenFolder(object sender, FolderEventArgs e)
    {
        // This doesn't hit in the debugger
        ThreadHelper.ThrowIfNotOnUIThread();
    }
}
</code>```

Body:
My extension currently supports solutions, but I'd like to make it also work with folders. Following the same approach I'm using for solutions, I've added a handler for the SolutionEvents.OnAfterOpenFolder event. But when I open a folder, this event doesn't fire. I wonder if it's firing before the handler is wired up. Can anyone shed some light here? Thanks a lot for any ideas.

Here is my package class (irrelevant stuff removed):

[ProvideAutoLoad(VSConstants.UICONTEXT.FolderOpened_string, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class MyExtensionPackage : AsyncPackage
{
    protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
    {
        SolutionEvents.OnAfterOpenFolder += this.SolutionEvents_OnAfterOpenFolder;
    }

    private void SolutionEvents_OnAfterOpenFolder(object sender, FolderEventArgs e)
    {
        // This doesn't hit in the debugger
        ThreadHelper.ThrowIfNotOnUIThread();
    }
}


问:
I am not sure why my programm doesn't work
So there is no error but it's also not doing what it's supposed to

```<code>from turtle import*
y = 3
x = 0

def Sydney():
    x = 10

while x < 5:
    if y == 3:
        onkey(Sydney,"w")
        listen()
    else:
        rt(90)

fd(100)
</code>```

I'm expecting that if i press f the programm continues and the turtle moves 100 pixels forward

Body:
So there is no error but it's also not doing what it's supposed to

from turtle import*
y = 3
x = 0

def Sydney():
    x = 10

while x < 5:
    if y == 3:
        onkey(Sydney,"w")
        listen()
    else:
        rt(90)

fd(100)

I'm expecting that if i press f the programm continues and the turtle moves 100 pixels forward


问:
ReactJS button not rendering on android device
I'm trying to write an app in React Native that scans QR codes, and for some reason, no matter whether i use the react native Button component or TouchableOpacity component, i cannot get a button to actually render onto the screen. I have no idea what the problem is, as i literally copy-pasted code from the BarCodeScanner docs, and I'm still unable to get the button to show. Here is my App.js code, any help would be appreciated:

Sorry in advance for the horrific formatting, stackoverflow didnt want me to post it with good formatting so this is the best i could do to get the post up.

```<code>import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button, TouchableOpacity } from 'react-native';
import React, { useState, useEffect } from 'react';
import  { Camera, CameraType } from 'expo-camera';
import { BarCodeScanner } from 'expo-barcode-scanner';

export default function App() {
    return (
        <View style={styles.container}>
            <View style={styles.camera}>
                <BarCodeScanner
                    onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
                    style={StyleSheet.absoluteFillObject} />
                    {scanned && <Button style={styles.button} title={'Tap to Scan Again'}        onPress={() => setScanned(false)} />}
            </View>
        </View>
  );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        flexDirection: 'column',
        alignItems: 'center',
  },
    camera: {
        flex: 1,
        height: 250,
        width: 250,
  },
    button: {
        flex: 1,
        alignSelf: 'flex-end',
        alignItems: 'center'
  },
});
</code>```

I tried changing the button component to a TouchableOpacity component and neither would work. I also tried specifying a style for the button and that didnt work either.

When i tried inspecting on the app and looking at "touchables", nothing shows up.

Body:
I'm trying to write an app in React Native that scans QR codes, and for some reason, no matter whether i use the react native Button component or TouchableOpacity component, i cannot get a button to actually render onto the screen. I have no idea what the problem is, as i literally copy-pasted code from the BarCodeScanner docs, and I'm still unable to get the button to show. Here is my App.js code, any help would be appreciated:

Sorry in advance for the horrific formatting, stackoverflow didnt want me to post it with good formatting so this is the best i could do to get the post up.

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button, TouchableOpacity } from 'react-native';
import React, { useState, useEffect } from 'react';
import  { Camera, CameraType } from 'expo-camera';
import { BarCodeScanner } from 'expo-barcode-scanner';

export default function App() {
    return (
        <View style={styles.container}>
            <View style={styles.camera}>
                <BarCodeScanner
                    onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
                    style={StyleSheet.absoluteFillObject} />
                    {scanned && <Button style={styles.button} title={'Tap to Scan Again'}        onPress={() => setScanned(false)} />}
            </View>
        </View>
  );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        flexDirection: 'column',
        alignItems: 'center',
  },
    camera: {
        flex: 1,
        height: 250,
        width: 250,
  },
    button: {
        flex: 1,
        alignSelf: 'flex-end',
        alignItems: 'center'
  },
});

I tried changing the button component to a TouchableOpacity component and neither would work. I also tried specifying a style for the button and that didnt work either.

When i tried inspecting on the app and looking at "touchables", nothing shows up.


问:
How to create a complex Form in Remix Run component using useFetcher to post complex object in API
I am trying to create a "Task" object from a form in Remix Run which is very complex since it is made up of several parameters including an array of objects, an array of numbers, as well as simple objects. (Attached object structure).

This is the structure of the "Task" object

To post the task, I use useFetcher by changing the fetcherAction to an ActionFunction that receives a FormData in the request and objects to each of the parameters shown in the image and calls a service that makes the request to the backend.

ACTIONFUNCTION

```<code>const action: ActionFunction = async ({ request }) => {
  const [usuid, token] = await Promise.all([
    getUserId(request),
    getUserSucceful(request),
  ]);
  console.log(token);
  const date = new Date();
  const offset = date.getTimezoneOffset();
  const formData = await request.formData();
  console.log(Object.fromEntries(formData));
  const values = Object.fromEntries(formData);
  console.log("VALUES", values);
  const CLIID = values["cliid"];
  const TARCONTENIDO = formData.get("TARCONTENIDO");
  const TARPRIVADA = formData.get("TARPRIVADA");
  const TARHFIN = formData.get("TARHFIN");
  const TARVENCIMIENTO = formData.get("TARVENCIMIENTO");
  const TTAID = formData.get("TTAID");
  const TARHINI = formData.get("TARHINI");
  const TARTVIAJE = formData.get("TARTVIAJE");
  const TARTIMEZONE = formData.get("TARTIMEZONE");
  const NOTAS = formData.getAll("NOTAS");
  const SUBT = formData.getAll("SUBT");
  const RECORDATORIOS = formData.getAll("RECORDATORIOS");
  const USUID = usuid;
  const OFFSET = offset;
  const TAREMAIL = formData.get("TAREMAIL");
  const TARMENSAJE = formData.get("TARMENSAJE");
  const TARDIRECCION = formData.get("TARDIRECCION");
  const TARLINK = formData.get("TARLINK");
  const TARID = formData.get("TARID");
  return await registerTask(
    CLIID,
    TARCONTENIDO,
    TARPRIVADA,
    TARHFIN,
    TARVENCIMIENTO,
    TTAID,
    TARHINI,
    TARTVIAJE,
    TARTIMEZONE,
    NOTAS,
    SUBT,
    RECORDATORIOS,
    USUID,
    OFFSET,
    TAREMAIL,
    TARMENSAJE,
    TARDIRECCION,
    TARLINK,
    TARID,
    token
  );
};
</code>```

POST TASK SERVICE

```<code>export const registerTask = async (
  CLIID: any,
  TARCONTENIDO: string,
  TARPRIVADA: any,
  TARHFIN: string,
  TARVENCIMIENTO: any,
  TTAID: number,
  TARHINI: string,
  TARTVIAJE: string,
  TARTIMEZONE: string,
  NOTAS: any,
  SUBT: any,
  RECORDATORIOS: any,
  USUID: number,
  OFFSET: any,
  TAREMAIL: string,
  TARMENSAJE: string,
  TARDIRECCION: string,
  TARLINK: string,
  TARID?: string,
  token: any
) => {
  try {
    const data = {
      CLIID: CLIID,
      TARCONTENIDO: TARCONTENIDO,
      TARPRIVADA: TARPRIVADA,
      TARHFIN: TARHFIN,
      TARVENCIMIENTO: TARVENCIMIENTO,
      TTAID: TTAID,
      TARHINI: TARHINI,
      TARTVIAJE: TARTVIAJE,
      TARTIMEZONE: TARTIMEZONE,
      NOTAS: NOTAS,
      SUBT: SUBT,
      RECORDATORIOS: RECORDATORIOS,
      USUID: USUID,
      OFFSET: OFFSET,
      TAREMAIL: TAREMAIL,
      TARMENSAJE: TARMENSAJE,
      TARDIRECCION: TARDIRECCION,
      TARLINK: TARLINK,
      TARID: TARID,
    };
      let response = await fetch(
        ".../registertarea",
        {
          method: "POST",
          mode: "cors",
          headers: {
            "Content-Type": "application/json",
            user_token: token,
          },
          body: JSON.stringify(data),
        }
      );
      console.log(response);
      return { status: 200, data: response };
    }
  } catch (error) {
    console.error(error);
    return "Error Service";
  }
};

</code>```

The form is created correctly and each of the data is being set correctly to send the request. The problem is that when the ActionFunction receives the form, I don't know how to handle the arrays of the form, let alone how to obtain the array of objects that each object of the form has arrays of objects inside as parameters.

Not knowing how to get these arrays of objects from the formData, I also can't know how to add them to the data you sent in the request body.
The truth is that I spent time trying to figure out how to handle it and I can't. It would be very helpful if there is some documentation or an example of how to create complex forms in remix.

TypeForm
TaskForm = {
CLIID: [numbers],
TARCONTENIDO: string,
TARPRIVADA: number,
TARHFIN: string,
TARVENCIMIENTO: string,
TTAID: number,
TARHINI: string,
TARTVIAJE:string,
TARTIMEZONE: string,
NOTAS: [{notaid: number, nota: string }],
SUBT: [ These are subTasks, they have the same parameters as a task except for a few, but they also include some arrays of objects],
RECORDATORIOS: [{recid: number, recdescription: string, recunidad: string ... }],
USUID: 0,
OFFSET: string,
TAREMAIL: string,
TARMENSAJE: string,
TARDIRECCION:string,
TARLINK: string,
};

Not knowing how to get these arrays of objects from the formData, I also can't know how to add them to the data you sent in the request body.
The truth is that I spent time trying to figure out how to handle it and I can't. It would be very helpful if there is some documentation or an example of how to create complex forms in remix.

Body:
I am trying to create a "Task" object from a form in Remix Run which is very complex since it is made up of several parameters including an array of objects, an array of numbers, as well as simple objects. (Attached object structure).

This is the structure of the "Task" object

To post the task, I use useFetcher by changing the fetcherAction to an ActionFunction that receives a FormData in the request and objects to each of the parameters shown in the image and calls a service that makes the request to the backend.

ACTIONFUNCTION

const action: ActionFunction = async ({ request }) => {
  const [usuid, token] = await Promise.all([
    getUserId(request),
    getUserSucceful(request),
  ]);
  console.log(token);
  const date = new Date();
  const offset = date.getTimezoneOffset();
  const formData = await request.formData();
  console.log(Object.fromEntries(formData));
  const values = Object.fromEntries(formData);
  console.log("VALUES", values);
  const CLIID = values["cliid"];
  const TARCONTENIDO = formData.get("TARCONTENIDO");
  const TARPRIVADA = formData.get("TARPRIVADA");
  const TARHFIN = formData.get("TARHFIN");
  const TARVENCIMIENTO = formData.get("TARVENCIMIENTO");
  const TTAID = formData.get("TTAID");
  const TARHINI = formData.get("TARHINI");
  const TARTVIAJE = formData.get("TARTVIAJE");
  const TARTIMEZONE = formData.get("TARTIMEZONE");
  const NOTAS = formData.getAll("NOTAS");
  const SUBT = formData.getAll("SUBT");
  const RECORDATORIOS = formData.getAll("RECORDATORIOS");
  const USUID = usuid;
  const OFFSET = offset;
  const TAREMAIL = formData.get("TAREMAIL");
  const TARMENSAJE = formData.get("TARMENSAJE");
  const TARDIRECCION = formData.get("TARDIRECCION");
  const TARLINK = formData.get("TARLINK");
  const TARID = formData.get("TARID");
  return await registerTask(
    CLIID,
    TARCONTENIDO,
    TARPRIVADA,
    TARHFIN,
    TARVENCIMIENTO,
    TTAID,
    TARHINI,
    TARTVIAJE,
    TARTIMEZONE,
    NOTAS,
    SUBT,
    RECORDATORIOS,
    USUID,
    OFFSET,
    TAREMAIL,
    TARMENSAJE,
    TARDIRECCION,
    TARLINK,
    TARID,
    token
  );
};

POST TASK SERVICE

export const registerTask = async (
  CLIID: any,
  TARCONTENIDO: string,
  TARPRIVADA: any,
  TARHFIN: string,
  TARVENCIMIENTO: any,
  TTAID: number,
  TARHINI: string,
  TARTVIAJE: string,
  TARTIMEZONE: string,
  NOTAS: any,
  SUBT: any,
  RECORDATORIOS: any,
  USUID: number,
  OFFSET: any,
  TAREMAIL: string,
  TARMENSAJE: string,
  TARDIRECCION: string,
  TARLINK: string,
  TARID?: string,
  token: any
) => {
  try {
    const data = {
      CLIID: CLIID,
      TARCONTENIDO: TARCONTENIDO,
      TARPRIVADA: TARPRIVADA,
      TARHFIN: TARHFIN,
      TARVENCIMIENTO: TARVENCIMIENTO,
      TTAID: TTAID,
      TARHINI: TARHINI,
      TARTVIAJE: TARTVIAJE,
      TARTIMEZONE: TARTIMEZONE,
      NOTAS: NOTAS,
      SUBT: SUBT,
      RECORDATORIOS: RECORDATORIOS,
      USUID: USUID,
      OFFSET: OFFSET,
      TAREMAIL: TAREMAIL,
      TARMENSAJE: TARMENSAJE,
      TARDIRECCION: TARDIRECCION,
      TARLINK: TARLINK,
      TARID: TARID,
    };
      let response = await fetch(
        ".../registertarea",
        {
          method: "POST",
          mode: "cors",
          headers: {
            "Content-Type": "application/json",
            user_token: token,
          },
          body: JSON.stringify(data),
        }
      );
      console.log(response);
      return { status: 200, data: response };
    }
  } catch (error) {
    console.error(error);
    return "Error Service";
  }
};

The form is created correctly and each of the data is being set correctly to send the request. The problem is that when the ActionFunction receives the form, I don't know how to handle the arrays of the form, let alone how to obtain the array of objects that each object of the form has arrays of objects inside as parameters.

Not knowing how to get these arrays of objects from the formData, I also can't know how to add them to the data you sent in the request body.
The truth is that I spent time trying to figure out how to handle it and I can't. It would be very helpful if there is some documentation or an example of how to create complex forms in remix.

TypeForm
TaskForm = {
CLIID: [numbers],
TARCONTENIDO: string,
TARPRIVADA: number,
TARHFIN: string,
TARVENCIMIENTO: string,
TTAID: number,
TARHINI: string,
TARTVIAJE:string,
TARTIMEZONE: string,
NOTAS: [{notaid: number, nota: string }],
SUBT: [ These are subTasks, they have the same parameters as a task except for a few, but they also include some arrays of objects],
RECORDATORIOS: [{recid: number, recdescription: string, recunidad: string ... }],
USUID: 0,
OFFSET: string,
TAREMAIL: string,
TARMENSAJE: string,
TARDIRECCION:string,
TARLINK: string,
};

Not knowing how to get these arrays of objects from the formData, I also can't know how to add them to the data you sent in the request body.
The truth is that I spent time trying to figure out how to handle it and I can't. It would be very helpful if there is some documentation or an example of how to create complex forms in remix.


问:
Woocommerce - Change backorder status when the stock of a variation of a woocommerce product is updated
I can't change the backorder status of a variation when the stock of this variation is updated.

When the stock of a simple product updates, I can change the backorder status but for a variable product, the backorder status of a variation does not change when the stock of the variation updates.

Here is my code that works for simple products but not for product variations :

```<code>function stock_changed($product)
{
    $product_id = $product->get_id();
    $product_stock_qty = $product->get_stock_quantity();
    $product_stock_manage = $product->get_manage_stock();
    $variations = $product->get_children();

    if($product->is_type( 'simple' ))
    {
        if($product_stock_manage)
        {
            if ($product_stock_qty <= 0) {
                update_post_meta($product_id, '_backorders', 'yes');
            }
        }
    } else if($product->is_type( 'variable' ))
    {
        foreach ($variations as $variation) {
            $variation_obj = wc_get_product($variation);
            $variation_stock_qty = $variation_obj->get_stock_quantity();

            if ($variation_stock_qty <= 0) {
                $variation_obj->set_backorders( 'yes' );
                $variation_obj->save();
            }
        }
    }
}
add_action('woocommerce_product_set_stock', 'stock_changed');
add_action('woocommerce_variation_set_stock', 'stock_changed');
</code>```

Body:
I can't change the backorder status of a variation when the stock of this variation is updated.

When the stock of a simple product updates, I can change the backorder status but for a variable product, the backorder status of a variation does not change when the stock of the variation updates.

Here is my code that works for simple products but not for product variations :

function stock_changed($product)
{
    $product_id = $product->get_id();
    $product_stock_qty = $product->get_stock_quantity();
    $product_stock_manage = $product->get_manage_stock();
    $variations = $product->get_children();

    if($product->is_type( 'simple' ))
    {
        if($product_stock_manage)
        {
            if ($product_stock_qty <= 0) {
                update_post_meta($product_id, '_backorders', 'yes');
            }
        }
    } else if($product->is_type( 'variable' ))
    {
        foreach ($variations as $variation) {
            $variation_obj = wc_get_product($variation);
            $variation_stock_qty = $variation_obj->get_stock_quantity();

            if ($variation_stock_qty <= 0) {
                $variation_obj->set_backorders( 'yes' );
                $variation_obj->save();
            }
        }
    }
}
add_action('woocommerce_product_set_stock', 'stock_changed');
add_action('woocommerce_variation_set_stock', 'stock_changed');


问:
Neither JS or Selenium (FF or Chrome) can click a button in a modal dialog
I am trying to drive a web portal for my home heating (using python). There used to be an open source library to use it but this was broken when they introduced some complicate JS and they don't provide API keys to normal users.
Selenium has worked fine to log in and get status data, until I got to a modal dialog where js can't see most of the normal functions (e.g. click, dispatchEvent) that I'd like to use on this fragment:

```<code><a data-bind="click: updateZoneHeating, visible: currentZone().showZoneActivateBtn" class="button" style="">Activate</a>
</code>```

It is clearly visible and clickable in the selenium rendering (using Chrome or Firefox latest released versions).

In JS in the console, and Selenium, I can find the element, it has the expected outerhtml shown above in both cases so I think I have the right element.

Size reports correctly.

I was expecting to be able, via JS or selenium, to inject a click event to submit the modal dialog.

In my JS attempts to dispatchEvent or click result in Uncaught TypeError: b.dispatchEvent is not a function (and similar for click function)

Using Selenium I get a ElementNotInteractableException.

I have tried waiting a long time, waiting until "clickable" (timesout), scrolling into view (it is already in view but that didn't work either). I have tried various selectors xpath, css, and (on a different element with the same problem) id too.

I have tried sending a mouse event from Selenium too.

If I try checkVisibility() in JS I get false, but changing visibility, opacity, z-index doesn't change anything and it's perfectly visible and clickable by hand.

Further digging shows the following js libraries are used on the page:

bootstrap

jquery-ui

Application Insights

localytics

google analytics

msviewport

Body:
I am trying to drive a web portal for my home heating (using python). There used to be an open source library to use it but this was broken when they introduced some complicate JS and they don't provide API keys to normal users.
Selenium has worked fine to log in and get status data, until I got to a modal dialog where js can't see most of the normal functions (e.g. click, dispatchEvent) that I'd like to use on this fragment:

Activate

It is clearly visible and clickable in the selenium rendering (using Chrome or Firefox latest released versions).

In JS in the console, and Selenium, I can find the element, it has the expected outerhtml shown above in both cases so I think I have the right element.

Size reports correctly.

I was expecting to be able, via JS or selenium, to inject a click event to submit the modal dialog.

In my JS attempts to dispatchEvent or click result in Uncaught TypeError: b.dispatchEvent is not a function (and similar for click function)

Using Selenium I get a ElementNotInteractableException.

I have tried waiting a long time, waiting until "clickable" (timesout), scrolling into view (it is already in view but that didn't work either). I have tried various selectors xpath, css, and (on a different element with the same problem) id too.

I have tried sending a mouse event from Selenium too.

If I try checkVisibility() in JS I get false, but changing visibility, opacity, z-index doesn't change anything and it's perfectly visible and clickable by hand.

Further digging shows the following js libraries are used on the page:

bootstrap

jquery-ui

Application Insights

localytics

google analytics

msviewport


问:
How can I transfer funds from one Merchant account to another using GP API?
I'm attempting to implement a basic wallet using the Global Payments API, but I'm still getting to know it.

My target is for my users or clients to be able to pay another person who is a merchant on our platform or transfer money to them. However, I don't seem to know how to use the API to put this into practice. Please help me understand how to do this by providing code examples.

We are using NodeJS. So perhaps a straightforward API request example will work well for us.


问:
Aligning grid rows to inner grid rows
I have design where I need to place grid inside another grid. Inner grid spans 3 rows and have 3 rows itself with at least 3 columns (could be more). I want to align yellow inner rows to parent grid's rows corresponding so parent's grid-column: 1,  grid-row: 2/5 would be the same height as yellow rows.

I think grid-template-rows: subgrid would work, but it is not fully supported yet. Is the only solution to use single grid with 4 columns and span columns where 4 columns are not required?

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.grid>div {
  border: 1px solid black;
  background-color: blue;
}

.subgrid {
  align-items: center;
  grid-row: span 3;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.subgrid>div:nth-child(-n+3) {
  height: 20px;
  border: 1px solid gray;
  background-color: yellow;
}

.subgrid>div:nth-child(n+4):nth-child(-n+6) {
  height: 50px;
  border: 1px solid gray;
  background-color: yellow;
}

.subgrid>div:nth-child(n+7):nth-child(-n+9) {
  height: 20px;
  border: 1px solid gray;
  background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>First Row First Col</div>
  <div>First Row Second Col</div>
  <div>Empty Col</div>
  <div class="subgrid">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div>Third Row First Col</div>
  <div>Fourth Row First Col</div>
  <div>Fifth Row First Col</div>
  <div>Fifth Row Second Col</div>
</div></code>```

Title: Aligning grid rows to inner grid rows

Body:
I have design where I need to place grid inside another grid. Inner grid spans 3 rows and have 3 rows itself with at least 3 columns (could be more). I want to align yellow inner rows to parent grid's rows corresponding so parent's grid-column: 1,  grid-row: 2/5 would be the same height as yellow rows.

I think grid-template-rows: subgrid would work, but it is not fully supported yet. Is the only solution to use single grid with 4 columns and span columns where 4 columns are not required?

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.grid>div {
  border: 1px solid black;
  background-color: blue;
}

.subgrid {
  align-items: center;
  grid-row: span 3;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.subgrid>div:nth-child(-n+3) {
  height: 20px;
  border: 1px solid gray;
  background-color: yellow;
}

.subgrid>div:nth-child(n+4):nth-child(-n+6) {
  height: 50px;
  border: 1px solid gray;
  background-color: yellow;
}

.subgrid>div:nth-child(n+7):nth-child(-n+9) {
  height: 20px;
  border: 1px solid gray;
  background-color: yellow;
}

First Row First Col

First Row Second Col

Empty Col

Third Row First Col

Fourth Row First Col

Fifth Row First Col

Fifth Row Second Col


问:
Changing keyboard language using UIKit in SwiftUI (UIViewRepresentable)
I'm trying to change the on screen keyboard's language layout to a different language, when user taps on a foreign phrase text field. The foreign text field is the foreign equivalent of what they typed into another text field in their native language.

When the user has entered the native and foreign translation they submit their input, and it's stored as a phrase for the language they're learning.

There is no native support for this in SwiftUI, so I have to bridge UIKit to SwiftUI.

The problem is that UITextFieldViewRepresentable seems to be instantiated before the keyboard language can be worked out when initialise() is called from the .onAppear() view modifier. So the declared value "en-GB" of keyboardLanguage is passed into UITextFieldViewRepresentable().

I expect the keyboardLanguage string to be something like 'de-DE', in the case that I'm entering phrases for German and using the German keyboard, rather than the native keyboard equivalent (not using transliteration). The transliteration boolean allows user to enter the foreign phrase using their native or foreign keyboard. If it's true, then keyboard is set to native language and is set to foreign language is it's false. So user has choice of sticking with their native keyboard and making transliterations for the foreign phrase, or entering the foreign phrase in the foreign spelling using a foreign keyboard.

The value of language in: print("text input mode: (language)") on the 11th last line in the code is always "en-GB".

If I change the: @State var keyboardLanguage: String = "en-GB"

line to: @State var keyboardLanguage: String = "de-DE",

the keyboard changes to German when I toggle transliteration to OFF and tap on the foreign text field. However, I expect to be able to leave the declared value as "en-GB", and be able to change the keyboardLanguage string to whatever language is being used when transliteration is OFF.

The language identifier is worked out by:

changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name ?? "")

The line above takes the string value of a language object name, e.g. German, and returns the language's BCP code, e.g. "de-DE". The BCP code is required to be passed to the UITextInputMode? variable, which is how iOS knows what keyboard language to display.

My code is:

```<code>import SwiftUI
import Combine
import SwiftGoogleTranslate

struct AddSectionThingAlert: View {

    @Binding var showingModal: Bool

    @State private var scale: CGFloat = 0.1
    @State private var nativeValidationError = false
    @State private var foreignValidationError = false
    @State private var nativeThing = ""
    @State private var foreignThing = ""
    @State private var yOffset = 0
    @State private var submitDisabled = true
    @State private var transliteration = true
    @State var keyboardLanguage: String = "en-GB"

    var sectionThings: [SectionThing]
    var language: Language
    var titleText = ""
    var nativePlaceholderText = ""
    var foreignPlaceholderText = ""
    var buttonText = "Ok"
    var action: (String, String) -> Void
    var dataOps = DataHandler()

    var yOffsetDevice: Int {
        switch (UIDevice.current.name, sectionThings.count > 0) {
        case ("iPhone 6s", true), ("iPhone 6s Plus", true), ("iPhone 7", true), ("iPhone 8", true), ("iPhone SE (1st generation)", true), ("iPhone SE (2nd generation)", true), ("iPhone SE (3rd generation)", true), ("iPod touch (7th generation)", true):
            return -15
        case ("iPhone 6s", false), ("iPhone 6s Plus", false), ("iPhone 7", false), ("iPhone 8", false), ("iPhone SE (1st generation)", false), ("iPhone SE (2nd generation)", false), ("iPhone SE (3rd generation)", false):
            return -125
        case ("iPod touch (7th generation)", true):
            return -20
        case ("iPod touch (7th generation)", false):
            return -150
        case ("iPhone 12 mini", true):
            return -30
        case ("iPhone 12 mini", false):
            return -90
        case ("iPhone 13 mini", true):
            return 0
        case ("iPhone 13 mini", false):
            return -120
        case ("iPhone 11 Pro Max", true), ("iPhone 12 Pro Max", true), ("iPhone 13 Pro Max", true):
            return -35
        case ("iPhone 11 Pro Max", false), ("iPhone 12 Pro Max", false), ("iPhone 13 Pro Max", false):
            return -15
        default:
            return -35
        }
    }

    var dialogueWidth: Double {
        switch UIDevice.current.name {
        case "iPhone 6s", "iPhone 6s Plus", "iPhone 7", "iPhone 8", "iPhone SE (1st generation)", "iPhone SE (2nd generation)", "iPhone SE (3rd generation)", "iPod touch (7th generation)":
            return 0.8
        default:
            return 0.6
        }
    }

    @Environment(\.colorScheme) var colorScheme

    @StateObject var core = Core()

    @FocusState private var answerIsFocused: Bool

    var body: some View {
        ZStack {
            Color.secondary.opacity(0.4).edgesIgnoringSafeArea(.all)
            VStack(spacing: 0) {
                Text(titleText)
                    .bold()
                    .lineLimit(1)
                    .padding(.horizontal)
                    .padding(.top)
                TextField("", text: $nativeThing)
                    .modifier(TextFieldClearButton2(text: $nativeThing))
                    .placeholder(when: nativeThing.isEmpty) {
                        Text("\(nativePlaceholderText)").foregroundColor(.gray)
                    }
                    .onReceive(Just(nativeThing)) { nativeThing in
                        if self.nativeThing.count < 40 && self.foreignThing.count < 40 && !self.nativeThing.isEmpty && !self.foreignThing.isEmpty {
                            submitDisabled = false
                        } else {
                            submitDisabled = true
                        }
                        if self.nativeThing.count > 39 { nativeValidationError = true } else { nativeValidationError = false }
                    }
                    .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                    .padding(5)
                    .multilineTextAlignment(.center)
                    .overlay(RoundedRectangle(cornerRadius: 6).stroke(nativeValidationError ? Color.red : Color(UIColor.systemGray4), lineWidth: 1))
                    .font(.subheadline)
                    .padding(.horizontal, 15)
                    .padding(.bottom)
                    .padding(.top)
                    .focused($answerIsFocused)
                    .onAppear {
                        // key part: delay setting isFocused until after some-internal-iOS setup
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            answerIsFocused = true
                        }
                    }

                    Button(action: {
                        doAutoTranslate()
                    }) {
                        Text("Instant Translation")
                            .foregroundColor(Color(UIColor.systemBlue))
                            .cornerRadius(40)
                            .frame(minWidth: 0, maxWidth: .infinity)
                            .font(.system(size: 15))
                    }
                    .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                    .padding(5)
                    .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(UIColor.systemBlue), lineWidth: 1))
                    .padding(.horizontal, 15)
                    .padding(.bottom)

                    Toggle("", isOn: $transliteration)
                        .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                        .toggleStyle(CustomToggleStyle())
                        .onChange(of: transliteration, perform: { value in
                            core.setTransliteration(set: transliteration)
                            if transliteration {
                                keyboardLanguage = Locale.current.languageCode!
                            } else { keyboardLanguage = changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name ?? "") }
                            print("toggle keyboard language: \(keyboardLanguage)")
                        })
                    .padding(5)
                    .overlay(RoundedRectangle(cornerRadius: 6).stroke(lineWidth: 1).foregroundColor(transliteration ? Color(UIColor.systemGreen) : Color(UIColor.lightGray)))
                    .padding(.bottom)

                UITextFieldViewRepresentable(foreignThing: $foreignThing, placeholder: foreignPlaceholderText, language: keyboardLanguage)
                    .modifier(TextFieldClearButton2(text: $foreignThing))
//                    .placeholder(when: foreignThing.isEmpty) {
//                        Text("\(foreignPlaceholderText)").foregroundColor(.gray)
//                    }
                    .onReceive(Just(foreignThing)) { foreignThing in

                        if self.nativeThing.count < 40 && self.foreignThing.count < 40 && !self.nativeThing.isEmpty && !self.foreignThing.isEmpty {
                            submitDisabled = false
                        } else { submitDisabled = true }
                        if self.foreignThing.count > 39 { foreignValidationError = true } else { foreignValidationError = false }
                    }
                    .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                    .padding(5)
                    .multilineTextAlignment(.center)
                    .overlay(
                        RoundedRectangle(cornerRadius: 6)
                            .stroke(foreignValidationError ? Color.red : Color(UIColor.systemGray4), lineWidth: 1)
                    )
                    .font(.subheadline)
                    .padding(.horizontal, 15)
                    .padding(.bottom)
                Divider()
                HStack(spacing: 0) {
                    HStack {
                        Spacer()
                        Button(action: {
                            self.showingModal.toggle()
                            answerIsFocused = false
                        }) { Text("Cancel") }
                        Spacer()
                    }
                    Divider()
                    HStack {
                        Spacer()
                        Button(action: {
                            self.returnTextFieldInput()
                            answerIsFocused = false
                        }) { Text("Submit") }
                        .disabled(submitDisabled)
                        Spacer()
                    }
                }.frame(height: 50)
            }
            .background(colorScheme == .light ?  Color.white : Color.black)
            .clipShape(RoundedRectangle(cornerRadius: 15))
            .frame(width: screenSize.width * dialogueWidth, height: 500, alignment: .center)
            .scaleEffect(scale)
            .padding()
            .onAppear {
                initialize()
                withAnimation(.interpolatingSpring(mass: 0.1, stiffness: 100, damping: 10, initialVelocity: 50)) { self.scale = 1 }
            }
            .offset(CGSize(width: 0, height: self.yOffset))
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification)) { _ in
            withAnimation { self.yOffset = yOffsetDevice }
        }
    }

    func initialize() {
        self.transliteration = core.transliteration()
        if transliteration {
            keyboardLanguage = Locale.current.languageCode!
        } else { keyboardLanguage = changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name ?? "") }
        print("initialize keyboard language: \(keyboardLanguage)")
    }

    func returnTextFieldInput() {
        self.action(nativeThing, foreignThing)
        self.showingModal.toggle()
    }

    func doAutoTranslate() {
        SwiftGoogleTranslate.shared.start(with: "AIzaSyAhqjSritgMQFqOiVxSMNfJjDp58hDKdQM")
        let languageLocale = Locale.current.languageCode?.components(separatedBy: "-").first ?? "en"
        let foreignLanguageCode = changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name!).components(separatedBy: "-").first ?? "en"
        if nativeThing.count > 0 {
            SwiftGoogleTranslate.shared.translate(nativeThing, foreignLanguageCode, languageLocale) { (text, error) in
                if let _ = text {
                    self.foreignThing = text!
                }
            }
        } else if foreignThing.count > 0 {
            SwiftGoogleTranslate.shared.translate(foreignThing, languageLocale, foreignLanguageCode) { (text, error) in
                if let _ = text {
                    self.nativeThing = text!
                }
            }
        }
    }
}

struct UITextFieldViewRepresentable: UIViewRepresentable {

    @Binding var foreignThing: String

    let placeholder: String
    let placeholderColor: UIColor
    let language: String

    init(foreignThing: Binding<String>, placeholder: String, placeholderColor: UIColor = .gray, language: String) {
        self._foreignThing = foreignThing
        self.placeholder = placeholder
        self.placeholderColor = placeholderColor
        self.language = language
    }

    func makeUIView(context: Context) -> UITextField {

        let textField = getTextField()
        textField.delegate = context.coordinator

        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = foreignThing
    }

    private func getTextField() -> UITextField {

        let textField = WordTextField(frame: .zero)
        textField.language = self.language
        let placeholder = NSAttributedString(
            string: placeholder,
            attributes: [
                .foregroundColor: placeholderColor
            ])
        textField.attributedPlaceholder = placeholder
        return textField
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(foreignThing: $foreignThing)
    }

    class Coordinator: NSObject, UITextFieldDelegate {

        @Binding var foreignThing: String

        init(foreignThing: Binding<String>) {
            self._foreignThing = foreignThing
        }
        func textFieldDidChangeSelection(_ textField: UITextField) {
            foreignThing = textField.text ?? ""
        }
    }

    class WordTextField: UITextField {

        var language: String? {
            didSet {
                if self.isFirstResponder{
                    self.resignFirstResponder()
                    self.becomeFirstResponder()
                }
            }
        }

        override var textInputMode: UITextInputMode? {
            if let language = self.language {
                print("text input mode: \(language)")
                for inputMode in UITextInputMode.activeInputModes {
                    if let inputModeLanguage = inputMode.primaryLanguage, inputModeLanguage == language {
                        return inputMode
                    }
                }
            }
            return super.textInputMode
        }
    }
}
</code>```

Body:
I'm trying to change the on screen keyboard's language layout to a different language, when user taps on a foreign phrase text field. The foreign text field is the foreign equivalent of what they typed into another text field in their native language.

When the user has entered the native and foreign translation they submit their input, and it's stored as a phrase for the language they're learning.

There is no native support for this in SwiftUI, so I have to bridge UIKit to SwiftUI.

The problem is that UITextFieldViewRepresentable seems to be instantiated before the keyboard language can be worked out when initialise() is called from the .onAppear() view modifier. So the declared value "en-GB" of keyboardLanguage is passed into UITextFieldViewRepresentable().

I expect the keyboardLanguage string to be something like 'de-DE', in the case that I'm entering phrases for German and using the German keyboard, rather than the native keyboard equivalent (not using transliteration). The transliteration boolean allows user to enter the foreign phrase using their native or foreign keyboard. If it's true, then keyboard is set to native language and is set to foreign language is it's false. So user has choice of sticking with their native keyboard and making transliterations for the foreign phrase, or entering the foreign phrase in the foreign spelling using a foreign keyboard.

The value of language in: print("text input mode: (language)") on the 11th last line in the code is always "en-GB".

If I change the: @State var keyboardLanguage: String = "en-GB"

line to: @State var keyboardLanguage: String = "de-DE",

the keyboard changes to German when I toggle transliteration to OFF and tap on the foreign text field. However, I expect to be able to leave the declared value as "en-GB", and be able to change the keyboardLanguage string to whatever language is being used when transliteration is OFF.

The language identifier is worked out by:

changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name ?? "")

The line above takes the string value of a language object name, e.g. German, and returns the language's BCP code, e.g. "de-DE". The BCP code is required to be passed to the UITextInputMode? variable, which is how iOS knows what keyboard language to display.

My code is:

import SwiftUI
import Combine
import SwiftGoogleTranslate

struct AddSectionThingAlert: View {

    @Binding var showingModal: Bool

    @State private var scale: CGFloat = 0.1
    @State private var nativeValidationError = false
    @State private var foreignValidationError = false
    @State private var nativeThing = ""
    @State private var foreignThing = ""
    @State private var yOffset = 0
    @State private var submitDisabled = true
    @State private var transliteration = true
    @State var keyboardLanguage: String = "en-GB"

    var sectionThings: [SectionThing]
    var language: Language
    var titleText = ""
    var nativePlaceholderText = ""
    var foreignPlaceholderText = ""
    var buttonText = "Ok"
    var action: (String, String) -> Void
    var dataOps = DataHandler()

    var yOffsetDevice: Int {
        switch (UIDevice.current.name, sectionThings.count > 0) {
        case ("iPhone 6s", true), ("iPhone 6s Plus", true), ("iPhone 7", true), ("iPhone 8", true), ("iPhone SE (1st generation)", true), ("iPhone SE (2nd generation)", true), ("iPhone SE (3rd generation)", true), ("iPod touch (7th generation)", true):
            return -15
        case ("iPhone 6s", false), ("iPhone 6s Plus", false), ("iPhone 7", false), ("iPhone 8", false), ("iPhone SE (1st generation)", false), ("iPhone SE (2nd generation)", false), ("iPhone SE (3rd generation)", false):
            return -125
        case ("iPod touch (7th generation)", true):
            return -20
        case ("iPod touch (7th generation)", false):
            return -150
        case ("iPhone 12 mini", true):
            return -30
        case ("iPhone 12 mini", false):
            return -90
        case ("iPhone 13 mini", true):
            return 0
        case ("iPhone 13 mini", false):
            return -120
        case ("iPhone 11 Pro Max", true), ("iPhone 12 Pro Max", true), ("iPhone 13 Pro Max", true):
            return -35
        case ("iPhone 11 Pro Max", false), ("iPhone 12 Pro Max", false), ("iPhone 13 Pro Max", false):
            return -15
        default:
            return -35
        }
    }

    var dialogueWidth: Double {
        switch UIDevice.current.name {
        case "iPhone 6s", "iPhone 6s Plus", "iPhone 7", "iPhone 8", "iPhone SE (1st generation)", "iPhone SE (2nd generation)", "iPhone SE (3rd generation)", "iPod touch (7th generation)":
            return 0.8
        default:
            return 0.6
        }
    }

    @Environment(\.colorScheme) var colorScheme

    @StateObject var core = Core()

    @FocusState private var answerIsFocused: Bool

    var body: some View {
        ZStack {
            Color.secondary.opacity(0.4).edgesIgnoringSafeArea(.all)
            VStack(spacing: 0) {
                Text(titleText)
                    .bold()
                    .lineLimit(1)
                    .padding(.horizontal)
                    .padding(.top)
                TextField("", text: $nativeThing)
                    .modifier(TextFieldClearButton2(text: $nativeThing))
                    .placeholder(when: nativeThing.isEmpty) {
                        Text("\(nativePlaceholderText)").foregroundColor(.gray)
                    }
                    .onReceive(Just(nativeThing)) { nativeThing in
                        if self.nativeThing.count < 40 && self.foreignThing.count < 40 && !self.nativeThing.isEmpty && !self.foreignThing.isEmpty {
                            submitDisabled = false
                        } else {
                            submitDisabled = true
                        }
                        if self.nativeThing.count > 39 { nativeValidationError = true } else { nativeValidationError = false }
                    }
                    .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                    .padding(5)
                    .multilineTextAlignment(.center)
                    .overlay(RoundedRectangle(cornerRadius: 6).stroke(nativeValidationError ? Color.red : Color(UIColor.systemGray4), lineWidth: 1))
                    .font(.subheadline)
                    .padding(.horizontal, 15)
                    .padding(.bottom)
                    .padding(.top)
                    .focused($answerIsFocused)
                    .onAppear {
                        // key part: delay setting isFocused until after some-internal-iOS setup
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            answerIsFocused = true
                        }
                    }

                    Button(action: {
                        doAutoTranslate()
                    }) {
                        Text("Instant Translation")
                            .foregroundColor(Color(UIColor.systemBlue))
                            .cornerRadius(40)
                            .frame(minWidth: 0, maxWidth: .infinity)
                            .font(.system(size: 15))
                    }
                    .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                    .padding(5)
                    .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(UIColor.systemBlue), lineWidth: 1))
                    .padding(.horizontal, 15)
                    .padding(.bottom)

                    Toggle("", isOn: $transliteration)
                        .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                        .toggleStyle(CustomToggleStyle())
                        .onChange(of: transliteration, perform: { value in
                            core.setTransliteration(set: transliteration)
                            if transliteration {
                                keyboardLanguage = Locale.current.languageCode!
                            } else { keyboardLanguage = changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name ?? "") }
                            print("toggle keyboard language: \(keyboardLanguage)")
                        })
                    .padding(5)
                    .overlay(RoundedRectangle(cornerRadius: 6).stroke(lineWidth: 1).foregroundColor(transliteration ? Color(UIColor.systemGreen) : Color(UIColor.lightGray)))
                    .padding(.bottom)

                UITextFieldViewRepresentable(foreignThing: $foreignThing, placeholder: foreignPlaceholderText, language: keyboardLanguage)
                    .modifier(TextFieldClearButton2(text: $foreignThing))
//                    .placeholder(when: foreignThing.isEmpty) {
//                        Text("\(foreignPlaceholderText)").foregroundColor(.gray)
//                    }
                    .onReceive(Just(foreignThing)) { foreignThing in

                        if self.nativeThing.count < 40 && self.foreignThing.count < 40 && !self.nativeThing.isEmpty && !self.foreignThing.isEmpty {
                            submitDisabled = false
                        } else { submitDisabled = true }
                        if self.foreignThing.count > 39 { foreignValidationError = true } else { foreignValidationError = false }
                    }
                    .frame(width: screenSize.width * 0.7, height: 20, alignment: .center)
                    .padding(5)
                    .multilineTextAlignment(.center)
                    .overlay(
                        RoundedRectangle(cornerRadius: 6)
                            .stroke(foreignValidationError ? Color.red : Color(UIColor.systemGray4), lineWidth: 1)
                    )
                    .font(.subheadline)
                    .padding(.horizontal, 15)
                    .padding(.bottom)
                Divider()
                HStack(spacing: 0) {
                    HStack {
                        Spacer()
                        Button(action: {
                            self.showingModal.toggle()
                            answerIsFocused = false
                        }) { Text("Cancel") }
                        Spacer()
                    }
                    Divider()
                    HStack {
                        Spacer()
                        Button(action: {
                            self.returnTextFieldInput()
                            answerIsFocused = false
                        }) { Text("Submit") }
                        .disabled(submitDisabled)
                        Spacer()
                    }
                }.frame(height: 50)
            }
            .background(colorScheme == .light ?  Color.white : Color.black)
            .clipShape(RoundedRectangle(cornerRadius: 15))
            .frame(width: screenSize.width * dialogueWidth, height: 500, alignment: .center)
            .scaleEffect(scale)
            .padding()
            .onAppear {
                initialize()
                withAnimation(.interpolatingSpring(mass: 0.1, stiffness: 100, damping: 10, initialVelocity: 50)) { self.scale = 1 }
            }
            .offset(CGSize(width: 0, height: self.yOffset))
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification)) { _ in
            withAnimation { self.yOffset = yOffsetDevice }
        }
    }

    func initialize() {
        self.transliteration = core.transliteration()
        if transliteration {
            keyboardLanguage = Locale.current.languageCode!
        } else { keyboardLanguage = changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name ?? "") }
        print("initialize keyboard language: \(keyboardLanguage)")
    }

    func returnTextFieldInput() {
        self.action(nativeThing, foreignThing)
        self.showingModal.toggle()
    }

    func doAutoTranslate() {
        SwiftGoogleTranslate.shared.start(with: "AIzaSyAhqjSritgMQFqOiVxSMNfJjDp58hDKdQM")
        let languageLocale = Locale.current.languageCode?.components(separatedBy: "-").first ?? "en"
        let foreignLanguageCode = changeKeyboard.currentKeyboardLanguage(currentLanguage: language.name!).components(separatedBy: "-").first ?? "en"
        if nativeThing.count > 0 {
            SwiftGoogleTranslate.shared.translate(nativeThing, foreignLanguageCode, languageLocale) { (text, error) in
                if let _ = text {
                    self.foreignThing = text!
                }
            }
        } else if foreignThing.count > 0 {
            SwiftGoogleTranslate.shared.translate(foreignThing, languageLocale, foreignLanguageCode) { (text, error) in
                if let _ = text {
                    self.nativeThing = text!
                }
            }
        }
    }
}

struct UITextFieldViewRepresentable: UIViewRepresentable {

    @Binding var foreignThing: String

    let placeholder: String
    let placeholderColor: UIColor
    let language: String

    init(foreignThing: Binding<String>, placeholder: String, placeholderColor: UIColor = .gray, language: String) {
        self._foreignThing = foreignThing
        self.placeholder = placeholder
        self.placeholderColor = placeholderColor
        self.language = language
    }

    func makeUIView(context: Context) -> UITextField {

        let textField = getTextField()
        textField.delegate = context.coordinator

        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = foreignThing
    }

    private func getTextField() -> UITextField {

        let textField = WordTextField(frame: .zero)
        textField.language = self.language
        let placeholder = NSAttributedString(
            string: placeholder,
            attributes: [
                .foregroundColor: placeholderColor
            ])
        textField.attributedPlaceholder = placeholder
        return textField
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(foreignThing: $foreignThing)
    }

    class Coordinator: NSObject, UITextFieldDelegate {

        @Binding var foreignThing: String

        init(foreignThing: Binding<String>) {
            self._foreignThing = foreignThing
        }
        func textFieldDidChangeSelection(_ textField: UITextField) {
            foreignThing = textField.text ?? ""
        }
    }

    class WordTextField: UITextField {

        var language: String? {
            didSet {
                if self.isFirstResponder{
                    self.resignFirstResponder()
                    self.becomeFirstResponder()
                }
            }
        }

        override var textInputMode: UITextInputMode? {
            if let language = self.language {
                print("text input mode: \(language)")
                for inputMode in UITextInputMode.activeInputModes {
                    if let inputModeLanguage = inputMode.primaryLanguage, inputModeLanguage == language {
                        return inputMode
                    }
                }
            }
            return super.textInputMode
        }
    }
}


问:
Dynamically load (web component) custom elements into Blazor app
We have some nice JavaScript web components developed with custom elements so from HTML we can write e.g.

```<code><my-custom-element></my-custom-element>
</code>```

These have been wrapped into Blazor control components in a Razor Class Library.
I can use these in Blazor app if I load the web component's JS in the containing Blazor app's index.html, e.g.

```<code><script src="_content/MyRazorClassLibrary/components/my-custom-element.js"></script>
</code>```

Then I can reference the Blazor control wrappers in my Blazor app, e.g.

```<code><MyCustomElement></MyCustomElement>
</code>```

Lovely. However, I don’t want to load every component's JS in my Blazor app on start-up.  Instead I’d like to load them dynamically if and when they are needed.

Is it possible to update Blazor’s HTML parser with new custom element information after Blazor is loaded - perhaps using JavaScript Isolation to import via ES6 modules or some other way?

It seems that this is actually not possible and that I really have only two options:

Load all JS in index.html (even though they might not be needed)

Use JavaScript isolation to construct the the web components from a div via a JavaScript function call on the isolated module (and not use HTML custom elements).

Body:
We have some nice JavaScript web components developed with custom elements so from HTML we can write e.g.

<my-custom-element></my-custom-element>

These have been wrapped into Blazor control components in a Razor Class Library.
I can use these in Blazor app if I load the web component's JS in the containing Blazor app's index.html, e.g.

Then I can reference the Blazor control wrappers in my Blazor app, e.g.

<MyCustomElement></MyCustomElement>

Lovely. However, I don’t want to load every component's JS in my Blazor app on start-up.  Instead I’d like to load them dynamically if and when they are needed.

Is it possible to update Blazor’s HTML parser with new custom element information after Blazor is loaded - perhaps using JavaScript Isolation to import via ES6 modules or some other way?

It seems that this is actually not possible and that I really have only two options:

Load all JS in index.html (even though they might not be needed)

Use JavaScript isolation to construct the the web components from a div via a JavaScript function call on the isolated module (and not use HTML custom elements).


问:
In scala3/dotty. Why is it impossible to mix in a type definition with constraint?
In some cases it make sense to reuse a type constraint in both refinement and definition. E.g. the following definitions for Thing1 & Thing2 should be extensionally equivalent:

object TypeMixin {

  trait Thing {

    type TT
  }

  type ThingAux[T] = Thing { type TT = T }

  object Thing1 extends Thing {
    type TT = Int
  }

  object Thing2 extends Thing with ThingAux[Int]
}

```
<p><code>Thing2</code> has less boilerplate, but won't be compiled properly:</p>
```TypeMixin.scala:16:36: com.tribbloids.spike.dotty.TypeMixin.Thing{TT = Int} is not a class type
one error found
```

My question is: what's the repercussion of allowing the type system to resolve Thing2? What's the counter-example for which this syntax will causes some unsound definition?

Body:
In some cases it make sense to reuse a type constraint in both refinement and definition. E.g. the following definitions for Thing1 & Thing2 should be extensionally equivalent:

object TypeMixin {

  trait Thing {

    type TT
  }

  type ThingAux[T] = Thing { type TT = T }

  object Thing1 extends Thing {
    type TT = Int
  }

  object Thing2 extends Thing with ThingAux[Int]
}

Thing2 has less boilerplate, but won't be compiled properly:

TypeMixin.scala:16:36: com.tribbloids.spike.dotty.TypeMixin.Thing{TT = Int} is not a class type
one error found

My question is: what's the repercussion of allowing the type system to resolve Thing2? What's the counter-example for which this syntax will causes some unsound definition?


问:
How to create a theme in material ui v5 and import it, including classes?
I have been struggling with this problem all day, and i seriously have no idea how to fix it. Its about material ui5.

I have been following a tutorial that uses v4 and its syntax is different, so i have been trying to change it to material ui version 5 but it has been an impossible job.

Below you can find the code that i currently have, as you can see it has the theme object inside the header component, which i don't want. I want to be able to import it and use it. As you can also see theme const changes the default options from the theme object in uiv5. Also, the return in the components header uses classes. Which point to the theme const. So how can i import it, and use the styles exactly as they are laid out? I only want to be able to use those styles in the header component no matter how.

```<code>> import React from 'react';
> import {Autocomplete} from '@react-google-maps/api';
> import { AppBar, Toolbar, Typography, InputBase, Box} from '@mui/material'
> import SearchIcon from '@mui/icons-material/Search'
> import { ThemeProvider, useTheme, createTheme, alpha } from '@mui/material/styles';
>
> const Header = () => {
>
>     const classes = useTheme();
>
>     const theme = createTheme({
>         title: {
>           display: 'none',
>           [theme.breakpoints.up('sm')]: {
>             display: 'block',
>           },
>         },
>         search: {
>           position: 'relative',
>           borderRadius: theme.shape.borderRadius,
>           backgroundColor: alpha(theme.palette.common.white, 0.15),
>           '&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.25) },
>           marginRight: theme.spacing(2),
>           marginLeft: 0,
>           width: '100%',
>           [theme.breakpoints.up('sm')]: { marginLeft: theme.spacing(3), width: 'auto' },
>         },
>         searchIcon: {
>           padding: theme.spacing(0, 2), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
>         },
>         inputRoot: {
>           color: 'inherit',
>         },
>         inputInput: {
>           padding: theme.spacing(1, 1, 1, 0), paddingLeft: `calc(1em + ${theme.spacing(4)}px)`, transition: theme.transitions.create('width'), width: '100%', [theme.breakpoints.up('md')]: { width: '20ch' },
>         },
>         toolbar: {
>           display: 'flex', justifyContent: 'space-between',
>         },
>       })
>
>
>
>     return (
>
>         <ThemeProvider theme={theme}>
>         <AppBar position='static'>
>             <Toolbar className={classes.toolbar}>
>                 <Typography variant = 'h5' className={classes.title}>
>                      Travel Advisor
>                 </Typography>
>                 <Box display = 'flex'>
>                 <Typography variant = 'h6' className={classes.title}>
>                      Explore new places
>                 </Typography>
>                 {/*<Autocomplete>*/}
>                     <div className={classes.search}>
>                        <div className={classes.searchIcon}>
>                        <SearchIcon />
>                        </div>
>                     </div>
>                 {/*<Autocomplete>*/}
>                 </Box>
>             </Toolbar>
>         </AppBar>
>         </ThemeProvider >
>     )
>
> }
>
>
>
> export default Header
> ```
```
```
>                        <InputBase placeholder="Search..." classes={{root: classes.inputRoot, input: classes.inputInput}}/>
```

Body:
I have been struggling with this problem all day, and i seriously have no idea how to fix it. Its about material ui5.

I have been following a tutorial that uses v4 and its syntax is different, so i have been trying to change it to material ui version 5 but it has been an impossible job.

Below you can find the code that i currently have, as you can see it has the theme object inside the header component, which i don't want. I want to be able to import it and use it. As you can also see theme const changes the default options from the theme object in uiv5. Also, the return in the components header uses classes. Which point to the theme const. So how can i import it, and use the styles exactly as they are laid out? I only want to be able to use those styles in the header component no matter how.

> import React from 'react';
> import {Autocomplete} from '@react-google-maps/api';
> import { AppBar, Toolbar, Typography, InputBase, Box} from '@mui/material'
> import SearchIcon from '@mui/icons-material/Search'
> import { ThemeProvider, useTheme, createTheme, alpha } from '@mui/material/styles';
>
> const Header = () => {
>
>     const classes = useTheme();
>
>     const theme = createTheme({
>         title: {
>           display: 'none',
>           [theme.breakpoints.up('sm')]: {
>             display: 'block',
>           },
>         },
>         search: {
>           position: 'relative',
>           borderRadius: theme.shape.borderRadius,
>           backgroundColor: alpha(theme.palette.common.white, 0.15),
>           '&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.25) },
>           marginRight: theme.spacing(2),
>           marginLeft: 0,
>           width: '100%',
>           [theme.breakpoints.up('sm')]: { marginLeft: theme.spacing(3), width: 'auto' },
>         },
>         searchIcon: {
>           padding: theme.spacing(0, 2), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
>         },
>         inputRoot: {
>           color: 'inherit',
>         },
>         inputInput: {
>           padding: theme.spacing(1, 1, 1, 0), paddingLeft: `calc(1em + ${theme.spacing(4)}px)`, transition: theme.transitions.create('width'), width: '100%', [theme.breakpoints.up('md')]: { width: '20ch' },
>         },
>         toolbar: {
>           display: 'flex', justifyContent: 'space-between',
>         },
>       })
>
>
>
>     return (
>
>         <ThemeProvider theme={theme}>
>         <AppBar position='static'>
>             <Toolbar className={classes.toolbar}>
>                 <Typography variant = 'h5' className={classes.title}>
>                      Travel Advisor
>                 </Typography>
>                 <Box display = 'flex'>
>                 <Typography variant = 'h6' className={classes.title}>
>                      Explore new places
>                 </Typography>
>                 {/*<Autocomplete>*/}
>

>

>                        <SearchIcon />
>

>

>                 {/*<Autocomplete>*/}
>                 </Box>
>             </Toolbar>
>         </AppBar>
>         </ThemeProvider >
>     )
>
> }
>
>
>
> export default Header
> ```

>                        <InputBase placeholder="Search..." classes={{root: classes.inputRoot, input: classes.inputInput}}/>


问:
How to use Buy Stop Entries with the 'After Order is Filled' strategy parameter?
My strategy uses Buy Stops to enter a position, whereby it waits for a price target to be reached mid candle before taking an entry.

The strategy also has the "After Order is Filled" parameter set to True, which allows the position to be Exited on the same candle that it Enters, if the Take Profit target is reached.

I've found that for scenarios where the Entry and Exit are on the same candle, the position is ALWAYS Exited at either the High or the Low, and not the actual Take Profit target price. This occurs for ALL candles with this scenario, which is throwing off back test results.

Without using Buy Stops this works perfectly as expected as the position will be exited at the exact TP target price.

Hoping someone can identify why this is occurring only for entry's with Buy Stop? Is this a TV bug?

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bravo_One

//@version=5
strategy("Buy Stop Bug", overlay=true, calc_on_order_fills = true, process_orders_on_close = false, pyramiding = 1, initial_capital = 10000, commission_type = strategy.commission.percent, commission_value = 0.2, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, max_bars_back = 5000)

// >>>> Inputs
rrValue = input.float(0.5, "Risk Reward Multi", group = "Risk Management")
lookbackPeriod = input.int(21, "Lookback period for recent lows/ highs", group = "Risk Management")
//--------

// >>>> Entry / Exit / Close Indicators
ema1 = ta.ema(close, 5)
ema2 = ta.ema(close, 8)
//--------

// >>>> Entry Conditions
longEntry = ema1 > ema2
shortEntry = ema1 < ema2
//--------

// >>>> Position Entry
buyStop = ta.highest(high, 5)
sellStop = ta.lowest(low, 5)

if longEntry and ((strategy.closedtrades == 0) or (bar_index != strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1)))
    strategy.entry("Long Entry", strategy.long, stop = buyStop) // REMOVE BUY STOP --> TP target is hit correctly without a Buy Stop.

if shortEntry and ((strategy.closedtrades == 0) or (bar_index != strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1)))
    strategy.entry("Short Entry", strategy.short, stop = sellStop) // REMOVE BUY STOP --> TP target is hit correctly without a Buy Stop.
//--------

// >>>> TPSL Functions
barsSinceLastEntry() =>
    strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
barsSinceLastEntry = na(barsSinceLastEntry()) ? 0 : barsSinceLastEntry()
//--------

// >>>> Double Candle Above and Below (safeguard incase recent low is higher than entry price, or recent high is lower than entry price)
c2lw2x = math.abs(close - open) * 2
doubleCandleBelow = strategy.position_avg_price - c2lw2x[barsSinceLastEntry + 1]
doubleCandleAbove = strategy.position_avg_price + c2lw2x[barsSinceLastEntry + 1]
//--------

// >>>> Determine TPSL
recentLow = ta.lowest(low, lookbackPeriod)
recentHigh = ta.highest(high, lookbackPeriod)

longStopX = recentLow[barsSinceLastEntry + 1] <= strategy.position_avg_price ? recentLow[barsSinceLastEntry + 1] : doubleCandleBelow
longProfitX = strategy.position_avg_price + (math.abs(strategy.position_avg_price - longStopX) * rrValue)
shortStopX = recentHigh[barsSinceLastEntry + 1] >= strategy.position_avg_price ? recentHigh[barsSinceLastEntry + 1] : doubleCandleAbove
shortProfitX = strategy.position_avg_price - (math.abs(strategy.position_avg_price - shortStopX) * rrValue)
//--------

// >>>> Exit Comments
tradeNum = strategy.closedtrades - 1
lph = "Long TP Hit " + "(#" + str.tostring(tradeNum) + ") "
lsh = "Long SL Hit " + "(#" + str.tostring(tradeNum) + ") "
sph = "Short TP Hit " + "(#" + str.tostring(tradeNum) + ") "
ssh = "Short SL Hit " + "(#" + str.tostring(tradeNum) + ") "
//--------

// >>>> Exit Position
if strategy.position_size > 0
    strategy.exit("Long Exit", "Long Entry", limit = longProfitX, stop = longStopX, comment_profit = lph, comment_loss = lsh)
if strategy.position_size < 0
    strategy.exit("Short Exit", "Short Entry", limit = shortProfitX, stop = shortStopX, comment_profit = sph, comment_loss = ssh)
//--------

// >>>> Buy Stop Position Cancellation
if close < ema1 and close < ema2
    strategy.cancel("Long Entry")
if close > ema1 and close > ema2
    strategy.cancel("Short Entry")
//--------

//======================================//
//        Plots and Data Window
//======================================//

// >>>> Indicator Plots
plot(ema1, color=color.aqua)
plot(ema2, color=color.aqua)

// >>>> Data Window Variables
plot(longStopX, "long stop x", display = display.data_window, color = color.lime)
plot(shortStopX, "short Stop x", display = display.data_window, color = color.red)
plot(longProfitX, "long profit x", display = display.data_window, color = color.lime)
plot(shortProfitX, "short profit x", display = display.data_window, color = color.red)

// >>>> TPSL Plots
plot(strategy.position_size > 0 ? longProfitX : na, color=color.green, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size > 0 ? longStopX : na, color=color.red, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size < 0 ? shortProfitX : na, color=color.green, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size < 0 ? shortStopX : na, color=color.red, style=plot.style_linebr, linewidth=2)
</code>```

Body:
My strategy uses Buy Stops to enter a position, whereby it waits for a price target to be reached mid candle before taking an entry.

The strategy also has the "After Order is Filled" parameter set to True, which allows the position to be Exited on the same candle that it Enters, if the Take Profit target is reached.

I've found that for scenarios where the Entry and Exit are on the same candle, the position is ALWAYS Exited at either the High or the Low, and not the actual Take Profit target price. This occurs for ALL candles with this scenario, which is throwing off back test results.

Without using Buy Stops this works perfectly as expected as the position will be exited at the exact TP target price.

Hoping someone can identify why this is occurring only for entry's with Buy Stop? Is this a TV bug?

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bravo_One

//@version=5
strategy("Buy Stop Bug", overlay=true, calc_on_order_fills = true, process_orders_on_close = false, pyramiding = 1, initial_capital = 10000, commission_type = strategy.commission.percent, commission_value = 0.2, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, max_bars_back = 5000)

// >>>> Inputs
rrValue = input.float(0.5, "Risk Reward Multi", group = "Risk Management")
lookbackPeriod = input.int(21, "Lookback period for recent lows/ highs", group = "Risk Management")
//--------

// >>>> Entry / Exit / Close Indicators
ema1 = ta.ema(close, 5)
ema2 = ta.ema(close, 8)
//--------

// >>>> Entry Conditions
longEntry = ema1 > ema2
shortEntry = ema1 < ema2
//--------

// >>>> Position Entry
buyStop = ta.highest(high, 5)
sellStop = ta.lowest(low, 5)

if longEntry and ((strategy.closedtrades == 0) or (bar_index != strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1)))
    strategy.entry("Long Entry", strategy.long, stop = buyStop) // REMOVE BUY STOP --> TP target is hit correctly without a Buy Stop.

if shortEntry and ((strategy.closedtrades == 0) or (bar_index != strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1)))
    strategy.entry("Short Entry", strategy.short, stop = sellStop) // REMOVE BUY STOP --> TP target is hit correctly without a Buy Stop.
//--------

// >>>> TPSL Functions
barsSinceLastEntry() =>
    strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
barsSinceLastEntry = na(barsSinceLastEntry()) ? 0 : barsSinceLastEntry()
//--------

// >>>> Double Candle Above and Below (safeguard incase recent low is higher than entry price, or recent high is lower than entry price)
c2lw2x = math.abs(close - open) * 2
doubleCandleBelow = strategy.position_avg_price - c2lw2x[barsSinceLastEntry + 1]
doubleCandleAbove = strategy.position_avg_price + c2lw2x[barsSinceLastEntry + 1]
//--------

// >>>> Determine TPSL
recentLow = ta.lowest(low, lookbackPeriod)
recentHigh = ta.highest(high, lookbackPeriod)

longStopX = recentLow[barsSinceLastEntry + 1] <= strategy.position_avg_price ? recentLow[barsSinceLastEntry + 1] : doubleCandleBelow
longProfitX = strategy.position_avg_price + (math.abs(strategy.position_avg_price - longStopX) * rrValue)
shortStopX = recentHigh[barsSinceLastEntry + 1] >= strategy.position_avg_price ? recentHigh[barsSinceLastEntry + 1] : doubleCandleAbove
shortProfitX = strategy.position_avg_price - (math.abs(strategy.position_avg_price - shortStopX) * rrValue)
//--------

// >>>> Exit Comments
tradeNum = strategy.closedtrades - 1
lph = "Long TP Hit " + "(#" + str.tostring(tradeNum) + ") "
lsh = "Long SL Hit " + "(#" + str.tostring(tradeNum) + ") "
sph = "Short TP Hit " + "(#" + str.tostring(tradeNum) + ") "
ssh = "Short SL Hit " + "(#" + str.tostring(tradeNum) + ") "
//--------

// >>>> Exit Position
if strategy.position_size > 0
    strategy.exit("Long Exit", "Long Entry", limit = longProfitX, stop = longStopX, comment_profit = lph, comment_loss = lsh)
if strategy.position_size < 0
    strategy.exit("Short Exit", "Short Entry", limit = shortProfitX, stop = shortStopX, comment_profit = sph, comment_loss = ssh)
//--------

// >>>> Buy Stop Position Cancellation
if close < ema1 and close < ema2
    strategy.cancel("Long Entry")
if close > ema1 and close > ema2
    strategy.cancel("Short Entry")
//--------

//======================================//
//        Plots and Data Window
//======================================//

// >>>> Indicator Plots
plot(ema1, color=color.aqua)
plot(ema2, color=color.aqua)

// >>>> Data Window Variables
plot(longStopX, "long stop x", display = display.data_window, color = color.lime)
plot(shortStopX, "short Stop x", display = display.data_window, color = color.red)
plot(longProfitX, "long profit x", display = display.data_window, color = color.lime)
plot(shortProfitX, "short profit x", display = display.data_window, color = color.red)

// >>>> TPSL Plots
plot(strategy.position_size > 0 ? longProfitX : na, color=color.green, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size > 0 ? longStopX : na, color=color.red, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size < 0 ? shortProfitX : na, color=color.green, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size < 0 ? shortStopX : na, color=color.red, style=plot.style_linebr, linewidth=2)


问:
How to AWS EMR Cluster Id based on the cluster name?
Is there way I can get AWS EMR Cluster ID by Providing Clusrer Name Programatically by Java SDK?</p>


问:
Expose native addon from electron backend to renderer process
I have a native node addon which I will use in my Electron application. I can load the addon in my backend process and expose dedicated function to the main world with :

```<code>const addon = require('bindings')('myAddon');
contextBridge.exposeInMainWorld('test', {
  methodA: () => addon.methodA,
  methodB: () => addon.methodB,
})
</code>```

and then call the methods in the Electron renderer process:

```<code>{ test.methodA() }
{ test.methodB() }
</code>```

Now the addon has many methods exported. Is there an option to automatically expose all object methods to the main world ? Somehow loop over the method names and expose them wit the same name. I already found the method bellow to get all method names. But have no glue how to programaticaly map them in the exposeInMainWold method...

```<code>const getMethods = (obj) => {
  let properties = new Set()
  let currentObj = obj
  do {
    Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
  } while ((currentObj = Object.getPrototypeOf(currentObj)))
  return [...properties.keys()].filter(item => typeof obj[item] === 'function')
}
</code>```

Or alternatively, is there an option to load the addon directly in the renderer process?

Body:
I have a native node addon which I will use in my Electron application. I can load the addon in my backend process and expose dedicated function to the main world with :

const addon = require('bindings')('myAddon');
contextBridge.exposeInMainWorld('test', {
  methodA: () => addon.methodA,
  methodB: () => addon.methodB,
})

and then call the methods in the Electron renderer process:

{ test.methodA() }
{ test.methodB() }

Now the addon has many methods exported. Is there an option to automatically expose all object methods to the main world ? Somehow loop over the method names and expose them wit the same name. I already found the method bellow to get all method names. But have no glue how to programaticaly map them in the exposeInMainWold method...

const getMethods = (obj) => {
  let properties = new Set()
  let currentObj = obj
  do {
    Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
  } while ((currentObj = Object.getPrototypeOf(currentObj)))
  return [...properties.keys()].filter(item => typeof obj[item] === 'function')
}

Or alternatively, is there an option to load the addon directly in the renderer process?


问:
Stripe checkout only working on localhost?
I want to create a Checkout Session using the client and server integration from stripe, to sell my products but I have no experience in backends.

So, I followed these instructions: https://stripe.com/docs/checkout/quickstart?lang=node%3Fcanceled%3Dtrue

I downloaded the files, added the missing keys and I set up the server using node ($node server.js) and searched for "localhost:4242" in my browser, clicked the "Checkout" button and a checkout session was created effortlessly.
->Screenshot of files

Now, I thought I simply had to copy these files into my web hosting but obviously, that is not the case since no checkout session is being created no more...

How can I integrate the server checkout on my website?