问:
How can I terminate program that use a pool cleanly in python after receiving a sigterm signal?
I'm trying to write a service that run a task periodically. That task could take could take longer than the sleep time so it will start an other task in a pool. The thing is, because it's a service I'll like to be able to stop it. So it need to handle a SIGTERM. Here's what what I have got so far:

```<code>def test_task():
    task_id = random.randint(1000, 9999)
    logger = CustomLogger()

    for i in range(5):
        text = f"({task_id}) timestamp: {str(datetime.now())}"
        logger.out(text)
        time.sleep(SLEEP_TIME)

    logger.out(f"task ({task_id}) done")
</code>```
```<code>class TestService:
    def __init__(self):
        signal.signal(signal.SIGTERM, self._handle_sigterm)
        signal.signal(signal.SIGINT, self._handle_sigterm)
        self.logger = CustomLogger()
        self.pool = Pool(processes=12)

    def start(self):
        while True:
            self.pool.apply_async(test_task)
            time.sleep(2)

    def _handle_sigterm(self, sig, frame):
        self.logger.out("signal handled")
        self._stop()

    def _stop(self):
        self.pool.join()
        sys.exit(0)

</code>```

When I try to terminate it, I terminate all my subprocess and I don't know why

I tryed many things, like unsing contexte, try to send an event, have a custom process for my task but not luck. What I'll like to see it's when it receive the signal it wait that all subprocess dies then exit cleanly.

Body:
I'm trying to write a service that run a task periodically. That task could take could take longer than the sleep time so it will start an other task in a pool. The thing is, because it's a service I'll like to be able to stop it. So it need to handle a SIGTERM. Here's what what I have got so far:

def test_task():
    task_id = random.randint(1000, 9999)
    logger = CustomLogger()

    for i in range(5):
        text = f"({task_id}) timestamp: {str(datetime.now())}"
        logger.out(text)
        time.sleep(SLEEP_TIME)

    logger.out(f"task ({task_id}) done")

class TestService:
    def __init__(self):
        signal.signal(signal.SIGTERM, self._handle_sigterm)
        signal.signal(signal.SIGINT, self._handle_sigterm)
        self.logger = CustomLogger()
        self.pool = Pool(processes=12)

    def start(self):
        while True:
            self.pool.apply_async(test_task)
            time.sleep(2)

    def _handle_sigterm(self, sig, frame):
        self.logger.out("signal handled")
        self._stop()

    def _stop(self):
        self.pool.join()
        sys.exit(0)

When I try to terminate it, I terminate all my subprocess and I don't know why

I tryed many things, like unsing contexte, try to send an event, have a custom process for my task but not luck. What I'll like to see it's when it receive the signal it wait that all subprocess dies then exit cleanly.


来源: stackexchange

问:
GHC causes type mismatch by selecting the wrong type for a literal
Just today I discovered that when GHC (v8.8.4) puts a type to a value literal, it sometimes "guesses wrong" and causes type mismatches later on.  Here's a minimal (non)working example:

die :: (Integral a) => [a] -- If this line is commented out, compilation fails
die = [1..6]

-- Generate a list representing the multiset of all possible
-- rolls on n six-sided dice, summing each roll, such that each
-- possible roll has as many instances in the list as there are
-- valid rolls that add up to that number.
dieRolls :: Integral a => a -> [a]
dieRolls 0 = [0]
dieRolls n = [newRoll + oldSum |
    newRoll <- die,
    oldSum <- dieRolls $ n-1]

main = do print $ dieRolls 2
```
<p>As written, this compiles and runs as expected. But if I comment out the first line, I'm told this:</p>
```mnwe.hs:9:25: error:
    • Couldn't match expected type ‘Integer’ with actual type ‘a’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          dieRolls :: forall a. Integral a => a -> [a]
        at mnwe.hs:7:1-34
    • In the second argument of ‘(+)’, namely ‘oldSum’
      In the expression: newRoll + oldSum
      In the expression:
        [newRoll + oldSum | newRoll <- die, oldSum <- dieRolls $ n - 1]
    • Relevant bindings include
        oldSum :: a (bound at mnwe.hs:11:5)
        n :: a (bound at mnwe.hs:9:10)
        dieRolls :: a -> [a] (bound at mnwe.hs:8:1)
  |
