问:
How to render multiple markers in react-native using rnmapbox/maps?
I am trying to show multiple markers in Mapbox but there is nothing provided in the library about how to do it.

I have tried Mapbox.MarkerView and Mapbox.ShapeSource and Mapbox.PointAnnotation
When there is only one cordinate, it works fine. However, for more than one, the app crashes in both iOS and Android

I have tried this code

```<code><MapboxGL.MapView
  ref={(c) => (this._map = c)}
  tintColor={'red'}
  onLongPress={this.onLongPress}
  onDidFinishLoadingMap={this.onDidFinishLoadingStyle}
  logoEnabled={false}
  compassEnabled={true}
  style={{ flex: 1 }}>
  <MapboxGL.Camera
    ref={(c) => (this.map = c)}
    zoomLevel={5}
    centerCoordinate={CENTER_COORD}
  />
  {/* <MapboxGL.MarkerView id={'hello'} coordinate={[73.20813, 22.29941]}> */}
  {/* <MapboxGL.MarkerView
  id={'hello'}
  coordinate={[latitude, longitude]}> */}
  {/* <View>
    <Text>CYZ</Text>
  </View>
</MapboxGL.MarkerView> */}
  <MapboxGL.UserLocation
    onUpdate={this.handleLocationUpdate}
    renderMode='normal'
    androidRenderMode='normal'
    visible={true}
  />
  {this.state.isFilterApplied === false
  ? this.state.recordValuesItemWithStatus.length > 0 &&
  this.state.recordValuesItemWithStatus.map((data, index) => {
    if (data[0] !== null && data.locationData[0] !== 'NaN') {
      if (
        this.isLatitude(data.locationData[0]) === true &&
        this.isLongitude(data.locationData[1]) === true
      ) {
        return (
          <MapboxGL.PointAnnotation
            ref={(ref) => (this.annotationRef = ref)}
            coordinate={data.locationData}
            key={index}
            title={data.status}
            onSelected={() => this.handleEditForm(data)}
            style={{ zIndex: 1000 }}
            id={index.toString()}>
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <View
                style={{
                  width: wp(5),
                  height: wp(5),
                  borderWidth: 1,
                  borderRadius: 40,
                  borderColor:
                    this.selectedColor[data.status.toUpperCase()],
                  backgroundColor:
                    this.selectedColor[data.status.toUpperCase()],
                }}
              />
            </View>
          </MapboxGL.PointAnnotation>
        );
      }
    }
  })
  : this.state.filteredRecordValues.length > 0 &&
  this.state.filteredRecordValues.map((data, index) => {
    if (data[0] !== null && data.locationData[0] !== 'NaN') {
      if (
        this.isLatitude(data.locationData[0]) === true &&
        this.isLongitude(data.locationData[1]) === true
      ) {
        return (
          <MapboxGL.PointAnnotation
            ref={(ref) => (this.annotationRef = ref)}
            coordinate={data.locationData}
            key={index}
            title={data.status}
            onSelected={() => this.handleEditForm(data)}
            style={{ zIndex: 1000 }}
            id={index.toString()}>
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <View
                style={{
                  width: wp(5),
                  height: wp(5),
                  borderWidth: 1,
                  borderRadius: 40,
                  borderColor:
                    this.selectedColor[data.status.toUpperCase()],
                  backgroundColor:
                    this.selectedColor[data.status.toUpperCase()],
                }}
              />
            </View>
          </MapboxGL.PointAnnotation>
        );
      }
    }
  })}
</MapboxGL.MapView>
</code>```

Body:
I am trying to show multiple markers in Mapbox but there is nothing provided in the library about how to do it.

I have tried Mapbox.MarkerView and Mapbox.ShapeSource and Mapbox.PointAnnotation
When there is only one cordinate, it works fine. However, for more than one, the app crashes in both iOS and Android

I have tried this code

<MapboxGL.MapView
  ref={(c) => (this._map = c)}
  tintColor={'red'}
  onLongPress={this.onLongPress}
  onDidFinishLoadingMap={this.onDidFinishLoadingStyle}
  logoEnabled={false}
  compassEnabled={true}
  style={{ flex: 1 }}>
  <MapboxGL.Camera
    ref={(c) => (this.map = c)}
    zoomLevel={5}
    centerCoordinate={CENTER_COORD}
  />
  {/* <MapboxGL.MarkerView id={'hello'} coordinate={[73.20813, 22.29941]}> */}
  {/* <MapboxGL.MarkerView
  id={'hello'}
  coordinate={[latitude, longitude]}> */}
  {/* <View>
    <Text>CYZ</Text>
  </View>
</MapboxGL.MarkerView> */}
  <MapboxGL.UserLocation
    onUpdate={this.handleLocationUpdate}
    renderMode='normal'
    androidRenderMode='normal'
    visible={true}
  />
  {this.state.isFilterApplied === false
  ? this.state.recordValuesItemWithStatus.length > 0 &&
  this.state.recordValuesItemWithStatus.map((data, index) => {
    if (data[0] !== null && data.locationData[0] !== 'NaN') {
      if (
        this.isLatitude(data.locationData[0]) === true &&
        this.isLongitude(data.locationData[1]) === true
      ) {
        return (
          <MapboxGL.PointAnnotation
            ref={(ref) => (this.annotationRef = ref)}
            coordinate={data.locationData}
            key={index}
            title={data.status}
            onSelected={() => this.handleEditForm(data)}
            style={{ zIndex: 1000 }}
            id={index.toString()}>
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <View
                style={{
                  width: wp(5),
                  height: wp(5),
                  borderWidth: 1,
                  borderRadius: 40,
                  borderColor:
                    this.selectedColor[data.status.toUpperCase()],
                  backgroundColor:
                    this.selectedColor[data.status.toUpperCase()],
                }}
              />
            </View>
          </MapboxGL.PointAnnotation>
        );
      }
    }
  })
  : this.state.filteredRecordValues.length > 0 &&
  this.state.filteredRecordValues.map((data, index) => {
    if (data[0] !== null && data.locationData[0] !== 'NaN') {
      if (
        this.isLatitude(data.locationData[0]) === true &&
        this.isLongitude(data.locationData[1]) === true
      ) {
        return (
          <MapboxGL.PointAnnotation
            ref={(ref) => (this.annotationRef = ref)}
            coordinate={data.locationData}
            key={index}
            title={data.status}
            onSelected={() => this.handleEditForm(data)}
            style={{ zIndex: 1000 }}
            id={index.toString()}>
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <View
                style={{
                  width: wp(5),
                  height: wp(5),
                  borderWidth: 1,
                  borderRadius: 40,
                  borderColor:
                    this.selectedColor[data.status.toUpperCase()],
                  backgroundColor:
                    this.selectedColor[data.status.toUpperCase()],
                }}
              />
            </View>
          </MapboxGL.PointAnnotation>
        );
      }
    }
  })}
</MapboxGL.MapView>


来源: stackexchange

问:
Pycord bot not responding to commands
I have a discord bot with automod and XP system. I have made discord bots before so I know how to make a command, but now it does not seem to work and I don't know why.

When I say a curse it deletes my message and everything there works fine so the on_message works, but those commands don't work. It does not give any error when I type a command, but the but doesn't respond.
Any help would be appreciated.

Here is my code:

```<code>import discord
from discord.ext import commands

# Set up the client and command prefix
intents = discord.Intents.all()  # Enable all intents
client = commands.Bot(prefix='$', intents=intents)

@client.event
async def on_ready():
    print('Bot ready')

@client.command()
async def ping(ctx):
    print("ping")
    await ctx.send('pong')

@client.event
async def on_message(message):
    # Ignore messages sent by the bot
    if message.author == client.user:
        return

    # Do some XP things
    ...

    # AutoMod things
    ...

    # Process any commands that are sent by the user
    await client.process_commands(message)
    print("processing commands")

@client.command()
async def leaderboard(ctx):
    # do something
    ...

# Start the bot
client.run('TOKEN')
</code>```

Also all intents are enabled in discord developer portal

So what I expected to happen is the program would first print Bot ready. Then I would write $ping to discord and the program would print processing commands and then print pong and say pong in discord.

What actually happened is that the program Printed Bot ready. Then I wrote $ping, the program prints processing commands. And then nothing else happens

ContentLicense: CC BY-SA 4.0

Title: Pycord bot not responding to commands

Body:
I have a discord bot with automod and XP system. I have made discord bots before so I know how to make a command, but now it does not seem to work and I don't know why.

When I say a curse it deletes my message and everything there works fine so the on_message works, but those commands don't work. It does not give any error when I type a command, but the but doesn't respond.
Any help would be appreciated.

Here is my code:

import discord
from discord.ext import commands

# Set up the client and command prefix
intents = discord.Intents.all()  # Enable all intents
client = commands.Bot(prefix='$', intents=intents)

@client.event
async def on_ready():
    print('Bot ready')

@client.command()
async def ping(ctx):
    print("ping")
    await ctx.send('pong')

@client.event
async def on_message(message):
    # Ignore messages sent by the bot
    if message.author == client.user:
        return

    # Do some XP things
    ...

    # AutoMod things
    ...

    # Process any commands that are sent by the user
    await client.process_commands(message)
    print("processing commands")

@client.command()
async def leaderboard(ctx):
    # do something
    ...

# Start the bot
client.run('TOKEN')

Also all intents are enabled in discord developer portal

So what I expected to happen is the program would first print Bot ready. Then I would write $ping to discord and the program would print processing commands and then print pong and say pong in discord.

What actually happened is that the program Printed Bot ready. Then I wrote $ping, the program prints processing commands. And then nothing else happens


问:
React Native App - Expo SDK 47 I've lost all the TV control (focus)
Since i've made the update of the expo SDK to the sdk 47 and update of all the modules, i've lost all my TV navigation. In fact the focus doesn't work anymore.

I've checked all the code, I don't see any problem. There is no problem on the debugger. I'm quite lost.

Can you help me please.

This is my App.js

