问:
Audio not playing in react-native expo app
I used these docs to make a mp3 player, it does not show any errors but it does not play any sound either this is my complete code with screen shot of the directories.

```<code>                          import { StatusBar } from 'expo-status-bar';
                      import React from 'react';
                      import { SafeAreaView, StyleSheet, Text, View, ScrollView, Button
                       } from 'react-native';
                      import { MainLogo } from '../../logos/mainLogo';
                      import { TextInput } from "react-native";
                      import { Audio } from 'expo-av';

                      export function Home() {

                        const [sound, setSound] = React.useState();

                        async function playSound() {
                          console.log('Loading Sound');
                          const { sound } = await Audio.Sound.createAsync(
                           require('../../assets/music2.mp3')
                          );
                          setSound(sound);

                          console.log('Playing Sound');
                          await sound.playAsync();
                        }

                        React.useEffect(() => {
                          return sound
                            ? () => {
                                console.log('Unloading Sound');
                                sound.unloadAsync();
                              }
                            : undefined;
                        }, [sound]);

                        return (
                          <SafeAreaView>

                              <View style={styles.firstBackGround}>
                                <MainLogo/>
                                <Text style=
                               {{fontSize:25,fontWeight:'bold',color:'rgb(108, 150,
                              232)',}}>Music Player</Text>
                              </View>
                              <TextInput placeholder='Search Song or Artist' style=
                               {styles.secondBackGround} placeholderTextColor="#6b7eb1"
                               ></TextInput>
                              <Text style={styles.recommendedText}>Recommended</Text>
                              <ScrollView horizontal={true} style=
                                  {{marginTop:17,height:100}}
                                  showsHorizontalScrollIndicator={false}>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                              </ScrollView>
                              <Text style={styles.listenAgainText}>Listen Again</Text>
                              <ScrollView horizontal={true} style=
                                {{marginTop:17,height:100}}
                                 showsHorizontalScrollIndicator={false}>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                              </ScrollView>
                              <Text style={styles.listenAgainText}>Famous Artists</Text>
                              <View style={styles.famousArtist}></View>
                              <View style={styles.famousArtist1}></View>
                              <View style={styles.famousArtist1}></View>
                              <View style={styles.container}>
                                <Button title="Play Sound" onPress={playSound} />
                              </View>
                          </SafeAreaView>
                        );
                      }

                      const styles = StyleSheet.create(
                        {

                        container: {

                        },
                        firstBackGround: {
                          flexDirection:'row',
                          alignItems:'center',
                        },
                        secondBackGround:{
                          backgroundColor: '#3f4d7e',
                          width:275,
                          marginTop:15,
                          height:40,
                          borderRadius:20,
                          marginLeft:'auto',
                          marginRight:'auto',
                          paddingLeft: 20,
                        },
                        recommendedText:{
                          fontSize:17,
                          flexDirection:'row',
                          fontWeight:'bold',
                          color:'rgb(108, 150, 232)',
                          marginLeft:20,
                          marginTop:25,
                        },
                        recommendedBox:{
                          backgroundColor:'#3f4d7e',
                          height:85,
                          width:85,
                          marginLeft:15,
                          marginRight:3,
                          borderRadius:15,
                        },
                        listenAgainText:{
                          fontSize:17,
                          flexDirection:'row',
                          fontWeight:'bold',
                          color:'rgb(108, 150, 232)',
                          marginLeft:20,
                        },
                        famousArtist:{
                          width:285,
                          borderRadius:25,
                          marginLeft:'auto',
                          marginRight:'auto',
                          height:25,
                          backgroundColor:'#3f4d7e',
                          marginTop:13,
                        },
                        famousArtist1:{
                          width:285,
                          borderRadius:25,
                          marginLeft:'auto',
                          marginRight:'auto',
                          height:25,
                          backgroundColor:'#3f4d7e',
                          marginTop:8,
                        },
                      });
</code>```

Here is the screen shot so you can view the directories:

I have seen multiple questions related to this but most of them have not been answered and which have been answered are the ones with android or ios.