9 | dieRolls n = [newRoll + oldSum |
  |
```
<p>What seems to be happening is that, in the absence of an explicit type declaration, GHC is inferring that the elements of <code>[1..6]</code> are, not just any old integers, but specifically of the <code>Integer</code> type. This leads <code>(+)</code> to expect a second argument that it can guarantee will likewise have the type of <code>Integer</code>, which it can't do when the output of <code>dieRolls</code> is explicitly identified as <code>Integral a => [a]</code>. Another working version of the program is one that eliminates the <code>die</code> variable altogether and substitutes <code>[1..6]</code> directly into the body of <code>dieRolls</code>, so it seems like the problem starts when that variable is defined.</p>
<p>I don't understand this behavior. Why is GHC inferring that <code>die</code> is specifically supposed to be a list of capital-I <code>Integers</code>? Isn't that a violation of lazy evaluation? And why does it pick <code>Integer</code> here when GHCi tells me this:</p>
```GHCi, version 8.8.4: https://www.haskell.org/ghc/  :? for help
Prelude> :t [1..6]
[1..6] :: (Num a, Enum a) => [a]
Prelude> die = [1..6]
Prelude> :t die
die :: (Num a, Enum a) => [a]
```

Does type inference just work differently in GHCi?

ContentLicense: CC BY-SA 4.0

Body:
Just today I discovered that when GHC (v8.8.4) puts a type to a value literal, it sometimes "guesses wrong" and causes type mismatches later on.  Here's a minimal (non)working example:

die :: (Integral a) => [a] -- If this line is commented out, compilation fails
die = [1..6]

-- Generate a list representing the multiset of all possible
-- rolls on n six-sided dice, summing each roll, such that each
-- possible roll has as many instances in the list as there are
-- valid rolls that add up to that number.
dieRolls :: Integral a => a -> [a]
dieRolls 0 = [0]
dieRolls n = [newRoll + oldSum |
    newRoll <- die,
    oldSum <- dieRolls $ n-1]

main = do print $ dieRolls 2

As written, this compiles and runs as expected. But if I comment out the first line, I'm told this:

mnwe.hs:9:25: error:
    • Couldn't match expected type ‘Integer’ with actual type ‘a’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          dieRolls :: forall a. Integral a => a -> [a]
        at mnwe.hs:7:1-34
    • In the second argument of ‘(+)’, namely ‘oldSum’
      In the expression: newRoll + oldSum
      In the expression:
        [newRoll + oldSum | newRoll <- die, oldSum <- dieRolls $ n - 1]
    • Relevant bindings include
        oldSum :: a (bound at mnwe.hs:11:5)
        n :: a (bound at mnwe.hs:9:10)
        dieRolls :: a -> [a] (bound at mnwe.hs:8:1)
  |
9 | dieRolls n = [newRoll + oldSum |
  |

What seems to be happening is that, in the absence of an explicit type declaration, GHC is inferring that the elements of [1..6] are, not just any old integers, but specifically of the Integer type. This leads (+) to expect a second argument that it can guarantee will likewise have the type of Integer, which it can't do when the output of dieRolls is explicitly identified as Integral a => [a]. Another working version of the program is one that eliminates the die variable altogether and substitutes [1..6] directly into the body of dieRolls, so it seems like the problem starts when that variable is defined.

I don't understand this behavior. Why is GHC inferring that die is specifically supposed to be a list of capital-I Integers? Isn't that a violation of lazy evaluation? And why does it pick Integer here when GHCi tells me this:

GHCi, version 8.8.4: https://www.haskell.org/ghc/  :? for help
Prelude> :t [1..6]
[1..6] :: (Num a, Enum a) => [a]
Prelude> die = [1..6]
Prelude> :t die
die :: (Num a, Enum a) => [a]

Does type inference just work differently in GHCi?


问:
How can I make my VS Code run successfully in Replit?
I am new to python and have been working on a few projects. One of the projects requires me to make a function that formats the a time input. Like below:

```<code>add_time("11:30 AM", "2:32", "Monday")
# Returns: 2:02 PM, Monday

add_time("11:43 AM", "00:20")
# Returns: 12:03 PM

add_time("10:10 PM", "3:30")
# Returns: 1:40 AM (next day)

add_time("11:43 PM", "24:20", "tueSday")
# Returns: 12:03 AM, Thursday (2 days later)
</code>```

Then submit it in Replit.

The code I have written works perfectly when I run it in VS Code but when I run it in Replit it gives me a few failures.

```<code>def add_time(start, duration, dayOfWeek = " "):
    dayChange = 0 #Increases by one every time PM switches to AM
    periodCounter = 0 #Counts how many times we swap from AM to PM to AM to PM
    sevenDays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

    startSet = start.split(" ")                 #["3:00", "PM"]
    startHr = int(startSet[0].split(":")[0])    #"3:00" --> 3
    addHr = int(duration.split(":")[0])         #0:20 --> 0

    startMin = int(startSet[0].split(":")[1])   #"3:20" --> 20
    addMin = int(duration.split(":")[1])

    hour = (startHr + addHr)
    minute = (startMin + addMin)

    while(hour > 12):
        hour -= 12
        periodCounter += 1

    if(minute > 60):
        minute -= 60
        hour += 1
        if(hour > 11):
            periodCounter += 1

    for i in range(periodCounter):
        if(startSet[1] == "PM"):
            dayChange += 1
            startSet[1] = "AM"
        else:
            startSet[1] = "PM"

    for x in sevenDays:
        if(str(dayOfWeek).lower() == x):
            #index of x plus the amount of times the days change
            val = (int(sevenDays.index(x)) + dayChange)
            while(val >= 7):
                val -= 7

            dayOfWeek = sevenDays[val].capitalize()
            hasDate = True
            break
        else:
            hasDate = False

    strDayChange = ""

    if(dayChange > 1):
        strDayChange += (f"({str(dayChange)} days later)")
    elif(dayChange == 1):
        strDayChange = "(next day)"

    if(hasDate):
        return(f"{hour}:{minute:0>2} {startSet[1]}, {dayOfWeek} {strDayChange}")
    else:
        return(f"{hour}:{minute:0>2} {startSet[1]} {strDayChange}")
</code>```

These are the test cases where it fails.

```<code>#print(add_time("3:30 PM", "2:12"))
#expected = "5:42 PM"
#print(add_time("11:55 AM", "3:12")) ---- Failed
#expected = "3:07 PM"
#print(add_time("9:15 PM", "5:30"))
#expected = "2:45 AM (next day)"
#print(add_time("11:40 AM", "0:25")) ---- Failed
#expected = "12:05 PM"
#print(add_time("2:59 AM", "24:00"))
#expected = "2:59 AM (next day)"
#print(add_time("11:59 PM", "24:05"))
#expected = "12:04 AM (2 days later)"
#print(add_time("8:16 PM", "466:02", "tuesday"))
#expected = "6:18 AM, Monday (20 days later)"
#print(add_time("5:01 AM", "0:00")) -------- Failed
#expected = "5:01 AM"
#print(add_time("3:30 PM", "2:12", "Monday")) ------ Failed
#expected = "5:42 PM, Monday"
#print(add_time("2:59 AM", "24:00", "saturDay"))
#expected = "2:59 AM, Sunday (next day)"
#print(add_time("11:59 PM", "24:05", "Wednesday"))
#expected = "12:04 AM, Friday (2 days later)"
#print(add_time("8:16 PM", "466:02"))
#expected = "6:18 AM (20 days later)"
</code>```

Body:
I am new to python and have been working on a few projects. One of the projects requires me to make a function that formats the a time input. Like below:

add_time("11:30 AM", "2:32", "Monday")
# Returns: 2:02 PM, Monday

add_time("11:43 AM", "00:20")
# Returns: 12:03 PM

add_time("10:10 PM", "3:30")
# Returns: 1:40 AM (next day)

add_time("11:43 PM", "24:20", "tueSday")
# Returns: 12:03 AM, Thursday (2 days later)

Then submit it in Replit.

The code I have written works perfectly when I run it in VS Code but when I run it in Replit it gives me a few failures.

def add_time(start, duration, dayOfWeek = " "):
    dayChange = 0 #Increases by one every time PM switches to AM
    periodCounter = 0 #Counts how many times we swap from AM to PM to AM to PM
    sevenDays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

    startSet = start.split(" ")                 #["3:00", "PM"]
    startHr = int(startSet[0].split(":")[0])    #"3:00" --> 3
    addHr = int(duration.split(":")[0])         #0:20 --> 0

    startMin = int(startSet[0].split(":")[1])   #"3:20" --> 20
    addMin = int(duration.split(":")[1])

    hour = (startHr + addHr)
    minute = (startMin + addMin)

    while(hour > 12):
        hour -= 12
        periodCounter += 1

    if(minute > 60):
        minute -= 60
        hour += 1
        if(hour > 11):
            periodCounter += 1

    for i in range(periodCounter):
        if(startSet[1] == "PM"):
            dayChange += 1
            startSet[1] = "AM"
        else:
            startSet[1] = "PM"

    for x in sevenDays:
        if(str(dayOfWeek).lower() == x):
            #index of x plus the amount of times the days change
            val = (int(sevenDays.index(x)) + dayChange)
            while(val >= 7):
                val -= 7

            dayOfWeek = sevenDays[val].capitalize()
            hasDate = True
            break
        else:
            hasDate = False

    strDayChange = ""

    if(dayChange > 1):
        strDayChange += (f"({str(dayChange)} days later)")
    elif(dayChange == 1):
        strDayChange = "(next day)"

    if(hasDate):
        return(f"{hour}:{minute:0>2} {startSet[1]}, {dayOfWeek} {strDayChange}")
    else:
        return(f"{hour}:{minute:0>2} {startSet[1]} {strDayChange}")

These are the test cases where it fails.

#print(add_time("3:30 PM", "2:12"))
#expected = "5:42 PM"
#print(add_time("11:55 AM", "3:12")) ---- Failed
#expected = "3:07 PM"
#print(add_time("9:15 PM", "5:30"))
#expected = "2:45 AM (next day)"
#print(add_time("11:40 AM", "0:25")) ---- Failed
#expected = "12:05 PM"
#print(add_time("2:59 AM", "24:00"))
#expected = "2:59 AM (next day)"
#print(add_time("11:59 PM", "24:05"))
#expected = "12:04 AM (2 days later)"
#print(add_time("8:16 PM", "466:02", "tuesday"))
#expected = "6:18 AM, Monday (20 days later)"
#print(add_time("5:01 AM", "0:00")) -------- Failed
#expected = "5:01 AM"
#print(add_time("3:30 PM", "2:12", "Monday")) ------ Failed
#expected = "5:42 PM, Monday"
#print(add_time("2:59 AM", "24:00", "saturDay"))
#expected = "2:59 AM, Sunday (next day)"
#print(add_time("11:59 PM", "24:05", "Wednesday"))
#expected = "12:04 AM, Friday (2 days later)"
#print(add_time("8:16 PM", "466:02"))
#expected = "6:18 AM (20 days later)"


问:
How do I get actual close price instead of the adj close price getting returned now?
Need the actual close price of a stock for pricing American options, but all it is giving me is the adjusted close price, and when I print the history table used to index the price, there is not other available option other than just 'Close' (which is for some reason NOT the close, but the adjusted close).

```<code>        for i in find:
            i = i.history(period="max")
            i_val = float(i.loc[test_date, 'Close'])
            found.append(i_val)
</code>```

I have already tried the usual fix for this with the 'yf.download' (which gives both the adjusted and none adjusted close price) function, but data is not available for the VIX and 3 month treasury bond yield with that method.

Body:
Need the actual close price of a stock for pricing American options, but all it is giving me is the adjusted close price, and when I print the history table used to index the price, there is not other available option other than just 'Close' (which is for some reason NOT the close, but the adjusted close).

        for i in find:
            i = i.history(period="max")
            i_val = float(i.loc[test_date, 'Close'])
            found.append(i_val)

I have already tried the usual fix for this with the 'yf.download' (which gives both the adjusted and none adjusted close price) function, but data is not available for the VIX and 3 month treasury bond yield with that method.


问:
how to Add new custom fields to woocommerce product filter widget
i have added some new woocommerce custom Fields using ACF plugin, how can i add them to the Woo products filter widget?

Is there any manual way to make custom Fields filtrable as the theme fields?


问:
Some marker props not updating when state changes
I'm building a gig guide with React Native and react native maps.

The home screen features a map with markers showing the current day's gigs. The user can see the upcoming day's gig by pressing the 'Next day's gigs' button, which renders new markers for the cuurent day on the map.

The user can tap on a marker to show gig information in a popup, but here's the problem: if the user then navigates to the next day's gigs, the data in the popup doesn't change. So you have the information for yesterday's gig being displayed in the current day's popup, as follows:

Initial gig for 20th December:

What the map should show when user navigates to next day (21st December):

What the map actually shows - note that it's displaying the previous day gig information

What's confusing is that the marker coordinates are updated when the gig date changes, but the description and title props don't:

```<code>        {gigsToday.map((gig, i) => (
          <Marker
            key={i}
            coordinate={{
              latitude: gig.location.latitude,     // <--- This changes the way it should
              longitude: gig.location.longitude, // <--- This changes the way it should
            }}
            image={require("../assets/Icon_Gold_48x48.png")}
            description = {gig.venue}  // <--- This doesn't change the way it should
            title = {gig.gigName}   //<--- This doesn't change the way it should
          />
        ))}
      </MapView>
</code>```

Any ideas how to fix this, so the marker information changes when data changes? Or at least make the popup disappear when the user navigates to the next day?

Full code for map component (I've left out the styling sheet to make more concise):

GigMaps.js

```<code>import { useState, useMemo, useEffect } from "react";
import {
  StyleSheet,
  Text,
  View,
  Pressable,
  Image,
  TouchableOpacity,
} from "react-native";
import MapView from "react-native-maps";
import { Marker, Callout } from "react-native-maps";
import CalloutView from "./CalloutView";
import { mapStyle } from "../util/mapStyle";
import { useGigs } from "../hooks/useGigs";
import { AntDesign } from "@expo/vector-icons";

const GigMap = ({ navigation }) => {
  const [selectedDateMs, setSelectedDateMs] = useState(Date.now());
  const  [ currentDayGigs,setCurrentDayGigs ] = useState([])
  const gigs = useGigs();

  //generates current date in format DD/MM/YYYY
  const selectedDateString = useMemo(() => {
    const date = new Date(selectedDateMs);
    const dateToString = date.toString().slice(0,15)
    return dateToString // returns in form 'Tue Dec 20 2022'
  }, [selectedDateMs]);

  //Filtering through gigs to return only current day's gigs
  const gigsToday = gigs.filter((gig) => {
    const gigDate1 = new Date(gig.dateAndTime.seconds*1000)
    const gigDate2 = gigDate1.toString().slice(0,15) //return form 'Tue Dec 20 2022'
    return gigDate2 === selectedDateString
  })

  // const generateGigsToday = () => {
  //   useEffect(() => {
  //     const gigsToday = gigs.filter((gig) => {
  //       const gigDate1 = new Date(gig.dateAndTime.seconds*1000)
  //       const gigDate2 = gigDate1.toString().slice(0,15) //return form 'Tue Dec 20 2022'
  //       return gigDate2 === selectedDateString
  //     })
  //     setCurrentDayGigs(gigsToday)
  //   },[selectedDateMs])
  // }

  // generateGigsToday()

  // const gigsToday = useMemo(() => {
  //   return (
  //     gigs.filter((gig) => {
  //       const gigDate1 = new Date(gig.dateAndTime.seconds*1000)
  //       const gigDate2 = gigDate1.toString().slice(0,15)
  //       return gigDate2 === selectedDateString
  //     })
  //   )
  // },[selectedDateMs])

  //increments date by amount
  const addDays = (amount) => {
    setSelectedDateMs((curr) => curr + 1000 * 60 * 60 * 24 * amount);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.headerText}>{`Gigs on ${selectedDateString}`}</Text>

      <View style={styles.imageText}>
        <Text style = {styles.subHeader}>Tap on</Text>
        <Image
          style={styles.image}
          source={require("../assets/Icon_Gold_48x48.png")}
        />
        <Text style = {styles.subHeader}> to see gig info</Text>
      </View>

      <MapView
        initialRegion={{
          latitude: -41.29416,
          longitude: 174.77782,
          latitudeDelta: 0.03,
          longitudeDelta: 0.03,
        }}
        style={styles.map}
        customMapStyle={mapStyle}
      >
        {gigsToday.map((gig, i) => (
          <Marker
            key={i}
            coordinate={{
              latitude: gig.location.latitude,
              longitude: gig.location.longitude,
            }}
            image={require("../assets/Icon_Gold_48x48.png")}
            description = {gig.venue}
            title = {gig.gigName}
          />
        ))}
      </MapView>

      <View style={styles.buttonOptions}>
        <TouchableOpacity onPress={() => addDays(-1)} style = {styles.touchable}>
          <AntDesign name="caretleft" size={36} color="#778899" />
          <Text style = {{fontFamily:'Helvetica-Neue', color:'#778899'}}>Previous day's gigs</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => addDays(1)} style = {styles.touchable}>
          <AntDesign name="caretright" size={36} color="#778899" />
          <Text style = {{fontFamily:'Helvetica-Neue',color:'#778899'}}>Next day's gigs</Text>
        </TouchableOpacity>
      </View>
    </View>

  );
};
</code>```

Body:
I'm building a gig guide with React Native and react native maps.

The home screen features a map with markers showing the current day's gigs. The user can see the upcoming day's gig by pressing the 'Next day's gigs' button, which renders new markers for the cuurent day on the map.

The user can tap on a marker to show gig information in a popup, but here's the problem: if the user then navigates to the next day's gigs, the data in the popup doesn't change. So you have the information for yesterday's gig being displayed in the current day's popup, as follows:

Initial gig for 20th December:

What the map should show when user navigates to next day (21st December):

What the map actually shows - note that it's displaying the previous day gig information

What's confusing is that the marker coordinates are updated when the gig date changes, but the description and title props don't:

        {gigsToday.map((gig, i) => (
          <Marker
            key={i}
            coordinate={{
              latitude: gig.location.latitude,     // <--- This changes the way it should
              longitude: gig.location.longitude, // <--- This changes the way it should
            }}
            image={require("../assets/Icon_Gold_48x48.png")}
            description = {gig.venue}  // <--- This doesn't change the way it should
            title = {gig.gigName}   //<--- This doesn't change the way it should
          />
        ))}
      </MapView>

Any ideas how to fix this, so the marker information changes when data changes? Or at least make the popup disappear when the user navigates to the next day?

Full code for map component (I've left out the styling sheet to make more concise):

GigMaps.js

import { useState, useMemo, useEffect } from "react";
import {
  StyleSheet,
  Text,
  View,
  Pressable,
  Image,
  TouchableOpacity,
} from "react-native";
import MapView from "react-native-maps";
import { Marker, Callout } from "react-native-maps";
import CalloutView from "./CalloutView";
import { mapStyle } from "../util/mapStyle";
import { useGigs } from "../hooks/useGigs";
import { AntDesign } from "@expo/vector-icons";

const GigMap = ({ navigation }) => {
  const [selectedDateMs, setSelectedDateMs] = useState(Date.now());
  const  [ currentDayGigs,setCurrentDayGigs ] = useState([])
  const gigs = useGigs();

  //generates current date in format DD/MM/YYYY
  const selectedDateString = useMemo(() => {
    const date = new Date(selectedDateMs);
    const dateToString = date.toString().slice(0,15)
    return dateToString // returns in form 'Tue Dec 20 2022'
  }, [selectedDateMs]);

  //Filtering through gigs to return only current day's gigs
  const gigsToday = gigs.filter((gig) => {
    const gigDate1 = new Date(gig.dateAndTime.seconds*1000)
    const gigDate2 = gigDate1.toString().slice(0,15) //return form 'Tue Dec 20 2022'
    return gigDate2 === selectedDateString
  })

  // const generateGigsToday = () => {
  //   useEffect(() => {
  //     const gigsToday = gigs.filter((gig) => {
  //       const gigDate1 = new Date(gig.dateAndTime.seconds*1000)
  //       const gigDate2 = gigDate1.toString().slice(0,15) //return form 'Tue Dec 20 2022'
  //       return gigDate2 === selectedDateString
  //     })
  //     setCurrentDayGigs(gigsToday)
  //   },[selectedDateMs])
  // }

  // generateGigsToday()

  // const gigsToday = useMemo(() => {
  //   return (
  //     gigs.filter((gig) => {
  //       const gigDate1 = new Date(gig.dateAndTime.seconds*1000)
  //       const gigDate2 = gigDate1.toString().slice(0,15)
  //       return gigDate2 === selectedDateString
  //     })
  //   )
  // },[selectedDateMs])

  //increments date by amount
  const addDays = (amount) => {
    setSelectedDateMs((curr) => curr + 1000 * 60 * 60 * 24 * amount);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.headerText}>{`Gigs on ${selectedDateString}`}</Text>

      <View style={styles.imageText}>
        <Text style = {styles.subHeader}>Tap on</Text>
        <Image
          style={styles.image}
          source={require("../assets/Icon_Gold_48x48.png")}
        />
        <Text style = {styles.subHeader}> to see gig info</Text>
      </View>

      <MapView
        initialRegion={{
          latitude: -41.29416,
          longitude: 174.77782,
          latitudeDelta: 0.03,
          longitudeDelta: 0.03,
        }}
        style={styles.map}
        customMapStyle={mapStyle}
      >
        {gigsToday.map((gig, i) => (
          <Marker
            key={i}
            coordinate={{
              latitude: gig.location.latitude,
              longitude: gig.location.longitude,
            }}
            image={require("../assets/Icon_Gold_48x48.png")}
            description = {gig.venue}
            title = {gig.gigName}
          />
        ))}
      </MapView>

      <View style={styles.buttonOptions}>
        <TouchableOpacity onPress={() => addDays(-1)} style = {styles.touchable}>
          <AntDesign name="caretleft" size={36} color="#778899" />
          <Text style = {{fontFamily:'Helvetica-Neue', color:'#778899'}}>Previous day's gigs</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => addDays(1)} style = {styles.touchable}>
          <AntDesign name="caretright" size={36} color="#778899" />
          <Text style = {{fontFamily:'Helvetica-Neue',color:'#778899'}}>Next day's gigs</Text>
        </TouchableOpacity>
      </View>
    </View>

  );
};


问:
Maven multi module project with git submodule: release perform fails
I have a Maven multi-module project. One of the module is a git submodule

proj-root

proj-module

proj-submodule

When I try maven release:prepare, the project fails. I have tried multiple ways but still not succesful.

I follow the following steps:

Clone the root project and cd into the cloned project folder

git submodule sync

git submodule update --init --remote

mvn --batch-mode -DcommitByProject=true release:prepare

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:3.0.0-M7:prepare (default-cli) on project proj-root: An error is occurred in the checkin process: Exception while executing SCM command. Detecting the current branch failed: fatal: ref HEAD is not a symbolic ref -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-release-plugin:3.0.0-M7:prepare (default-cli) on project proj-root: An error is occurred in the checkin process: Exception while executing SCM command.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
  ...
Caused by: org.apache.maven.plugin.MojoExecutionException: An error is occurred in the checkin process: Exception while executing SCM command.
    at org.apache.maven.plugins.release.PrepareReleaseMojo.prepareRelease(PrepareReleaseMojo.java:417)
    at org.apache.maven.plugins.release.PrepareReleaseMojo.execute(PrepareReleaseMojo.java:349)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    ... 20 more
Caused by: org.apache.maven.shared.release.ReleaseExecutionException: An error is occurred in the checkin process: Exception while executing SCM command.
    at org.apache.maven.shared.release.phase.AbstractScmCommitPhase.checkin(AbstractScmCommitPhase.java:191)
    at org.apache.maven.shared.release.phase.AbstractScmCommitPhase.performCheckins(AbstractScmCommitPhase.java:168)
    at org.apache.maven.shared.release.phase.AbstractScmCommitPreparationPhase.runLogic(AbstractScmCommitPreparationPhase.java:88)
    ... 23 more
Caused by: org.apache.maven.scm.ScmException: Exception while executing SCM command.
    at org.apache.maven.scm.command.AbstractCommand.execute(AbstractCommand.java:64)
    at org.apache.maven.scm.provider.git.AbstractGitScmProvider.executeCommand(AbstractGitScmProvider.java:300)
    at org.apache.maven.scm.provider.git.AbstractGitScmProvider.checkin(AbstractGitScmProvider.java:218)
    ... 29 more
Caused by: org.apache.maven.scm.ScmException: Detecting the current branch failed: fatal: ref HEAD is not a symbolic ref

</code>```