```<code>import React, {useContext, useEffect} from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {Context as AuthContext, Provider as AuthProvider} from './context/authContext';
import {Context as UserContext, Provider as UserProvider} from './context/userContext';
import {GlobalizeProvider, loadCldr, loadMessages} from 'react-native-globalize';
import { globalizeRef } from './services/Globalize';
import * as fr from './locales/fr.json';
import * as en from './locales/en.json';
import LoginScreen from "./screens/LoginScreen";
import BroadcastScreen from "./screens/BroadcastScreen";
import AnimatorListScreen from "./screens/AnimatorListScreen";
import SettingsScreen from "./screens/SettingsScreen";
import EntrantScreen from "./screens/EntrantScreen";
import SplashScreen from "./screens/SplashScreen";

loadCldr(
    require('react-native-globalize/locale-data/fr'),
    require('react-native-globalize/locale-data/en'),
);
loadMessages({fr, en});

const Stack = createStackNavigator();

const Animator = createStackNavigator();
const AnimatorStack = () => {
    return (
        <Animator.Navigator initialRouteName="List" screenOptions={{headerShown: false}}>
            <Animator.Screen name="List" component={AnimatorListScreen} />
            <Animator.Screen name="Broadcast" component={BroadcastScreen} options={{ headerShown: false }} />
            <Animator.Screen name="Settings" component={SettingsScreen} />
        </Animator.Navigator>
    )
}

const Entrant = createStackNavigator();
const EntrantStack = () => {
    return (
        <Entrant.Navigator initialRouteName="Enter" screenOptions={{headerShown: false}}>
            <Entrant.Screen name="Enter" component={EntrantScreen} options={{ headerShown: false }} />
            <Entrant.Screen name="Settings" component={SettingsScreen} />
        </Entrant.Navigator>
    )
}

const App = () => {
    const {state: authState, restoreInfos} = useContext(AuthContext);
    const {state: userState, restoreLanguage} = useContext(UserContext);

    useEffect(() => {
        restoreInfos();
        restoreLanguage();
    }, []);

    return (
        (authState.loading || !userState.language) ?
            // We haven't finished checking for the token yet
            <Stack.Screen name="Splash" component={SplashScreen} /> :
            <GlobalizeProvider ref={globalizeRef} locale={userState.language}>
                <NavigationContainer>
                    <Stack.Navigator>
                        {(authState.token == null || authState.userType == null) ?
                            <Stack.Screen name="SignIn" component={LoginScreen} options={{ headerShown: false }} /> :
                            authState.userType === 'showman' ?
                                <Stack.Screen name="Showman" component={AnimatorStack} options={{ headerShown: false }} /> :
                                <Stack.Screen name="Entrant" component={AnimatorStack} options={{ headerShown: false }} />
                        }
                    </Stack.Navigator>
                </NavigationContainer>
            </GlobalizeProvider>
    );
}

export default () => {
    return (
        <AuthProvider>
            <UserProvider>
                <App />
            </UserProvider>
        </AuthProvider>
    )
}

</code>```

And one of my screen :

```<code>
import React, {useContext, useEffect, useRef, useState} from 'react';
import {Animated, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {Context as UserContext} from "../context/userContext";
import WebView from "react-native-webview";
import {LongPressGestureHandler, State as gestureState} from 'react-native-gesture-handler';
import {useGlobalize} from "react-native-globalize";
import {Ionicons} from '@expo/vector-icons';
import {useNavigation} from "@react-navigation/native";
import Colours from "../constants/Colours";
import Loader from "../components/Loader";

const EntrantScreen = () => {
    const navigation = useNavigation();
    const {formatMessage} = useGlobalize();
    const {state: userState, getChosenAnimation} = useContext(UserContext);
    const [reload, setReload] = useState(0);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        setLoading(true);
        getChosenAnimation().finally(() => {
            setLoading(false);
        });
    }, [reload]);

    const reloadNow = () => {
        setReload(reload + 1);
    }

    const goToSettings = () => {
        navigation.navigate('Settings');
    }

    const opacityHandler = useRef(new Animated.Value(0)).current;

    const fadeIn = () => {
        // Will change fadeAnim value to 1 in 5 seconds
        Animated.timing(opacityHandler, {
            toValue: 1,
            duration: 500,
            useNativeDriver: true
        }).start();

        setTimeout(() => {
            Animated.timing(opacityHandler, {
                toValue: 0,
                duration: 500,
                useNativeDriver: true
            }).start();
        }, 3000);
    };

    const runFirst = "window.oncontextmenu = function(event) {\n" +
        "     event.preventDefault();\n" +
        "     event.stopPropagation();\n" +
        "     return false;\n" +
        "};" +
        "document.onselectstart = new Function (\"return false\");" +
        "document.documentElement.style.property = 'user-select:none;';" +
        "document.getElementsByClassName('aha-footer')[0].remove();";

    return (
        <View style={styles.mainView}>
            {loading && <Loader />}
            { userState.chosenAnimation &&
            <View style={styles.mainView}>
                <LongPressGestureHandler
                    minDurationMs={5000}
                    onHandlerStateChange={({nativeEvent}) => {
                        if (nativeEvent.state === gestureState.ACTIVE) {
                            fadeIn();
                        }
                    }}>
                    <View style={styles.actionCaller}><></></View>
                </LongPressGestureHandler>

                <Animated.View style={{...styles.actionButtonHandler, opacity: (opacityHandler || 0)}}>
                    <TouchableOpacity onPress={() => reloadNow()}>
                        <Ionicons style={{color: Colours.bleu}} name="reload" size={48} />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => goToSettings()}>
                        <Ionicons style={{color: Colours.bleu}} name="settings-outline" size={48} />
                    </TouchableOpacity>
                </Animated.View>

                <WebView
                    style={styles.container}
                    source={{uri: userState.chosenAnimation.entrant_link}}
                    injectedJavaScript={runFirst}
                />
            </View>
            }
            {!loading && !userState.chosenAnimation &&
            <View style={styles.viewNoAnim}>
                <Text style={styles.textNoAnim}>{formatMessage('noChosenAnim')}</Text>
                <View style={styles.viewIconsNoAnim}>
                    <TouchableOpacity style={styles.iconsNoAnim} onPress={() => reloadNow()}>
                        <Ionicons style={{color: Colours.bleu}} name="reload" size={48} />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.iconsNoAnim} onPress={() => goToSettings()}>
                        <Ionicons style={{color: Colours.bleu}} name="settings-outline" size={48} />
                    </TouchableOpacity>
                </View>
            </View>
            }
        </View>
    )
}

const styles = StyleSheet.create({
    mainView: {
        flex: 1
    },
    actionCaller: {
        width: 50,
        height: 80,
        position: 'absolute',
        left: 0,
        top: 0,
        backgroundColor: 'transparent',
        zIndex: 2,
        opacity: 0.1
    },
    actionButtonHandler: {
        width: 80,
        height: '100%',
        position: 'absolute',
        left: 0,
        top: 0,
        justifyContent: 'space-evenly',
        alignItems: 'center',
        zIndex: 2
    },
    viewNoAnim: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    viewIconsNoAnim: {
        flexDirection: 'row',
    },
    iconsNoAnim: {
        margin: 10
    },
    textNoAnim: {
        fontSize: 24
    }
});

export default EntrantScreen;
</code>```

Thanks a lot for your help.

Body:
Since i've made the update of the expo SDK to the sdk 47 and update of all the modules, i've lost all my TV navigation. In fact the focus doesn't work anymore.

I've checked all the code, I don't see any problem. There is no problem on the debugger. I'm quite lost.

Can you help me please.

This is my App.js

import React, {useContext, useEffect} from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {Context as AuthContext, Provider as AuthProvider} from './context/authContext';
import {Context as UserContext, Provider as UserProvider} from './context/userContext';
import {GlobalizeProvider, loadCldr, loadMessages} from 'react-native-globalize';
import { globalizeRef } from './services/Globalize';
import * as fr from './locales/fr.json';
import * as en from './locales/en.json';
import LoginScreen from "./screens/LoginScreen";
import BroadcastScreen from "./screens/BroadcastScreen";
import AnimatorListScreen from "./screens/AnimatorListScreen";
import SettingsScreen from "./screens/SettingsScreen";
import EntrantScreen from "./screens/EntrantScreen";
import SplashScreen from "./screens/SplashScreen";

loadCldr(
    require('react-native-globalize/locale-data/fr'),
    require('react-native-globalize/locale-data/en'),
);
loadMessages({fr, en});

const Stack = createStackNavigator();

const Animator = createStackNavigator();
const AnimatorStack = () => {
    return (
        <Animator.Navigator initialRouteName="List" screenOptions={{headerShown: false}}>
            <Animator.Screen name="List" component={AnimatorListScreen} />
            <Animator.Screen name="Broadcast" component={BroadcastScreen} options={{ headerShown: false }} />
            <Animator.Screen name="Settings" component={SettingsScreen} />
        </Animator.Navigator>
    )
}

const Entrant = createStackNavigator();
const EntrantStack = () => {
    return (
        <Entrant.Navigator initialRouteName="Enter" screenOptions={{headerShown: false}}>
            <Entrant.Screen name="Enter" component={EntrantScreen} options={{ headerShown: false }} />
            <Entrant.Screen name="Settings" component={SettingsScreen} />
        </Entrant.Navigator>
    )
}

const App = () => {
    const {state: authState, restoreInfos} = useContext(AuthContext);
    const {state: userState, restoreLanguage} = useContext(UserContext);

    useEffect(() => {
        restoreInfos();
        restoreLanguage();
    }, []);

    return (
        (authState.loading || !userState.language) ?
            // We haven't finished checking for the token yet
            <Stack.Screen name="Splash" component={SplashScreen} /> :
            <GlobalizeProvider ref={globalizeRef} locale={userState.language}>
                <NavigationContainer>
                    <Stack.Navigator>
                        {(authState.token == null || authState.userType == null) ?
                            <Stack.Screen name="SignIn" component={LoginScreen} options={{ headerShown: false }} /> :
                            authState.userType === 'showman' ?
                                <Stack.Screen name="Showman" component={AnimatorStack} options={{ headerShown: false }} /> :
                                <Stack.Screen name="Entrant" component={AnimatorStack} options={{ headerShown: false }} />
                        }
                    </Stack.Navigator>
                </NavigationContainer>
            </GlobalizeProvider>
    );
}