Body:
I used these docs to make a mp3 player, it does not show any errors but it does not play any sound either this is my complete code with screen shot of the directories.

                          import { StatusBar } from 'expo-status-bar';
                      import React from 'react';
                      import { SafeAreaView, StyleSheet, Text, View, ScrollView, Button
                       } from 'react-native';
                      import { MainLogo } from '../../logos/mainLogo';
                      import { TextInput } from "react-native";
                      import { Audio } from 'expo-av';

                      export function Home() {

                        const [sound, setSound] = React.useState();

                        async function playSound() {
                          console.log('Loading Sound');
                          const { sound } = await Audio.Sound.createAsync(
                           require('../../assets/music2.mp3')
                          );
                          setSound(sound);

                          console.log('Playing Sound');
                          await sound.playAsync();
                        }

                        React.useEffect(() => {
                          return sound
                            ? () => {
                                console.log('Unloading Sound');
                                sound.unloadAsync();
                              }
                            : undefined;
                        }, [sound]);

                        return (
                          <SafeAreaView>

                              <View style={styles.firstBackGround}>
                                <MainLogo/>
                                <Text style=
                               {{fontSize:25,fontWeight:'bold',color:'rgb(108, 150,
                              232)',}}>Music Player</Text>
                              </View>
                              <TextInput placeholder='Search Song or Artist' style=
                               {styles.secondBackGround} placeholderTextColor="#6b7eb1"
                               ></TextInput>
                              <Text style={styles.recommendedText}>Recommended</Text>
                              <ScrollView horizontal={true} style=
                                  {{marginTop:17,height:100}}
                                  showsHorizontalScrollIndicator={false}>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                              </ScrollView>
                              <Text style={styles.listenAgainText}>Listen Again</Text>
                              <ScrollView horizontal={true} style=
                                {{marginTop:17,height:100}}
                                 showsHorizontalScrollIndicator={false}>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                                <View style={styles.recommendedBox}></View>
                              </ScrollView>
                              <Text style={styles.listenAgainText}>Famous Artists</Text>
                              <View style={styles.famousArtist}></View>
                              <View style={styles.famousArtist1}></View>
                              <View style={styles.famousArtist1}></View>
                              <View style={styles.container}>
                                <Button title="Play Sound" onPress={playSound} />
                              </View>
                          </SafeAreaView>
                        );
                      }

                      const styles = StyleSheet.create(
                        {

                        container: {

                        },
                        firstBackGround: {
                          flexDirection:'row',
                          alignItems:'center',
                        },
                        secondBackGround:{
                          backgroundColor: '#3f4d7e',
                          width:275,
                          marginTop:15,
                          height:40,
                          borderRadius:20,
                          marginLeft:'auto',
                          marginRight:'auto',
                          paddingLeft: 20,
                        },
                        recommendedText:{
                          fontSize:17,
                          flexDirection:'row',
                          fontWeight:'bold',
                          color:'rgb(108, 150, 232)',
                          marginLeft:20,
                          marginTop:25,
                        },
                        recommendedBox:{
                          backgroundColor:'#3f4d7e',
                          height:85,
                          width:85,
                          marginLeft:15,
                          marginRight:3,
                          borderRadius:15,
                        },
                        listenAgainText:{
                          fontSize:17,
                          flexDirection:'row',
                          fontWeight:'bold',
                          color:'rgb(108, 150, 232)',
                          marginLeft:20,
                        },
                        famousArtist:{
                          width:285,
                          borderRadius:25,
                          marginLeft:'auto',
                          marginRight:'auto',
                          height:25,
                          backgroundColor:'#3f4d7e',
                          marginTop:13,
                        },
                        famousArtist1:{
                          width:285,
                          borderRadius:25,
                          marginLeft:'auto',
                          marginRight:'auto',
                          height:25,
                          backgroundColor:'#3f4d7e',
                          marginTop:8,
                        },
                      });

Here is the screen shot so you can view the directories:

I have seen multiple questions related to this but most of them have not been answered and which have been answered are the ones with android or ios.


来源: stackexchange

问:
How to wrap elements in Jetpack Compose's LazyRow?
I have a LazyRow with elements and I'm developing a button that changes layout of items from list to grid and vice-versa, so instead LazyRow's default behaviour it wraps overflowing elements to the next row below.

So far I've implemented it by using LazyRow and FlowRow components based on current state of list type. It looks something like this:

```<code>// When button is clicked it changes listType

when (listType)
   LIST -> {
    LazyRow()  {
      items() {
        // show elements
      }
    }

   GRID -> {
    FlowRow() {
      elements.forEach {
        // show elements
      }
    }
  }

</code>```

And it works, but there's awful transition due to reloading elements into new component when changing layout on button click. I've been searching for some answer, but I can't find anything. Is there a way to use only LazyRow and change it so it wraps elements or maybe you have some other idea?

Tried using FlowRow and LazyRow

ContentLicense: CC BY-SA 4.0

Body:
I have a LazyRow with elements and I'm developing a button that changes layout of items from list to grid and vice-versa, so instead LazyRow's default behaviour it wraps overflowing elements to the next row below.

So far I've implemented it by using LazyRow and FlowRow components based on current state of list type. It looks something like this:

// When button is clicked it changes listType

when (listType)
   LIST -> {
    LazyRow()  {
      items() {
        // show elements
      }
    }

   GRID -> {
    FlowRow() {
      elements.forEach {
        // show elements
      }
    }
  }

And it works, but there's awful transition due to reloading elements into new component when changing layout on button click. I've been searching for some answer, but I can't find anything. Is there a way to use only LazyRow and change it so it wraps elements or maybe you have some other idea?

Tried using FlowRow and LazyRow


问:
Promise {<pending>} PromiseState: fulfilled on useGLTF error
The GLB file is OK, the URL is OK, so why can't I load the GLB? The same code runs on another computer.

```<code>        console.log("path to GLB is:", url);//looks good.. click to download glb
        try {
            let glb = useGLTF(url);
            // @ts-ignore
            console.log("Loaded GLB:", glb.scene);
        } catch(error){
            console.log("Nope I won't load it hihi!", error);
        }
</code>```

Here the full code in the loop:

```<code>console.log(data);
data = JSON.parse(data);
data.forEach((p: any) => {
    console.log("path to GLB is:",p.meta_data[0].value);
    try {
        let glb = useGLTF(p.meta_data[0].value);
        // @ts-ignore
        console.log("Loaded GLB:", glb.scene);
        // @ts-ignore
        let obj = glb.scene.clone();
        let box = new Box3().setFromObject(obj);
        let size = new Vector3();
        box.getSize(size);
        var scaleVec = new Vector3(1, 1, 1).divide(size);
        let scale = Math.min(scaleVec.x, Math.min(scaleVec.y, scaleVec.z));
        obj.scale.setScalar(scale * 1);
        let model = { scene: obj, name: p.name};
        console.log("MODEL", model);
        setMappedModels((mappedModels: any) => [
            ...mappedModels,
            model,
        ]);
    } catch (error) {
        console.log("Error on GLB Load:", error);
    }
});
</code>```

Body:
The GLB file is OK, the URL is OK, so why can't I load the GLB? The same code runs on another computer.

        console.log("path to GLB is:", url);//looks good.. click to download glb
        try {
            let glb = useGLTF(url);
            // @ts-ignore
            console.log("Loaded GLB:", glb.scene);
        } catch(error){
            console.log("Nope I won't load it hihi!", error);
        }

Here the full code in the loop:

console.log(data);
data = JSON.parse(data);
data.forEach((p: any) => {
    console.log("path to GLB is:",p.meta_data[0].value);
    try {
        let glb = useGLTF(p.meta_data[0].value);
        // @ts-ignore
        console.log("Loaded GLB:", glb.scene);
        // @ts-ignore
        let obj = glb.scene.clone();
        let box = new Box3().setFromObject(obj);
        let size = new Vector3();
        box.getSize(size);
        var scaleVec = new Vector3(1, 1, 1).divide(size);
        let scale = Math.min(scaleVec.x, Math.min(scaleVec.y, scaleVec.z));
        obj.scale.setScalar(scale * 1);
        let model = { scene: obj, name: p.name};
        console.log("MODEL", model);
        setMappedModels((mappedModels: any) => [
            ...mappedModels,
            model,
        ]);
    } catch (error) {
        console.log("Error on GLB Load:", error);
    }
});


问:
block some routes in next js dynamic routing
If I have a route like this: pages/[id] and I want to enable just pages with id from 1 to 20 (for example: pages/17) and not allowed something outside this range (for example: pages/198), how to I do that?</p>


问:
Active Link styling in Next JS
Using the below className is not working since I've tried passing ${styles.active} through it. It works when I just used a global class name like 'active'. Have I got the wrong formatting?</p>
```<code><Link href='/' className={`${currentRoute}  === '/' ? ${styles.active} : ''`}> Overview </Link>

</code>```

Title: Active Link styling in Next JS

Body:
Using the below className is not working since I've tried passing ${styles.active} through it. It works when I just used a global class name like 'active'. Have I got the wrong formatting?

<Link href='/' className={`${currentRoute}  === '/' ? ${styles.active} : ''`}> Overview </Link>


问:
I have a large dataset with 2000000 records. Performed linear regression but r2_score value is just 19 percent . What can be done to improve score?
I have a dataset with 2 000 000 records. Performed linear regression but r2_score value is just 19 percent. Outliers have been removed as much as possible. I tried taking correlation, but none of the features have a good correlation with output.

link for my github

Please also let me know if this could be done in any other way.

Used SGD bt din yeild any better result, infact r2_score reduced to 17 percent.
I tried SVM but due to very large dataset it taking more than 5 hours. What can be done to improve the model? Any other alternate regression model that can be used for such large data set?


问:
Python Not Responding when I Run it
Python doesn't respond when I play it. No syntax error appears either. Not sure what is wrong. I tried running another game I made which worked fine so I don't think it's my computer. error message

This is my code:

import pygame
import math

# Inisialisasi pygame
pygame.init()

# Buat window pygame dengan ukuran 800x600
screen = pygame.display.set_mode((800, 600))
poly_color=(128,128,128)

while True:

    # Gambar garis putih pada radius 200, 300, 400, 500, dan 600
    for r in range(100,210,50):
        pygame.draw.circle(screen, (128, 128, 128), (400, 300), r, 1)

    # Gambar garis-garis merah pada sudut 0, 45, 90, 135, 180, 225, 270, dan 315 derajat
    for a in range(0,360,45):

        x = 400 + 200 * math.cos(math.radians(a)/0.5)
        y = 300 + 200 * math.sin(math.radians(a)/0.5)
        pygame.draw.line(screen, (128, 128, 128), (400, 300), (x, y), 1)

    for b in range(0,360,30):

        x = 400 + 200 * math.cos(math.radians(b))
        y = 300 + 200 * math.sin(math.radians(b))
        pygame.draw.line(screen, poly_color, (400, 300), (x, y), 1)

    # Tampilkan window pygame
    pygame.display.flip()

```

Python doesn't respond when I play it. No syntax error appears either. Not sure what is wrong. I tried running another game I made which worked fine so I don't think it's my computer.

Title: Python Not Responding when I Run it

Body:
Python doesn't respond when I play it. No syntax error appears either. Not sure what is wrong. I tried running another game I made which worked fine so I don't think it's my computer. error message

This is my code:

import pygame
import math

# Inisialisasi pygame
pygame.init()

# Buat window pygame dengan ukuran 800x600
screen = pygame.display.set_mode((800, 600))
poly_color=(128,128,128)

while True:

    # Gambar garis putih pada radius 200, 300, 400, 500, dan 600
    for r in range(100,210,50):
        pygame.draw.circle(screen, (128, 128, 128), (400, 300), r, 1)

    # Gambar garis-garis merah pada sudut 0, 45, 90, 135, 180, 225, 270, dan 315 derajat
    for a in range(0,360,45):

        x = 400 + 200 * math.cos(math.radians(a)/0.5)
        y = 300 + 200 * math.sin(math.radians(a)/0.5)
        pygame.draw.line(screen, (128, 128, 128), (400, 300), (x, y), 1)

    for b in range(0,360,30):

        x = 400 + 200 * math.cos(math.radians(b))
        y = 300 + 200 * math.sin(math.radians(b))
        pygame.draw.line(screen, poly_color, (400, 300), (x, y), 1)

    # Tampilkan window pygame
    pygame.display.flip()

Python doesn't respond when I play it. No syntax error appears either. Not sure what is wrong. I tried running another game I made which worked fine so I don't think it's my computer.


问:
How to add custom id, class or data attribute to 'Set' and 'Cancel' buttons for Angular owl-date-time-picker?
How I can add my own class, id or data-attribute for 'Set' and 'Cancel' buttons for Angular owl-date-time-picker? I need to add some unique identifier for my automation tests.

Something like this


问:
How to set cookie with javascript in wordpress site to be global
I have a wordpress site where I have JS code that sets cookie values. When I go to another page on the same domain, my cookie isn't there. When I return to the page where it was set, it is there. So I don't understand what I'm doing wrong.

```<code>var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
document.cookie= "package_selected" + "=" + encodeURIComponent("My Package") + "; expires=" + date.toGMTString(); + "; path=/;";
</code>```

As you can see the "; path=/;" is added to allow for global usage, but it does nothing.

Page cookie is set: Console log

document.cookie

'package_selected=My%20Package; none=none; wordpress_test_cookie=WP%20Cookie%20check; wp_lang=en_US; wp-settings-4=libraryContent%3Dbrowse; wp-settings-time-4=1672384213'

Home Page: Console log

document.cookie

'wordpress_test_cookie=WP%20Cookie%20check; wp_lang=en_US; wp-settings-4=libraryContent%3Dbrowse; wp-settings-time-4=1672384213'

Body:
I have a wordpress site where I have JS code that sets cookie values. When I go to another page on the same domain, my cookie isn't there. When I return to the page where it was set, it is there. So I don't understand what I'm doing wrong.

var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
document.cookie= "package_selected" + "=" + encodeURIComponent("My Package") + "; expires=" + date.toGMTString(); + "; path=/;";

As you can see the "; path=/;" is added to allow for global usage, but it does nothing.

Page cookie is set: Console log

document.cookie

'package_selected=My%20Package; none=none; wordpress_test_cookie=WP%20Cookie%20check; wp_lang=en_US; wp-settings-4=libraryContent%3Dbrowse; wp-settings-time-4=1672384213'

Home Page: Console log

document.cookie

'wordpress_test_cookie=WP%20Cookie%20check; wp_lang=en_US; wp-settings-4=libraryContent%3Dbrowse; wp-settings-time-4=1672384213'


问:
AWS Glue Search Tables API InternalServiceException: An error occurred when calling the SearchTables operation : Unknown exception occurred
I had a job running everyday that uses aws glue search tables api. I also had a filter to get results only for certain databases.

```<code>"Filter" = {"Key": "DatabaseName", "Value": "my_db"}
</code>```

Until today (30 Dec 2022), everything was working fine. But, now I am getting below exception.

```<code>InternalServiceException: An error occurred (InternalServiceException) when calling the SearchTables operation (reached max retries: 4): Unknown exception occurred.
</code>```

When I decrease the number of filters to 10, it works fine. But when I make it >10, it is giving error.
Normally, there were no limitation on number of filters that you can use. When I check AWS documentation, it is also not mentioning any kind of limitation.

https://docs.aws.amazon.com/glue/latest/webapi/API_SearchTables.html

Is it possible that AWS added a new limitation but not updated their documentation?

Edit: I wanted to test it myself with trial databases. See below image.

Body:
I had a job running everyday that uses aws glue search tables api. I also had a filter to get results only for certain databases.

"Filter" = {"Key": "DatabaseName", "Value": "my_db"}

Until today (30 Dec 2022), everything was working fine. But, now I am getting below exception.

InternalServiceException: An error occurred (InternalServiceException) when calling the SearchTables operation (reached max retries: 4): Unknown exception occurred.

When I decrease the number of filters to 10, it works fine. But when I make it >10, it is giving error.
Normally, there were no limitation on number of filters that you can use. When I check AWS documentation, it is also not mentioning any kind of limitation.

https://docs.aws.amazon.com/glue/latest/webapi/API_SearchTables.html

Is it possible that AWS added a new limitation but not updated their documentation?

Edit: I wanted to test it myself with trial databases. See below image.


问:
Quarkus, SSE - No events after reconnect
I'm trying to implement a SSE Resource with Quarkus (Version 2.12.3.Final), but I always end up with the problem that the client(s) don't receive any SSE events after reconnect or connecting after the first client being connected already.
So after re-/starting Quarkus receiving of SSE events works only for the first client that connects as long as it does not reconnect itself. Here is some minimal template code which is based on different documentations (resteasy, Quarkus,....):

`

package com.example.sse;

import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.sse.OutboundSseEvent;
import javax.ws.rs.sse.Sse;
import javax.ws.rs.sse.SseBroadcaster;
import javax.ws.rs.sse.SseEventSink;
import java.time.Instant;

@Path("/internal/sse2")
@Singleton
public class Sse2Resource {

    @Context
    private Sse sse;

    private volatile SseBroadcaster sseBroadcaster;

    @GET
    @Path("register")
    @Produces(MediaType.SERVER_SENT_EVENTS)
    public void register(@Context SseEventSink eventSink) {

        if (sseBroadcaster == null) {
            sseBroadcaster = sse.newBroadcaster();
            Thread broadcasting = new Thread(broadcast);
            broadcasting.start();
            System.out.println("!!!!! Broadcasting Thread started....");
        }
        eventSink.send(sse.newEvent("welcome!"));
        sseBroadcaster.register(eventSink);
    }

    @POST
    @Path("broadcast")
    @Consumes(MediaType.TEXT_PLAIN)
    public void broadcast(String event) {
        sseBroadcaster.broadcast(sse.newEvent(event));
    }

    private Runnable broadcast = new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(2000);
                    OutboundSseEvent event = sse.newEvent(String.valueOf((Instant.now().toEpochMilli())));
                    sseBroadcaster.broadcast(event);
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    };

}
```

`

After the first client connects the output on client side looks like this:

welcome!
1672394462931
1672394464933
1672394466933
1672394468934
1672394470935....

As soon as the client reconnects it only gets TimeoutExceptions and doesn't receive any further data. Nor does any subsequent client receive any data at all.

I tried different and more complex implementations like the one provided above.
But this minimal example which is based on this one:

https://quarkus.io/specs/jaxrs/2.1/index.html#sse_broadcasting

already leads to the explained behavior

Does somebody have an idea what goes wrong here?

Thanks for help

Body:
I'm trying to implement a SSE Resource with Quarkus (Version 2.12.3.Final), but I always end up with the problem that the client(s) don't receive any SSE events after reconnect or connecting after the first client being connected already.
So after re-/starting Quarkus receiving of SSE events works only for the first client that connects as long as it does not reconnect itself. Here is some minimal template code which is based on different documentations (resteasy, Quarkus,....):

`

package com.example.sse;

import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.sse.OutboundSseEvent;
import javax.ws.rs.sse.Sse;
import javax.ws.rs.sse.SseBroadcaster;
import javax.ws.rs.sse.SseEventSink;
import java.time.Instant;

@Path("/internal/sse2")
@Singleton
public class Sse2Resource {

    @Context
    private Sse sse;

    private volatile SseBroadcaster sseBroadcaster;

    @GET
    @Path("register")
    @Produces(MediaType.SERVER_SENT_EVENTS)
    public void register(@Context SseEventSink eventSink) {

        if (sseBroadcaster == null) {
            sseBroadcaster = sse.newBroadcaster();
            Thread broadcasting = new Thread(broadcast);
            broadcasting.start();
            System.out.println("!!!!! Broadcasting Thread started....");
        }
        eventSink.send(sse.newEvent("welcome!"));
        sseBroadcaster.register(eventSink);
    }

    @POST
    @Path("broadcast")
    @Consumes(MediaType.TEXT_PLAIN)
    public void broadcast(String event) {
        sseBroadcaster.broadcast(sse.newEvent(event));
    }

    private Runnable broadcast = new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(2000);
                    OutboundSseEvent event = sse.newEvent(String.valueOf((Instant.now().toEpochMilli())));
                    sseBroadcaster.broadcast(event);
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    };

}

`

After the first client connects the output on client side looks like this:

welcome!
1672394462931
1672394464933
1672394466933
1672394468934
1672394470935....

As soon as the client reconnects it only gets TimeoutExceptions and doesn't receive any further data. Nor does any subsequent client receive any data at all.

I tried different and more complex implementations like the one provided above.
But this minimal example which is based on this one:

https://quarkus.io/specs/jaxrs/2.1/index.html#sse_broadcasting

already leads to the explained behavior

Does somebody have an idea what goes wrong here?

Thanks for help


问:
How to remove index.php from codeigniter url
My URL looks like localhost/codeigniter/index.php/software/10-best-software-company-2022

I need URL like below

localhost/codeigniter/software/10-best-software-company-2022

How to configure route file in codegniter for the above

Need a solution for the above question


问:
anaconda installation, not getting the question 'do you accept the terms?'
while installing anaconda in ubuntu 22.10, i followed this steps below:
sudo apt update
sudo apt install curl -y
cd /tmp
curl --output anaconda.sh https://repo.anaconda.com/archive/Anaconda3-5.3.1-Linux-x86_64.sh
sha256sum anaconda.sh
bash anaconda.sh

every thing was smooth, but after reading all the terms, i didn't get the question that asks if i do accept the license terms, and the installation doesn't start i've waited a fair amount of time but nothings happen. How do i fix this problem?


问:
flutter_gallery_3d not scrolling when used inside a pageview
I am using flutter_gallery_3d https://pub.dev/packages/flutter_gallery_3d package inside a pageview and facing a issue is that flutter_gallery_3d view is not scrolling anymore
When I tried to scroll it, then main pageview  is navigating but flutter_gallery_3d is not scrolling.

I just simply want that  flutter_gallery_3d view should normally scroll as normal listview  and when I scroll outside then it must be navigate to next pageview screen.


问:
Plotting signals from list of custom objects
I have a list of custom Signal objects, where each object looks something like

```<code>@dataclass(slots=True)
class Signal:
    id: str
    values: List[float]
    weights: List[float]
</code>```

For example, id=1, values=[1,2,3], weights=[.5,.3,.2]

I want to plot these on top of each other, with values on the X axis and weights on the Y, so I can see common patterns in the signals.

I tried something like this:

```<code>    plt.xlabel("Values")
    plt.ylabel("Weights")
    plt.title("Signals")
    for i in range(len(signals)):
        plt.plot(signals[i].values,signals[i].weights,label = 'id %s'%signals[i].id)
    plt.legend()
    plt.show()
    plt.show()
</code>```

Does anyone know a more pythonic approach to this?

Body:
I have a list of custom Signal objects, where each object looks something like

@dataclass(slots=True)
class Signal:
    id: str
    values: List[float]
    weights: List[float]

For example, id=1, values=[1,2,3], weights=[.5,.3,.2]

I want to plot these on top of each other, with values on the X axis and weights on the Y, so I can see common patterns in the signals.

I tried something like this:

    plt.xlabel("Values")
    plt.ylabel("Weights")
    plt.title("Signals")
    for i in range(len(signals)):
        plt.plot(signals[i].values,signals[i].weights,label = 'id %s'%signals[i].id)
    plt.legend()
    plt.show()
    plt.show()

Does anyone know a more pythonic approach to this?


问:
How to inverse audio and play it back in real time?
I am trying to make an active noise cancelling program that records microphone audio, inverses the audio and plays it back in real time to cancel out sounds. Although I'm not receiving the results I want. Any suggestions ?

```<code>

import pyaudio
import numpy as np

# Set up PyAudio
p = pyaudio.PyAudio()

# Open a stream
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, output=True)

# Create a loop to continuously record and play back audio
while stream.is_active():
    # Capture audio from the microphone
    audio_data = stream.read(1024)

    # Convert the audio data to a NumPy array
    audio_data = np.fromstring(audio_data, dtype=np.int16)

    # Invert the audio data
    audio_data = audio_data * -1
    # Convert the audio data back to a bytes object
    audio_data = audio_data.tobytes()

    # Play back the inverted audio data
    stream.write(audio_data)

# Close the stream
stream.stop_stream()
stream.close()`

# Close PyAudio
p.terminate()

</code>```

I tried to inverse the sound but now i hear even more noise. I know the latency and processing delay will be a problem but thats fine, i just want it to work.

Body:
I am trying to make an active noise cancelling program that records microphone audio, inverses the audio and plays it back in real time to cancel out sounds. Although I'm not receiving the results I want. Any suggestions ?

import pyaudio
import numpy as np

# Set up PyAudio
p = pyaudio.PyAudio()

# Open a stream
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, output=True)

# Create a loop to continuously record and play back audio
while stream.is_active():
    # Capture audio from the microphone
    audio_data = stream.read(1024)

    # Convert the audio data to a NumPy array
    audio_data = np.fromstring(audio_data, dtype=np.int16)

    # Invert the audio data
    audio_data = audio_data * -1
    # Convert the audio data back to a bytes object
    audio_data = audio_data.tobytes()

    # Play back the inverted audio data
    stream.write(audio_data)

# Close the stream
stream.stop_stream()
stream.close()`

# Close PyAudio
p.terminate()

I tried to inverse the sound but now i hear even more noise. I know the latency and processing delay will be a problem but thats fine, i just want it to work.


问:
Docker Containers return with incorrect environment variable
for a course in my Bachelor's degree, I need to set up RPC communication between 1 master/controller and 3 workers using thrift. The issue I have right now is that while the environment variables are correctly set for the worker containers, when the master sends the ping request, it throws an exception stating the correctly set environment variable is null.
The container images are built using Jib.

EDIT/RESOLVED: I found the answer - In both the pom file of the master and worker, I declared the image name as master-image. It is a simple copy-paste error. Now it works! Thank you so much :)