My finding is that the above error is because the submodule "proj-submodule" is at HEAD and not specific branch.

```<code>* (HEAD detached from c560983)
  master

</code>```

I tried it differently now:

Clone the root project and cd into the cloned project folder

git submodule sync

git submodule update --init --remote

cd proj-submodule && git checkout master && cd -

mvn --batch-mode -DcommitByProject=true release:prepare

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:3.0.0-M7:prepare (default-cli) on project proj-root: Unable to commit files
[ERROR] Provider message:
[ERROR] The git-push command failed.
[ERROR] Command output:
[ERROR] To github.com:user1234/proj-root.git
[ERROR] ! [rejected]        master -> master (fetch first)
[ERROR] error:********@github.com:user1234/proj-root.git'
[ERROR] hint: Updates were rejected because the remote contains work that you do
[ERROR] hint: not have locally. This is usually caused by another repository pushing
[ERROR] hint: to the same ref. You may want to first integrate the remote changes
[ERROR] hint: (e.g., 'git pull ...') before pushing again.
[ERROR] hint: See the 'Note about fast-forwards' in 'git push --help' for details.
[ERROR] -> [Help 1]
</code>```

I don't understand why the above error even through there were no changes pushed to repo. When I looked into it the repo, the release version of pom files were updated to root and proj-module but not to proj-submodule. So my analysis is that the failure is again due to the submodule (git submodule project).

Can anyone help resolve the issue? Regular release builds with or without modules complete successfully but not the one with a submodule (git submodule).

Body:
I have a Maven multi-module project. One of the module is a git submodule

proj-root

proj-module

proj-submodule

When I try maven release:prepare, the project fails. I have tried multiple ways but still not succesful.

I follow the following steps:

Clone the root project and cd into the cloned project folder

git submodule sync

git submodule update --init --remote

mvn --batch-mode -DcommitByProject=true release:prepare

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:3.0.0-M7:prepare (default-cli) on project proj-root: An error is occurred in the checkin process: Exception while executing SCM command. Detecting the current branch failed: fatal: ref HEAD is not a symbolic ref -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-release-plugin:3.0.0-M7:prepare (default-cli) on project proj-root: An error is occurred in the checkin process: Exception while executing SCM command.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
  ...
Caused by: org.apache.maven.plugin.MojoExecutionException: An error is occurred in the checkin process: Exception while executing SCM command.
    at org.apache.maven.plugins.release.PrepareReleaseMojo.prepareRelease(PrepareReleaseMojo.java:417)
    at org.apache.maven.plugins.release.PrepareReleaseMojo.execute(PrepareReleaseMojo.java:349)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    ... 20 more
Caused by: org.apache.maven.shared.release.ReleaseExecutionException: An error is occurred in the checkin process: Exception while executing SCM command.
    at org.apache.maven.shared.release.phase.AbstractScmCommitPhase.checkin(AbstractScmCommitPhase.java:191)
    at org.apache.maven.shared.release.phase.AbstractScmCommitPhase.performCheckins(AbstractScmCommitPhase.java:168)
    at org.apache.maven.shared.release.phase.AbstractScmCommitPreparationPhase.runLogic(AbstractScmCommitPreparationPhase.java:88)
    ... 23 more
Caused by: org.apache.maven.scm.ScmException: Exception while executing SCM command.
    at org.apache.maven.scm.command.AbstractCommand.execute(AbstractCommand.java:64)
    at org.apache.maven.scm.provider.git.AbstractGitScmProvider.executeCommand(AbstractGitScmProvider.java:300)
    at org.apache.maven.scm.provider.git.AbstractGitScmProvider.checkin(AbstractGitScmProvider.java:218)
    ... 29 more
Caused by: org.apache.maven.scm.ScmException: Detecting the current branch failed: fatal: ref HEAD is not a symbolic ref

My finding is that the above error is because the submodule "proj-submodule" is at HEAD and not specific branch.

* (HEAD detached from c560983)
  master

I tried it differently now:

Clone the root project and cd into the cloned project folder

git submodule sync

git submodule update --init --remote

cd proj-submodule && git checkout master && cd -

mvn --batch-mode -DcommitByProject=true release:prepare

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:3.0.0-M7:prepare (default-cli) on project proj-root: Unable to commit files
[ERROR] Provider message:
[ERROR] The git-push command failed.
[ERROR] Command output:
[ERROR] To github.com:user1234/proj-root.git
[ERROR] ! [rejected]        master -> master (fetch first)
[ERROR] error:********@github.com:user1234/proj-root.git'
[ERROR] hint: Updates were rejected because the remote contains work that you do
[ERROR] hint: not have locally. This is usually caused by another repository pushing
[ERROR] hint: to the same ref. You may want to first integrate the remote changes
[ERROR] hint: (e.g., 'git pull ...') before pushing again.
[ERROR] hint: See the 'Note about fast-forwards' in 'git push --help' for details.
[ERROR] -> [Help 1]

I don't understand why the above error even through there were no changes pushed to repo. When I looked into it the repo, the release version of pom files were updated to root and proj-module but not to proj-submodule. So my analysis is that the failure is again due to the submodule (git submodule project).

Can anyone help resolve the issue? Regular release builds with or without modules complete successfully but not the one with a submodule (git submodule).


问:
Find duplicate elements in xml, then delete itself but still format xml properly
Running a massive xml and don't have access to the code they used to get the information from sql, so I can't parse it from that end.  Need to stop repeating elements, but someone still capture all the info inside of that element, and keep it attached to the original element that had duplicate integers.

xml is formatted like this:

```<code>?xml version="1.0" encoding="UTF-8"?>
<root>
    <clients>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>FRANK</firstName>
                <middleName>N.</middleName>
                <lastName>FUR</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
        <client>
            <uci>5585</uci>
            <contact>
                <firstName>ANN</firstName>
                <middleName>P.</middleName>
                <lastName>TERR</lastName>
                <address>
                    <address1>5 KING ST</address1>
                    <address2></address2>
                    <city>BARRIE</city>
                    <province>ON</province>
                    <postalCode>L4M 2N9</postalCode>
                    <country>CANADA</country>
                </address>
            </contact>
            <contact>
                <firstName>ANN</firstName>
                <middleName>P.</middleName>
                <lastName>TERR</lastName>
                <address>
                    <address1>5 KING ST</address1>
                    <address2></address2>
                    <city>BARRIE</city>
                    <province>ON</province>
                    <postalCode>L4M 2N9</postalCode>
                    <country>CANADA</country>
                </address>
            </contact>
        </client>