export default () => {
    return (
        <AuthProvider>
            <UserProvider>
                <App />
            </UserProvider>
        </AuthProvider>
    )
}

And one of my screen :

import React, {useContext, useEffect, useRef, useState} from 'react';
import {Animated, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {Context as UserContext} from "../context/userContext";
import WebView from "react-native-webview";
import {LongPressGestureHandler, State as gestureState} from 'react-native-gesture-handler';
import {useGlobalize} from "react-native-globalize";
import {Ionicons} from '@expo/vector-icons';
import {useNavigation} from "@react-navigation/native";
import Colours from "../constants/Colours";
import Loader from "../components/Loader";

const EntrantScreen = () => {
    const navigation = useNavigation();
    const {formatMessage} = useGlobalize();
    const {state: userState, getChosenAnimation} = useContext(UserContext);
    const [reload, setReload] = useState(0);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        setLoading(true);
        getChosenAnimation().finally(() => {
            setLoading(false);
        });
    }, [reload]);

    const reloadNow = () => {
        setReload(reload + 1);
    }

    const goToSettings = () => {
        navigation.navigate('Settings');
    }

    const opacityHandler = useRef(new Animated.Value(0)).current;

    const fadeIn = () => {
        // Will change fadeAnim value to 1 in 5 seconds
        Animated.timing(opacityHandler, {
            toValue: 1,
            duration: 500,
            useNativeDriver: true
        }).start();

        setTimeout(() => {
            Animated.timing(opacityHandler, {
                toValue: 0,
                duration: 500,
                useNativeDriver: true
            }).start();
        }, 3000);
    };

    const runFirst = "window.oncontextmenu = function(event) {\n" +
        "     event.preventDefault();\n" +
        "     event.stopPropagation();\n" +
        "     return false;\n" +
        "};" +
        "document.onselectstart = new Function (\"return false\");" +
        "document.documentElement.style.property = 'user-select:none;';" +
        "document.getElementsByClassName('aha-footer')[0].remove();";

    return (
        <View style={styles.mainView}>
            {loading && <Loader />}
            { userState.chosenAnimation &&
            <View style={styles.mainView}>
                <LongPressGestureHandler
                    minDurationMs={5000}
                    onHandlerStateChange={({nativeEvent}) => {
                        if (nativeEvent.state === gestureState.ACTIVE) {
                            fadeIn();
                        }
                    }}>
                    <View style={styles.actionCaller}><></></View>
                </LongPressGestureHandler>

                <Animated.View style={{...styles.actionButtonHandler, opacity: (opacityHandler || 0)}}>
                    <TouchableOpacity onPress={() => reloadNow()}>
                        <Ionicons style={{color: Colours.bleu}} name="reload" size={48} />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => goToSettings()}>
                        <Ionicons style={{color: Colours.bleu}} name="settings-outline" size={48} />
                    </TouchableOpacity>
                </Animated.View>

                <WebView
                    style={styles.container}
                    source={{uri: userState.chosenAnimation.entrant_link}}
                    injectedJavaScript={runFirst}
                />
            </View>
            }
            {!loading && !userState.chosenAnimation &&
            <View style={styles.viewNoAnim}>
                <Text style={styles.textNoAnim}>{formatMessage('noChosenAnim')}</Text>
                <View style={styles.viewIconsNoAnim}>
                    <TouchableOpacity style={styles.iconsNoAnim} onPress={() => reloadNow()}>
                        <Ionicons style={{color: Colours.bleu}} name="reload" size={48} />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.iconsNoAnim} onPress={() => goToSettings()}>
                        <Ionicons style={{color: Colours.bleu}} name="settings-outline" size={48} />
                    </TouchableOpacity>
                </View>
            </View>
            }
        </View>
    )
}

const styles = StyleSheet.create({
    mainView: {
        flex: 1
    },
    actionCaller: {
        width: 50,
        height: 80,
        position: 'absolute',
        left: 0,
        top: 0,
        backgroundColor: 'transparent',
        zIndex: 2,
        opacity: 0.1
    },
    actionButtonHandler: {
        width: 80,
        height: '100%',
        position: 'absolute',
        left: 0,
        top: 0,
        justifyContent: 'space-evenly',
        alignItems: 'center',
        zIndex: 2
    },
    viewNoAnim: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    viewIconsNoAnim: {
        flexDirection: 'row',
    },
    iconsNoAnim: {
        margin: 10
    },
    textNoAnim: {
        fontSize: 24
    }
});

export default EntrantScreen;

Thanks a lot for your help.


问:
How to create buffer of hexadecimal value from hexa string?
given the following string:

```<code>char *hexa_string= "ab010210000000000000000000000a0040890080006400950000920050050900300c3b811504a0ff2c8cf5e91740e466b219c2a3318ce80b66e1c43ba65ade66"
</code>```

how can I convert it to buffer so that any cell in the buffer will be the value of any two digits from the above string ?

I tried to do something like that:

```<code>    char *hexa_string= "ab010210000000000000000000000a0040890080006400950000920050050900300c3b811504a0ff2c8cf5e91740e466b219c2a3318ce80b66e1c43ba65ade66";
    int hexa_string_size = strlen(hexa_string);
    uint8_t hexa_buffer[64];
    char *temp = hexa_string;
    for(int i = 0; i < hexa_string_size; i++){
        sscanf(temp, "%02hhx", &hexa_buffer[i]);
        temp += 2;
    }
</code>```

but while I trying to printf the hexa_buffer I see nothing..

I want to get the following buffer:

```<code>hexa_buffer[0] = 0xab
hexa_buffer[1] = 0x01
hexa_buffer[2] = 0x02
..
</code>```

Body:
given the following string:

char *hexa_string= "ab010210000000000000000000000a0040890080006400950000920050050900300c3b811504a0ff2c8cf5e91740e466b219c2a3318ce80b66e1c43ba65ade66"

how can I convert it to buffer so that any cell in the buffer will be the value of any two digits from the above string ?

I tried to do something like that:

    char *hexa_string= "ab010210000000000000000000000a0040890080006400950000920050050900300c3b811504a0ff2c8cf5e91740e466b219c2a3318ce80b66e1c43ba65ade66";
    int hexa_string_size = strlen(hexa_string);
    uint8_t hexa_buffer[64];
    char *temp = hexa_string;
    for(int i = 0; i < hexa_string_size; i++){
        sscanf(temp, "%02hhx", &hexa_buffer[i]);
        temp += 2;
    }

but while I trying to printf the hexa_buffer I see nothing..

I want to get the following buffer:

hexa_buffer[0] = 0xab
hexa_buffer[1] = 0x01
hexa_buffer[2] = 0x02
..


问:
clean method not called in modelform

As written in the title, the form gets validated whatever happens, I don't understand why are my clean and clean_ methods are not called. Used forms for quite some time but here I am puzzled on what I am forgetting.

Thanks
```<code>simplified forms.py

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ["workcity", "post_address", "billing_address", "country", "phone"]

        def clean(self):
                #not called
                cleaned_data = super().clean()
                billing_address = cleaned_data.get('billing_address')
                post_address= cleaned_data.get('post_adress')

                if not billing_address == post_address:
                    do some raising validation error

        def clean_workcity(self, *args, **kwargs):
            #not called
            workcity= self.cleaned_data.get("workcity")
            if xxx:
               do some raising validation error

            return workcity

</code>```
```<code>simplified  views.py

def profileform(request):

    if request.method =='POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            messages.success(request, 'Profile created successfully')
            return redirect('profile')
        else :
            handle errors
    else:
        form = ProfileForm()

    return render(request, "CORE/home.html", {"form": form})
</code>```

Title: clean method not called in modelform

Body:
As written in the title, the form gets validated whatever happens, I don't understand why are my clean and clean_ methods are not called. Used forms for quite some time but here I am puzzled on what I am forgetting.

Thanks

simplified forms.py

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ["workcity", "post_address", "billing_address", "country", "phone"]

        def clean(self):
                #not called
                cleaned_data = super().clean()
                billing_address = cleaned_data.get('billing_address')
                post_address= cleaned_data.get('post_adress')

                if not billing_address == post_address:
                    do some raising validation error

        def clean_workcity(self, *args, **kwargs):
            #not called
            workcity= self.cleaned_data.get("workcity")
            if xxx:
               do some raising validation error

            return workcity

simplified  views.py

def profileform(request):

    if request.method =='POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            messages.success(request, 'Profile created successfully')
            return redirect('profile')
        else :
            handle errors
    else:
        form = ProfileForm()

    return render(request, "CORE/home.html", {"form": form})


问:
How to create Generic Method which returns named ValueTuple in c#
I want to create a generic method which returns named TupleValue. Here is my code:

```<code>        public static void SetIndex<T>()
        {
            T tuple = default(T);
            var t = tuple.GetType();
            var isTuple = t.BaseType == typeof(ValueTuple).BaseType;
            if (isTuple)
            {
                var fields = t.GetFields();
                object tuple_ = tuple;
                foreach (var field in fields)
                {
                    field.SetValue(tuple_, "A");
                }

                //var f = t.GetField("Item1");
                //f.SetValue(tuple_, "X");
                tuple = (T)tuple_;
            }

            T x = tuple;

        }
</code>```

I call it as follows: SetIndex<(string str1, string str2)>(); The only problem is that the tuple is not named, so the field names are still Item1 and Item2. What should I change here?

Body:
I want to create a generic method which returns named TupleValue. Here is my code:

        public static void SetIndex<T>()
        {
            T tuple = default(T);
            var t = tuple.GetType();
            var isTuple = t.BaseType == typeof(ValueTuple).BaseType;
            if (isTuple)
            {
                var fields = t.GetFields();
                object tuple_ = tuple;
                foreach (var field in fields)
                {
                    field.SetValue(tuple_, "A");
                }

                //var f = t.GetField("Item1");
                //f.SetValue(tuple_, "X");
                tuple = (T)tuple_;
            }

            T x = tuple;

        }

I call it as follows: SetIndex<(string str1, string str2)>(); The only problem is that the tuple is not named, so the field names are still Item1 and Item2. What should I change here?