stack-trace: //I don´t understand why the worker-port is printed as null in the master container.

```<code>master    | PORT: null
master    | Exception in thread "main" java.lang.NumberFormatException: Cannot parse null string
master    |     at java.base/java.lang.Integer.parseInt(Unknown Source)
master    |     at java.base/java.lang.Integer.parseInt(Unknown Source)
master    |     at org.example.worker.Worker.start(Worker.java:137)
master    |     at org.example.worker.Main.main(Main.java:10)
database  | Exception in thread "Thread-3" java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "inputLine" is null
database  |     at org.example.database.DatabaseServer$EchoClientHandler.run(DatabaseServer.java:57)
master exited with code 1
</code>```

docker-compose:

```<code>version: '3.9'

services:

  master:
    image: master-image:latest
    container_name: master
    build:
      context: ./VS_Project/Master
      dockerfile: ./Dockerfile
    ports:
      - '8080:8080'
    environment:
      network_mode: host
    depends_on:
      - worker_1
      - worker_2
      - worker_3

  worker_1:
    image: worker-image:latest
    container_name: worker_1
    build:
      context: ./VS_Project/Worker
      dockerfile: ./Dockerfile
    ports:
      - '8081:8080'
    depends_on:
      - database
    environment:
      - PORT=8081

  worker_2:
    image: worker-image:latest
    container_name: worker_2
    build:
      context: ./VS_Project/Worker
      dockerfile: ./Dockerfile
    ports:
      - '8082:8080'
    depends_on:
      - database
    environment:
      - PORT=8082

  worker_3:
    image: worker-image:latest
    container_name: worker_3
    build:
      context: ./VS_Project/Worker
      dockerfile: ./Dockerfile
    ports:
      - '8083:8080'
    depends_on:
      - database
    environment:
      - PORT=8083
</code>```