</root>
----------------------------------------------------------------------------------

If you'll notice on <uci>5585<uci> a second contact is added before it moves on to the next client.

In the xml doc I was given, all of those second/third/etc contacts were assigned a uci, even though they were duplicated.  So instead of something like this:

  <clients>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>FRANK</firstName>
                <middleName>N.</middleName>
                <lastName>FUR</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>Justin</firstName>
                <middleName>T</middleName>
                <lastName>Thomas</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
------------------------------------------------------------------------
it would be like this for all duplicated ucis:
 <clients>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>FRANK</firstName>
                <middleName>N.</middleName>
                <lastName>FUR</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
            <contact>
                <firstName>Justin</firstName>
                <middleName>T</middleName>
                <lastName>Thomas</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
---------------------------------------------------------------------------

I have no way of accessing the FileWriter that was used, but still need to make these changes.
I'm guessing Python?  Originally I was just going to edit this in notepad++ by hand, but once I looked at the file, it's 50,000+ lines.

You'll notice that I can't just do find duplicate lines, as that would pull in things like
<country>ABC<country>
<country>ABC<country>

Would appreciate any and all help

Tried Find and Replace in Notepad++ and even tried doing a delete every so many lines, but that doesn't format the xml properly and apparently some of these accounts have 3+ contacts.