问:
startActivityForResult Deprecated in java
i got an error in this code i.e. on gallery and take foto. the error code is startActivityForResult Deprecated</p>
```<code>            @Override
            public void onClick(View view) {
                if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, 3);
                } else {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                }
            }
        });
        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(cameraIntent, 1);
            }
        });
    }

</code>```

Body:
i got an error in this code i.e. on gallery and take foto. the error code is startActivityForResult Deprecated

            @Override
            public void onClick(View view) {
                if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, 3);
                } else {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                }
            }
        });
        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(cameraIntent, 1);
            }
        });
    }


问:
Using port 80 for airflow in AWS ECS
I am trying to deploy airflow webserver in ECS. I am using the default airflow docker container. I have tried to run the airflow webserver in port 80 by setting

```<code>AIRFLOW__WEBSERVER__WEB_SERVER_PORT = 80
</code>```

However it provides an error gunicorn can't connect to port 80.

It works perfectly however if I use port 8080. Does airflow webserver use port 80 for something already?

Title: Using port 80 for airflow in AWS ECS

Body:
I am trying to deploy airflow webserver in ECS. I am using the default airflow docker container. I have tried to run the airflow webserver in port 80 by setting

AIRFLOW__WEBSERVER__WEB_SERVER_PORT = 80

However it provides an error gunicorn can't connect to port 80.

It works perfectly however if I use port 8080. Does airflow webserver use port 80 for something already?


问:
How does swagger present the DateTime type as having no nested properties?
I was wondering how we could make a class/struct appear to be a value type, rather than have multiple nested properties using C#/.NET Core and Swagger

For example, the image shows the DateTime struct be presented as "date": "20022-12-18T13:28:42.409Z"

I have tried to replicate this presentation with the other properties in the attached image by using classes, structs with various public or private properties. My guess would be something to do with either Swagger configuration or operator overloads.

Thanks.


问:
Firebase Functions Emulator ignores environment variables in .env file, prompts "Enter a string value for {ENV_KEY}"
After upgrading Firebase CLI tools to version 11.15.0 (needed for NodeJS 18), my local Firebase Emulator ignores the environment variables defined in ./functions/.env or ./functions/.env.dev (when dev is aliased to the project ID).

```<code>firebase emulators:start
</code>```

...prompts me to:

```<code>"Enter a string value for {ENV_KEY}: "
</code>```

...even if that environment variable is defined in .env.

Piping env vars into emulator stops it from happening:

```<code>env $(cat ./functions/.env) | firebase emulators:start
</code>```

On a previous version the same .env file worked fine. I have tried adding an alias, with same results. Secrets in ./functions/.secret.local (same format as .env) are being picked up.

Why is the Firebase Emulator ignoring my .env file or this is a regression?

Body:
After upgrading Firebase CLI tools to version 11.15.0 (needed for NodeJS 18), my local Firebase Emulator ignores the environment variables defined in ./functions/.env or ./functions/.env.dev (when dev is aliased to the project ID).

firebase emulators:start

...prompts me to:

"Enter a string value for {ENV_KEY}: "

...even if that environment variable is defined in .env.

Piping env vars into emulator stops it from happening:

env $(cat ./functions/.env) | firebase emulators:start

On a previous version the same .env file worked fine. I have tried adding an alias, with same results. Secrets in ./functions/.secret.local (same format as .env) are being picked up.

Why is the Firebase Emulator ignoring my .env file or this is a regression?


问:
Proper way to define sequelize model interface so it can be used elsewhere
I am trying to use a Quest Model interface as a type interface. But the way I am defining it seems to send back ALL of the Sequelize interface fields. I want to be able to use the type interface from Quest instead of having to define interface IQuest for example and importing that instead, how do I go about doing that?

Quest Model

lass Quest extends Model<
  InferAttributes<Quest>,
  InferCreationAttributes<Quest>
> {
  declare id: number;
  navigator_class_title!: string;
  navigator_class_id!: string;
  navigator_lesson_id!: string;
  navigator_unit_id!: string;
  navigator_course_id!: string;
  navigator_milestone_id!: string;
  navigator_grade_seq!: string;
  navigator_grade_name!: string;
  subject!: string;
  title!: string;
  static Objective: any;
  static UserQuest: any;
}

Quest.init(
  {
    // Model attributes are defined here
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },

    navigator_class_id: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    navigator_class_title: { type: DataTypes.STRING, allowNull: false },
    navigator_lesson_id: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    navigator_unit_id: { type: DataTypes.STRING, allowNull: false },
    navigator_course_id: { type: DataTypes.STRING, allowNull: false },
    navigator_milestone_id: { type: DataTypes.STRING, allowNull: false },
    navigator_grade_seq: { type: DataTypes.STRING, allowNull: false },
    navigator_grade_name: { type: DataTypes.STRING, allowNull: false },
    subject: { type: DataTypes.STRING, allowNull: false },
    title: { type: DataTypes.STRING, allowNull: false },
    repeatable: { type: DataTypes.BOOLEAN, defaultValue: false },
  },
  {
    underscored: true,
    sequelize,
    modelName: "quest",
  }
);

Quest.Objective = Quest.hasMany(Objective);
Quest.UserQuest = Quest.hasMany(UserQuest);

export default Quest;

```
<p>I am defining the following function,</p>
<pre class="lang-js prettyprint-override"><code>import Quest from "../models/quest";

...

async convertJourneyToQuestBody(
    learningJourney: ILearningJourney
  ): Promise<Quest> { <======= Defining return value as type Quest from model
    try {
      let questObject = null;
      const { milestone_id, class_info, subject, grade_name, grade_seq } =
        learningJourney;

      for (let lesson of learningJourney.lessons) {
        questObject = {
          title: lesson.title,
          subject: subject,
          navigator_milestone_id: milestone_id,
          navigator_class_id: class_info.class_id,
          navigator_class_title: class_info.class_title,
          navigator_lesson_id: lesson.lesson_id,
          navigator_unit_id: lesson.unit_id,
          navigator_course_id: lesson.course_id,
          navigator_grade_name: grade_name,
          navigator_grade_seq: grade_seq,
        };

        const objectiveList = lesson.collection_summary.map(
          (collectionItem) => {
            return {
              title: collectionItem.title,
              navigator_collection_id: collectionItem.id,
              objective_description: collectionItem.learning_objective,
            };
          }
        );
        // Naming field "objectives" because we will include it when creating the Quest as a whole
        Object.assign(questObject, { objectives: objectiveList });
      }
      if (questObject) return questObject;
      else throw { message: "Whoops, look like we hit a snag" };
    } catch (e) {
      throw e;
    }
  }

</code>```

Body:
I am trying to use a Quest Model interface as a type interface. But the way I am defining it seems to send back ALL of the Sequelize interface fields. I want to be able to use the type interface from Quest instead of having to define interface IQuest for example and importing that instead, how do I go about doing that?

Quest Model

lass Quest extends Model<
  InferAttributes<Quest>,
  InferCreationAttributes<Quest>
> {
  declare id: number;
  navigator_class_title!: string;
  navigator_class_id!: string;
  navigator_lesson_id!: string;
  navigator_unit_id!: string;
  navigator_course_id!: string;
  navigator_milestone_id!: string;
  navigator_grade_seq!: string;
  navigator_grade_name!: string;
  subject!: string;
  title!: string;
  static Objective: any;
  static UserQuest: any;
}

Quest.init(
  {
    // Model attributes are defined here
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },

    navigator_class_id: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    navigator_class_title: { type: DataTypes.STRING, allowNull: false },
    navigator_lesson_id: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    navigator_unit_id: { type: DataTypes.STRING, allowNull: false },
    navigator_course_id: { type: DataTypes.STRING, allowNull: false },
    navigator_milestone_id: { type: DataTypes.STRING, allowNull: false },
    navigator_grade_seq: { type: DataTypes.STRING, allowNull: false },
    navigator_grade_name: { type: DataTypes.STRING, allowNull: false },
    subject: { type: DataTypes.STRING, allowNull: false },
    title: { type: DataTypes.STRING, allowNull: false },
    repeatable: { type: DataTypes.BOOLEAN, defaultValue: false },
  },
  {
    underscored: true,
    sequelize,
    modelName: "quest",
  }
);

Quest.Objective = Quest.hasMany(Objective);
Quest.UserQuest = Quest.hasMany(UserQuest);

export default Quest;

I am defining the following function,

import Quest from "../models/quest";

...

async convertJourneyToQuestBody(
    learningJourney: ILearningJourney
  ): Promise<Quest> { <======= Defining return value as type Quest from model
    try {
      let questObject = null;
      const { milestone_id, class_info, subject, grade_name, grade_seq } =
        learningJourney;

      for (let lesson of learningJourney.lessons) {
        questObject = {
          title: lesson.title,
          subject: subject,
          navigator_milestone_id: milestone_id,
          navigator_class_id: class_info.class_id,
          navigator_class_title: class_info.class_title,
          navigator_lesson_id: lesson.lesson_id,
          navigator_unit_id: lesson.unit_id,
          navigator_course_id: lesson.course_id,
          navigator_grade_name: grade_name,
          navigator_grade_seq: grade_seq,
        };

        const objectiveList = lesson.collection_summary.map(
          (collectionItem) => {
            return {
              title: collectionItem.title,
              navigator_collection_id: collectionItem.id,
              objective_description: collectionItem.learning_objective,
            };
          }
        );
        // Naming field "objectives" because we will include it when creating the Quest as a whole
        Object.assign(questObject, { objectives: objectiveList });
      }
      if (questObject) return questObject;
      else throw { message: "Whoops, look like we hit a snag" };
    } catch (e) {
      throw e;
    }
  }


问:
Spring Boot Microservice -> Docker Issue : API Gateway cannot connect to configserver (ResourceAccessException)
I have a problem about running all services on docker. The only thing which I cannot handle is related with connection problem between api gateway and configserver. Config server is based on git file based system and it fetchs all values from github repo.

When I try to run api gateway, I get this issue shown below.

```<code>Caused by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://configserver:9296/API-GATEWAY/default": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)
</code>```