master-code:

```<code>public void start() {
    //RPC connection to worker

    for(Map.Entry<Integer, String>  worker : workers.entrySet()) {

        try {
            TTransport transport;

            transport = new TSocket(worker.getValue(), worker.getKey());
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            Calculator.Client client = new Calculator.Client(protocol);

            System.out.print("Calling remote method...worker port:" + worker.getKey()); //e.g. Port 8081

            client.ping();

            System.out.println("done.");

            transport.close();

        } catch (TException e) {
            e.printStackTrace();
        }
    }
</code>```

worker-code:

```<code>public void start() {

    assert (System.getenv("PORT") != null);
     System.out.println("PORT: " + System.getenv("PORT"));
    try {
      serverTransport = new TServerSocket(Integer.parseInt(System.getenv("PORT")));
      server = new TSimpleServer(new TServer.Args(serverTransport).processor(new Calculator.Processor<>(new CalculatorImpl())));
      System.out.print("Starting the server... Port:" + System.getenv("PORT"));
      server.serve();
      System.out.println("done.");
    }
    catch (TTransportException e) {
        e.printStackTrace();
        stop();
    }
}
</code>```

Body:
for a course in my Bachelor's degree, I need to set up RPC communication between 1 master/controller and 3 workers using thrift. The issue I have right now is that while the environment variables are correctly set for the worker containers, when the master sends the ping request, it throws an exception stating the correctly set environment variable is null.
The container images are built using Jib.

EDIT/RESOLVED: I found the answer - In both the pom file of the master and worker, I declared the image name as master-image. It is a simple copy-paste error. Now it works! Thank you so much :)

stack-trace: //I don´t understand why the worker-port is printed as null in the master container.

master    | PORT: null
master    | Exception in thread "main" java.lang.NumberFormatException: Cannot parse null string
master    |     at java.base/java.lang.Integer.parseInt(Unknown Source)
master    |     at java.base/java.lang.Integer.parseInt(Unknown Source)
master    |     at org.example.worker.Worker.start(Worker.java:137)
master    |     at org.example.worker.Main.main(Main.java:10)
database  | Exception in thread "Thread-3" java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "inputLine" is null
database  |     at org.example.database.DatabaseServer$EchoClientHandler.run(DatabaseServer.java:57)
master exited with code 1

docker-compose:

version: '3.9'

services:

  master:
    image: master-image:latest
    container_name: master
    build:
      context: ./VS_Project/Master
      dockerfile: ./Dockerfile
    ports:
      - '8080:8080'
    environment:
      network_mode: host
    depends_on:
      - worker_1
      - worker_2
      - worker_3

  worker_1:
    image: worker-image:latest
    container_name: worker_1
    build:
      context: ./VS_Project/Worker
      dockerfile: ./Dockerfile
    ports:
      - '8081:8080'
    depends_on:
      - database
    environment:
      - PORT=8081

  worker_2:
    image: worker-image:latest
    container_name: worker_2
    build:
      context: ./VS_Project/Worker
      dockerfile: ./Dockerfile
    ports:
      - '8082:8080'
    depends_on:
      - database
    environment:
      - PORT=8082

  worker_3:
    image: worker-image:latest
    container_name: worker_3
    build:
      context: ./VS_Project/Worker
      dockerfile: ./Dockerfile
    ports:
      - '8083:8080'
    depends_on:
      - database
    environment:
      - PORT=8083

master-code:

public void start() {
    //RPC connection to worker

    for(Map.Entry<Integer, String>  worker : workers.entrySet()) {

        try {
            TTransport transport;

            transport = new TSocket(worker.getValue(), worker.getKey());
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            Calculator.Client client = new Calculator.Client(protocol);

            System.out.print("Calling remote method...worker port:" + worker.getKey()); //e.g. Port 8081

            client.ping();

            System.out.println("done.");

            transport.close();

        } catch (TException e) {
            e.printStackTrace();
        }
    }

worker-code:

public void start() {

    assert (System.getenv("PORT") != null);
     System.out.println("PORT: " + System.getenv("PORT"));
    try {
      serverTransport = new TServerSocket(Integer.parseInt(System.getenv("PORT")));
      server = new TSimpleServer(new TServer.Args(serverTransport).processor(new Calculator.Processor<>(new CalculatorImpl())));
      System.out.print("Starting the server... Port:" + System.getenv("PORT"));
      server.serve();
      System.out.println("done.");
    }
    catch (TTransportException e) {
        e.printStackTrace();
        stop();
    }
}


问:
how can I read float string and format it to mpq_t in gmp
I can use gmp_sscanf to read float number like 0x12f.3p3 to mpf_t. However, I can't use it to read as mpq_t. If I fisrt read it as mpf_t, and convert it to mpq_t. The result is not right because of the precision. How can I achieve this?</p>


问:
Laravel Cashier invoicePrice unit_amount too high
I'm using Laravel Cashier 14.5.0 in my Laravel 9 project. I need to access the third argument of the invoiceFor method to set some custom metadata to update my project's database, to do this means having to set the second option, the amount argument.

I'm working with GBP currency, and am retrieving my product price from Stripe, I'm given the unit_amount in the smallest possible currency, pence, but when charged, the amount is significantly higher. What am I missing?

For exmaple:

My price is: £4.99
But I'm charged: £2,490.01

Here's my code:

$productPrice = Cashier::stripe()->prices->retrieve($productOption->stripe_id);

// get user
$user = Auth::user();

$user->createOrGetStripeCustomer();
$user->updateDefaultPaymentMethod($request->input('token'));
$user->invoicePrice(
    $productOption->stripe_id, intval($productPrice->unit_amount), [
        'metadata' => [
            'created_at' => Carbon::now(),
            'user_id' => $user->id,
            'api_key_uuid' => $apiKey->uuid,
            'quantity' => $productOption->quantity,
            'apply_credit_balance' => true
        ]
    ]
);
```


问:
How to include search bar in react js website to search through firestore database?
I want to know how to include search bar in my react js project where the data come from the firestore database. I watched some videos on yt but majority has their from json file. I need a search bar that is reponsive to the changes on what user typed in the input box.

I tried to insert the following code but the screen only turns white

```<code>const [search, setSearch] = useState({});

<input onChange={(e) => setSearch(e.target.value)} placeholder="Search"/>

account.filter((account)=>{
                    return search.toLowerCase() === ''
                      ? account
                      : account.name.toLowerCase().includes(search);
                  }).map(account=>{
                    return(//some table)
</code>```

Body:
I want to know how to include search bar in my react js project where the data come from the firestore database. I watched some videos on yt but majority has their from json file. I need a search bar that is reponsive to the changes on what user typed in the input box.

I tried to insert the following code but the screen only turns white

const [search, setSearch] = useState({});

<input onChange={(e) => setSearch(e.target.value)} placeholder="Search"/>

account.filter((account)=>{
                    return search.toLowerCase() === ''
                      ? account
                      : account.name.toLowerCase().includes(search);
                  }).map(account=>{
                    return(//some table)


问:
Narrator narrating UI element with `isTabStop=false`
I have one xaml page where there are multiple UI elements are there, and i wanted narrator to pick some UI element and ignore other. So with below code you can, see that I have four Grid Row Definition the last UI element is rendered on screen as Grid.RowSpan=4 and other UI elements also got intialized just for performance reason, but it won't be visible intially untill the last element Visibility will be set to Collapsed.

What i want when that "UserControlView1" control is rendered narrator should not pick other UI element, but once that is gone then narrator should start picking those UI element.

I have tried IsTabStop=false but not sure why it is not working.

<Page
    xmlns:mvvm="using:Prism.Windows.Mvvm"
    mvvm:ViewModelLocator.AutoWireViewModel="True"
    // some random namespaces declaration
    Loaded="PageLoaded">
        <Grid>
            <Grid.ColumnDefinitions>
               // some Grid Column definition
            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
               // "4" Grid Row definition...
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <ctl:UserControlView2
               x:Name="UserControlView2"
                Grid.Row="1"
                Grid.ColumnSpan="2"
                IsTabStop="False"/>

            <ctl:UserControlView3
                x:Name="UserControlView2"
                Grid.Row="2"
                Grid.Column="0"
                IsTabStop="False" --> I have set IsTabStop to false />

            <ctl:UserControlView4
                x:Name="UserControlView3"
                Grid.Row="3"
                Grid.Column="0"
                IsTabStop="False" --> I have set IsTabStop to false />

            <ctl:UserControlView1
                d:Visibility="Collapsed"
                x:Name="UserControlView1"
                x:Load="{x:Bind ViewModel.UserControlView1}"
                Grid.Row="0"
                Grid.RowSpan="4" // as it span to four rows the reason being its gets render at top of the screen and other UI element will be there beneath it.
                Grid.ColumnSpan="2"
                TabIndex="0"/>
        </Grid>
</Page>
```


问:
Silverstripe get site attributes from SiteTree
in my site I have the pages "Product" and "Reference".

I'm trying to link the references to their product and display the product icon on the reference page.

I'm using SiteTree with a TreeDropdownField to select the page in the admin backend

On the Frontend I'm trying to use $ProductLink.ProductLogo.URL but that does not return anything.

$ProductLink.Title and $ProductLink.AbsoluteLink work. It seems like accessing native page attributes works but attributes from my ProductPage do not work


问:
Http error 400 during authentication when adding a group on a checkpoint R81 Firewall
When I run ansible-playbook -i Inventory/host_file createGroup.yml I get the output:

PLAY [Create Groupt in SMS] ********************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.19.5]

TASK [set-group] *******************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ansible.module_utils.connection.ConnectionError: Server returned response without token info during connection authentication: 400
fatal: [192.168.19.5]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-local-38146d7ypqb5/ansible-tmp-1672395718.4953148-3880-262337703017219/AnsiballZ_cp_mgmt_group.py\", line 107, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-local-38146d7ypqb5/ansible-tmp-1672395718.4953148-3880-262337703017219/AnsiballZ_cp_mgmt_group.py\", line 99, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-local-38146d7ypqb5/ansible-tmp-1672395718.4953148-3880-262337703017219/AnsiballZ_cp_mgmt_group.py\", line 47, in invoke_module\n    runpy.run_module(mod_name='ansible_collections.check_point.mgmt.plugins.modules.cp_mgmt_group', init_globals=dict(_module_fqn='ansible_collections.check_point.mgmt.plugins.modules.cp_mgmt_group', _modlib_path=modlib_path),\n  File \"/usr/lib64/python3.9/runpy.py\", line 225, in run_module\n    return _run_module_code(code, init_globals, run_name, mod_spec)\n  File \"/usr/lib64/python3.9/runpy.py\", line 97, in _run_module_code\n    _run_code(code, mod_globals, init_globals,\n  File \"/usr/lib64/python3.9/runpy.py\", line 87, in _run_code\n    exec(code, run_globals)\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/modules/cp_mgmt_group.py\", line 139, in <module>\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/modules/cp_mgmt_group.py\", line 134, in main\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/module_utils/checkpoint.py\", line 317, in api_call\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/module_utils/checkpoint.py\", line 71, in send_request\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible/module_utils/connection.py\", line 200, in __rpc__\nansible.module_utils.connection.ConnectionError: Server returned response without token info during connection authentication: 400\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

PLAY RECAP *************************************************************************************************************************
192.168.19.5               : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

```
<p>This is the playbook:</p>
<pre class="lang-yaml prettyprint-override"><code>---
- name: Create Group in SMS
  hosts: gvSMS

  connection: httpapi
  gather_facts: yes
  vars:
    ansible_network_os: checkpoint
    mgmt_user: ansible
    mgmt_password: *****
    mgmt_server: 192.168.19.5
    mgmt_fingerprint: RITE OS NELL WEAR SOY FLAW LOY DENT DENY SOUR PIE PEN
    policy_name: standard
    ansible_httpapi_validate_certs: no
    ansible_httpapi_use_ssl: yes

  tasks:

    - name: set-group
      cp_mgmt_group:
        name: EXT-PermittedToCOM
        state: present
        auto_publish_session: yes
      notify: publishPolicy
  handlers:
    - name: publishPolicy
      cp_mgmt_publish:
</code>```

This is my host file (Inventory/host_file):

[gvSMS]
192.168.19.5 ansible_user=ansible ansible_password=*****
```
<p>These are the vars for my object(Inventory/group_vars/gvSMS.yml ):</p>
<pre class="lang-yaml prettyprint-override"><code>#group_vars/gvSMS.yml
ansible_httpapi_validate_certs: no
ansible_httpapi_use_ssl:  yes
ansible_network_os:  checkpoint
mgmt_server:  192.168.19.5
mgmt_user:  ansible
mgmt_password:  *****
mgmt_fingerprint:  RITE OS NELL WEAR SOY FLAW LOY DENT DENY SOUR PIE PEN
policy_name:  Standard
</code>```

This is my ansible.cfg file :

# Since Ansible 2.12 (core):
# To generate an example config file (a "disabled" one with all default settings, commented out):
#               $ ansible-config init --disabled > ansible.cfg
#
# Also you can now have a more complete file by including existing plugins:
# ansible-config init --disabled -t all > ansible.cfg

# For previous versions of Ansible you can check for examples in the 'stable' branches of each version
# Note that this file was always incomplete  and lagging changes to configuration settings

# for example, for 2.9: https://github.com/ansible/ansible/blob/stable-2.9/examples/ansible.cfg
[defaults]
inventory = Inventory/host_file
host_key_checking = true
retry_files_enabled = false
interpreter_python = /usr/bin/python3
[galaxy]
server=https://galaxy.ansible.com

```

There is connectivity between the firewall and the Server, I also enabled API management on the firewall.

I tried different playbooks however i get the same result. The ansible ping works, so  I think the problems is with the playbook.

Body:
When I run ansible-playbook -i Inventory/host_file createGroup.yml I get the output:

PLAY [Create Groupt in SMS] ********************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.19.5]

TASK [set-group] *******************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ansible.module_utils.connection.ConnectionError: Server returned response without token info during connection authentication: 400
fatal: [192.168.19.5]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-local-38146d7ypqb5/ansible-tmp-1672395718.4953148-3880-262337703017219/AnsiballZ_cp_mgmt_group.py\", line 107, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-local-38146d7ypqb5/ansible-tmp-1672395718.4953148-3880-262337703017219/AnsiballZ_cp_mgmt_group.py\", line 99, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-local-38146d7ypqb5/ansible-tmp-1672395718.4953148-3880-262337703017219/AnsiballZ_cp_mgmt_group.py\", line 47, in invoke_module\n    runpy.run_module(mod_name='ansible_collections.check_point.mgmt.plugins.modules.cp_mgmt_group', init_globals=dict(_module_fqn='ansible_collections.check_point.mgmt.plugins.modules.cp_mgmt_group', _modlib_path=modlib_path),\n  File \"/usr/lib64/python3.9/runpy.py\", line 225, in run_module\n    return _run_module_code(code, init_globals, run_name, mod_spec)\n  File \"/usr/lib64/python3.9/runpy.py\", line 97, in _run_module_code\n    _run_code(code, mod_globals, init_globals,\n  File \"/usr/lib64/python3.9/runpy.py\", line 87, in _run_code\n    exec(code, run_globals)\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/modules/cp_mgmt_group.py\", line 139, in <module>\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/modules/cp_mgmt_group.py\", line 134, in main\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/module_utils/checkpoint.py\", line 317, in api_call\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible_collections/check_point/mgmt/plugins/module_utils/checkpoint.py\", line 71, in send_request\n  File \"/tmp/ansible_cp_mgmt_group_payload_h8pp29fy/ansible_cp_mgmt_group_payload.zip/ansible/module_utils/connection.py\", line 200, in __rpc__\nansible.module_utils.connection.ConnectionError: Server returned response without token info during connection authentication: 400\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

PLAY RECAP *************************************************************************************************************************
192.168.19.5               : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

This is the playbook:

---
- name: Create Group in SMS
  hosts: gvSMS

  connection: httpapi
  gather_facts: yes
  vars:
    ansible_network_os: checkpoint
    mgmt_user: ansible
    mgmt_password: *****
    mgmt_server: 192.168.19.5
    mgmt_fingerprint: RITE OS NELL WEAR SOY FLAW LOY DENT DENY SOUR PIE PEN
    policy_name: standard
    ansible_httpapi_validate_certs: no
    ansible_httpapi_use_ssl: yes

  tasks:

    - name: set-group
      cp_mgmt_group:
        name: EXT-PermittedToCOM
        state: present
        auto_publish_session: yes
      notify: publishPolicy
  handlers:
    - name: publishPolicy
      cp_mgmt_publish:

This is my host file (Inventory/host_file):

[gvSMS]
192.168.19.5 ansible_user=ansible ansible_password=*****

These are the vars for my object(Inventory/group_vars/gvSMS.yml ):

#group_vars/gvSMS.yml
ansible_httpapi_validate_certs: no
ansible_httpapi_use_ssl:  yes
ansible_network_os:  checkpoint
mgmt_server:  192.168.19.5
mgmt_user:  ansible
mgmt_password:  *****
mgmt_fingerprint:  RITE OS NELL WEAR SOY FLAW LOY DENT DENY SOUR PIE PEN
policy_name:  Standard

This is my ansible.cfg file :

# Since Ansible 2.12 (core):
# To generate an example config file (a "disabled" one with all default settings, commented out):
#               $ ansible-config init --disabled > ansible.cfg
#
# Also you can now have a more complete file by including existing plugins:
# ansible-config init --disabled -t all > ansible.cfg

# For previous versions of Ansible you can check for examples in the 'stable' branches of each version
# Note that this file was always incomplete  and lagging changes to configuration settings

# for example, for 2.9: https://github.com/ansible/ansible/blob/stable-2.9/examples/ansible.cfg
[defaults]
inventory = Inventory/host_file
host_key_checking = true
retry_files_enabled = false
interpreter_python = /usr/bin/python3
[galaxy]
server=https://galaxy.ansible.com

There is connectivity between the firewall and the Server, I also enabled API management on the firewall.

I tried different playbooks however i get the same result. The ansible ping works, so  I think the problems is with the playbook.


问:
“operation not supported” when invoking an RPC call on Windows 2008
The application uses Microsoft RPC for interprocess communications. The application works flawlessly on Windows Server 2003 (Server WS2003 or WS 2008 --- Client WS2003). But the application fails when the client is on Windows Server 2008.

Here is the flow of client part

RpcStringBindingCompose(.....)
RpcBindingFromStringBinding(.....)
RpcMgmtIsServerListening(....) //This method returns success even on WS2008

After this whenever i call a method rpcMethod(...) defined in IDL file (code generated using MIDL compiler 6.00.0366), it thorws an exception (Error Code 1764) "Operation is not Supported".
The MIDL-generated stub redirects to NdrClientCall2() which throws this exception.

Similar issue reported here: Operation is not supported

ContentLicense: CC BY-SA 3.0


问:
MariaDB 10.3. - Error 2006 server has gone away in a PHP-Loop after a certain number of queries. Any idea?
EDIT: In my opinion is this not a duplicate because non of the mentioned answers are solving the problem.

We have running a MariaDB 10.3. on a Synology-Server and almost everything works fine. But after a certain number of queries within one PHP-connection (mysqli) the server isn't reacting any more so PHP throws after a while 2006 server has gone away.

The number of queries until the error raises depends on the query. To example "SELECT RAND()" within a PHP-loop gives 3714 results and then the error, "SELECT RAND() * $i" (with $i the PHP-loop-index) gives 2718 results and than the error, both examples are reproducible and regardless any build-in PHP-loop-delay or the server-load. For real-live complex queries this number until the error raises reduce to something between 100 and 200 queries, that's the problem.

All the buffer- and timing-settings seems to be OK. To example wait_timeout = 28800, interactive_timeout = 28800 and max_allowed_packed = 128M.

I have searching stackoverflow and the internet with no results and also asking the Synology service with no result and i didn't find any related system-variable in the mySql- or MariaDB-documention.

To close the PHP-connection and open a new PHP-connection after each query (or after N queries) is a possible work-a-round until you need the last_insert_id or you use transactions or you have to update hundreds of records. we need all of this.


问:
502 Bad Gateway error after iRedMail installation
Just installed iRedMail on a server, the admin panel works fine but the mail url is not working
https://<my-domain>/mail. When I open it in the browser it throws a 502 bad gateway error.


问:
Firebase App Check Quota Limits when using with firestore SDK in android
Our android app uses firestore as the DB and uses firestore SDK to make the reads and writes. We use firebase app check via safetynet(planning to migrate play integrity) as one of our security measure.

```<code>FirebaseApp.initializeApp(this)
        val appCheck = FirebaseAppCheck.getInstance()
        appCheck.installAppCheckProviderFactory(SafetyNetAppCheckProviderFactory.getInstance())
</code>```

That's all we do for app check, We do not have any custom attestation and verify flow and we don't have any throttling call logic to firestore since it is all handled by firestore SDK. The issue we see is since our customer base is growing large we often see quota limit exceeding error from app check which leads to PERMISSION_DENIED errors resulting in app unusable state. Before we raise quota increase limit , we wanted to clarify the following questions,

We see quota for attest, verify requests. Is there any document that clearly explains the use cases for the above quota? Please see the attached screenshot for quota categories.

Is the app check token is same as JWT , like it has its expiration time once after that it will fetch new token from google play services. Until then it wont request for new token. If so what is the expiration time? Asking this to understand how the quota expires?

Whether for each install/update or clear storage of android app will it re init the whole process?

Body:
Our android app uses firestore as the DB and uses firestore SDK to make the reads and writes. We use firebase app check via safetynet(planning to migrate play integrity) as one of our security measure.

FirebaseApp.initializeApp(this)
        val appCheck = FirebaseAppCheck.getInstance()
        appCheck.installAppCheckProviderFactory(SafetyNetAppCheckProviderFactory.getInstance())

That's all we do for app check, We do not have any custom attestation and verify flow and we don't have any throttling call logic to firestore since it is all handled by firestore SDK. The issue we see is since our customer base is growing large we often see quota limit exceeding error from app check which leads to PERMISSION_DENIED errors resulting in app unusable state. Before we raise quota increase limit , we wanted to clarify the following questions,

We see quota for attest, verify requests. Is there any document that clearly explains the use cases for the above quota? Please see the attached screenshot for quota categories.

Is the app check token is same as JWT , like it has its expiration time once after that it will fetch new token from google play services. Until then it wont request for new token. If so what is the expiration time? Asking this to understand how the quota expires?

Whether for each install/update or clear storage of android app will it re init the whole process?


问:
WordPress navigation suddenly disappears in backend and frontend
WordPress navigation suddenly disappears in backend and frontend every some weeks, sometimes more than one time a week.

When the navigation disappears it can be recovered by saving the menu in the backend.After saving the menu is back with all items.

The website is a multisite / network installation with WPML and custom 3 Menus on each site.

The website and the navigation is huge. The menu has hundreds of entries, the DB is >500MB.

The problem drops no Fatal Errors in the log, also the warnings can’t help to catch it. We didn’t find any action to reproduce the problem.

The problem exists since the server has changed to one with more performance. With the sever change thy made some updates (but this was all bevor I come up to check the problem)

I set the values of post max size, memory limit, execution time and input vars higher but with no effect.

Over all I think it can be WPML because this plugin makes many problems, but this is just a feeling.


问:
error don't hold value in increase and decrease quantity in php using loop
I have a problem, when I click to other -/+ in new row, the old row return initial value. How can I fix it?

```<code><?php
$arr = array(1, 2, 3);
for ($i = 0; $i < 3; $i++) {
    $arr[$i] = isset($_POST["item".$i]) ? $_POST['item'.$i] : $arr[$i];
    if (isset($_POST['incqty'.$i])) {
        $arr[$i] += 1;
    }

    if (isset($_POST['decqty'.$i])) {
        $arr[$i] -= 1;
    }
}
?>
<?php

for ($i = 0; $i < 3; $i++) {

?>
    <form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
        <td>
            <button name='decqty<?php echo $i; ?>'>-</button>
            <input type='text' size='1' name='item<?php echo $i; ?>' value='<?= $arr[$i]; ?>' />
            <button name='incqty<?php echo $i; ?>'>+</button>
        </td>
    </form>
<?php
 }
 ?>
</code>```

change value when end click other row

Body:
I have a problem, when I click to other -/+ in new row, the old row return initial value. How can I fix it?

<?php
$arr = array(1, 2, 3);
for ($i = 0; $i < 3; $i++) {
    $arr[$i] = isset($_POST["item".$i]) ? $_POST['item'.$i] : $arr[$i];
    if (isset($_POST['incqty'.$i])) {
        $arr[$i] += 1;
    }

    if (isset($_POST['decqty'.$i])) {
        $arr[$i] -= 1;
    }
}
?>
<?php

for ($i = 0; $i < 3; $i++) {

?>
    <form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>

            <button name='decqty<?php echo $i; ?>'>-</button>
            <input type='text' size='1' name='item<?php echo $i; ?>' value='<?= $arr[$i]; ?>' />
            <button name='incqty<?php echo $i; ?>'>+</button>

    </form>
<?php
 }
 ?>

change value when end click other row


问:
How do I get the data usage of applications from adb logs?
I want to automate the apps which are running in background or in foreground and how much data the app is consuming.
Where do I get this info in adb logs ? like if any keyword is there for network data usage then it would be helpful for me</p>


问:
matplotlib x-axis bugs out after several hours
In my current project I am reading measurement data from a pH meter and an Arduino via a Python script and then visualizing the results. Everything is also working satisfactorily. However, about two hours after the start of the measurement, the graph starts to bug. The red line does not seem to understand the x-values, which it gets via a stopwatch, correctly. The blue line, which gets its x-values via the same stopwatch function, however, works (see picture).

The function for the stopwatch is the following:

```<code>#Stoppuhr
def stoppuhr():
    global stoppuhrZeit
    stoppuhrVar = 0
    #Endlosschleife
    while True:
        if messungRunning:
            stoppuhrVar = stoppuhrVar + 1
            #Stoppuhr konfigurieren
            stoppuhrZeit = str(dt.timedelta(seconds=stoppuhrVar))
            time.sleep(1)
</code>```

and here is a paste of the code for the drawing of the graph:
https://pastebin.com/6pGPfAPW

As you can see, both lines are defined the same, but bugs still occur with the red line. Any idea what the problem could be?

Body:
In my current project I am reading measurement data from a pH meter and an Arduino via a Python script and then visualizing the results. Everything is also working satisfactorily. However, about two hours after the start of the measurement, the graph starts to bug. The red line does not seem to understand the x-values, which it gets via a stopwatch, correctly. The blue line, which gets its x-values via the same stopwatch function, however, works (see picture).

The function for the stopwatch is the following:

#Stoppuhr
def stoppuhr():
    global stoppuhrZeit
    stoppuhrVar = 0
    #Endlosschleife
    while True:
        if messungRunning:
            stoppuhrVar = stoppuhrVar + 1
            #Stoppuhr konfigurieren
            stoppuhrZeit = str(dt.timedelta(seconds=stoppuhrVar))
            time.sleep(1)

and here is a paste of the code for the drawing of the graph:
https://pastebin.com/6pGPfAPW

As you can see, both lines are defined the same, but bugs still occur with the red line. Any idea what the problem could be?


问:
how to get client IP from RKE2 nginx ingress?
i have set up the RKE2 cluster. And there is an "embedded" rke2 nginx ingress in there, their document says that the ingress controller can be modified via the helm rke ingress manifest, but normally in the EKS, there are "externalTrafficPolicy: Local" to set in the LoadBalancer 's Service, but they don't exist in RKE because they use the nginx external Layer 4 LB.
So my question is how to get the original client IP that nginx stream pass to rke-nginx-ingress? I check their latest document but did not find.
the nginx layer 4 config is

```<code>stream {
    upstream rancher_servers_http {
        least_conn;
        server rke1:80 max_fails=3 fail_timeout=5s;
        server rke2:80 max_fails=3 fail_timeout=5s;
        server rke3:80 max_fails=3 fail_timeout=5s;

    }
    server {
        listen 80;
        proxy_pass rancher_servers_http;
    }

    upstream rancher_servers_https {
        least_conn;
        server rke1:443 max_fails=3 fail_timeout=5s;
        server rke2:443 max_fails=3 fail_timeout=5s;
        server rke3:443 max_fails=3 fail_timeout=5s;

    }
    server {
        listen     443;
        proxy_pass rancher_servers_https;
    }

}
</code>```

Thank you.

Body:
i have set up the RKE2 cluster. And there is an "embedded" rke2 nginx ingress in there, their document says that the ingress controller can be modified via the helm rke ingress manifest, but normally in the EKS, there are "externalTrafficPolicy: Local" to set in the LoadBalancer 's Service, but they don't exist in RKE because they use the nginx external Layer 4 LB.
So my question is how to get the original client IP that nginx stream pass to rke-nginx-ingress? I check their latest document but did not find.
the nginx layer 4 config is

stream {
    upstream rancher_servers_http {
        least_conn;
        server rke1:80 max_fails=3 fail_timeout=5s;
        server rke2:80 max_fails=3 fail_timeout=5s;
        server rke3:80 max_fails=3 fail_timeout=5s;

    }
    server {
        listen 80;
        proxy_pass rancher_servers_http;
    }

    upstream rancher_servers_https {
        least_conn;
        server rke1:443 max_fails=3 fail_timeout=5s;
        server rke2:443 max_fails=3 fail_timeout=5s;
        server rke3:443 max_fails=3 fail_timeout=5s;

    }
    server {
        listen     443;
        proxy_pass rancher_servers_https;
    }

}

Thank you.


问:
how to create several buttons using button class in alien invasion game in python
I am unable to create buttons with a single class in python , so kindly give some suggestion on this.

I tried to create more buttons using the button class but failed to do so.


问:
How to use unplugin-icons in a vue-3 project?
I am currently working on a project with vue-3.
Now i want to use icons in my project.
I watched some youtube-videos, searched some icon libraries on google.
Then I have found unplugin-icons. I want to use it in my project.
So I googelt "unplugin-icons vue-3". But everything I found was about vite.js and uses the "vite.config.js".
But I do not have a vite.js project. I have a vue-3 project.
I unplugin-icons installed using npm.
So: can someone please help me. How can I implement unplugin-icons in a vue-3 project?

I had no idea, what i could try.


问:
Getting started with building a WMS server based on Mapnik
I'd like to setup my own WMS server based on Mapnik to request OSM layers, but I don't find the documentation regarding that issue so clear... for example, I reached a couple of web pages stating some steps to follow concerning Mapnik and WMS:

http://wiki.openstreetmap.org/wiki/Mod_mapnik_wms

http://code.google.com/p/mapnik-utils/wiki/WmsInstallGuide

Taking into account that I'm running on Windows... which path should I follow? Or could somebody explain me how can I achieve my goal in clearer steps? And what about requesting OpenStreetMap layers through Mapnik?

Thanks in advance!


问:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component
I have a react app that I'm trying to start locally with npm start. The page that loads is completely blank and the console gives the following message:

```<code>Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See `url` for tips about how to debug and fix this problem.
    React 2
    useTheme useTheme.js:4
    ThemeProvider ThemeProvider.js:34
    React 17
    tsx index.tsx:7
    factory react refresh:6
    Webpack 3
        __webpack_require__
        <anonymous>
        <anonymous>
react.development.js:1465
    React 2
    useTheme useTheme.js:4
    ThemeProvider ThemeProvider.js:34
    React 17
    tsx index.tsx:7
    factory react refresh:6
    Webpack 3
</code>```

I'm very new to React so I'm not sure how to go about solving this. I suspect that error 3 is to blame (multiple copies of React), but I'm not sure. This app has been running in production for the better part of 2 years, and still is, with absolutely no changes so I'm finding it hard to believe that there is a version problem (point 1) or incorrect usage of hooks (point 2) as that would cause it to not work in production either, right? It's only locally that it's failing. So that leaves the possibility that I have more than one copy of React, and I'm not sure what this means or how to fix it.

Here is my package.json:

```<code>{
{
  "name": "my-app-react-pwa",
  "version": "0.1.0",
  "private": true,
  "homepage": ".",
  "dependencies": {
    "@azure/msal-browser": "^2.22.0",
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/lab": "^4.0.0-alpha.60",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.3",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.4.0",
    "@types/node": "^17.0.19",
    "@types/react": "^17.0.39",
    "@types/react-dom": "^17.0.11",
    "date-fns": "^2.28.0",
    "material-table": "^1.69.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.1",
    "react-scripts": "^5.0.0",
    "store2": "^2.13.1",
    "swr": "^1.2.2",
    "typescript": "^4.5.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

And here is the output of npm ls react:

```<code>  +-- @material-ui/core@4.12.3
  | +-- @material-ui/styles@4.11.4
  | | `-- react@16.14.0 deduped
  | +-- @material-ui/system@4.12.1
  | | `-- react@16.14.0 deduped
  | +-- @material-ui/utils@4.11.2
  | | `-- react@16.14.0 deduped
  | +-- react-dom@16.14.0
  | | `-- react@16.14.0 deduped
  | +-- react-transition-group@4.4.2
  | | `-- react@16.14.0 deduped
  | `-- react@16.14.0
  +-- @material-ui/icons@4.11.2
  | `-- react@16.14.0 deduped
  +-- @material-ui/lab@4.0.0-alpha.60
  | `-- react@16.14.0 deduped
  +-- @testing-library/react@12.1.3
  | `-- react@16.14.0 deduped
  +-- material-table@1.69.3
  | +-- @material-ui/pickers@3.2.2
  | | +-- react@16.14.0 deduped
  | | `-- rifm@0.7.0
  | |   `-- react@16.14.0 deduped
  | +-- react-beautiful-dnd@13.0.0
  | | +-- react-redux@7.2.6
  | | | `-- react@16.14.0 deduped
  | | +-- react@16.14.0 deduped
  | | `-- use-memo-one@1.1.2
  | |   `-- react@16.14.0 deduped
  | +-- react-double-scrollbar@0.0.15
  | | `-- react@16.14.0 deduped
  | `-- react@16.14.0 deduped
  +-- react-dom@17.0.2
  | `-- react@17.0.2 deduped
  +-- react-router-dom@6.2.1
  | +-- react-router@6.2.1
  | | `-- react@16.14.0 deduped
  | `-- react@17.0.2 deduped
  +-- react-scripts@5.0.0
  | `-- react@16.14.0 deduped
  +-- react@17.0.2
  `-- swr@1.2.2
    `-- react@16.14.0 deduped
</code>```

And index.tsx:

```<code>import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
  <React.Fragment>
    <App />
  </React.Fragment>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();
</code>```

The app only has a single page/URL, here is the App.tsx:

```<code>import { ThemeProvider } from "@material-ui/core";
import React, { createContext } from "react";
import { SWRConfig } from "swr";
import AzureAdAuthenticator from "./components/AzureAdAuthenticator";
import Tables from "./components/Tables";
import config from "./config";
import theme from "./theme";

function createDataFetcher(
  adAuthenticatedFetch: (path: string, options: any) => Promise<Response>
) {
  return async (path: string, paramOptions: any) => {
    const contentTypeHeader = {
      "Content-Type": "application/json",
    };
    paramOptions = paramOptions ? paramOptions : { headers: {} };

    if (paramOptions.body) {
      paramOptions.body = JSON.stringify(paramOptions.body);
    }

    var options = {
      ...paramOptions,
      headers: {
        ...paramOptions.headers,
        ...contentTypeHeader,
      },
    };

    return adAuthenticatedFetch(config.API_HOST + path, options).then((r) =>
      r.json()
    );
  };
}

export const AooContext = createContext({
  dataFetcher: createDataFetcher(fetch),
});

function App() {
  return (
    <ThemeProvider theme={theme}>
      <AzureAdAuthenticator
        render={(
          adAuthenticatedFetch: (
            path: string,
            options: any
          ) => Promise<Response>
        ) => (
          <AppContext.Provider
            value={{
              alvtimeFetcher: createDataFetcher(adAuthenticatedFetch),
            }}
          >
            <SWRConfig
              value={{
                fetcher: createDataFetcher(adAuthenticatedFetch),
                revalidateOnFocus: false,
              }}
            >
              <Tables />
            </SWRConfig>
          </AppContext.Provider>
        )}
      ></AzureAdAuthenticator>
    </ThemeProvider>
  );
}

export default App;
</code>```

Which loads the Tables.tsx component:

```<code>import { Options } from "material-table";
import React from "react";
import { mutate } from "swr";
import CustomerTable from "./CustomerTable";
import UserTable from "./UserTable";

export const setCache = (path: string, data: any) => mutate(path, data, false);

export const globalTableOptions: Options<object> = {
  addRowPosition: "first",
};

export default function Tables() {
  return (
    <>
      <UserTable />
      <CustomerTable />
    </>
  );
}
</code>```

Body:
I have a react app that I'm trying to start locally with npm start. The page that loads is completely blank and the console gives the following message:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See `url` for tips about how to debug and fix this problem.
    React 2
    useTheme useTheme.js:4
    ThemeProvider ThemeProvider.js:34
    React 17
    tsx index.tsx:7
    factory react refresh:6
    Webpack 3
        __webpack_require__
        <anonymous>
        <anonymous>
react.development.js:1465
    React 2
    useTheme useTheme.js:4
    ThemeProvider ThemeProvider.js:34
    React 17
    tsx index.tsx:7
    factory react refresh:6
    Webpack 3

I'm very new to React so I'm not sure how to go about solving this. I suspect that error 3 is to blame (multiple copies of React), but I'm not sure. This app has been running in production for the better part of 2 years, and still is, with absolutely no changes so I'm finding it hard to believe that there is a version problem (point 1) or incorrect usage of hooks (point 2) as that would cause it to not work in production either, right? It's only locally that it's failing. So that leaves the possibility that I have more than one copy of React, and I'm not sure what this means or how to fix it.

Here is my package.json:

{
{
  "name": "my-app-react-pwa",
  "version": "0.1.0",
  "private": true,
  "homepage": ".",
  "dependencies": {
    "@azure/msal-browser": "^2.22.0",
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/lab": "^4.0.0-alpha.60",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.3",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.4.0",
    "@types/node": "^17.0.19",
    "@types/react": "^17.0.39",
    "@types/react-dom": "^17.0.11",
    "date-fns": "^2.28.0",
    "material-table": "^1.69.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.1",
    "react-scripts": "^5.0.0",
    "store2": "^2.13.1",
    "swr": "^1.2.2",
    "typescript": "^4.5.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

And here is the output of npm ls react:

  +-- @material-ui/core@4.12.3
  | +-- @material-ui/styles@4.11.4
  | | `-- react@16.14.0 deduped
  | +-- @material-ui/system@4.12.1
  | | `-- react@16.14.0 deduped
  | +-- @material-ui/utils@4.11.2
  | | `-- react@16.14.0 deduped
  | +-- react-dom@16.14.0
  | | `-- react@16.14.0 deduped
  | +-- react-transition-group@4.4.2
  | | `-- react@16.14.0 deduped
  | `-- react@16.14.0
  +-- @material-ui/icons@4.11.2
  | `-- react@16.14.0 deduped
  +-- @material-ui/lab@4.0.0-alpha.60
  | `-- react@16.14.0 deduped
  +-- @testing-library/react@12.1.3
  | `-- react@16.14.0 deduped
  +-- material-table@1.69.3
  | +-- @material-ui/pickers@3.2.2
  | | +-- react@16.14.0 deduped
  | | `-- rifm@0.7.0
  | |   `-- react@16.14.0 deduped
  | +-- react-beautiful-dnd@13.0.0
  | | +-- react-redux@7.2.6
  | | | `-- react@16.14.0 deduped
  | | +-- react@16.14.0 deduped
  | | `-- use-memo-one@1.1.2
  | |   `-- react@16.14.0 deduped
  | +-- react-double-scrollbar@0.0.15
  | | `-- react@16.14.0 deduped
  | `-- react@16.14.0 deduped
  +-- react-dom@17.0.2
  | `-- react@17.0.2 deduped
  +-- react-router-dom@6.2.1
  | +-- react-router@6.2.1
  | | `-- react@16.14.0 deduped
  | `-- react@17.0.2 deduped
  +-- react-scripts@5.0.0
  | `-- react@16.14.0 deduped
  +-- react@17.0.2
  `-- swr@1.2.2
    `-- react@16.14.0 deduped

And index.tsx:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
  <React.Fragment>
    <App />
  </React.Fragment>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();

The app only has a single page/URL, here is the App.tsx:

import { ThemeProvider } from "@material-ui/core";
import React, { createContext } from "react";
import { SWRConfig } from "swr";
import AzureAdAuthenticator from "./components/AzureAdAuthenticator";
import Tables from "./components/Tables";
import config from "./config";
import theme from "./theme";

function createDataFetcher(
  adAuthenticatedFetch: (path: string, options: any) => Promise<Response>
) {
  return async (path: string, paramOptions: any) => {
    const contentTypeHeader = {
      "Content-Type": "application/json",
    };
    paramOptions = paramOptions ? paramOptions : { headers: {} };

    if (paramOptions.body) {
      paramOptions.body = JSON.stringify(paramOptions.body);
    }

    var options = {
      ...paramOptions,
      headers: {
        ...paramOptions.headers,
        ...contentTypeHeader,
      },
    };

    return adAuthenticatedFetch(config.API_HOST + path, options).then((r) =>
      r.json()
    );
  };
}

export const AooContext = createContext({
  dataFetcher: createDataFetcher(fetch),
});

function App() {
  return (
    <ThemeProvider theme={theme}>
      <AzureAdAuthenticator
        render={(
          adAuthenticatedFetch: (
            path: string,
            options: any
          ) => Promise<Response>
        ) => (
          <AppContext.Provider
            value={{
              alvtimeFetcher: createDataFetcher(adAuthenticatedFetch),
            }}
          >
            <SWRConfig
              value={{
                fetcher: createDataFetcher(adAuthenticatedFetch),
                revalidateOnFocus: false,
              }}
            >
              <Tables />
            </SWRConfig>
          </AppContext.Provider>
        )}
      ></AzureAdAuthenticator>
    </ThemeProvider>
  );
}

export default App;

Which loads the Tables.tsx component:

import { Options } from "material-table";
import React from "react";
import { mutate } from "swr";
import CustomerTable from "./CustomerTable";
import UserTable from "./UserTable";

export const setCache = (path: string, data: any) => mutate(path, data, false);

export const globalTableOptions: Options<object> = {
  addRowPosition: "first",
};

export default function Tables() {
  return (
    <>
      <UserTable />
      <CustomerTable />
    </>
  );
}


问:
How to Calculate ViewPager2's fakeDragBy offsetPcFloat Parameter
I am creating a fragment containing 2 viewPagers. My goal is to disable user input for the top view pager so that it's scroll will be dependent on the bottom view pager.

so far I've figured out how to detect the drag of bottom viewPager, however I am unable to calculate the parameter of offsetPxFloat required by fakeDragBy() to determine how much scroll is required for the top viewPager.

```<code>private val moviePosterVpOnPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
    override fun onPageScrolled(
        position: Int,
        positionOffset: Float,
        positionOffsetPixels: Int,
    ) {
        super.onPageScrolled(position, positionOffset, positionOffsetPixels)
        binding.movieBackdropVp.fakeDragBy(-positionOffsetPixels.toFloat())
    }

    override fun onPageScrollStateChanged(state: Int) {
        super.onPageScrollStateChanged(state)
        if (state > 0){
            binding.movieBackdropVp.beginFakeDrag()
        }else{
            binding.movieBackdropVp.endFakeDrag()
        }
    }
}
</code>```

Body:
I am creating a fragment containing 2 viewPagers. My goal is to disable user input for the top view pager so that it's scroll will be dependent on the bottom view pager.

so far I've figured out how to detect the drag of bottom viewPager, however I am unable to calculate the parameter of offsetPxFloat required by fakeDragBy() to determine how much scroll is required for the top viewPager.

private val moviePosterVpOnPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
    override fun onPageScrolled(
        position: Int,
        positionOffset: Float,
        positionOffsetPixels: Int,
    ) {
        super.onPageScrolled(position, positionOffset, positionOffsetPixels)
        binding.movieBackdropVp.fakeDragBy(-positionOffsetPixels.toFloat())
    }

    override fun onPageScrollStateChanged(state: Int) {
        super.onPageScrollStateChanged(state)
        if (state > 0){
            binding.movieBackdropVp.beginFakeDrag()
        }else{
            binding.movieBackdropVp.endFakeDrag()
        }
    }
}


问:
Intersecting lines with a circle after polar coordinates conversion
I have a dataset in polar coordinates.
The dataset contains the coordinates of points that I cast in lines.
Then I want to intersect these lines with a circle. From the polar coordinates, you can see that the Boundary of the line is always 18 (which is also the limit of the circle).
In order to do the intersect I convert Polar coordinates to cartesian.
In the end, only some of the lines correctly intersect the circle, and I do not know why.
What works for me is a Not So Elegant Solution: I reduce the circle radius from 18 to 17.999. This works and I suppose that it is because the conversion from polar to cartesian is not 100%. For my purpose, the solution I found is enough, but I want to report it here (I do not know if this is a bug or I made some mistake),

Here is the reproducible example (with plots):

```<code>#My Dataset
Boundaries<- data.frame(UE = c(127,127,128,128,128,129,129,129,129,129),
                    ID_Line = c(1,1,1,1,1,1,1,1,2,2),
                    ID_Point = c(1,2,1,2,3,1,2,3,1,2),
                    Azimut = c(10,120,120,90,230,120,90,230,90,270),
                    Distance = c(18,18,18,5,18,18,5,18,5,18)
                    )

library(tidyverse)
library(useful)

#Polar to Cartesian coordinates conversion
Boundariesxy<-as_tibble(Boundaries) %>%
  mutate(Theta = 2*pi*Azimut/360,
         x = pol2cart(Distance, Theta, degrees=F)[["y"]],
         y = pol2cart(Distance, Theta, degrees=F)[["x"]])

library(sf)
#Conversion to sf object
Boundaries_sf <- st_as_sf(Boundariesxy,
                          coords = c('x', 'y')) %>%
  st_set_crs("102010")  %>%
  group_by(UE, ID_Line)  %>%
  summarise() %>%
  ungroup()

#Cast as Linestring
Bound_lines <- st_cast(Boundaries_sf, "LINESTRING")

#Preparing a circle polygon
Point<- data.frame(
  Plot = c("A"),
  x = c(0),
  y = c(0))
#We convert the center of the circle in a spatial object using a CRS in meters
Point_sf <- st_as_sf(Point,
                     coords = c('x', 'y')) %>%
  st_set_crs("102010") %>%
  st_convex_hull()
#Buffer
Circle_st_18<-st_buffer(Point_sf,18)
Circle_st_17999<-st_buffer(Point_sf,17.999)

library(lwgeom)
#For each UE I do an intersect Line->Circle
B127<-Bound_lines[which(Bound_lines$UE==127),]
plot(B127)
Split_127<-st_split(Circle_st_18,B127)
plot(Split_127)
Split_127_2<-st_split(Circle_st_17999,B127)
plot(Split_127_2)
Poly_127 <- (Split_127 %>% st_collection_extract(c("POLYGON")))
st_area(Poly_127)
B128<-Bound_lines[which(Bound_lines$UE==128),]
plot(B128)
Split_128<-st_split(Circle_st_18,B128)
plot(Split_128)
Split_128_2<-st_split(Circle_st_17999,B128)
plot(Split_128_2)
Poly_128 <- (Split_128 %>% st_collection_extract(c("POLYGON")))
st_area(Poly_128)
B129<-Bound_lines[which(Bound_lines$UE==129),]
plot(B129)
Split_129<-st_split(Circle_st_18,B129)
plot(Split_129)
Poly_129 <- (Split_129 %>% st_collection_extract(c("POLYGON")))
st_area(Poly_129)
Split_129_2<-st_split(Circle_st_17999,B129)
plot(Split_129_2)
</code>```

Body:
I have a dataset in polar coordinates.
The dataset contains the coordinates of points that I cast in lines.
Then I want to intersect these lines with a circle. From the polar coordinates, you can see that the Boundary of the line is always 18 (which is also the limit of the circle).
In order to do the intersect I convert Polar coordinates to cartesian.
In the end, only some of the lines correctly intersect the circle, and I do not know why.
What works for me is a Not So Elegant Solution: I reduce the circle radius from 18 to 17.999. This works and I suppose that it is because the conversion from polar to cartesian is not 100%. For my purpose, the solution I found is enough, but I want to report it here (I do not know if this is a bug or I made some mistake),

Here is the reproducible example (with plots):

#My Dataset
Boundaries<- data.frame(UE = c(127,127,128,128,128,129,129,129,129,129),
                    ID_Line = c(1,1,1,1,1,1,1,1,2,2),
                    ID_Point = c(1,2,1,2,3,1,2,3,1,2),
                    Azimut = c(10,120,120,90,230,120,90,230,90,270),
                    Distance = c(18,18,18,5,18,18,5,18,5,18)
                    )

library(tidyverse)
library(useful)

#Polar to Cartesian coordinates conversion
Boundariesxy<-as_tibble(Boundaries) %>%
  mutate(Theta = 2*pi*Azimut/360,
         x = pol2cart(Distance, Theta, degrees=F)[["y"]],
         y = pol2cart(Distance, Theta, degrees=F)[["x"]])

library(sf)
#Conversion to sf object
Boundaries_sf <- st_as_sf(Boundariesxy,
                          coords = c('x', 'y')) %>%
  st_set_crs("102010")  %>%
  group_by(UE, ID_Line)  %>%
  summarise() %>%
  ungroup()

#Cast as Linestring
Bound_lines <- st_cast(Boundaries_sf, "LINESTRING")

#Preparing a circle polygon
Point<- data.frame(
  Plot = c("A"),
  x = c(0),
  y = c(0))
#We convert the center of the circle in a spatial object using a CRS in meters
Point_sf <- st_as_sf(Point,
                     coords = c('x', 'y')) %>%
  st_set_crs("102010") %>%
  st_convex_hull()
#Buffer
Circle_st_18<-st_buffer(Point_sf,18)
Circle_st_17999<-st_buffer(Point_sf,17.999)

library(lwgeom)
#For each UE I do an intersect Line->Circle
B127<-Bound_lines[which(Bound_lines$UE==127),]
plot(B127)
Split_127<-st_split(Circle_st_18,B127)
plot(Split_127)
Split_127_2<-st_split(Circle_st_17999,B127)
plot(Split_127_2)
Poly_127 <- (Split_127 %>% st_collection_extract(c("POLYGON")))
st_area(Poly_127)
B128<-Bound_lines[which(Bound_lines$UE==128),]
plot(B128)
Split_128<-st_split(Circle_st_18,B128)
plot(Split_128)
Split_128_2<-st_split(Circle_st_17999,B128)
plot(Split_128_2)
Poly_128 <- (Split_128 %>% st_collection_extract(c("POLYGON")))
st_area(Poly_128)
B129<-Bound_lines[which(Bound_lines$UE==129),]
plot(B129)
Split_129<-st_split(Circle_st_18,B129)
plot(Split_129)
Poly_129 <- (Split_129 %>% st_collection_extract(c("POLYGON")))
st_area(Poly_129)
Split_129_2<-st_split(Circle_st_17999,B129)
plot(Split_129_2)