I also thought about finding duplicates in C#, but not sure how to replace it so that the xml formats correctly.  I even tried grabbing the base data and just running an xml in excel after trying to delete every other line in the uci column, but that deletes all of the contact info, as name/address/etc are tied to the uci.

I thought this whole format was going to be needlessly complicated, and now I'm the one who has to fix it.
</code>```

Body:
Running a massive xml and don't have access to the code they used to get the information from sql, so I can't parse it from that end.  Need to stop repeating elements, but someone still capture all the info inside of that element, and keep it attached to the original element that had duplicate integers.

xml is formatted like this:

?xml version="1.0" encoding="UTF-8"?>
<root>
    <clients>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>FRANK</firstName>
                <middleName>N.</middleName>
                <lastName>FUR</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
        <client>
            <uci>5585</uci>
            <contact>
                <firstName>ANN</firstName>
                <middleName>P.</middleName>
                <lastName>TERR</lastName>
                <address>
                    <address1>5 KING ST</address1>
                    <address2></address2>
                    <city>BARRIE</city>
                    <province>ON</province>
                    <postalCode>L4M 2N9</postalCode>
                    <country>CANADA</country>
                </address>
            </contact>
            <contact>
                <firstName>ANN</firstName>
                <middleName>P.</middleName>
                <lastName>TERR</lastName>
                <address>
                    <address1>5 KING ST</address1>
                    <address2></address2>
                    <city>BARRIE</city>
                    <province>ON</province>
                    <postalCode>L4M 2N9</postalCode>
                    <country>CANADA</country>
                </address>
            </contact>
        </client>
</root>
----------------------------------------------------------------------------------

If you'll notice on <uci>5585<uci> a second contact is added before it moves on to the next client.

In the xml doc I was given, all of those second/third/etc contacts were assigned a uci, even though they were duplicated.  So instead of something like this:

  <clients>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>FRANK</firstName>
                <middleName>N.</middleName>
                <lastName>FUR</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>Justin</firstName>
                <middleName>T</middleName>
                <lastName>Thomas</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
------------------------------------------------------------------------
it would be like this for all duplicated ucis:
 <clients>
        <client>
            <uci>5581</uci>
            <contact>
                <firstName>FRANK</firstName>
                <middleName>N.</middleName>
                <lastName>FUR</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
            <contact>
                <firstName>Justin</firstName>
                <middleName>T</middleName>
                <lastName>Thomas</lastName>
                <address>
                    <address1>9 LOA</address1>
                    <address2></address2>
                    <city>TENO</city>
                    <province>MAULE</province>
                    <postalCode>1000000</postalCode>
                    <country>CHILE</country>
                </address>
            </contact>
        </client>
---------------------------------------------------------------------------

I have no way of accessing the FileWriter that was used, but still need to make these changes.
I'm guessing Python?  Originally I was just going to edit this in notepad++ by hand, but once I looked at the file, it's 50,000+ lines.

You'll notice that I can't just do find duplicate lines, as that would pull in things like
<country>ABC<country>
<country>ABC<country>

Would appreciate any and all help

Tried Find and Replace in Notepad++ and even tried doing a delete every so many lines, but that doesn't format the xml properly and apparently some of these accounts have 3+ contacts.

I also thought about finding duplicates in C#, but not sure how to replace it so that the xml formats correctly.  I even tried grabbing the base data and just running an xml in excel after trying to delete every other line in the uci column, but that deletes all of the contact info, as name/address/etc are tied to the uci.

I thought this whole format was going to be needlessly complicated, and now I'm the one who has to fix it.


问:
Don't have permisson to access a file inside Electron directory
So I made my app in Electron to make a JSON file if it doesn't exist read its values, it works when I run through development.. but as soon as I package it it has a permission issue accessing the JSON from its own directory I even tried seeing if running it in admin perms would help but it didn't.

all I do it require it like let info = require("./info.json") then get a value like "version" by doing info.version like usual but it will complain about perms


问:
How to show data of two firebase collection in table on the base of ids in react js
I have these two collections. Now I want display these data in a table on the base of id that is highlighted.

Product Collections:

Category Table:

```<code>useEffect(() => {
   var list = [];
   const q = query(collection(db, "products"));
   onSnapshot( q,
        (snapShot) => {
            snapShot.docs.forEach((doc) => {
                list.push({ id: doc.id, ...doc.data() });
              });
              console.log(list);
        },
        (error) => {
            console.log(error);
        }
    );

}, []);

useEffect(() => {
    var list1 = [];
    const q = query(collection(db, "categories"));
   onSnapshot( q,
        (snapShot) => {
            snapShot.docs.forEach((doc) => {
                list1.push({ id: doc.id, ...doc.data() });
              });
            const children = list.concat(list1);
              console.log(children);
        },
        (error) => {
            console.log(error);
        }
    );
}, []);
</code>```

Body:
I have these two collections. Now I want display these data in a table on the base of id that is highlighted.

Product Collections:

Category Table:

useEffect(() => {
   var list = [];
   const q = query(collection(db, "products"));
   onSnapshot( q,
        (snapShot) => {
            snapShot.docs.forEach((doc) => {
                list.push({ id: doc.id, ...doc.data() });
              });
              console.log(list);
        },
        (error) => {
            console.log(error);
        }
    );

}, []);

useEffect(() => {
    var list1 = [];
    const q = query(collection(db, "categories"));
   onSnapshot( q,
        (snapShot) => {
            snapShot.docs.forEach((doc) => {
                list1.push({ id: doc.id, ...doc.data() });
              });
            const children = list.concat(list1);
              console.log(children);
        },
        (error) => {
            console.log(error);
        }
    );
}, []);


问:
Get Text from id="countdowndate" into new Date via Javascript
Apologies i know this is likely to be vey simple for many but appreciate the help. Im creating a countdown based on code collected from various spots including here.

The text date in the HTML ID "countdowndate" will be updated dynamically elsewhere. What i'd like to is replace the date in var end = new Date('10/26/2023 4:00 PM'); with the date from id="countdown". Full code below and thank you.

```<code><div class="gwd-page-content gwd-page-size">
          <!-- Display the countdown timer in an element -->
          <p id="countdown" class="gwd-p-1m9p"></p>
          <p id="countdowndate" class="gwd-p-hm4b">'10/26/2026 6:00 PM'</p>
        </div>
      </gwd-page>
    </gwd-pagedeck>
  </gwd-google-ad>
            <script>

            var end = new Date('10/26/2023 4:00 PM');

            var _second = 1000;
            var _minute = _second * 60;
            var _hour = _minute * 60;
            var _day = _hour * 24;
            var timer;

            function showRemaining() {
              var now = new Date();
              var nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
              var distance = end - nowUTC;
              if (distance < 0) {

                clearInterval(timer);
                document.getElementById('countdown').innerHTML = 'The Lottery Draw is Closed';

                return;
              }
              var days = Math.floor(distance / _day);
              var hours = Math.floor((distance % _day) / _hour);
              var minutes = Math.floor((distance % _hour) / _minute);
              var seconds = Math.floor((distance % _minute) / _second);

              document.getElementById('countdown').innerHTML = days + ' days ' + hours + ' hours ' + minutes + ' mins ' + seconds + ' secs';
            }

            timer = setInterval(showRemaining, 1000);
          </script>
</code>```

Tried lots of things but really shooting in the dark as im no coder.

Body:
Apologies i know this is likely to be vey simple for many but appreciate the help. Im creating a countdown based on code collected from various spots including here.

The text date in the HTML ID "countdowndate" will be updated dynamically elsewhere. What i'd like to is replace the date in var end = new Date('10/26/2023 4:00 PM'); with the date from id="countdown". Full code below and thank you.

'10/26/2026 6:00 PM'

      </gwd-page>
    </gwd-pagedeck>
  </gwd-google-ad>

Tried lots of things but really shooting in the dark as im no coder.


问:
WindowsCryptographicException: The system cannot find the file specified only on my computer
Currently I am receiving this exception when I try to debug a console application (.NET Core 3.1) Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: The system cannot find the file specified but comparing with other computers it doesn't happen.  There is no a cert file used to run it, there shouldn´t be an addition step but I still don't know why I am getting this exception.  I tried to run as administrator but nothing.

Code where it happens

```<code>using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;

namespace AppNamespace
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
                webBuilder
                    .UseStartup<Startup>())
            .ConfigureAppConfiguration((context, builder) =>
                builder
                    .AddEnvironmentVariables());

    }
}
</code>```

Stacktrace

```<code>   en Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
   en System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
   en System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password)
   en Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadCertificate(CertificateConfig certInfo, String endpointName)
   en Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadDefaultCert(ConfigurationReader configReader)
   en Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.Load()
   en Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.ValidateOptions()
   en Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<StartAsync>d__21`1.MoveNext()
   en Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__31.MoveNext()
   en Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__12.MoveNext()
   en Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   en Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   en Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   en Application.Program.Main(String[] args) en C:\Application\Application\Program.cs: línea 12
</code>```

Body:
Currently I am receiving this exception when I try to debug a console application (.NET Core 3.1) Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: The system cannot find the file specified but comparing with other computers it doesn't happen.  There is no a cert file used to run it, there shouldn´t be an addition step but I still don't know why I am getting this exception.  I tried to run as administrator but nothing.