Here is the related part of docker-compose.yml file

```<code>configserver:
    image: 'microservicedailybuffer/configserver:0.0.1'
    container_name: configserver
    ports:
      - '9296:9296'
    environment:
      - EUREKA_SERVER_ADDRESS=http://serviceregistry:8761/eureka
    healthcheck:
      test: [ "CMD", "curl", "-f", "http://configserver:9296/actuator/health" ]
      interval: 10s
      timeout: 5s
      retries: 5
    depends_on:
      - serviceregistry
    networks:
      - backend

  apigateway:
    image: 'microservicedailybuffer/apigateway:0.0.1'
    container_name: apigateway
    ports:
      - '9090:9090'
    environment:
      - EUREKA_SERVER_ADDRESS=http://serviceregistry:8761/eureka
      - CONFIG_SERVER_URL=configserver
      - ZIPKIN_URL=http://zipkin:9411
      - REDIS_URL=redis://redis:6379
    depends_on:
      - configserver
      - zipkin
      - redis
      - serviceregistry
    networks:
      - backend
</code>```

How can I fix the issue?

Here is the application.yml file of api gateway : Link

Here is the git based file system file : Link

Here is the docker-compose.yml file : Link

Body:
I have a problem about running all services on docker. The only thing which I cannot handle is related with connection problem between api gateway and configserver. Config server is based on git file based system and it fetchs all values from github repo.

When I try to run api gateway, I get this issue shown below.

Caused by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://configserver:9296/API-GATEWAY/default": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)

Here is the related part of docker-compose.yml file

configserver:
    image: 'microservicedailybuffer/configserver:0.0.1'
    container_name: configserver
    ports:
      - '9296:9296'
    environment:
      - EUREKA_SERVER_ADDRESS=http://serviceregistry:8761/eureka
    healthcheck:
      test: [ "CMD", "curl", "-f", "http://configserver:9296/actuator/health" ]
      interval: 10s
      timeout: 5s
      retries: 5
    depends_on:
      - serviceregistry
    networks:
      - backend

  apigateway:
    image: 'microservicedailybuffer/apigateway:0.0.1'
    container_name: apigateway
    ports:
      - '9090:9090'
    environment:
      - EUREKA_SERVER_ADDRESS=http://serviceregistry:8761/eureka
      - CONFIG_SERVER_URL=configserver
      - ZIPKIN_URL=http://zipkin:9411
      - REDIS_URL=redis://redis:6379
    depends_on:
      - configserver
      - zipkin
      - redis
      - serviceregistry
    networks:
      - backend

How can I fix the issue?

Here is the application.yml file of api gateway : Link

Here is the git based file system file : Link

Here is the docker-compose.yml file : Link


问:
Choosing from a list of dictionaries in iOS shortcuts
In the iOS Shortcuts app, I am using Get Dictionary on my x-callback return, which in fact returns many different dictionaries, which you can cycle through in Quick Look:

How do I allow the user of the shortcut to choose from the dictionaries, for example with the name field being presented to the user for each dictionary?

I imagine a Repeat with Each action is necessary - and indeed I found this answer, which appears to be out of date because I cannot seem to Get Dictionary from the the empty variable - Shortcuts won't let me.


问:
The "render" prop in the React Link element
I was wondering what is the replacement of the prop Render in the React Link element. I have to know that in order to stop the recycling methods from being called every single time I click the link multiple times.

```<code><div className="App">
  <NavBar />
  <Switch>
    <Route exact path="/" render={()=> <Home />} />
    <Route exact path="/about" element={<About />} />
    <Route exact path="/contact" element={<Contact />} />
  </Switch>
</div>
</code>```

In the console :

utils.ts:874 Matched leaf route at location "/" does not have an
element. This means it will render an  with a null value by
default resulting in an "empty" page.

Body:
I was wondering what is the replacement of the prop Render in the React Link element. I have to know that in order to stop the recycling methods from being called every single time I click the link multiple times.

  <NavBar />
  <Switch>
    <Route exact path="/" render={()=> <Home />} />
    <Route exact path="/about" element={<About />} />
    <Route exact path="/contact" element={<Contact />} />
  </Switch>

In the console :

utils.ts:874 Matched leaf route at location "/" does not have an
element. This means it will render an  with a null value by
default resulting in an "empty" page.


问:
How to publish window application with gmap?
I published a window application and using visual studio, I installed it on different computer but didn't run/open on both computers.

Before I publish it I run it in visual studio and it seem there's no problem. What can I do now?


问:
How to use the GSC API dimensionFilterGroups parameter to filter data for multiple countries?
I'd like to extract data for the USA, GBR and AUS using the GSC API but can only do it for the USA.

Can you help amend the existing code show below so it works for all 3 countries?

Best

Mark

```<code>request = {
    'startDate': '2022-01-01',
    'endDate': '2022-01-31',
    'dimensions': ['country'],
    'rowLimit': 1000,
    'dimensionFilterGroups': [{
    'filters': [
        {'dimension': 'country',
        'operators': 'equals',
        'expression': 'USA'}
    ]
}]
}

response = service.searchanalytics().query(siteUrl=SITE_URL, body=request).execute()
</code>```

Body:
I'd like to extract data for the USA, GBR and AUS using the GSC API but can only do it for the USA.

Can you help amend the existing code show below so it works for all 3 countries?

Best

Mark

request = {
    'startDate': '2022-01-01',
    'endDate': '2022-01-31',
    'dimensions': ['country'],
    'rowLimit': 1000,
    'dimensionFilterGroups': [{
    'filters': [
        {'dimension': 'country',
        'operators': 'equals',
        'expression': 'USA'}
    ]
}]
}

response = service.searchanalytics().query(siteUrl=SITE_URL, body=request).execute()


问:
sync or async for waitforexistence in XCTest?
I am new to XCTest and see the following code but get one question about waitforexistence

```<code>if aXCUIElement.waitforexistence(timeout: 60) || bXCUIElement.waitforexistence(timeout: 60) {
}
</code>```

in this case, are we waiting for one minutes to see if aXCUIElement or bXCUIElement exists? or we are waiting for one min for aXCUIElement then waiting for another 1 mins for bXCUIElement?

Body:
I am new to XCTest and see the following code but get one question about waitforexistence

if aXCUIElement.waitforexistence(timeout: 60) || bXCUIElement.waitforexistence(timeout: 60) {
}

in this case, are we waiting for one minutes to see if aXCUIElement or bXCUIElement exists? or we are waiting for one min for aXCUIElement then waiting for another 1 mins for bXCUIElement?


问:
the meaning of Time_step in Time series Data
I have an application that can generate 50 data in 1 second,which means the sampling_rate of my application is 50Hz. then theb data type is timeseries. then I make my data like below before training.

```<code>steps= 50
inp = []
out = []
for i in range(len(data_scaled_out) - (steps)):
    inp.append(data_scaled_in[i:i+steps])
    out.append(data_scaled_out[i+steps])
</code>```

Data shape is (50,89)

if I use data shape (50,89) is it the same I change the model's sampling rate to 1Hz? means that the model can only predict 1 data in 1 second? because my professor said that if I use the input shape (50.89) it is the same as me downsampling the frequency. Is that true?

Body:
I have an application that can generate 50 data in 1 second,which means the sampling_rate of my application is 50Hz. then theb data type is timeseries. then I make my data like below before training.

steps= 50
inp = []
out = []
for i in range(len(data_scaled_out) - (steps)):
    inp.append(data_scaled_in[i:i+steps])
    out.append(data_scaled_out[i+steps])

Data shape is (50,89)

if I use data shape (50,89) is it the same I change the model's sampling rate to 1Hz? means that the model can only predict 1 data in 1 second? because my professor said that if I use the input shape (50.89) it is the same as me downsampling the frequency. Is that true?


问:
Alpakka search in elasticsearch without scrolling
can someone help me how can I search without using the scroll feature inside the elastic with alpakka.

I want to use alpakka or akka-stream to reactively send a query to elastic without scrolling, But the only thing I found was "ElasticsearchSource" in alpakka, which sends search requests using scroll.

In aplakka ElasticsearchSourceSettings document there is two parameters for control scroll scan:

bufferSize => ElasticsearchSource retrieves messages from
Elasticsearch by scroll scan. This buffer size is used as the
scroll size.

scrollDuration => ElasticsearchSource retrieves messages from
Elasticsearch by scroll scan. This parameter is used as a scroll
value.

and in githup source code The only function that sends an elastic request is "sendScrollScanRequest".

Does setting these values to zero disable scroll scanning?

Is it possible to send search requests without scrolling using alpakka or akka-stream?


问:
Passing object with Vue router
I'm trying to make an edit button for an object(song). I want to pass my data to the edit form, so the input it will be completed with the actual data, but I always get undefined. I tried a lot of solutions but no one worked for me. What's the problem?

My Song Component, I am trying to pass its data to the edit form

```<code><template>
  <div class="hello">
    <h1>{{ song.name }}</h1>
    <p>Author: {{ song.author }}</p>
    <p>Views: {{ song.views }}</p>
    <!-- <button @click="$router.push('/update-song?id=' + song.id )">Update</button> -->
    <button @click="$router.push({path: '/update-song', Component: UpdateSong, props: {song: song}})">Update</button>
  </div>
</template>

<script>
export default {
  name: 'Song',
  props: {
    song: Object
  }
}
</script>
</code>```

My edit view:

```<code><template>
    <div>
        <p>Update a song: {{this.author}} - {{this.name}}</p>
        <input type="text" id="name" placeholder="Name" v-model="name"/><br/>
        <input type="text" id="author" placeholder="Author" v-model="author"/><br/>
        <input type="text" id="country" placeholder="Country" v-model="country"/><br/>
        <input type="text" id="duration" placeholder="Duration" v-model="duration"/><br/>
        <input type="text" id="views" placeholder="Views" v-model="views"/><br/>
        <input type="text" id="genre" placeholder="Genre" v-model="genre"/><br/>
        <button @click="updateSong">Update Song</button>
    </div>
</template>

<script>
export default{
    name: 'UpdateSong',
    props: {
        song: Object
    },
    mounted() {
         console.log(this.song) //undefined
     },
    data(){
        return{
            name: '',
            author: '',
            country: '',
            duration: 0,
            views: 0,
            genre: ''
        }
    },
    methods: {
        updateSong(){...}
    }
}
</script>
</code>```

My routes:

```<code>const routes = [...,
    {
        path: '/update-song',
        name: "updateSong",
        component: UpdateSong
    }
]
</code>```

Title: Passing object with Vue router

Body:
I'm trying to make an edit button for an object(song). I want to pass my data to the edit form, so the input it will be completed with the actual data, but I always get undefined. I tried a lot of solutions but no one worked for me. What's the problem?

My Song Component, I am trying to pass its data to the edit form

<template>

{{ song.name }}

Author: {{ song.author }}

Views: {{ song.views }}

    <button @click="$router.push({path: '/update-song', Component: UpdateSong, props: {song: song}})">Update</button>

</template>

My edit view:

<template>

Update a song: {{this.author}} - {{this.name}}

        <input type="text" id="name" placeholder="Name" v-model="name"/>

        <input type="text" id="author" placeholder="Author" v-model="author"/>

        <input type="text" id="country" placeholder="Country" v-model="country"/>

        <input type="text" id="duration" placeholder="Duration" v-model="duration"/>

        <input type="text" id="views" placeholder="Views" v-model="views"/>

        <input type="text" id="genre" placeholder="Genre" v-model="genre"/>

        <button @click="updateSong">Update Song</button>

</template>

My routes:

const routes = [...,
    {
        path: '/update-song',
        name: "updateSong",
        component: UpdateSong
    }
]


问:
Using if statement for 2d arrays with dtype = object in Python
I have an array for an example map layout. The array is of object dtype, which is then assigned letters to create a path ('P') for a simple garbage disposal robot example:

import numpy as np
map_example = np.zeros((6, 8), dtype = object)

```<code>for i in range(8):
    map_example[2, i] = 'P' # Assign the Pathway
map_example[3, 1] = 'L';map_example[0, 3] = 'L' # Assign the Litter
map_example[1, 3] = 'R';map_example[1, 2] = 'R' # Assign the River
map_example[2,0] = 'V' # The first path tile will already be marked as visited
</code>```
```<code>['0', '0', '0', 'L', '0', '0', '0', '0']
['0', '0', 'R', 'R', '0', '0', '0', '0']
['V', 'P', 'P', 'P', 'P', 'P', 'P', 'P']
['0', 'L', '0', '0', '0', '0', '0', '0']
['0', '0', '0', '0', '0', '0', '0', '0']
['0', '0', '0', '0', '0', '0', '0', '0']
</code>```

I have multiple arrays such as above with pre-assigned values, and I am trying to find the 'P' values inside these arrays in order to tell the path to my knowledge base for the robot.

I tried to use an if statement to check which elements are 'P' in these arrays (parklayout_array in below), and then use the locations to create a Path in my knowledge base:
`

```<code>    for x in parklayout_array[0]:
        for y in parklayout_array[1]:
           if parklayout_array[x, y] == "P":
                kb.append(Path(parklayout_array[0],parklayout_array[1]))
</code>```

`
Then I got the error below, which is, I assume because of the data type (object) of the array.

```<code>**IndexError:** only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
</code>```

What would be the correct way of using the if statement for such an example?

Body:
I have an array for an example map layout. The array is of object dtype, which is then assigned letters to create a path ('P') for a simple garbage disposal robot example:

import numpy as np
map_example = np.zeros((6, 8), dtype = object)

for i in range(8):
    map_example[2, i] = 'P' # Assign the Pathway
map_example[3, 1] = 'L';map_example[0, 3] = 'L' # Assign the Litter
map_example[1, 3] = 'R';map_example[1, 2] = 'R' # Assign the River
map_example[2,0] = 'V' # The first path tile will already be marked as visited

['0', '0', '0', 'L', '0', '0', '0', '0']
['0', '0', 'R', 'R', '0', '0', '0', '0']
['V', 'P', 'P', 'P', 'P', 'P', 'P', 'P']
['0', 'L', '0', '0', '0', '0', '0', '0']
['0', '0', '0', '0', '0', '0', '0', '0']
['0', '0', '0', '0', '0', '0', '0', '0']

I have multiple arrays such as above with pre-assigned values, and I am trying to find the 'P' values inside these arrays in order to tell the path to my knowledge base for the robot.

I tried to use an if statement to check which elements are 'P' in these arrays (parklayout_array in below), and then use the locations to create a Path in my knowledge base:
`

    for x in parklayout_array[0]:
        for y in parklayout_array[1]:
           if parklayout_array[x, y] == "P":
                kb.append(Path(parklayout_array[0],parklayout_array[1]))

`
Then I got the error below, which is, I assume because of the data type (object) of the array.

**IndexError:** only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

What would be the correct way of using the if statement for such an example?


问:
Spring/Tomcat closes the connection on exception
Recently I was debugging a problem that a client reported when they were stress-testing a spring application running in tomcat. They ran the tests, but most of the requests immediately resulted in an exception, causing a 500 response code.

At some point the client was no longer able to open new connections because the ephemeral port range was exhausted - all ports were in a TIME_WAIT state. The reason appears to be that when an exception occurs the connection is closed by either spring or tomcat.

I created a simple spring boot 2.7.6 application with a single controller, with two endpoints - /5xx which throws ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR), and /4xx
to throw ResponseStatusException(HttpStatus.BAD_REQUEST).

After requesting these endpoints, the response contains a Connection: close header, and looking at the local ports with ss the ports in TIME_WAIT get increased.

Further, requesting an endpoint that doesn't exist - doesn't close the connection and simply returns 404.

When I switched to undertow, instead of tomcat - the connection wasn't closed for all endpoints.

When I switched to spring boot 3 and tomcat - the connection isn't closed as well for all three endpoints.

So, my questions are:

What is the correct behavior? I'm thinking that the connection shouldn't be closed.

Does anyone know if this is a spring or tomcat feature and is there a configuration for this?

EDIT #1:

OS details:

Ubuntu 22.04.1 LTS

Linux 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

net.ipv4.ip_local_port_range = 1024   60999

Tomcat:

embedded tomcat v9.0.69 with default configuration provided by spring boot

the situation improves by increasing maxConnections to 30000 (default is 10000)


问:
ValueError: The truth value of a Series is ambiguous in multiple if condition
I want to apply multiple if conditions on a series and get the results of my function.
I have the following dictionary:

```<code>cardinal_Temp = ["Tbas_veg", "Topt1_veg", "Topt2_veg","Tmax_veg"]
wheat_CardTemp_vegetative = [4, 22, 28, 38]
Veg_CardTemp= dict(zip(cardinal_Temp, wheat_CardTemp_vegetative))
</code>```

And a daily temperature list with more than 400 values as:
df= pd.DataFrame(Date_MeanTemp, columns=["Date","Tmean"])
I wrote the below script to compute my function as:

```<code>def Temfunction(Tmean):
     if ((Veg_CardTemp["Tbas_veg"]<(df["Tmean"])) and ((df["Tmean"])<Veg_CardTemp["Topt1_veg"])).any():
         return  [((df["Tmean"])-Veg_CardTemp["Tbas_veg"])/(Veg_CardTemp["Topt1_veg"]-Veg_CardTemp["Tbas_veg"])]
     elif ((Veg_CardTemp["Topt1_veg"]<=(df["Tmean"])) and ((df["Tmean"])<=Veg_CardTemp["Topt2_veg"])).any():
           return 1
     elif ((Veg_CardTemp["Topt2_veg"]<(df["Tmean"])) and ((df["Tmean"])<Veg_CardTemp["Tmax_veg"])).any():
           return [(Veg_CardTemp["Tmax_veg"]-df["Tmean"])/(Veg_CardTemp["Tmax_veg"]-Veg_CardTemp["Topt2_veg"])]
     elif (((df["Tmean"])<=Veg_CardTemp["Tbas_veg"]) or ((df["Tmean"])>=Veg_CardTemp["Tmax_veg"])).any():
          return 0
function = np.vectorize(Temfunction)
Tempfunction = function(df["Tmean"])
print("final Tempfunc:", Tempfunction)
</code>```

I run to ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I tried to make a function to compute a temperature function between 0 and 1, for each day in "df" list.

Body:
I want to apply multiple if conditions on a series and get the results of my function.
I have the following dictionary:

cardinal_Temp = ["Tbas_veg", "Topt1_veg", "Topt2_veg","Tmax_veg"]
wheat_CardTemp_vegetative = [4, 22, 28, 38]
Veg_CardTemp= dict(zip(cardinal_Temp, wheat_CardTemp_vegetative))

And a daily temperature list with more than 400 values as:
df= pd.DataFrame(Date_MeanTemp, columns=["Date","Tmean"])
I wrote the below script to compute my function as:

def Temfunction(Tmean):
     if ((Veg_CardTemp["Tbas_veg"]<(df["Tmean"])) and ((df["Tmean"])<Veg_CardTemp["Topt1_veg"])).any():
         return  [((df["Tmean"])-Veg_CardTemp["Tbas_veg"])/(Veg_CardTemp["Topt1_veg"]-Veg_CardTemp["Tbas_veg"])]
     elif ((Veg_CardTemp["Topt1_veg"]<=(df["Tmean"])) and ((df["Tmean"])<=Veg_CardTemp["Topt2_veg"])).any():
           return 1
     elif ((Veg_CardTemp["Topt2_veg"]<(df["Tmean"])) and ((df["Tmean"])<Veg_CardTemp["Tmax_veg"])).any():
           return [(Veg_CardTemp["Tmax_veg"]-df["Tmean"])/(Veg_CardTemp["Tmax_veg"]-Veg_CardTemp["Topt2_veg"])]
     elif (((df["Tmean"])<=Veg_CardTemp["Tbas_veg"]) or ((df["Tmean"])>=Veg_CardTemp["Tmax_veg"])).any():
          return 0
function = np.vectorize(Temfunction)
Tempfunction = function(df["Tmean"])
print("final Tempfunc:", Tempfunction)