Code where it happens

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;

namespace AppNamespace
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
                webBuilder
                    .UseStartup<Startup>())
            .ConfigureAppConfiguration((context, builder) =>
                builder
                    .AddEnvironmentVariables());

    }
}

Stacktrace

   en Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
   en System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
   en System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password)
   en Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadCertificate(CertificateConfig certInfo, String endpointName)
   en Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadDefaultCert(ConfigurationReader configReader)
   en Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.Load()
   en Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.ValidateOptions()
   en Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<StartAsync>d__21`1.MoveNext()
   en Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__31.MoveNext()
   en Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__12.MoveNext()
   en Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   en Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   en Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   en Application.Program.Main(String[] args) en C:\Application\Application\Program.cs: línea 12


问:
How to fix my function to obtain track ID by searching with Spotify API?
I would like to obtain the track ID from Spotify by searching with the track name. I have set up my Spotify developer account and am using spotipy. I found people with similar issues (Correct python syntax to search by artist in Spotify's Search API?) but cannot find any major differences between my code and the answers they received.

Here is my function. I am not getting any error messages, but it keeps returning "None." What should I change?

```<code>def get_id(track_name:str, token:str) -> str:
    headers = {
    'Accept':'application/json',
    'Content-Type':'application/json',
    'Authorization': 'Bearer {tokenjson}'.format(tokenjson=auth_token)
    }
    params = {
    'q':track_name,
    'type':'track'
    }
    try:
        response =  requests.get('https://api.spotify.com/v1/search',
                    headers = headers,
                    params = params
                    )
        json = response.json()
        first_result = json['tracks']['items'][0]
        track_id = first_result['id']
        return track_id
    except:
        return None
</code>```

Body:
I would like to obtain the track ID from Spotify by searching with the track name. I have set up my Spotify developer account and am using spotipy. I found people with similar issues (Correct python syntax to search by artist in Spotify's Search API?) but cannot find any major differences between my code and the answers they received.

Here is my function. I am not getting any error messages, but it keeps returning "None." What should I change?

def get_id(track_name:str, token:str) -> str:
    headers = {
    'Accept':'application/json',
    'Content-Type':'application/json',
    'Authorization': 'Bearer {tokenjson}'.format(tokenjson=auth_token)
    }
    params = {
    'q':track_name,
    'type':'track'
    }
    try:
        response =  requests.get('https://api.spotify.com/v1/search',
                    headers = headers,
                    params = params
                    )
        json = response.json()
        first_result = json['tracks']['items'][0]
        track_id = first_result['id']
        return track_id
    except:
        return None


问:
How to properly sanitize user input in WordPress search form: get_search_query()
I am attempting to sanitize user input for a search form that I am building in WordPress (in searchform.php file).

I used a built-in WordPress function, sanitize_text_field():

```<code>function wpdocs_my_search_form( $form ) {
    $search_query = sanitize_text_field( get_search_query() );

    $form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
    <div><label class="screen-reader-text" for="s">' . __( 'Search for:' ) . '</label>
    <input type="text" value="' . $search_query . '" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
    </div>
    </form>';

    return $form;
}
add_filter( 'get_search_form', 'wpdocs_my_search_form' );
</code>```

This however, is still not properly sanitizing input such as

I also attempted to add additional code to detect if it has been submitted however, that is also not working. I would appreciate any direction/pointers.

Body:
I am attempting to sanitize user input for a search form that I am building in WordPress (in searchform.php file).

I used a built-in WordPress function, sanitize_text_field():

function wpdocs_my_search_form( $form ) {
    $search_query = sanitize_text_field( get_search_query() );

    $form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >

' . __( 'Search for:' ) . '
    <input type="text" value="' . $search_query . '" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />

    </form>';

    return $form;
}
add_filter( 'get_search_form', 'wpdocs_my_search_form' );

This however, is still not properly sanitizing input such as

I also attempted to add additional code to detect if it has been submitted however, that is also not working. I would appreciate any direction/pointers.


问:
Malformed entry 1 in list file /etc/apt/sources.list.d/mongodb-org-6.0.list (Component)
I was trying to install MongoDb on Ubuntu 22.04 but i couldnt or there were some errors so I decided uninstall everything and reinstall fresh. So i did some purge commands that i found on the net and after doing that now if I do: sudo apt update

i get the following messages

E: Malformed entry 1 in list file /etc/apt/sources.list.d/mongodb-org-6.0.list (Component)
E: The list of sources could not be read.

i used the following command to delete mongodb >sudo apt-get purge mongodb-org* –
Getting $ sudo apt-get purge mongodb-enterprise E: Malformed entry 1 in list file /etc/apt/sources.list.d/mongodb-enterprise.list (URI) E: The list of sources could not be read. E: Malformed entry 1 in list file /etc/apt/sources.list.d/mongodb-enterprise.list (URI) E: The list of sources could not be read..

I also used the following command to delete mongodb > sudo rm /etc/apt/sources.list.d/MongoDb.list
here again i am getting the following message :-

sudo rm /etc/apt/sources.list.d/MongoDb.list
rm: cannot remove '/etc/apt/sources.list.d/MongoDb.list': No such file or directory


问:
Celery doesn't wait for tasks to finish
I am running a FastApi backend that is supposed to accept /generate calls and spin up model training processes. Given that the GPU capacity is limited, I am trying to implement a queue with Celery backed by Amazon SQS. For some reason, celery doesn't wait for my previous task to accomplish despite me using the delay() call.

For reference, my router file

```<code>from workers.trainer import trainModel

...

@app.post("/generate")
async def generate(
   images: List[UploadFile] = File(...),
   deviceId: str = Form(...),
):
    ...
    # some preprocessing
    ...
    trainModel.delay()

    return response
</code>```

and my worker code

```<code>from celery import Celery
import boto3

...

app = Celery("my_app", broker=f"sqs://{awsAccessKeyId}:{awsSecretAccessKey}@")

@app.task(name="trainModel")
def trainModel(deviceId: str, unique_token: str) -> str:
    # train the model here
    # Note: doesn't return anything

</code>```

Tried async_apply as well but same issue. The processing of tasks starts happening in parallel instead of being queued.

Title: Celery doesn't wait for tasks to finish

Body:
I am running a FastApi backend that is supposed to accept /generate calls and spin up model training processes. Given that the GPU capacity is limited, I am trying to implement a queue with Celery backed by Amazon SQS. For some reason, celery doesn't wait for my previous task to accomplish despite me using the delay() call.

For reference, my router file

from workers.trainer import trainModel

...

@app.post("/generate")
async def generate(
   images: List[UploadFile] = File(...),
   deviceId: str = Form(...),
):
    ...
    # some preprocessing
    ...
    trainModel.delay()

    return response

and my worker code

from celery import Celery
import boto3

...

app = Celery("my_app", broker=f"sqs://{awsAccessKeyId}:{awsSecretAccessKey}@")

@app.task(name="trainModel")
def trainModel(deviceId: str, unique_token: str) -> str:
    # train the model here
    # Note: doesn't return anything

Tried async_apply as well but same issue. The processing of tasks starts happening in parallel instead of being queued.


问:
designing distributed system with celery and rabbitMQ
Consider the following high level design:

I have a server (call it rabbitMQ) and it create some tasks and place them in a messaging queue.

some servers (A,B,C,D...) 'see' that there are some tasks on the queue and they take a task to process on their end.

My questions:

is this explanation is correct in terms of distributed system design? and

if so where does the celery comes into play? is it on the serverA/B or C side? so each has its own celery?


问:
Unable to auto adjust the height and width of iframe and weird behavior when reloading the iframe
I am using the iframe tag and it has an image embedded in it.
This is my code:

https://jsfiddle.net/uLsg1pw9/7/

My first problem is that the iframe doesn't auto adjust its height and width depending on the picture. I have to scroll through the frame to see the full picture. I want the iframe itself to have the whole picture. I tried this: make iframe height dynamic based on content inside- JQUERY/Javascript

```<code>ARiframe.height = ARiframe.contentWindow.document.body.scrollHeight + "px";
</code>```

but that did not seem to do the trick.

My second problem is that when I click on the picture, it does reload the iframe (as expected) but the image disappears. What happened to the image and how do I prevent it from disappearing?

Body:
I am using the iframe tag and it has an image embedded in it.
This is my code:

https://jsfiddle.net/uLsg1pw9/7/

My first problem is that the iframe doesn't auto adjust its height and width depending on the picture. I have to scroll through the frame to see the full picture. I want the iframe itself to have the whole picture. I tried this: make iframe height dynamic based on content inside- JQUERY/Javascript

ARiframe.height = ARiframe.contentWindow.document.body.scrollHeight + "px";

but that did not seem to do the trick.

My second problem is that when I click on the picture, it does reload the iframe (as expected) but the image disappears. What happened to the image and how do I prevent it from disappearing?


问:
Can you render jsp/html elements (i.e. a form:form) dynamically in one page?
I am new to web-dev, and coding in general, so I apologize if this question doesn't make sense.

Background: I am working on a web application utilizing the Spring Framework.  My application allows users to register a user account, post pictures, make comments on pictures, like pictures etc. (think of a mini Pintrest clone).  Users and comments (along with some other non-relevant entities) are all saved as in table entities in a MySQL database.

Problem: I would like users be able to edit their comments after they post them.  For the best user experience  I do not want users to be taken to a separate page with a form to edit their comment.  I would like user to be able to edit their comment in a single page/the same page, without rendering a new one. Flow goes something like this: User goes to their comment on a picture, presses an "edit" button/link and the comment is put in a text box (form:form) which is then editable.

So far I have tried conditional rendering with a boolean switch of "editPressed" but I can't seem to work out the logic.  Is this the correct approach or should something like JS be used here? (not sure how js handles form:forms) Below are some code snippets of the models and the .jsp where the comment would be edited.

.jsp:

```<code><c:forEach var="eachComment" items="${allCommentsByPhotoId}">
    <div class="card-text d-flex gap-2 mb-4">

        <img class="user-comment-card" src="https://cdn-icons-png.flaticon.com/512/1053/1053244.png" alt="" />

        <div>

            <div class="mb-2">
                <c:choose>
                    <c:when test="${ editPressed == false }">
                        <c:out value="${eachComment.user.getFirstName()} says: ${ eachComment.getComment() }"></c:out>
                    </c:when>
                    <c:otherwise>
                        <span class="username">
                            <c:out value="${eachComment.user.getFirstName()}"></c:out>:
                        </span>
                        <c:out value="${ eachComment.getComment()}"></c:out>
                    </c:otherwise>
                </c:choose>
            </div>
            <div class="d-flex align-items-center gap-3">

                <!--  -->

                <c:if test="${ eachComment.user.getId() == currentUser.id }">

                    <form:form action="/delete/${eachComment.getId()}" method="delete">
                        <p class="submit">
                            <input class="btn btn-danger del-cmt-btn" type="submit" value="Delete" />
                        </p>
                    </form:form>

                    <form:form action="/edit/comment/${eachComment.getId()}">
                        <p class="submit">
                            <input class="btn btn-secondary edit-cmt-btn" type="submit" value="Edit" />
                        </p>
                    </form:form>
                </c:if>
            </div>
        </div>
    </div>