I run to ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I tried to make a function to compute a temperature function between 0 and 1, for each day in "df" list.


问:
Take screenshot of outer div while clicking on holding an inner element using Selenium Python
I want to take the screenshot of a product on some online ecommerce site by Selenium Python. There are many variants in one product and their corresponding image is only visible on hovering or clicking. I want to take the screenshot of the whole outer element with id="block-jIYvugZ-If" to get as much information as I could in one screenshot (shop name, rating, product price, item image...).

With the following code, it returns a screenshot but still fails to keep the selected item image in focus while screenshotting.

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(options=options)

URL = 'https://www.lazada.vn/products/hinh-xam-dan-hinh-dai-bang-bo-cap-lua-khong-tha-nuoc-lau-phai-cho-nam-va-nu-san-pham-co-nhieu-phien-ban-lua-chon-vui-long-chon-dung-san-pham-can-mua-intl-i1489534397-s6222160259.html?'
path = "./test.png"

driver.get(URL)

S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)
driver.set_window_size(S('Width'),S('Height'))
sku_img = driver.find_element(By.CLASS_NAME,"sku-variable-img-wrap-selected")
ActionChains(driver).click_and_hold(sku_img).perform()
driver.find_element(By.ID, "block-jIYvugZ-If").screenshot(path)
driver.quit()
</code>```

I got the original screenshot code from the Internet and then do some changes to adapt my case so sorry if it's messy.

Body:
I want to take the screenshot of a product on some online ecommerce site by Selenium Python. There are many variants in one product and their corresponding image is only visible on hovering or clicking. I want to take the screenshot of the whole outer element with id="block-jIYvugZ-If" to get as much information as I could in one screenshot (shop name, rating, product price, item image...).

With the following code, it returns a screenshot but still fails to keep the selected item image in focus while screenshotting.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(options=options)

URL = 'https://www.lazada.vn/products/hinh-xam-dan-hinh-dai-bang-bo-cap-lua-khong-tha-nuoc-lau-phai-cho-nam-va-nu-san-pham-co-nhieu-phien-ban-lua-chon-vui-long-chon-dung-san-pham-can-mua-intl-i1489534397-s6222160259.html?'
path = "./test.png"

driver.get(URL)

S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)
driver.set_window_size(S('Width'),S('Height'))
sku_img = driver.find_element(By.CLASS_NAME,"sku-variable-img-wrap-selected")
ActionChains(driver).click_and_hold(sku_img).perform()
driver.find_element(By.ID, "block-jIYvugZ-If").screenshot(path)
driver.quit()

I got the original screenshot code from the Internet and then do some changes to adapt my case so sorry if it's messy.


问:
Python connection with database
I am trying to connect the database mysql to mycode but i don't know what is the problen i have treid many solution but still confuse if any body can help ?
`

```<code>e:\hotelManagnment\customer.py:38: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.LANCZOS instead.
  img2=img2.resize((100,40),Image.ANTIALIAS)
Traceback (most recent call last):
  File "e:\hotelManagnment\customer.py", line 262, in <module>
    obj=Cust_Win(root)
  File "e:\hotelManagnment\customer.py", line 212, in __init__
    self.fetch_data()
  File "e:\hotelManagnment\customer.py", line 245, in fetch_data
    conn=mysql.connector.connect(host="localhost",username="root",password="",database="managment")
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\pooling.py", line 287, in connect
    return MySQLConnection(*args, **kwargs)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\connection.py", line 137, in __init__
    self.connect(**kwargs)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\abstracts.py", line 1108, in connect
    self._open_connection()
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\connection.py", line 544, in _open_connection
    self.set_converter_class(self._converter_class)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\abstracts.py", line 1284, in set_converter_class
    self.converter = convclass(charset_name, self._use_unicode)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\conversion.py", line 136, in __init__
    MySQLConverterBase.__init__(self, charset, use_unicode, str_fallback)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\conversion.py", line 59, in __init__
    self.set_charset(charset)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\conversion.py", line 73, in set_charset
    self.charset_id = CharacterSet.get_charset_info(self.charset)[0]
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\constants.py", line 775, in get_charset_info
    info = cls.get_default_collation(charset)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\constants.py", line 746, in get_default_collation
    raise ProgrammingError(f"Character set '{charset}' unsupported")
mysql.connector.errors.ProgrammingError: Character set 'utf8' unsupported
</code>```

`

Title: Python connection with database

Body:
I am trying to connect the database mysql to mycode but i don't know what is the problen i have treid many solution but still confuse if any body can help ?
`

e:\hotelManagnment\customer.py:38: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.LANCZOS instead.
  img2=img2.resize((100,40),Image.ANTIALIAS)
Traceback (most recent call last):
  File "e:\hotelManagnment\customer.py", line 262, in <module>
    obj=Cust_Win(root)
  File "e:\hotelManagnment\customer.py", line 212, in __init__
    self.fetch_data()
  File "e:\hotelManagnment\customer.py", line 245, in fetch_data
    conn=mysql.connector.connect(host="localhost",username="root",password="",database="managment")
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\pooling.py", line 287, in connect
    return MySQLConnection(*args, **kwargs)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\connection.py", line 137, in __init__
    self.connect(**kwargs)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\abstracts.py", line 1108, in connect
    self._open_connection()
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\connection.py", line 544, in _open_connection
    self.set_converter_class(self._converter_class)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\abstracts.py", line 1284, in set_converter_class
    self.converter = convclass(charset_name, self._use_unicode)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\conversion.py", line 136, in __init__
    MySQLConverterBase.__init__(self, charset, use_unicode, str_fallback)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\conversion.py", line 59, in __init__
    self.set_charset(charset)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\conversion.py", line 73, in set_charset
    self.charset_id = CharacterSet.get_charset_info(self.charset)[0]
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\constants.py", line 775, in get_charset_info
    info = cls.get_default_collation(charset)
  File "C:\Users\hp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\mysql\connector\constants.py", line 746, in get_default_collation
    raise ProgrammingError(f"Character set '{charset}' unsupported")
mysql.connector.errors.ProgrammingError: Character set 'utf8' unsupported

`


问:
Mineflayer bot crashing after listener timeout
```<code>from javascript import require, On, Once, AsyncTask, once, off

mineflayer = require('mineflayer')
inventoryViewer = require('mineflayer-web-inventory')
item = require('prismarine-item')

# create bot
BOT_USERNAME = 'Robol'
bot = mineflayer.createBot({
    'host': 'localhost',
    'port': 55337,
    'username': BOT_USERNAME,
    'hideErrors': False,
    'version': '1.18.1'})

inventoryViewer(bot)

@On(bot, 'chat')
def handle(this, sender, message, *args):
    if sender == BOT_USERNAME:
        return

    msg = message.split()

    if message.startswith('.stop'):
        bot.end()
    if message.startswith('.tph'):
        teleport(sender)
    if message.startswith('.dig'):
        dig_down()
    if message.startswith('.drop'):
        if len(msg) > 1:
            drop(msg[1])
        else:
            drop(1)

def blockUnder(playerName):
    if playerName == BOT_USERNAME:
        return bot.blockAt(bot.entity.position.offset(0, -1, 0))
    else:
        return bot.blockAt(bot.players[playerName].entity.position.offset(0, -1, 0))

def teleport(playerName):
    if playerName in bot.players:
        if blockUnder(playerName).displayName == 'Air':
            bot.chat('You have to stand on the ground')
        else:
            bot.chat(f'/tp {playerName}')
    else:
        bot.chat('No entity was found')

def dig_down():
    try:
        while bot.canDigBlock(blockUnder(BOT_USERNAME)):
            bot.dig(blockUnder(BOT_USERNAME))

        bot.chat("Can't dig deeper")
    except Exception:
        bot.chat("Stopped digging")
</code>```

^^^^
This throws:

```<code>[JSE] C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:149
[JSE]       throw new BridgeException(`Attempt to access '${stack.join('.')}' failed.`)
[JSE]             ^
[JSE]
[JSE] BridgeException [Error]: Attempt to access '' failed. Python didn't respond in time (100000ms), look above for any Python errors. If no errors, the API call hung.
[JSE]     at C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:149:13
[JSE]     at waitFor (C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:46:26)
[JSE]     at async PyBridge.call (C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:148:18)
[JSE]
[JSE] Node.js v18.12.1

Process finished with exit code 0
</code>```

After sending a message in chat while bot is digging

What is the problem here and how to break from loop like in dig_down() with a chat command

Body:
from javascript import require, On, Once, AsyncTask, once, off

mineflayer = require('mineflayer')
inventoryViewer = require('mineflayer-web-inventory')
item = require('prismarine-item')

# create bot
BOT_USERNAME = 'Robol'
bot = mineflayer.createBot({
    'host': 'localhost',
    'port': 55337,
    'username': BOT_USERNAME,
    'hideErrors': False,
    'version': '1.18.1'})

inventoryViewer(bot)

@On(bot, 'chat')
def handle(this, sender, message, *args):
    if sender == BOT_USERNAME:
        return

    msg = message.split()

    if message.startswith('.stop'):
        bot.end()
    if message.startswith('.tph'):
        teleport(sender)
    if message.startswith('.dig'):
        dig_down()
    if message.startswith('.drop'):
        if len(msg) > 1:
            drop(msg[1])
        else:
            drop(1)

def blockUnder(playerName):
    if playerName == BOT_USERNAME:
        return bot.blockAt(bot.entity.position.offset(0, -1, 0))
    else:
        return bot.blockAt(bot.players[playerName].entity.position.offset(0, -1, 0))

def teleport(playerName):
    if playerName in bot.players:
        if blockUnder(playerName).displayName == 'Air':
            bot.chat('You have to stand on the ground')
        else:
            bot.chat(f'/tp {playerName}')
    else:
        bot.chat('No entity was found')

def dig_down():
    try:
        while bot.canDigBlock(blockUnder(BOT_USERNAME)):
            bot.dig(blockUnder(BOT_USERNAME))

        bot.chat("Can't dig deeper")
    except Exception:
        bot.chat("Stopped digging")

^^^^
This throws:

[JSE] C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:149
[JSE]       throw new BridgeException(`Attempt to access '${stack.join('.')}' failed.`)
[JSE]             ^
[JSE]
[JSE] BridgeException [Error]: Attempt to access '' failed. Python didn't respond in time (100000ms), look above for any Python errors. If no errors, the API call hung.
[JSE]     at C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:149:13
[JSE]     at waitFor (C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:46:26)
[JSE]     at async PyBridge.call (C:\Users\BigGay\PycharmProjects\BOT\venv\lib\site-packages\javascript\js\pyi.js:148:18)
[JSE]
[JSE] Node.js v18.12.1

Process finished with exit code 0

After sending a message in chat while bot is digging

What is the problem here and how to break from loop like in dig_down() with a chat command


问:
How to fix error [SyntaxError: JSON Parse error: Unrecognized token '<']
I have this "

```<code>error [SyntaxError: JSON Parse error: Unrecognized token '<']"
</code>```

in my code.

It's an android app I have been working on for about a year. The app was compiling and run successfully before I took a break.

when I wanted to run the code again I started getting that error.

it's occuring when I load an image into the app to scan. I don't know it's origin or why it's popping up since the code was working perfectly.

anyone to help?

I have tried to reset cache, reload the code or reinstall the dependencies. nothing is working

Body:
I have this "

error [SyntaxError: JSON Parse error: Unrecognized token '<']"

in my code.

It's an android app I have been working on for about a year. The app was compiling and run successfully before I took a break.

when I wanted to run the code again I started getting that error.

it's occuring when I load an image into the app to scan. I don't know it's origin or why it's popping up since the code was working perfectly.

anyone to help?

I have tried to reset cache, reload the code or reinstall the dependencies. nothing is working


问:
Angular Mat tab does not show another component HTML view
I have used Mat Tab component to show a view of another component (which is currently a raised mat Hello button).. Earlier, there was an issue of tabs not showing full view during when the hello was shown in a tiny scroll along with Content 1.. when I resolved the full view problem using dynamic height, all other content is showing up except the component reference HTML element..

```<code>
<mat-tab-group dynamicHeight="True">
        <mat-tab label="L1">
           <div>bda></div>
           <app-project-form></app-project-form>
           <div>bda></div>
           <div>bda></div>
    </mat-tab>
    <mat-tab label="L2"></mat-tab>
    <mat-tab label="L3"></mat-tab>

</mat-tab-group>

</code>```

What's actually shown:

Expected output should show the Hello button after the first bda>, instead it is ignored.. Please help in resolving this...

Body:
I have used Mat Tab component to show a view of another component (which is currently a raised mat Hello button).. Earlier, there was an issue of tabs not showing full view during when the hello was shown in a tiny scroll along with Content 1.. when I resolved the full view problem using dynamic height, all other content is showing up except the component reference HTML element..

<mat-tab-group dynamicHeight="True">
        <mat-tab label="L1">

bda>

           <app-project-form></app-project-form>

bda>

bda>

    </mat-tab>
    <mat-tab label="L2"></mat-tab>
    <mat-tab label="L3"></mat-tab>

</mat-tab-group>

What's actually shown:

Expected output should show the Hello button after the first bda>, instead it is ignored.. Please help in resolving this...


问:
Refreshing page in JavaScript when another page is loaded
Currently I am working on one project, that is a little complicated for my programming capabilities, so the general idea might be wrong. I need to do just one more thing to make everything functionable. I am using local storage in order to temporarily save data from page1.php and after that, display data on page2.php. But when I load page2.php, there is no data because I did not load page1.php first (it is needed to send data to local storage).
The user for his needs does not have to load page1.php first and that is a problem.
Is there any way to reload page1.php when any other page is loaded in order to save data on local storage. In JavaScript or PHP. Thanks in advance.

I tried some manipulations with reload() function, but did not find any solution.


问:
How to store an Integer val in room database and fetch The updated integer val from room
I want to store an Integer val in room database and update That Int val Then Fetch That integer val from roomdatabase in jetpack compose</p>
```<code>@Entity(tableName = "users_table")

data class User(
    @PrimaryKey val id: Int = 1,
    var Day: Int = 0
)
</code>```

Body:
I want to store an Integer val in room database and update That Int val Then Fetch That integer val from roomdatabase in jetpack compose

@Entity(tableName = "users_table")

data class User(
    @PrimaryKey val id: Int = 1,
    var Day: Int = 0
)


问:
How to do a database-style right join on indexes without moving the indexes into the columns?
I am trying to create df3 by right joining df1 and df2 on the indexes.  This can be achieved using merge.  For example:

```<code>df3 = df1.reset_index().merge(df2.reset_index(), how='right', on=df2.index.names).set_index(df1.index.names)
</code>```

However, I would like to be able to do this without moving the indexes into the columns.  I tried doing this with merge, join, and concat; however, none of the approaches I tried produced df3.

df1:

```<code>         data1
id1 id2
1   1        1
2   2        2
</code>```

df2:

```<code>     data2
id2
1        1
2        2
3        3
</code>```

df3:

```<code>         data1  data2
id1 id2
1.0 1      1.0      1
2.0 2      2.0      2
NaN 3      NaN      3
</code>```

Body:
I am trying to create df3 by right joining df1 and df2 on the indexes.  This can be achieved using merge.  For example:

df3 = df1.reset_index().merge(df2.reset_index(), how='right', on=df2.index.names).set_index(df1.index.names)

However, I would like to be able to do this without moving the indexes into the columns.  I tried doing this with merge, join, and concat; however, none of the approaches I tried produced df3.

df1:

         data1
id1 id2
1   1        1
2   2        2

df2:

     data2
id2
1        1
2        2
3        3

df3:

         data1  data2
id1 id2
1.0 1      1.0      1
2.0 2      2.0      2
NaN 3      NaN      3


问:
Setting preselected value as object via v-model in child component made of DevExtreme DxSelectBox not working in Vue3 composition API
I have made a child component - Dropdown based on Devextreme DxSelectBox.

I set in parent component v-model as attribute and forward to it an variable as ref, which is set to initial selected valueconst item = ref({ value: "option 1" }), but the DxSelectBox is empty when loading the project.

Child component - Dropdown is emitting the right selected option, but unfortunately the initial selected value is not set.

Code for Parent App.vue component is:

<template>
<template>
  <Dropdown :items="items" v-model:option="item" />

Emitting: {{ item }}

</template>

```
<p>and code for <code>Dropdown.vue</code> component is:</p>
<pre class="lang-html prettyprint-override"><code><template>
<template>
  <div class="dx-field">
    <DxSelectBox
      :data-source="items"
      :value="option"
      @valueChanged="emitValue"
      :width="width"
      :height="height"
      :drop-down-options="{ width: width }"
      display-expr="value"
      :disabled="disabled"
      :read-only="readOnly"
      :hint="hint"
      :placeholder="placeholder"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, watch, ref } from "vue";
import DxSelectBox from "devextreme-vue/select-box";

export default defineComponent({
  name: "DpmDropdown",
  components: {
    DxSelectBox,
  },
  emits: ["update:option"],
  props: {
    label: { type: String, default: "" },
    showLabel: { type: Boolean, default: true },

    headingTooltip: { type: String, default: "" },
    items: { type: Array, default: () => [] },
    option: { type: Object, default: () => ({}) },
    width: { type: [Number, String], default: "100%" },
    height: { type: String, default: "40px" },
    icon: { type: String, default: "" },
    hint: { type: String, default: "" },
    disabled: { type: Boolean, default: false },
    readOnly: { type: Boolean, default: false },
    placeholder: { type: String, default: "" },
  },

  setup(props, context) {
    const emitValue = (e: any) => {
      context.emit("update:option", e.value);
    };

    return {
      emitValue,
    };
  },
});
</script>
</code>```

The link for sandbox project is here.

Body:
I have made a child component - Dropdown based on Devextreme DxSelectBox.

I set in parent component v-model as attribute and forward to it an variable as ref, which is set to initial selected valueconst item = ref({ value: "option 1" }), but the DxSelectBox is empty when loading the project.

Child component - Dropdown is emitting the right selected option, but unfortunately the initial selected value is not set.

Code for Parent App.vue component is:

<template>
<template>
  <Dropdown :items="items" v-model:option="item" />

Emitting: {{ item }}

</template>

and code for Dropdown.vue component is:

<template>
<template>

    <DxSelectBox
      :data-source="items"
      :value="option"
      @valueChanged="emitValue"
      :width="width"
      :height="height"
      :drop-down-options="{ width: width }"
      display-expr="value"
      :disabled="disabled"
      :read-only="readOnly"
      :hint="hint"
      :placeholder="placeholder"
    />

</template>

The link for sandbox project is here.


问:
Getting colorbar to work in matplotlib/Seaborn for a graph
I have had success getting my 4D graph to come out, but I cannot get the colorbar to display correctly. I am new to this and grateful for help. Here is the code and output:

```<code>a = cdf['P']
b = cdf['Weight']
c = cdf['MELD']
d = cdf['SV']
sns.set(style = "darkgrid")

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
ax.scatter(a,b,d, c=c)
ax.set_xlabel("Portal Pressure")
ax.set_ylabel("Weight")
ax.set_zlabel("Spleen Volume")
fig.colorbar(fig)
plt.show()
</code>```

I get an error with the colorbar the way it is, and it isn't displayed correctly.
The MELD variable has a range from 4-44.

I am trying to get the colorbar to display the legend correctly and get a '4D' graph.

Body:
I have had success getting my 4D graph to come out, but I cannot get the colorbar to display correctly. I am new to this and grateful for help. Here is the code and output:

a = cdf['P']
b = cdf['Weight']
c = cdf['MELD']
d = cdf['SV']
sns.set(style = "darkgrid")

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
ax.scatter(a,b,d, c=c)
ax.set_xlabel("Portal Pressure")
ax.set_ylabel("Weight")
ax.set_zlabel("Spleen Volume")
fig.colorbar(fig)
plt.show()

I get an error with the colorbar the way it is, and it isn't displayed correctly.
The MELD variable has a range from 4-44.

I am trying to get the colorbar to display the legend correctly and get a '4D' graph.