</c:forEach>
</code>```

Comment Model:

```<code>@Entity
@Table(name="user_comments_on_photo")
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String comment;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="photo_id")
    private Photo photo;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(
            name="user_likes_comment",
            joinColumns = @JoinColumn(name="comment_id"),
            inverseJoinColumns = @JoinColumn(name="user_id")
            )
    private List<User> usersWhoLikeComment;

    @Column(updatable=false)
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date createdAt;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date updatedAt;
</code>```

USER MODEL:

```<code>    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Size(min=3)
    private String firstName;

    @Size(min=3)
    private String lastName;

    @Email
    private String email;

    @Size(min=8)
    private String password;

    @Transient
    private String passwordConfirmation;

    @Column(updatable=false)
    private Date createdAt;
    private Date updatedAt;

    //RELATIONSHIPS
    @OneToMany(mappedBy="user", fetch = FetchType.LAZY)
    private List<Photo> photos;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "user_likes_photo",
            joinColumns = @JoinColumn(name="user_id"),
            inverseJoinColumns = @JoinColumn(name="photo_id")
            )
    private List<Photo> likedPhotos;

    //NEW ONE-TO-MANY
    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    private List<Comment> userComments;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(
            name="user_likes_comment",
            joinColumns = @JoinColumn(name="user_id"),
            inverseJoinColumns = @JoinColumn(name="comment_id")
            )
    private List<Comment> commentsUserLikes;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "users_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
    private List<Role> roles;

</code>```

PHOTO MODEL:

```<code>@Entity
@Table(name="photos")
public class Photo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String photoURL;
    private String photoFileName;

    @NotEmpty
    private String photoTitle;
    @NotEmpty
    private String photoDescription;
    //will add tags later

    //RELATIONSHIPS
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(
            name="user_likes_photo",
            joinColumns = @JoinColumn(name="photo_id"),
            inverseJoinColumns = @JoinColumn(name="user_id")
            )
    private List<User> usersWhoLikePhoto;

    //NEW ONE-TO-MANY
    @OneToMany(mappedBy="photo", fetch = FetchType.LAZY)
    private List<Comment> comments;

    //CREATED AND UPDATED AT
    @Column(updatable=false)
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date createdAt;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date updatedAt;
</code>```

Body:
I am new to web-dev, and coding in general, so I apologize if this question doesn't make sense.

Background: I am working on a web application utilizing the Spring Framework.  My application allows users to register a user account, post pictures, make comments on pictures, like pictures etc. (think of a mini Pintrest clone).  Users and comments (along with some other non-relevant entities) are all saved as in table entities in a MySQL database.

Problem: I would like users be able to edit their comments after they post them.  For the best user experience  I do not want users to be taken to a separate page with a form to edit their comment.  I would like user to be able to edit their comment in a single page/the same page, without rendering a new one. Flow goes something like this: User goes to their comment on a picture, presses an "edit" button/link and the comment is put in a text box (form:form) which is then editable.

So far I have tried conditional rendering with a boolean switch of "editPressed" but I can't seem to work out the logic.  Is this the correct approach or should something like JS be used here? (not sure how js handles form:forms) Below are some code snippets of the models and the .jsp where the comment would be edited.

.jsp:

<c:forEach var="eachComment" items="${allCommentsByPhotoId}">

                <c:choose>
                    <c:when test="${ editPressed == false }">
                        <c:out value="${eachComment.user.getFirstName()} says: ${ eachComment.getComment() }"></c:out>
                    </c:when>
                    <c:otherwise>

                            <c:out value="${eachComment.user.getFirstName()}"></c:out>:

                        <c:out value="${ eachComment.getComment()}"></c:out>
                    </c:otherwise>
                </c:choose>

                <c:if test="${ eachComment.user.getId() == currentUser.id }">

                    <form:form action="/delete/${eachComment.getId()}" method="delete">

                            <input class="btn btn-danger del-cmt-btn" type="submit" value="Delete" />

                    </form:form>

                    <form:form action="/edit/comment/${eachComment.getId()}">

                            <input class="btn btn-secondary edit-cmt-btn" type="submit" value="Edit" />

                    </form:form>
                </c:if>

</c:forEach>

Comment Model:

@Entity
@Table(name="user_comments_on_photo")
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String comment;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="photo_id")
    private Photo photo;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(
            name="user_likes_comment",
            joinColumns = @JoinColumn(name="comment_id"),
            inverseJoinColumns = @JoinColumn(name="user_id")
            )
    private List<User> usersWhoLikeComment;

    @Column(updatable=false)
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date createdAt;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date updatedAt;

USER MODEL:

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Size(min=3)
    private String firstName;

    @Size(min=3)
    private String lastName;

    @Email
    private String email;

    @Size(min=8)
    private String password;

    @Transient
    private String passwordConfirmation;

    @Column(updatable=false)
    private Date createdAt;
    private Date updatedAt;

    //RELATIONSHIPS
    @OneToMany(mappedBy="user", fetch = FetchType.LAZY)
    private List<Photo> photos;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "user_likes_photo",
            joinColumns = @JoinColumn(name="user_id"),
            inverseJoinColumns = @JoinColumn(name="photo_id")
            )
    private List<Photo> likedPhotos;

    //NEW ONE-TO-MANY
    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    private List<Comment> userComments;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(
            name="user_likes_comment",
            joinColumns = @JoinColumn(name="user_id"),
            inverseJoinColumns = @JoinColumn(name="comment_id")
            )
    private List<Comment> commentsUserLikes;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "users_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
    private List<Role> roles;

PHOTO MODEL:

@Entity
@Table(name="photos")
public class Photo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String photoURL;
    private String photoFileName;

    @NotEmpty
    private String photoTitle;
    @NotEmpty
    private String photoDescription;
    //will add tags later

    //RELATIONSHIPS
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(
            name="user_likes_photo",
            joinColumns = @JoinColumn(name="photo_id"),
            inverseJoinColumns = @JoinColumn(name="user_id")
            )
    private List<User> usersWhoLikePhoto;

    //NEW ONE-TO-MANY
    @OneToMany(mappedBy="photo", fetch = FetchType.LAZY)
    private List<Comment> comments;

    //CREATED AND UPDATED AT
    @Column(updatable=false)
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date createdAt;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date updatedAt;


问:
Flutter how to requestFocus for a FocusNode?
I'm trying to give focus to a FocusNode on a tap. I can do this with a GestureDetector's onTap callback but I am running into an issue of propagation in nested GestureDetectors as noted in the documents:

Given a parent GestureDetector with an onTap callback, and a child GestureDetector that also defines an onTap callback, when the inner GestureDetector is tapped, both GestureDetectors send a GestureRecognizer into the gesture arena. This is because the pointer coordinates are within the bounds of both GestureDetectors. The child GestureDetector wins in this scenario because it was the first to enter the arena, resolving as first come, first served. The child onTap is called, and the parent's is not as the gesture has been consumed.

This causes an issue for me if I have a deep section of a window to be considered "in focus" such as a row in a DataTable that will listen for certain shortcuts, like the delete key, but I also want other widgets which are higher up in the window to listen for a ESC or Enter key.

If I use a GestureDetector to request focus then it is consumed. Is there some other way to requestFocus() instead of a GestureDector so that I'm not trapping myself?


问:
Rotating second object to match rotation of first object relative to camera in Unity

I am attempting to make an object that is attached to the UI achieve the same appearance/rotation relative to the camera as an object that is being looked at in world space. For example in the image, how would I get the cube in the black UI which is fixed to the camera to look the same as the cube in world space no matter what angle I viewed the world space cube from/How would I get the UI cube to change its rotation to match the world space cube based on what angle I was viewing the world space cube from in real time?

I'm not wanting another camera view as a solution as I would like to change the object in the UI to other objects.


问:
VSCode Vim Addon: How do I set up Insert mode to basicity be normal VSCode (Vim disabled)?
I love the keyboard shortcuts offered in Vim Normal mode and find them very helpful but I also like the keyboard shortcuts in normal VSCode. For example all the multi-cursor stuff. like ctrl+d (highlight next occurrence) or ctrl+f2: (highlight all occurrences).  For some reason whenever I use ctrl+d or ctrl+f2 it appears to work normally but puts me in visual mode even though I have turned off mouse selection goes into Visual mode.

TL/DR: Basically I just want Vim to act like it is off when in Insert mode but still allow me to go to normal mode with Escape

Current Settings/Preferences

User/settings.json:

```<code>    "vim.useCtrlKeys": false, //appears to not work for me, I just removed bindings for some stuff with ctrl keys
    "vim.startInInsertMode": true,
    "vim.mouseSelectionGoesIntoVisualMode": false,
    "vim.smartRelativeLine": true,
    "vim.useSystemClipboard": true,
</code>```

User/keybindings.json:

(minus sign in front of command means it is disabled):

```<code>    {
        "key": "shift+alt+down",
        "command": "-extension.vim_cmd+alt+down",
        "when": "editorTextFocus && vim.active && !inDebugRepl"
    },
    {
        "key": "shift+alt+up",
        "command": "-extension.vim_cmd+alt+up",
        "when": "editorTextFocus && vim.active && !inDebugRepl"
    },
    {
        "key": "ctrl+d",
        "command": "-extension.vim_ctrl+d",
        "when": "editorTextFocus && vim.active && vim.use<C-d> && !inDebugRepl"
    }
</code>```

OS: Windows 11 (don't bully me plz)

Body:
I love the keyboard shortcuts offered in Vim Normal mode and find them very helpful but I also like the keyboard shortcuts in normal VSCode. For example all the multi-cursor stuff. like ctrl+d (highlight next occurrence) or ctrl+f2: (highlight all occurrences).  For some reason whenever I use ctrl+d or ctrl+f2 it appears to work normally but puts me in visual mode even though I have turned off mouse selection goes into Visual mode.

TL/DR: Basically I just want Vim to act like it is off when in Insert mode but still allow me to go to normal mode with Escape

Current Settings/Preferences

User/settings.json:

    "vim.useCtrlKeys": false, //appears to not work for me, I just removed bindings for some stuff with ctrl keys
    "vim.startInInsertMode": true,
    "vim.mouseSelectionGoesIntoVisualMode": false,
    "vim.smartRelativeLine": true,
    "vim.useSystemClipboard": true,

User/keybindings.json:

(minus sign in front of command means it is disabled):

    {
        "key": "shift+alt+down",
        "command": "-extension.vim_cmd+alt+down",
        "when": "editorTextFocus && vim.active && !inDebugRepl"
    },
    {
        "key": "shift+alt+up",
        "command": "-extension.vim_cmd+alt+up",
        "when": "editorTextFocus && vim.active && !inDebugRepl"
    },
    {
        "key": "ctrl+d",
        "command": "-extension.vim_ctrl+d",
        "when": "editorTextFocus && vim.active && vim.use<C-d> && !inDebugRepl"
    }

OS: Windows 11 (don't bully me plz)


问:
How to extract data from a rose chart (image)?
I want to extract the data from this chart which is a rose chart

I want to figure out the percentage of each leaflet

I was looking for a tool to convert the image into data, or an algorithm to do that


问:
How to get texture2d pixels positions?
```<code>using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class ReadPixelsFromImage : MonoBehaviour
{
    public Texture2D texture2DWithClouds;
    public Texture2D textxture2DWithoutClouds;
    public RawImage ri;

    // Start is called before the first frame update
    void Start()
    {
        ReadPixelsFromT2D(texture2DWithClouds, textxture2DWithoutClouds);
        ri.texture = texture2DWithClouds;
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void ReadPixelsFromT2D(Texture2D Texturewithclouds, Texture2D Texturewithoutclouds)
    {
        Color[] colorswithclouds = Texturewithclouds.GetPixels();
        Color[] colorswithoutclouds = Texturewithoutclouds.GetPixels();

        for (int i = 0; i < colorswithclouds.Length; i++)
        {
            if (colorswithclouds[i] != colorswithoutclouds[i])
            {
                colorswithclouds[i] = Color.yellow;
            }
        }

        Texturewithclouds.SetPixels(colorswithclouds);
        Texturewithclouds.Apply();
    }
}
</code>```

i want from another script to raycast hit on this pixels.

so color in yellow the pixels that are only under the rotating transform.
now i'm coloring in yellow all the pixels i'm getting but i want that it will color only the pixels that are under the rotating transform.

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Unity.VisualScripting.Member;

public class ConeRotation : MonoBehaviour
{
    public float rotSpeed = 250;
    public float damping = 10;
    public Texture2D texture2DSpriteWithClouds;
    public Texture2D texture2DSpriteWithoutClouds;
    public Vector3 point;

    private float desiredRot;
    private bool autoRotate = false;
    private Color borderColor = new Color(255, 0, 0);

    // Start is called before the first frame update
    void Start()
    {
        desiredRot = transform.eulerAngles.z;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
            else desiredRot += rotSpeed * Time.deltaTime;
        }

        if (Input.GetMouseButton(1))
        {
            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
            else desiredRot -= rotSpeed * Time.deltaTime;
        }

        if (Input.GetMouseButtonDown(2))
        {
            autoRotate = !autoRotate; // To make here that each time stopped
            // then when continue to rotate to change rotation direction.
        }

        if (autoRotate)
        {
            desiredRot += rotSpeed * Time.deltaTime;
        }

        var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y, desiredRot);
        transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * damping);

        Vector3 dir = transform.position - point;
        Ray r = new Ray(transform.position, dir);
        if (Physics.Raycast(r))
        {

        }
    }
}
</code>```

i added this part :

```<code>Vector3 dir = transform.position - point;
        Ray r = new Ray(transform.position, dir);
        if (Physics.Raycast(r))
        {

        }
</code>```

but not sure how to get the point(Vector3) of each pixels from the top script ReadPixelsFromImage.

Title: How to get texture2d pixels positions?

Body:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class ReadPixelsFromImage : MonoBehaviour
{
    public Texture2D texture2DWithClouds;
    public Texture2D textxture2DWithoutClouds;
    public RawImage ri;

    // Start is called before the first frame update
    void Start()
    {
        ReadPixelsFromT2D(texture2DWithClouds, textxture2DWithoutClouds);
        ri.texture = texture2DWithClouds;
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void ReadPixelsFromT2D(Texture2D Texturewithclouds, Texture2D Texturewithoutclouds)
    {
        Color[] colorswithclouds = Texturewithclouds.GetPixels();
        Color[] colorswithoutclouds = Texturewithoutclouds.GetPixels();

        for (int i = 0; i < colorswithclouds.Length; i++)
        {
            if (colorswithclouds[i] != colorswithoutclouds[i])
            {
                colorswithclouds[i] = Color.yellow;
            }
        }

        Texturewithclouds.SetPixels(colorswithclouds);
        Texturewithclouds.Apply();
    }
}

i want from another script to raycast hit on this pixels.

so color in yellow the pixels that are only under the rotating transform.
now i'm coloring in yellow all the pixels i'm getting but i want that it will color only the pixels that are under the rotating transform.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Unity.VisualScripting.Member;

public class ConeRotation : MonoBehaviour
{
    public float rotSpeed = 250;
    public float damping = 10;
    public Texture2D texture2DSpriteWithClouds;
    public Texture2D texture2DSpriteWithoutClouds;
    public Vector3 point;

    private float desiredRot;
    private bool autoRotate = false;
    private Color borderColor = new Color(255, 0, 0);

    // Start is called before the first frame update
    void Start()
    {
        desiredRot = transform.eulerAngles.z;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
            else desiredRot += rotSpeed * Time.deltaTime;
        }

        if (Input.GetMouseButton(1))
        {
            if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime;
            else desiredRot -= rotSpeed * Time.deltaTime;
        }

        if (Input.GetMouseButtonDown(2))
        {
            autoRotate = !autoRotate; // To make here that each time stopped
            // then when continue to rotate to change rotation direction.
        }

        if (autoRotate)
        {
            desiredRot += rotSpeed * Time.deltaTime;
        }

        var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y, desiredRot);
        transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * damping);

        Vector3 dir = transform.position - point;
        Ray r = new Ray(transform.position, dir);
        if (Physics.Raycast(r))
        {

        }
    }
}

i added this part :

Vector3 dir = transform.position - point;
        Ray r = new Ray(transform.position, dir);
        if (Physics.Raycast(r))
        {

        }

but not sure how to get the point(Vector3) of each pixels from the top script ReadPixelsFromImage.