问:
How to run some element in recyle from an array?
Well, I know my question is very difficult. But I want to know Things?

Suppose, I have an array element?

```<code>const array = [
   "AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
]
</code>```

I need here on Function that can run only 10 element every time. When I run function for first time it's show me first 10 element. Then If I run again then it show me the rest element.

Suppose this is function

```<code>const runElement = () => {
    console.log(element)
}
</code>```

If I run this function first time it show me first 10 element from array.

```<code>"AEDAUD"
"AEDCAD"
"AEDCHF"
"AEDEUR"
"AEDGBP"
"AEDINR"
"AEDJPY"
"AEDNOK"
"AEDNZD"
"AEDPKR"
</code>```

Then If I run that function again it should show me the rest element-

```<code>"AEDSAR"
"AEDSEK"
"AEDZAR"
"ANG"
"ARSBRL"
"ARSEUR"
"ARSGBP"
</code>```

If I run the function again it should go first 10 element again. In that It should run for always.

Is this possible in javascript?

答:
You can use a variable to store a flag and the function can reference to this variable to output differently.

const array = [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "10",
    "11",
    "12",
    "13",
    "14",
    "15",
    "16",
    "17",
];

let isShowFirstTenItem = true;
const show = () => {
    let output;
    if (isShowFirstTenItem) {
        output = array.slice(0, 10);
    } else {
        output = array.slice(10, -1);
    }
    isShowFirstTenItem = !isShowFirstTenItem;
    console.log(output);
};

show();
show();
show();```

Body:
Well, I know my question is very difficult. But I want to know Things?

Suppose, I have an array element?

const array = [
   "AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
]

I need here on Function that can run only 10 element every time. When I run function for first time it's show me first 10 element. Then If I run again then it show me the rest element.

Suppose this is function

const runElement = () => {
    console.log(element)
}

If I run this function first time it show me first 10 element from array.

"AEDAUD"
"AEDCAD"
"AEDCHF"
"AEDEUR"
"AEDGBP"
"AEDINR"
"AEDJPY"
"AEDNOK"
"AEDNZD"
"AEDPKR"

Then If I run that function again it should show me the rest element-

"AEDSAR"
"AEDSEK"
"AEDZAR"
"ANG"
"ARSBRL"
"ARSEUR"
"ARSGBP"

If I run the function again it should go first 10 element again. In that It should run for always.

Is this possible in javascript?


来源: stackexchange

问:
Best way to create a wix fragment file based on User-defined directories to be used in MSBUILD
In the spirit of this question by Si here: WiX tricks and tips.  I am trying to determine the best way to get create wix fragments based on a directories.  File harvesting, so to speak.  For example under the bin\release folder I could have many different folders plus files that I want to capture very easily in fragments.  I have been doing this by typing them or using wixedit.

Please note I haven't tried anything just done the reasearch here:
A)I read a little bit on heat.(http://installing.blogspot.com/2006/04/heatexe-making-setup-easier.html)  I am not sure though about running it from msbuild?
B)I found this blog article from Newagesolution which discusses using t4 script: http://blog.newagesolution.net/2008/06/how-to-use-msbuild-and-wix-to-msi.html

I would like to know what others are doing to solve this.

Regards, Brian

答: For what it's worth, we are, in fact, using heat.exe from msbuild. If you're as picky as I am, the output of heat is probably not exactly what you want, but this is easy to rectify with an XSL transformation (I believe heat.exe has a command-line parameter expressly for this purpose).</p>

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Daniel Pratt


问:
Total digits are inconsistent
I m using following code to get random hex values. But the output is inconsistent
Sometimes it returns 6 digits sometimes 5 digits</p>

```<code>function generateHexValue($length=6)
{
    $chars = "0123456789abcdef";

    $i = 0;
    $str = "";

    while ($i<$length) {
        $str .= $chars[mt_rand(0,strlen($chars))];
        $i++;
    }

    return $str;
}

$col=generateHexValue();
echo "<div style='background-color:#".$col."; width:100px; height:100px;'></div>";
echo $col."<br/>";
</code>```

答: substr(md5(mt_rand()), 0, 6) does the same thing but faster.

ContentLicense: CC BY-SA 3.0

Title: Total digits are inconsistent

Body:
I m using following code to get random hex values. But the output is inconsistent
Sometimes it returns 6 digits sometimes 5 digits

function generateHexValue($length=6)
{
    $chars = "0123456789abcdef";

    $i = 0;
    $str = "";

    while ($i<$length) {
        $str .= $chars[mt_rand(0,strlen($chars))];
        $i++;
    }

    return $str;
}

$col=generateHexValue();
echo "

";
echo $col."
";


问:
Handle state variable initialization
I'm trying to fill form data using state variable. Data of state variable is getting from redux store as shown below :

```<code>  const [location, setLocation] = useState(post && post.location);
  const [hastage, setHastage] = useState(post && post.hastage);
  const [caption, setCaption] = useState(post && post.caption);
  const [postImg, setPostImg] = useState(post && post.postImg);
</code>```

In above code 'post' is redux store instance.

Every thing is working Fine. However, Problem is that :

When I refresh page 'post' data is async call therefore before getting post data all variable is initialized with " "(Blank). and form is getting empty.

Hoe to initialize all state variable after 'post' data is ready ?

答:
You can use an useEffect with post as a dependency, where it updates all states values if post exists.

```<code>useEffect(() => {
  if (post) {
    setLocation(post.location)
    setHastage(post.hastage)
    setCaption(post.caption)
    setPostImg(post.postImg)
  }
}, [post])
</code>```

ContentLicense: CC BY-SA 4.0

Title: Handle state variable initialization

Body:
I'm trying to fill form data using state variable. Data of state variable is getting from redux store as shown below :

  const [location, setLocation] = useState(post && post.location);
  const [hastage, setHastage] = useState(post && post.hastage);
  const [caption, setCaption] = useState(post && post.caption);
  const [postImg, setPostImg] = useState(post && post.postImg);

In above code 'post' is redux store instance.

Every thing is working Fine. However, Problem is that :

When I refresh page 'post' data is async call therefore before getting post data all variable is initialized with " "(Blank). and form is getting empty.

Hoe to initialize all state variable after 'post' data is ready ?

Body:
You can use an useEffect with post as a dependency, where it updates all states values if post exists.

useEffect(() => {
  if (post) {
    setLocation(post.location)
    setHastage(post.hastage)
    setCaption(post.caption)
    setPostImg(post.postImg)
  }
}, [post])


问:
Android Emulator issues in new versions - The emulator process has terminated
After updating to Android Studio 2020.3.1 canary 15, when I try to run an emulator, it gets killed with this error:

The emulator process for AVD Pixel_4_API_30 has terminated.

It was working correctly in the previous version (4.1.3), but now after installing the new one, it shows the same error.

I've tried some solutions had suggested in almost similar cases; however, It still doesn't work.

I deleted my emulator (also I cleared inside of directory: /.android/avd/) and created a new one again

I updated the HAXM installer to version 7.6.5

I tried to run an emulator with lower APIs but...

Image of the error:

答:
change the "Graphics" property in the AVD,choose "Soft ware --Gles2.0".
it works for me.</p>


问:
Regex for validating comma separated java fields, referenced fields, and Sets
I have a code which parses comma separated names of java class fields, and optionally field names with class names and dot operator(i.e. foreign fields) and also set/array like notation to refer to multiple foreign fields without using class name multiple times: e.g. following are valid scenarios:

MyField1,MyField2,AnotherClass.ACField1,AnotherClass2[AC2Field1,AC2Field2,AC2Field3]

MyField1,MyField2

I have written following regex/java code:
But see the last line in main method (i.e. first example above). It should be valid but regex is not matching.

```<code>import java.util.regex.Pattern;

public class RegexTest {

  static Pattern fieldListPattern = Pattern.compile("^(\\w+)(([.,]\\w+)|([\\[]\\w+([,]?\\w+)[\\]]))*$");

  public static void main(String[] args) {
    validate("MyField1,MyField2"); // valid
    validate("ABC,A.CDE"); // valid
    validate("ABC"); // valid
    validate("ABC,CDE"); // valid
    validate("ABC.CDE"); // valid
    validate("ABC,.CDE"); // XXXXXXX
    validate("ABC.,CDE"); // XXXXXXX
    validate(",ABC,CDE"); // XXXXXXX
    validate(",ABC"); // XXXXXXX
    validate(".ABC"); // XXXXXXX
    validate(".ABC.CDE"); // XXXXXXX
    validate(".ABC,CDE"); // XXXXXXX
    validate(",ABC.CDE"); // XXXXXXX

    // arrays

    validate("ABC[CDE]"); // Valid
    validate("ABC[]"); // XXXXXXX
    validate("ABC.[CDE]"); // XXXXXXX
    validate("MyField1,MyField2,AnotherClass.ACField1,AnotherClass2[AC2Field1,AC2Field2]"); // Valid
    validate("MyField1,MyField2,AnotherClass.ACField1,AnotherClass2[AC2Field1,AC2Field2,AC2Field3]"); // This should be valid, but coming as invalid
  }

  static void validate(String s) {
    System.out.println(s);
    fieldListPattern.matcher("").matches();
    System.out.println("Valid ? " + fieldListPattern.matcher(s).matches());
  }
}
</code>```

答:
As a pattern, you can optionally repeat matching from an opening till closing square bracket:

```<code>^\w+(?:\[\w+(?:,\w+)*\])?(?:[.,]\w+(?:\[\w+(?:,\w+)*\])?)*$
</code>```

^ Start of string

\w+ Match 1+ word chars

(?:\[\w+(?:,\w+)*\])? Optionally match word characters separated by a comma in between square brackets

(?: Non capture group

[.,] Match either . or ,

\w+(?:\[\w+(?:,\w+)*\])*

)? Close the group and make it optional

$ End of string

Regex demo

In Java with the double escaped backslashes:

```<code>String regex = "^\\w+(?:\\[\\w+(?:,\\w+)*\\])?(?:[.,]\\w+(?:\\[\\w+(?:,\\w+)*\\])?)*$";
</code>```

Body:
I have a code which parses comma separated names of java class fields, and optionally field names with class names and dot operator(i.e. foreign fields) and also set/array like notation to refer to multiple foreign fields without using class name multiple times: e.g. following are valid scenarios:

MyField1,MyField2,AnotherClass.ACField1,AnotherClass2[AC2Field1,AC2Field2,AC2Field3]

MyField1,MyField2

I have written following regex/java code:
But see the last line in main method (i.e. first example above). It should be valid but regex is not matching.

import java.util.regex.Pattern;

public class RegexTest {

  static Pattern fieldListPattern = Pattern.compile("^(\\w+)(([.,]\\w+)|([\\[]\\w+([,]?\\w+)[\\]]))*$");

  public static void main(String[] args) {
    validate("MyField1,MyField2"); // valid
    validate("ABC,A.CDE"); // valid
    validate("ABC"); // valid
    validate("ABC,CDE"); // valid
    validate("ABC.CDE"); // valid
    validate("ABC,.CDE"); // XXXXXXX
    validate("ABC.,CDE"); // XXXXXXX
    validate(",ABC,CDE"); // XXXXXXX
    validate(",ABC"); // XXXXXXX
    validate(".ABC"); // XXXXXXX
    validate(".ABC.CDE"); // XXXXXXX
    validate(".ABC,CDE"); // XXXXXXX
    validate(",ABC.CDE"); // XXXXXXX

    // arrays

    validate("ABC[CDE]"); // Valid
    validate("ABC[]"); // XXXXXXX
    validate("ABC.[CDE]"); // XXXXXXX
    validate("MyField1,MyField2,AnotherClass.ACField1,AnotherClass2[AC2Field1,AC2Field2]"); // Valid
    validate("MyField1,MyField2,AnotherClass.ACField1,AnotherClass2[AC2Field1,AC2Field2,AC2Field3]"); // This should be valid, but coming as invalid
  }

  static void validate(String s) {
    System.out.println(s);
    fieldListPattern.matcher("").matches();
    System.out.println("Valid ? " + fieldListPattern.matcher(s).matches());
  }
}

Body:
As a pattern, you can optionally repeat matching from an opening till closing square bracket:

^\w+(?:\[\w+(?:,\w+)*\])?(?:[.,]\w+(?:\[\w+(?:,\w+)*\])?)*$

^ Start of string

\w+ Match 1+ word chars

(?:\[\w+(?:,\w+)*\])? Optionally match word characters separated by a comma in between square brackets

(?: Non capture group

[.,] Match either . or ,

\w+(?:\[\w+(?:,\w+)*\])*

)? Close the group and make it optional

$ End of string

Regex demo

In Java with the double escaped backslashes:

String regex = "^\\w+(?:\\[\\w+(?:,\\w+)*\\])?(?:[.,]\\w+(?:\\[\\w+(?:,\\w+)*\\])?)*$";


问:
how to perform string operation in an input string and get the desired output
I have to write a shell script  to accept the product order details as string input and display the total order amount and number of order under each category.
INPUT:
101:Redmi:Mobile:15000#102:Samsung:TV:20000#103:OnePlus:Mobile:35000#104:HP:Laptop:65000#105:Samsung:Mobile:10000#106:Samsung:TV:30000

OUTPUT:
 Mobile:60000:3#TV:50000:2#Laptop:65000:1

I have to achieve this using sort,tr,cut,grep command only no sed awk should be used.

答:
Here is my solution, it is improvable, I will explain it:

```<code>    x="101:Redmi:Mobile:15000#102:Samsung:TV:20000#103:OnePlus:Mobile:35000#104:HP:Laptop:65000#105:Samsung:Mobile:10000#106:Samsung:TV:30000"

echo $x > origin.txt

cat origin.txt | grep -E -o ':[a-Z]+:[0-9]+' | cut -c 2- > temp.txt

categories=()
quantity=()
items=()

while IFS= read -r line
do

    category=$(echo $line | grep -E -o '[a-Z]+')
    amount=($(( $(echo $line | grep -E -o '[0-9]+') )))

    if [ "0" = "${#categories[@]}" ]
    then
        # Add new element at the end of the array
        categories+=( $category )
        quantity+=( $amount )
        items+=(1)

    else

        let in=0
        let index=0
        let i=0
        # Iterate the loop to read and print each array element
        for value in "${categories[@]}"
        do
             if [ $category = $value ]
             then
                let in=$in+1
                let index=$i
             fi
             let i=$i+1
        done

        if [ $in = 0 ]
        then
            categories+=( $category )
            quantity+=( $amount )
            items+=(1)
        else

            let sum=$amount+${quantity[$index]}
            quantity[$index]=$sum

            let newitems=${items[$index]}+1
            items[$index]=$newitems

        fi

   fi

done < temp.txt

let j=0
for value in "${categories[@]}"
    do
        echo -n $value
        echo -n ':'
        echo -n ${quantity[$j]}
        echo -n ':'
        echo -n ${items[$j]}

        let k=$j+1
        if [ $k != ${#categories[@]} ]
        then
            echo -n '#'
        fi

        let j=$j+1
done
</code>```

First i save the string in x and later in origin.txt, with cat, grep and cut I obtain the string in this format inside of temp.txt:

Mobile:15000 \n
TV:20000 \n
Mobile:35000 \n
Laptop:65000 \n
Mobile:10000 \n
TV:30000

I create three arrays: categories for storage the name of the category, quantity for storage the amount of the category and items the objects of the category.

Later I read temp.txt line by line and using a simple regex I can get the name of the category and the amount of that line.

```<code>amount=($(( $(echo $line | grep -E -o '[0-9]+') )))
</code>```

This is used to convert string into int.

The first if is for check if the array is empty, if it's empty we append the category, the amount and 1 object.

If is not empty we need to declare three variables:

in, for check if the incoming category is in the array or not

index, for storage the index of the existing category

i, for count the times we loop

If the category already exist in the array $in is setted to 1 or higher.
If not $in still have the default value 0.

Next if in is equal to 0, means the category is new, we append to the three arrays.

If in is not equal to 0 using the index we can sum the new amount to the stored amount.

Finally when the main loop finish I print the data following the format you have mentioned.

The variable k is for not print the last "#", we compare k with the size of the array. Note that arrays start with 0 index.

Body:
Here is my solution, it is improvable, I will explain it:

    x="101:Redmi:Mobile:15000#102:Samsung:TV:20000#103:OnePlus:Mobile:35000#104:HP:Laptop:65000#105:Samsung:Mobile:10000#106:Samsung:TV:30000"

echo $x > origin.txt

cat origin.txt | grep -E -o ':[a-Z]+:[0-9]+' | cut -c 2- > temp.txt

categories=()
quantity=()
items=()

while IFS= read -r line
do

    category=$(echo $line | grep -E -o '[a-Z]+')
    amount=($(( $(echo $line | grep -E -o '[0-9]+') )))

    if [ "0" = "${#categories[@]}" ]
    then
        # Add new element at the end of the array
        categories+=( $category )
        quantity+=( $amount )
        items+=(1)

    else

        let in=0
        let index=0
        let i=0
        # Iterate the loop to read and print each array element
        for value in "${categories[@]}"
        do
             if [ $category = $value ]
             then
                let in=$in+1
                let index=$i
             fi
             let i=$i+1
        done

        if [ $in = 0 ]
        then
            categories+=( $category )
            quantity+=( $amount )
            items+=(1)
        else

            let sum=$amount+${quantity[$index]}
            quantity[$index]=$sum

            let newitems=${items[$index]}+1
            items[$index]=$newitems

        fi

   fi

done < temp.txt

let j=0
for value in "${categories[@]}"
    do
        echo -n $value
        echo -n ':'
        echo -n ${quantity[$j]}
        echo -n ':'
        echo -n ${items[$j]}

        let k=$j+1
        if [ $k != ${#categories[@]} ]
        then
            echo -n '#'
        fi

        let j=$j+1
done

First i save the string in x and later in origin.txt, with cat, grep and cut I obtain the string in this format inside of temp.txt:

Mobile:15000 \n
TV:20000 \n
Mobile:35000 \n
Laptop:65000 \n
Mobile:10000 \n
TV:30000

I create three arrays: categories for storage the name of the category, quantity for storage the amount of the category and items the objects of the category.

Later I read temp.txt line by line and using a simple regex I can get the name of the category and the amount of that line.

amount=($(( $(echo $line | grep -E -o '[0-9]+') )))

This is used to convert string into int.

The first if is for check if the array is empty, if it's empty we append the category, the amount and 1 object.

If is not empty we need to declare three variables:

in, for check if the incoming category is in the array or not

index, for storage the index of the existing category

i, for count the times we loop

If the category already exist in the array $in is setted to 1 or higher.
If not $in still have the default value 0.

Next if in is equal to 0, means the category is new, we append to the three arrays.

If in is not equal to 0 using the index we can sum the new amount to the stored amount.

Finally when the main loop finish I print the data following the format you have mentioned.

The variable k is for not print the last "#", we compare k with the size of the array. Note that arrays start with 0 index.


问:
queries executed using spark-sql run on driver or on the executors
I am curious to understand as where does the query executes when we run it using spark-sql -e.

```<code>spark-sql -e "SELECT count(*) FROM table"
</code>```

moreover when we do a count, is the action called only on the driver?

答:
An Action means do something. That Action comes from the Driver and work is distributed to Workers where Executors run Tasks against Partitions.

So, counting occurs on Executors. Partial count results from the Executors for counting Partition are sent to- and aggregated on the Driver.

Body:
I am curious to understand as where does the query executes when we run it using spark-sql -e.

spark-sql -e "SELECT count(*) FROM table"

moreover when we do a count, is the action called only on the driver?


问:
Google Sheets: by the last non-empty cell in column, return the value in corresponding cell in another column?
 Hello!

 So I have dates in Column A (A3:A). And I have transactions (formatted as currency) in Column C (C3:C). So I want a cell D3 in Column D to show the date (preferably only month but it is not vital) of the last transaction.

 In other words I need a formula that would check the whole Column C, find the last transaction (assuming that there will be blank cells in that column), find the corresponding date in Column A (date when transaction occured) and return that value (date) in cell D3 of Column D.

 INDEX? MATCH? HLOOKUP?

 Please advise.

```<code>Column A          Column C          Column D
</code>```

3   01/01/2021                   10.98                                   01/05/2021

4   01/02/2021                   15.64

5   01/03/2021

6   01/04/2021

7   01/05/2021                   20.93

8   01/05/2021                   76.28

答:
Try

```<code>=+sort(A:A, row(A:A)*(C:C<>""),)
</code>```

or

```<code>=INDEX(A:A, MATCH(2, IF(C:C<>"", 1), 1))
</code>```

or even

```<code>=lookup(9^9, C:C, A:A)
</code>```

and see if that works?

Body:
 Hello!

 So I have dates in Column A (A3:A). And I have transactions (formatted as currency) in Column C (C3:C). So I want a cell D3 in Column D to show the date (preferably only month but it is not vital) of the last transaction.

 In other words I need a formula that would check the whole Column C, find the last transaction (assuming that there will be blank cells in that column), find the corresponding date in Column A (date when transaction occured) and return that value (date) in cell D3 of Column D.

 INDEX? MATCH? HLOOKUP?

 Please advise.

Column A          Column C          Column D

3   01/01/2021                   10.98                                   01/05/2021

4   01/02/2021                   15.64

5   01/03/2021

6   01/04/2021

7   01/05/2021                   20.93

8   01/05/2021                   76.28

Body:
Try

=+sort(A:A, row(A:A)*(C:C<>""),)

or

=INDEX(A:A, MATCH(2, IF(C:C<>"", 1), 1))

or even

=lookup(9^9, C:C, A:A)

and see if that works?


问:
Swift Firebase 'FIRInvalidArgumentException' when updating data
In short, I am using image picker to upload images to firebase storage and saving the image id to a document in firestore. The images are uploaded successfully however, when trying to save the data to the document I am getting an error: 'FIRInvalidArgumentException', reason: 'Unsupported type: __SwiftValue'

Why is this happening?

Call to upload images, and then save to document:

```<code>ImagePickerView(currentEventID: self.liveEventID, configuration: self.pickerConfig) { imagesData in
   print("PICKER DONE: \(imagesData)")
   var eventImages: [EventImage] = []
   for imageData in imagesData {
      let imageUUID = UUID().uuidString
      self.isvm.uploadImage(currentEventID: self.liveEventID, imageUUID: imageUUID, selectedImagesData: imageData) { imageURL in
                        eventImages.append(EventImage(id: imageUUID, url: imageURL, voteCount: 1))

         if eventImages.count == imagesData.count {
            print("LOOP DONE: \(eventImages)")
               self.isvm.saveImagesToEvent(currentEventID: self.liveEventID, eventImages: eventImages) { isSavedToEvent in
                  if isSavedToEvent {
                     print("SAVED IMAGES SUCCESSFULLY")
                     self.isReloadingImages = true
                                    self.isvm.getUpdatedEventPhotos(currentEventID: self.liveEventID) { liveEvent in
                     self.liveEvent = liveEvent
                     if !self.liveEvent.isEmpty {
                        self.liveEventID = self.liveEvent[0].id
                        self.isReloadingImages = false
                    }
                 }
               }
            }
         }
      }
   }
}
</code>```

Where the error occurs:

```<code>    public func saveImagesToEvent(currentEventID: String, eventImages: [EventImage], completion: @escaping (_ isSavedToEvent: Bool) -> Void) {
        self.eventsDataCollection.document(currentEventID).updateData([
            "eventImages" : FieldValue.arrayUnion(eventImages)
        ]) { error in
            if let error = error {
                print("ERROR SAVING URLS TO EVENT: \(error)")
                completion(false)
            }
        }
        completion(true)
    }
</code>```

The data model:

```<code>struct EventModel: Identifiable, Codable {
    var id: String
    var isLive: Bool
    var coors: [Coor]
    var eventCenterCoorFormatted: [Double]
    var hostTitle: String
    var eventName: String
    var eventDescription: String
    var isEventPrivate: Bool
    var eventGuestsJoined: [String]
    var eventEndDate: String
    var eventImages: [EventImage]

    private enum CodingKeys: String, CodingKey {
        case id
        case isLive
        case coors
        case eventCenterCoorFormatted
        case hostTitle
        case eventName
        case eventDescription
        case isEventPrivate
        case eventGuestsJoined
        case eventEndDate
        case eventImages
    }
}

struct Coor: Identifiable, Codable {
    var id = UUID()
    var coorDoubles: [Double]

    private enum CodingKeys: String, CodingKey {
        case coorDoubles
    }
}

struct EventImage: Identifiable, Codable {
    var id = UUID().uuidString
    var url: String
    var voteCount: Int

    private enum eventImage: String, CodingKey {
        case id
        case imageURL
        case voteCount
    }
}
</code>```

Please note: The last print statement before the error is: "Loop done: " And it successfully gets all the eventImages of type EventImage.

答:
The error is caused by trying to save a custom Swift object to Firestore in your saveImagesToEvent function:

"eventImages" : FieldValue.arrayUnion(eventImages)

You need to encode your EventImage objects before trying to store them in Firestore.  Your EventImage struct already conforms to Codable, but the set/update data methods for Firestore don't automatically encode your data.

To solve this, make sure you have included the Firestore swift extensions in your project:

pod 'FirebaseFirestoreSwift'

Now you can use Firestore.Encoder to encode your data before sending it to Firestore:

```<code>val encodedEventImages = eventImages.map { Firestore.Encoder().encode($0) }

self.eventsDataCollection.document(currentEventID).updateData([
            "eventImages" : FieldValue.arrayUnion(encodedEventImages)
        ]) { error in
...

</code>```

If you want to read the data in Firestore document as a custom Swift object you will need to decode it as in this example from the Firestore documentation:

```<code>docRef.getDocument { (document, error) in
    // Construct a Result type to encapsulate deserialization errors or
    // successful deserialization. Note that if there is no error thrown
    // the value may still be `nil`, indicating a successful deserialization
    // of a value that does not exist.
    //
    // There are thus three cases to handle, which Swift lets us describe
    // nicely with built-in Result types:
    //
    //      Result
    //        /\
    //   Error  Optional<City>
    //               /\
    //            Nil  City
    let result = Result {
      try document?.data(as: City.self)
    }
    switch result {
    case .success(let city):
        if let city = city {
            // A `City` value was successfully initialized from the DocumentSnapshot.
            print("City: \(city)")
        } else {
            // A nil value was successfully initialized from the DocumentSnapshot,
            // or the DocumentSnapshot was nil.
            print("Document does not exist")
        }
    case .failure(let error):
        // A `City` value could not be initialized from the DocumentSnapshot.
        print("Error decoding city: \(error)")
    }
}
</code>```

Body:
In short, I am using image picker to upload images to firebase storage and saving the image id to a document in firestore. The images are uploaded successfully however, when trying to save the data to the document I am getting an error: 'FIRInvalidArgumentException', reason: 'Unsupported type: __SwiftValue'

Why is this happening?

Call to upload images, and then save to document:

ImagePickerView(currentEventID: self.liveEventID, configuration: self.pickerConfig) { imagesData in
   print("PICKER DONE: \(imagesData)")
   var eventImages: [EventImage] = []
   for imageData in imagesData {
      let imageUUID = UUID().uuidString
      self.isvm.uploadImage(currentEventID: self.liveEventID, imageUUID: imageUUID, selectedImagesData: imageData) { imageURL in
                        eventImages.append(EventImage(id: imageUUID, url: imageURL, voteCount: 1))

         if eventImages.count == imagesData.count {
            print("LOOP DONE: \(eventImages)")
               self.isvm.saveImagesToEvent(currentEventID: self.liveEventID, eventImages: eventImages) { isSavedToEvent in
                  if isSavedToEvent {
                     print("SAVED IMAGES SUCCESSFULLY")
                     self.isReloadingImages = true
                                    self.isvm.getUpdatedEventPhotos(currentEventID: self.liveEventID) { liveEvent in
                     self.liveEvent = liveEvent
                     if !self.liveEvent.isEmpty {
                        self.liveEventID = self.liveEvent[0].id
                        self.isReloadingImages = false
                    }
                 }
               }
            }
         }
      }
   }
}

Where the error occurs:

    public func saveImagesToEvent(currentEventID: String, eventImages: [EventImage], completion: @escaping (_ isSavedToEvent: Bool) -> Void) {
        self.eventsDataCollection.document(currentEventID).updateData([
            "eventImages" : FieldValue.arrayUnion(eventImages)
        ]) { error in
            if let error = error {
                print("ERROR SAVING URLS TO EVENT: \(error)")
                completion(false)
            }
        }
        completion(true)
    }

The data model:

struct EventModel: Identifiable, Codable {
    var id: String
    var isLive: Bool
    var coors: [Coor]
    var eventCenterCoorFormatted: [Double]
    var hostTitle: String
    var eventName: String
    var eventDescription: String
    var isEventPrivate: Bool
    var eventGuestsJoined: [String]
    var eventEndDate: String
    var eventImages: [EventImage]

    private enum CodingKeys: String, CodingKey {
        case id
        case isLive
        case coors
        case eventCenterCoorFormatted
        case hostTitle
        case eventName
        case eventDescription
        case isEventPrivate
        case eventGuestsJoined
        case eventEndDate
        case eventImages
    }
}

struct Coor: Identifiable, Codable {
    var id = UUID()
    var coorDoubles: [Double]

    private enum CodingKeys: String, CodingKey {
        case coorDoubles
    }
}

struct EventImage: Identifiable, Codable {
    var id = UUID().uuidString
    var url: String
    var voteCount: Int

    private enum eventImage: String, CodingKey {
        case id
        case imageURL
        case voteCount
    }
}

Please note: The last print statement before the error is: "Loop done: " And it successfully gets all the eventImages of type EventImage.

Body:
The error is caused by trying to save a custom Swift object to Firestore in your saveImagesToEvent function:

"eventImages" : FieldValue.arrayUnion(eventImages)

You need to encode your EventImage objects before trying to store them in Firestore.  Your EventImage struct already conforms to Codable, but the set/update data methods for Firestore don't automatically encode your data.

To solve this, make sure you have included the Firestore swift extensions in your project:

pod 'FirebaseFirestoreSwift'

Now you can use Firestore.Encoder to encode your data before sending it to Firestore:

val encodedEventImages = eventImages.map { Firestore.Encoder().encode($0) }

self.eventsDataCollection.document(currentEventID).updateData([
            "eventImages" : FieldValue.arrayUnion(encodedEventImages)
        ]) { error in
...

If you want to read the data in Firestore document as a custom Swift object you will need to decode it as in this example from the Firestore documentation:

docRef.getDocument { (document, error) in
    // Construct a Result type to encapsulate deserialization errors or
    // successful deserialization. Note that if there is no error thrown
    // the value may still be `nil`, indicating a successful deserialization
    // of a value that does not exist.
    //
    // There are thus three cases to handle, which Swift lets us describe
    // nicely with built-in Result types:
    //
    //      Result
    //        /\
    //   Error  Optional<City>
    //               /\
    //            Nil  City
    let result = Result {
      try document?.data(as: City.self)
    }
    switch result {
    case .success(let city):
        if let city = city {
            // A `City` value was successfully initialized from the DocumentSnapshot.
            print("City: \(city)")
        } else {
            // A nil value was successfully initialized from the DocumentSnapshot,
            // or the DocumentSnapshot was nil.
            print("Document does not exist")
        }
    case .failure(let error):
        // A `City` value could not be initialized from the DocumentSnapshot.
        print("Error decoding city: \(error)")
    }
}


问:
Laravel average of numbers per group
For my project, I want students to see the average grade per school subject.

```<code>$grades = Auth::user()->student->grades()
    ->with('subject')->orderByDesc('created_at')
    ->get()->groupBy('subject_id');
</code>```

Now I first get the grades with the subject and then group them by subject.
How can I add the average grade per subject group?

Table columns

答:
The simplest would be to select all rows with subject id X, loop through and and add all the scores to a total, then divide that total by the count() of the rows returned.

A nicer way might be through crafting a cool SQL query that does the same, but that's for you to decide, this is roughly how you do it.

Title: Laravel average of numbers per group

Body:
For my project, I want students to see the average grade per school subject.

$grades = Auth::user()->student->grades()
    ->with('subject')->orderByDesc('created_at')
    ->get()->groupBy('subject_id');

Now I first get the grades with the subject and then group them by subject.
How can I add the average grade per subject group?

Table columns


答:
You can do something like this.
Here tracker is used to keep track of what elements are displayed already. If tracker is 0, nothing is displayed yet, if 1 it means, first ten is already displayed. For loop only displays 10 elements once.

const array = [
   "AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
]

let tracker = 0;

const display = () => {
  for(let i = tracker*10; i<10*tracker + 10 ; i++){
    if(!array[i]) break;
    console.log(array[i])
  }
  if(tracker >= array.length){
    tracker = 0;
  } else {
    tracker = tracker+1
  }
}

display()
display()
```

Title: How to run some element in recyle from an array?


问:
PHP redirect link only updates sql database once every minute
For tracking the number of clicks (and IP) for a website I created a php script that stores the date and IP info and only once the query was executed successfully it redirects the user to the link. Even though the following script is very minimal, it works.

However, if I click the link twice within one minute (tested both in Chrome and Edge) it does not save this as a click but it does redirect me to the correct page which I find very odd. I have tried this by clicking multiple times and only the values after +-1 min get stored.

Opening a new Chrome window does not work. Opening an incognito screen within 1 min does work and this click gets saved.

Addition info: in the SQL database there is a primary ID column with AUTO_INCREMENT.

Question: is there any reason why this happens (perhaps caching?) and would there be any way to prevent this?

The URL to redirect to link 1 is: thisphpfile.php?link=1

```<code>//---------
// Get info on which link to point to
$link = $_GET["link"];

// Check link value to prevent SQL injection
if($link =='1'){
    $link_sql = "https://www.url1.com";
}
if($link =='2'){
    $link_sql = "https://www.url2.com";
}

// If link was a valid input, continue, else back to homepage
if($link =='1' || $link == '2'){

$date = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];

$sql = "INSERT INTO tablename (DATE , IP, LINK) VALUES ('$date', '$ip','$link_sql')";

//Execute query
if ($conn->query($sql) === TRUE) {
ob_end_flush();

// Redirect link
header("Location: " . $link_sql);
}

}else{
    // Redirect link
    header("Location: https://www.default.com" );
}
</code>```

答:
I don't see the reason, why it shouldn't get saved. But your code structure is a little bit unclear. Maybe you can try it with the following code and we can work it out somehow:</p>
```<code>$links = [
    1 => 'https://www.url1.com',
    2 => 'https://www.url2.com'
];

// Check if GET-parameter is numeric and if the number is in the links array above
if (is_numeric($_GET["link"]) && isset($links[intval($_GET["link"])])) {
    $link = $links[intval($_GET["link"])];

    $sql = sprintf("INSERT INTO tablename (DATE, IP, LINK) values ('%s', '%s', '%s')",
        date("Y-m-d H:i:s"),
        $_SERVER['REMOTE_ADDR'],
        $link
    );

    if ($conn->query($sql) === TRUE) {
        header("Location: " . $link);
        exit;
    }
}

// This will be the default header when the exit above cannot be reached (because of errors)
header("Location: https://www.default.com");
</code>```

Body:
For tracking the number of clicks (and IP) for a website I created a php script that stores the date and IP info and only once the query was executed successfully it redirects the user to the link. Even though the following script is very minimal, it works.

However, if I click the link twice within one minute (tested both in Chrome and Edge) it does not save this as a click but it does redirect me to the correct page which I find very odd. I have tried this by clicking multiple times and only the values after +-1 min get stored.

Opening a new Chrome window does not work. Opening an incognito screen within 1 min does work and this click gets saved.

Addition info: in the SQL database there is a primary ID column with AUTO_INCREMENT.

Question: is there any reason why this happens (perhaps caching?) and would there be any way to prevent this?

The URL to redirect to link 1 is: thisphpfile.php?link=1

//---------
// Get info on which link to point to
$link = $_GET["link"];

// Check link value to prevent SQL injection
if($link =='1'){
    $link_sql = "https://www.url1.com";
}
if($link =='2'){
    $link_sql = "https://www.url2.com";
}

// If link was a valid input, continue, else back to homepage
if($link =='1' || $link == '2'){

$date = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];

$sql = "INSERT INTO tablename (DATE , IP, LINK) VALUES ('$date', '$ip','$link_sql')";

//Execute query
if ($conn->query($sql) === TRUE) {
ob_end_flush();

// Redirect link
header("Location: " . $link_sql);
}

}else{
    // Redirect link
    header("Location: https://www.default.com" );
}

Body:
I don't see the reason, why it shouldn't get saved. But your code structure is a little bit unclear. Maybe you can try it with the following code and we can work it out somehow:

$links = [
    1 => 'https://www.url1.com',
    2 => 'https://www.url2.com'
];

// Check if GET-parameter is numeric and if the number is in the links array above
if (is_numeric($_GET["link"]) && isset($links[intval($_GET["link"])])) {
    $link = $links[intval($_GET["link"])];

    $sql = sprintf("INSERT INTO tablename (DATE, IP, LINK) values ('%s', '%s', '%s')",
        date("Y-m-d H:i:s"),
        $_SERVER['REMOTE_ADDR'],
        $link
    );

    if ($conn->query($sql) === TRUE) {
        header("Location: " . $link);
        exit;
    }
}

// This will be the default header when the exit above cannot be reached (because of errors)
header("Location: https://www.default.com");


问:
Detecting Green Colour from Image - CV2 Python
I am trying to detect green colour from images, for that I using cv2, by defining upper and lower limit of green colour as [40, 0, 0] and [90, 255, 255], this works well,

but, when I tested this image, I got detected the white region also, the output is mask image, the expected mask output is only black colour

the code is

```<code>frame = cv2.imread('img.jpg')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower = np.array([40, 0, 0])
upper = np.array([90, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
res = cv2.bitwise_and(frame,frame, mask= mask)
cv2.imshow('mask',mask)
</code>```

Why the upper and lower bound of green detects the white regions in the input image, and is there any other way to detect only green colour from the image

thanks

答:
Here are the colors that can be found in this image.

Where is "your" green ?

Body:
I am trying to detect green colour from images, for that I using cv2, by defining upper and lower limit of green colour as [40, 0, 0] and [90, 255, 255], this works well,

but, when I tested this image, I got detected the white region also, the output is mask image, the expected mask output is only black colour

the code is

frame = cv2.imread('img.jpg')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower = np.array([40, 0, 0])
upper = np.array([90, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
res = cv2.bitwise_and(frame,frame, mask= mask)
cv2.imshow('mask',mask)

Why the upper and lower bound of green detects the white regions in the input image, and is there any other way to detect only green colour from the image

thanks


问:
errorTypeError: Cannot read properties of undefined (reading 'map')
I'm trying to use Strapi Headless CMS to create blog posts. I managed to fetch the JSON data but I'm unable to display it as HTML using the map() function. I want to display this data into the HTML but I keep getting this error. I already tried with a for loop and foreach() but I keep getting the same error like this or errorTypeError: Cannot read properties of undefined (reading 'data'). Here's my code so far:

```<code> const blogPosts = "http://localhost:1337/api/blogposts";

fetch(blogPosts)
.then((response) => {
  return response.json();
})
.then((data) => console.log(data.data[0].attributes))

.then((data) => {
  let posts = data;

  posts.map(function (post) {
    let body = document.createElement("div");

    body.innerHTML = `${post.data.data[0].attributes.body}`;
    li.appendChild(body);
  });
})

.catch(function (err) {
  console.log("error" + err);
});
</code>```

The JSON file looks like this:

```<code>{data: Array(1)
     data: Array(1)
       0:
         attributes:
           body: "text"
           createdAt: "2022-02-11T10:29:48.930Z"
           publishedAt: "2022-02-11T10:29:58.780Z"
           updatedAt: "2022-02-11T10:29:58.790Z"
</code>```

答:
Try to replace this line:

```<code>body.innerHTML = `${post.data.data[0].attributes.body}`;
</code>```

with:

```<code>body.innerHTML = `${post.data[0].attributes.body}`;
</code>```

Body:
I'm trying to use Strapi Headless CMS to create blog posts. I managed to fetch the JSON data but I'm unable to display it as HTML using the map() function. I want to display this data into the HTML but I keep getting this error. I already tried with a for loop and foreach() but I keep getting the same error like this or errorTypeError: Cannot read properties of undefined (reading 'data'). Here's my code so far:

 const blogPosts = "http://localhost:1337/api/blogposts";

fetch(blogPosts)
.then((response) => {
  return response.json();
})
.then((data) => console.log(data.data[0].attributes))

.then((data) => {
  let posts = data;

  posts.map(function (post) {
    let body = document.createElement("div");

    body.innerHTML = `${post.data.data[0].attributes.body}`;
    li.appendChild(body);
  });
})

.catch(function (err) {
  console.log("error" + err);
});

The JSON file looks like this:

{data: Array(1)
     data: Array(1)
       0:
         attributes:
           body: "text"
           createdAt: "2022-02-11T10:29:48.930Z"
           publishedAt: "2022-02-11T10:29:58.780Z"
           updatedAt: "2022-02-11T10:29:58.790Z"

Body:
Try to replace this line:

body.innerHTML = `${post.data.data[0].attributes.body}`;

with:

body.innerHTML = `${post.data[0].attributes.body}`;


问:
Phonograph2: how to use nextPageToken
I am syncing a data set with about 300k rows to Phonograph2 and need to make those records available via REST (End Point: /phonograph2/api/search/tables).

My requests looks as following (retrieving records after a certain timestamp):

```<code>{
    "tableRids": [
        "ri.phonograph2.main.table.xxxxxxxxxxxxxxx"
     ],
    "filter": {
       "type" : "range",
        "range": {
            "field": "reco_timestamp",
            "gte": "1634408219000"
            }
        }

    }
}
</code>```

The response ends with:

```<code> "nextPageToken": "xxxxxxx"
</code>```

This leads me to the following questions:

How do I use the "nextPageToken" to retrieve the next set of results?

Can the consumer get a list/array of pages to consume?

Can the number of hits which are displayed until the nextPageToken is written be configured?

答: We discussed this with our Palantir project support and will use Objects Gateway - as suggested. Thanks for pointing us into this direction.</p>

Title: Phonograph2: how to use nextPageToken

Body:
I am syncing a data set with about 300k rows to Phonograph2 and need to make those records available via REST (End Point: /phonograph2/api/search/tables).

My requests looks as following (retrieving records after a certain timestamp):

{
    "tableRids": [
        "ri.phonograph2.main.table.xxxxxxxxxxxxxxx"
     ],
    "filter": {
       "type" : "range",
        "range": {
            "field": "reco_timestamp",
            "gte": "1634408219000"
            }
        }

    }
}

The response ends with:

 "nextPageToken": "xxxxxxx"

This leads me to the following questions:

How do I use the "nextPageToken" to retrieve the next set of results?

Can the consumer get a list/array of pages to consume?

Can the number of hits which are displayed until the nextPageToken is written be configured?


问:
FlutterMap LateInitializationError State Management
I'm trying to make a Flutter app, using Riverpod for state management and FlutterMaps. I have set up notifiers for pages, and am also using a (State)NotifierProvider for the map page. I am building a search function, which goes to a search page which displays a list with search results. When one of these results (in a list) is clicked, I update the notifier of the  map page. However, here comes the tricky part: I want to update the map according to the LatLng of the search result (center it).

My implementation of the Notifier contains:
late MapController? _mapController;

My map page is loaded in and gets the mapController from the Notifier: mapController: notifier.getMapController()

Using Riverpod state management, this all should work, however I get the following Error:

```<code>LateError (LateInitializationError: Field '_state@1225051772' has already been initialized.)
</code>```

This Error is within the MapController itself (which is part of the FlutterMaps package), so I do not want to touch that. Does anyone have any idea how to tackle this?

答:
lateerror is caused by nulling a variable that will fill before the application starts.

```<code>late MapController? _mapController;
</code>```

this definition is wrong. Here, you are saying that this value will fill in soon. You also say that this value can be null.

```<code>late MapController _mapController;
</code>```

if you do so this variable should not be null at runtime. if it is null you will get a lateerror error.

```<code>MapController? _mapController;
</code>```

if you do it this way. This means that the value can be null. You should check when using.
like this

```<code>void sameFunction(){
 if(_mapController!=null){
  ... your code
 // here make sure this variable is not null. For this reason ! i put this
  MapController anotherController=_mapController!;
}
}
</code>```

or

```<code> void sameFunction(){
  // Your code will not throw an error if this variable is null. Because specify that
  //it can be null
     mapController?.moveTo(...)
    }
</code>```

for more detailed information

Body:
I'm trying to make a Flutter app, using Riverpod for state management and FlutterMaps. I have set up notifiers for pages, and am also using a (State)NotifierProvider for the map page. I am building a search function, which goes to a search page which displays a list with search results. When one of these results (in a list) is clicked, I update the notifier of the  map page. However, here comes the tricky part: I want to update the map according to the LatLng of the search result (center it).

My implementation of the Notifier contains:
late MapController? _mapController;

My map page is loaded in and gets the mapController from the Notifier: mapController: notifier.getMapController()

Using Riverpod state management, this all should work, however I get the following Error:

LateError (LateInitializationError: Field '_state@1225051772' has already been initialized.)

This Error is within the MapController itself (which is part of the FlutterMaps package), so I do not want to touch that. Does anyone have any idea how to tackle this?

Body:
lateerror is caused by nulling a variable that will fill before the application starts.

late MapController? _mapController;

this definition is wrong. Here, you are saying that this value will fill in soon. You also say that this value can be null.

late MapController _mapController;

if you do so this variable should not be null at runtime. if it is null you will get a lateerror error.

MapController? _mapController;

if you do it this way. This means that the value can be null. You should check when using.
like this

void sameFunction(){
 if(_mapController!=null){
  ... your code
 // here make sure this variable is not null. For this reason ! i put this
  MapController anotherController=_mapController!;
}
}

or

 void sameFunction(){
  // Your code will not throw an error if this variable is null. Because specify that
  //it can be null
     mapController?.moveTo(...)
    }

for more detailed information


问:
How to create global variables once when app is launched in Go?
Good day for all readers!

I have api service which needs key for some decrypt issues. Key calculates all time when I make request. That is wrong from an architectural point of view.

The option with environments (.env, viper...) drops because, in the future, I want to bring out this module to a separate library.

Hint me, how it is possible without using environments to calculate the key when starting the application and use it until stopping the application?

答:
If you are sure you need a global variable, you can do this:

package main

var globalVar string = "My string"

func init(){
    globalVar = "The new value of the variable"
}

func main(){
    println(globalVar)
}

```


问:
How to implement Angular Social Login with Express Server
I have successfully implemented Angular Social Login into my Angular app, but now I need to implement it into the server part of the application, which I have done in Node.js with Express. What am I suppose to do? I understand it is something to do with the token that Google sends, but what exactly is the way to implement this token with Express? Can you please point me to some source for this?</p>

答:
You have several options to achieve this
I'm assuming you're going to use JSON Web Tokens of some sort. If so, then you'd get your token from the FrontEnd, you then would attach the token to the header of your requests and the Backend would authenticate the validity of the token

Some good options would be to use a service like Auth0 (here's a quickstart guide) or Firebase (Add Firebase to your JavaScript project)

Some Links that may help:

Add the Firebase Admin SDK to your server(firebase docs)

Authenticate a Firebase User on the Server(fireship.io)

Using Firebase as an Authenticating Middleware in Express.js(stackoverflow)


问:
Clock Timer is showing wrong time JavaScript
I am working on timer when user clock in the timer starts. It is working fine until it reaches the 60 minutes figure and it keeps on going doesn't added hour. Here is my code

```<code>  export enum HMS{
  hours=3600,
  MinSec=60,
}

 transform(value: number = 3600): any {
// here values is in minutes
    const hours: number = Math.floor(value / HMS.hours)
    const minutes: number = Math.floor(value / HMS.MinSec);
    const seconds: number = (value - minutes * HMS.MinSec);
    return ((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds)
  }
</code>```

Below is the image display time. It shows like this.

答:
You definitely need a Modulo in there:</p>
```<code>export enum HMS{
      hours=3600,
      MinSec=60,
    }

transform(value: number = 3600): any {
    // here values is in minutes
    const hours: number = Math.floor(value / HMS.hours)
    const minutes: number = Math.floor(value / HMS.MinSec % 60);
    const seconds: number = Math.floor(value % 60);
    return ((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds)
}
</code>```

Body:
I am working on timer when user clock in the timer starts. It is working fine until it reaches the 60 minutes figure and it keeps on going doesn't added hour. Here is my code

  export enum HMS{
  hours=3600,
  MinSec=60,
}

 transform(value: number = 3600): any {
// here values is in minutes
    const hours: number = Math.floor(value / HMS.hours)
    const minutes: number = Math.floor(value / HMS.MinSec);
    const seconds: number = (value - minutes * HMS.MinSec);
    return ((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds)
  }

Below is the image display time. It shows like this.

Body:
You definitely need a Modulo in there:

export enum HMS{
      hours=3600,
      MinSec=60,
    }

transform(value: number = 3600): any {
    // here values is in minutes
    const hours: number = Math.floor(value / HMS.hours)
    const minutes: number = Math.floor(value / HMS.MinSec % 60);
    const seconds: number = Math.floor(value % 60);
    return ((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds)
}


问:
auto, try-catch, and scopes
I have a piece of code like this:

```<code>auto theval = myfunc();

dosomething(theval);
</code>```

Now, I want to wrap the first part in a try/catch block:

```<code>try {
  auto theval = myfunc();
} catch (const std::exception& ex){
  // do some error handling
}
dosomething(theval);
</code>```

Unfortunately, this doesn't work, because theval is inside the try scope.

The conventional way to solve this would be to just move the declaration outside the scope like this:

```<code>auto theval;
try {
  theval = myfunc();
} catch (const std::exception& ex){
  // do some error handling
}
dosomething(theval);
</code>```

But this doesn't work either, because auto can't be used without an initialization.

Is there a way in which I can solve this without having to explicitly use the return type of myfunc and without having to move the call to dosomething inside the try block?

答:
One possible solution is to use decltype like this:

```<code>decltype(myfunc()) theval;
try {
  theval = myfunc();
} catch (const std::exception& ex){
  // do some error handling
}
dosomething(theval);
</code>```

perhaps augmented with std::remove_reference<...>::type to avoid issues with functions returning references.

Title: auto, try-catch, and scopes

Body:
I have a piece of code like this:

auto theval = myfunc();

dosomething(theval);

Now, I want to wrap the first part in a try/catch block:

try {
  auto theval = myfunc();
} catch (const std::exception& ex){
  // do some error handling
}
dosomething(theval);

Unfortunately, this doesn't work, because theval is inside the try scope.

The conventional way to solve this would be to just move the declaration outside the scope like this:

auto theval;
try {
  theval = myfunc();
} catch (const std::exception& ex){
  // do some error handling
}
dosomething(theval);

But this doesn't work either, because auto can't be used without an initialization.

Is there a way in which I can solve this without having to explicitly use the return type of myfunc and without having to move the call to dosomething inside the try block?

Body:
One possible solution is to use decltype like this:

decltype(myfunc()) theval;
try {
  theval = myfunc();
} catch (const std::exception& ex){
  // do some error handling
}
dosomething(theval);

perhaps augmented with std::remove_reference<...>::type to avoid issues with functions returning references.


问:
Data frame string matching from one to another and replace with original value
i have two data frame , A and B . In A Data frame two column value and filed . and in B data frame  have also value and filed column.
i want to match the  'value' column of B to A of'Filed' column, replace the Filed of A to  value of B.

A=

```<code> Value                     Filed

valid username            username
valid username           input_txtuserid
valid username           name
Password                 input_txtpassword
Password                 txtPassword
Login                     input_submit_log_in
Login                     loginid
LOG IN                    SIGNIN
</code>```

B=

```<code> Value                     Filed

input_txtuserid           "JOHN"
input_txtpassword          "78945"
input_submit_log_in        "Sucessfully"
City                       "London"
PLACE                      "4-A avenue Street"
PHONE                      789456
</code>```

I want my data frame to look like this:

C=

```<code> Value                     Filed

valid username            "JOHN"
Password                   "78945"
Login                       "Sucessfully"
City                       "London"
PLACE                      "4-A avenue Street"
PHONE                      789456
</code>```

答:
I would make a custom function to embed the logic and then apply it to the DataFrame by row.</p>
```<code>import pandas as pd

A = pd.DataFrame({
    'Value':['valid username','valid username','valid username'],
    'Filed':['username', 'input_txtuserid', 'name']
})

B = pd.DataFrame({
    'Value':['input_txtuserid'],
    'Filed':['JOHN']
})

#dictionary mapping A.Filed and A.Value
_map = dict(zip(A.Filed.values, A.Value.values))

#Function embedding the logic
#It uses _map to determine the correct "filed" string
def get_correct_value(row, _map=_map):
    new_value = _map[row.Value]
    filed = row.Filed
    return new_value, filed

#Make a new df from the result of B.apply(function)
C = B.apply(get_correct_value, axis=1, result_type='expand')
C.columns = ['Value','Filed']
print(C)

#            Value Filed
#0  valid username  JOHN
</code>```

Body:
i have two data frame , A and B . In A Data frame two column value and filed . and in B data frame  have also value and filed column.
i want to match the  'value' column of B to A of'Filed' column, replace the Filed of A to  value of B.

A=

 Value                     Filed

valid username            username
valid username           input_txtuserid
valid username           name
Password                 input_txtpassword
Password                 txtPassword
Login                     input_submit_log_in
Login                     loginid
LOG IN                    SIGNIN

B=

 Value                     Filed

input_txtuserid           "JOHN"
input_txtpassword          "78945"
input_submit_log_in        "Sucessfully"
City                       "London"
PLACE                      "4-A avenue Street"
PHONE                      789456

I want my data frame to look like this:

C=

 Value                     Filed

valid username            "JOHN"
Password                   "78945"
Login                       "Sucessfully"
City                       "London"
PLACE                      "4-A avenue Street"
PHONE                      789456

Body:
I would make a custom function to embed the logic and then apply it to the DataFrame by row.

import pandas as pd

A = pd.DataFrame({
    'Value':['valid username','valid username','valid username'],
    'Filed':['username', 'input_txtuserid', 'name']
})

B = pd.DataFrame({
    'Value':['input_txtuserid'],
    'Filed':['JOHN']
})

#dictionary mapping A.Filed and A.Value
_map = dict(zip(A.Filed.values, A.Value.values))

#Function embedding the logic
#It uses _map to determine the correct "filed" string
def get_correct_value(row, _map=_map):
    new_value = _map[row.Value]
    filed = row.Filed
    return new_value, filed

#Make a new df from the result of B.apply(function)
C = B.apply(get_correct_value, axis=1, result_type='expand')
C.columns = ['Value','Filed']
print(C)

#            Value Filed
#0  valid username  JOHN


问:
Pseudo Code for a Merge Join (Left Outer Join) In SSIS
I have a Merge Join Transform that is doing a Left Outer Join.  Can anyone show me the pseudo code for this transform?  I think I understand the output, but I'm curious to know the logic that is used to produce it.

Thank you!

答:
The merge join works follows by traversing all the records in two sorted lists.  The merge matches the records where it can, but always returns the records from the left list, even without a corresponding record in the right list.  As the records are sorted in both lists, the process knows that it can discard the possibility of any matches further down the list;</p>

```<code>Get first record from leftList
Get first record from rightList

While not at the end of either list
begin
    if leftList key matches right list key
    begin
        return (leftList and rightList row)
        move to next rightList row
    end
    else if no previous match found on leftList
    begin
        return (leftList)
        move to next leftList row
    end
    else
        move to next leftList row
end
</code>```

Body:
The merge join works follows by traversing all the records in two sorted lists.  The merge matches the records where it can, but always returns the records from the left list, even without a corresponding record in the right list.  As the records are sorted in both lists, the process knows that it can discard the possibility of any matches further down the list;

Get first record from leftList
Get first record from rightList

While not at the end of either list
begin
    if leftList key matches right list key
    begin
        return (leftList and rightList row)
        move to next rightList row
    end
    else if no previous match found on leftList
    begin
        return (leftList)
        move to next leftList row
    end
    else
        move to next leftList row
end


问:
How to Load Cypher File into Neo4j
I have generated a cypher file and want to load it into neo4j.

The only relevant documentation I could find was about loading csv's.

I also tried the shell but it seems to have no effect

```<code>cypher-shell.bat -uneo4j -pne04j < db.cql
</code>```

Copy paste into localhost:7474/browser makes the browser unresponsive.

答: Not sure when this has been added but in the current version (4.4) an alternative way to load a cypher file to NEO4J (GUI) is by dragging and dropping the cypher file over the web browser, which then offers two options, either to add it to the favorites or to paste it in the editor.</p>

Title: How to Load Cypher File into Neo4j

Body:
I have generated a cypher file and want to load it into neo4j.

The only relevant documentation I could find was about loading csv's.

I also tried the shell but it seems to have no effect

cypher-shell.bat -uneo4j -pne04j < db.cql

Copy paste into localhost:7474/browser makes the browser unresponsive.


问:
In Expressive Annotations using the AssertThat attribute - how to modify the error message at runtime or pass in string values
In Expressive Annotations, using the "AssertThat" attribute is it possible to modify the error message at runtime? I am working in ASP.NET MVC Classic environment and needed to add to my existing validations. The new validation would check that the date entered was within a specific date range and I wanted to incorporate the boundary date in the error message but the date is not a constant and can change (every 3-4 months). The issue is that the "AssertThat" ErrorMessage attribute only seems to allow constant strings.

The code looks something like this

```<code>[AssertThat ("!IsDateBeforeDataRange(BeginDate.Value)"
, ErrorMessage ="Requested Date is prior to data ingest range ")]
public DateMvcModel BeginDate { get; set; }
</code>```

This works, but I wanted to incorporate the actual date boundary in the error message like this:

```<code>[AssertThat ("!IsDateBeforeDataRange(BeginDate.Value)"
, ErrorMessage ="Requested Date is prior to data ingest range{IngestDataDtBegnin} ")]
</code>```

But this is not allowed. In the examples for "AssertThat" the default error message does incorporate string interpolation, but I can't figure how to pass my own values in.

答:
A bit late for the OP, but yes this can be done, using the curly bracket syntax in your second snippet.

The trick is the date has to be stored in a property, and posted into the action.

If the date property is alresdy used in your view, it should just work, but if it is a value that is not currently displayed in your view, you'll need to store it in a hidden field so that the value will be available for both client side and server side.

Body:
In Expressive Annotations, using the "AssertThat" attribute is it possible to modify the error message at runtime? I am working in ASP.NET MVC Classic environment and needed to add to my existing validations. The new validation would check that the date entered was within a specific date range and I wanted to incorporate the boundary date in the error message but the date is not a constant and can change (every 3-4 months). The issue is that the "AssertThat" ErrorMessage attribute only seems to allow constant strings.

The code looks something like this

[AssertThat ("!IsDateBeforeDataRange(BeginDate.Value)"
, ErrorMessage ="Requested Date is prior to data ingest range ")]
public DateMvcModel BeginDate { get; set; }

This works, but I wanted to incorporate the actual date boundary in the error message like this:

[AssertThat ("!IsDateBeforeDataRange(BeginDate.Value)"
, ErrorMessage ="Requested Date is prior to data ingest range{IngestDataDtBegnin} ")]

But this is not allowed. In the examples for "AssertThat" the default error message does incorporate string interpolation, but I can't figure how to pass my own values in.


问:
Not able to add time in SQL
I have been learning SQL,and I was trying out this command:

```<code>SELECT TO_CHAR (SYSDATE,'HH:MM:SS'),TO_CHAR(SYSDATE+INTERVAL '15' MINUTE,'HH:MM:SS') FROM DUAL;
</code>```

However the output I am getting is

I even tried out this command:

```<code>SELECT TO_CHAR (SYSDATE,'HH:MM:SS'),TO_CHAR(SYSDATE+15/1440,'HH:MM:SS') FROM DUAL;
</code>```

Even then I am getting this output:

Can anyone explain why am I not getting the second time as 15 minutes ahead of the current system date?

PS: I am using Oracle LiveSQL.

答:
As mentioned by Barbaros Özhan in comments

The MM format model is for months. You want the MI format model for minutes.

Additionally, the HHformat model is an abbreviation for HH12 and will show the hours in a 12-hour clock. You want HH24 to use a 24-hour clock.

SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') AS now,
       TO_CHAR(SYSDATE+INTERVAL '15' MINUTE,'HH24:MI:SS') AS now_plus_15
FROM   DUAL;
```

Outputs:

NOW
NOW_PLUS_15

12:38:13
12:53:13

db<>fiddle here

Title: Not able to add time in SQL

Body:
I have been learning SQL,and I was trying out this command:

SELECT TO_CHAR (SYSDATE,'HH:MM:SS'),TO_CHAR(SYSDATE+INTERVAL '15' MINUTE,'HH:MM:SS') FROM DUAL;

However the output I am getting is

I even tried out this command:

SELECT TO_CHAR (SYSDATE,'HH:MM:SS'),TO_CHAR(SYSDATE+15/1440,'HH:MM:SS') FROM DUAL;

Even then I am getting this output:

Can anyone explain why am I not getting the second time as 15 minutes ahead of the current system date?

PS: I am using Oracle LiveSQL.

Body:
As mentioned by Barbaros Özhan in comments

The MM format model is for months. You want the MI format model for minutes.

Additionally, the HHformat model is an abbreviation for HH12 and will show the hours in a 12-hour clock. You want HH24 to use a 24-hour clock.

SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') AS now,
       TO_CHAR(SYSDATE+INTERVAL '15' MINUTE,'HH24:MI:SS') AS now_plus_15
FROM   DUAL;

Outputs:

NOW
NOW_PLUS_15

12:38:13
12:53:13

db<>fiddle here


问:
How to customize React native track player notification bar
I am using react-native-track-player to create a music app. Can I customize the notification area, and lock screen player?

What I need to do is changing the background color and add custom theming to the notification area and lock screen play options. Can someone please let me know how to do it please?

Following is the code I have used to enable track player options. How can I modified it to do above tasks? Or is there any other method to perform customization. Thank you so much.

const setUpTrackPlayer = async () => {
  try {
    await TrackPlayer.setupPlayer();
    await TrackPlayer.add(audioClipsArray);
    await TrackPlayer.updateOptions({
      stopWithApp: true,
      capabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
        Capability.Stop,
      ],
      compactCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
      notificationCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
    });
  } catch (e) {
    console.log(e);
  }
};```

答:
Some customization is possible.

You can change background color and icons in the notification, as it is decribed here: http://react-native-track-player.js.org/documentation/#player-functions

You can also specify artwork for each track, and it will be used nicely as a notification background image.

All the above would also affect lock screen notification. Sample usage:

```<code>const audioClipsArray = [{
    title: "Title",
    artist: "Artist",
    url: "./path/to/track.mp3",
    artwork: "./path/to/artwork.jpg"
}];

const setUpTrackPlayer = async () => {
  try {
    await TrackPlayer.setupPlayer();
    await TrackPlayer.add(audioClipsArray);
    await TrackPlayer.updateOptions({
      stopWithApp: true,
      capabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
        Capability.Stop,
      ],
      compactCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
      notificationCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
      // Obviously, color property would not work if artwork is specified. It can be used as a fallback.
      color: 99410543
    });
  } catch (e) {
    console.log(e);
  }
};
</code>```

Body:
Some customization is possible.

You can change background color and icons in the notification, as it is decribed here: http://react-native-track-player.js.org/documentation/#player-functions

You can also specify artwork for each track, and it will be used nicely as a notification background image.

All the above would also affect lock screen notification. Sample usage:

const audioClipsArray = [{
    title: "Title",
    artist: "Artist",
    url: "./path/to/track.mp3",
    artwork: "./path/to/artwork.jpg"
}];

const setUpTrackPlayer = async () => {
  try {
    await TrackPlayer.setupPlayer();
    await TrackPlayer.add(audioClipsArray);
    await TrackPlayer.updateOptions({
      stopWithApp: true,
      capabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
        Capability.Stop,
      ],
      compactCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
      notificationCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
      // Obviously, color property would not work if artwork is specified. It can be used as a fallback.
      color: 99410543
    });
  } catch (e) {
    console.log(e);
  }
};


问:
different width for same column of different row
I have a table with several rows.

My 1st row has the full width of the table table.

The 2nd row has 4 columns with different sizes for each of them.

The 3rd row's first column's width is greater than the total width (1st coloumn's width+2nd coloumn's width +25) of the 2nd row.

Which attribute should I use for this type of design? colonspan is not working in this case

答:
In a table the cells have the width of the column and the height of the row.

Thus, the only way to have two cells above each-other with different widths is if you use colspan.

So you will have to juggle colspans. See: http://jsfiddle.net/CBWJf/

You can maybe set the widths using colgroups.


问:
Browser page becomes unresponsive on sign in using firebase google login
I'm using React.js and firebase to build a web app. Using firebase, when the auth state changes as the user signs in with google, the pages is supposed to be redirected to the "/home" route. instead, it signs in and then "freezes". The page becomes unresponsive. I have checked the console logs on the localhost:3000 page. It keeps throwing a warning multiple times. see below
Kindly help me fix this.

Throttling navigation to prevent the browser from hanging. See https://crbug.com/1038223. Command line switch --disable-ipc-flooding-protection can be used to bypass the protection

below is my code.

```<code>//Header.js component
import { signInWithPopup } from "firebase/auth";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { selectUserEmail, selectUserName, selectUserPhoto, setSignOutState, setUserLoginDetails } from "../features/user/userSlice";
import { auth, provider } from "../firebase";

//header component.
const Header = (props) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const userEmail = useSelector(selectUserEmail);
  const userName = useSelector(selectUserName);
  const userPhoto = useSelector(selectUserPhoto);

  // moniter auth state. if user signs in , redirect him to homepage
  useEffect(() => {
    auth.onAuthStateChanged(
      async (user) => {
        if (user) {
          setUser(user);
          navigate("/home");
        }
      },
      [userName, userEmail, userPhoto]
    );
  });
  //handle auth ftn
  const handleAuth = async () => {
    provider.addScope("profile");
    provider.addScope("email");
    if (!userName) {
      const result = await signInWithPopup(auth, provider);
      setUser(result.user).catch((error) => {
        alert(error.message);
      });
      console.log(result);
    } else if (userName) {
      auth
        .signOut()
        .then(() => {
          dispatch(setSignOutState());
          navigate("/");
        })
        .catch((error) => {
          alert(error.message);
        });
    }
  };

  //dispatch ftn
  const setUser = (user) => {
    dispatch(
      setUserLoginDetails({
        name: user.displayName,
        email: user.email,
        photo: user.photoURL,
      })
    );
  };

  //UI of the COMPONENT
  return (
    <Nav>
      <Logo>
        <img src="/images/logo.svg" alt="Disney Logo" />
      </Logo>
      {!userName ? (
        <Login onClick={handleAuth}>LOGIN</Login>
      ) : (
        <>
          <NavMenu>
            <a href="/home">
              <img src="/images/home-icon.svg" alt="home" />
              <span>HOME</span>
            </a>
            <a href="/search">
              <img src="/images/search-icon.svg" alt="home" />
              <span>SEARCH</span>
            </a>
            <a href="/watchlist">
              <img src="/images/watchlist-icon.svg" alt="home" />
              <span>WATCHLIST</span>
            </a>
            <a href="/original">
              <img src="/images/original-icon.svg" alt="home" />
              <span>ORIGINALS</span>
            </a>
            <a href="/movies">
              <img src="/images/movie-icon.svg" alt="home" />
              <span>MOVIES</span>
            </a>
            <a href="/series">
              <img src="/images/series-icon.svg" alt="home" />
              <span>SERIES</span>
            </a>
          </NavMenu>
          <Signout>
            <UserImg src={userPhoto} alt={userName} />
            <DropDown>
              <span onClick={handleAuth}>Sign out</span>
            </DropDown>
          </Signout>
        </>
      )}
    </Nav>
  );
};

//App.js code

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./App.css";
import Header from "./components/Header";
import Home from "./components/Home";
import Login from "./components/Login";
function App() {
  return (
    <div className="App">
      <Router>
        <Header />
        <Routes>
          <Route path="/" element={<Login />}></Route>
          <Route path="/home" element={<Home />}></Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;
</code>```

答:
```<code>useEffect(() => {
    auth.onAuthStateChanged(async (user) => {
      if (user) {
        setUser(user);
        navigate("/home");
      }
    });
  }, [userName]);
</code>```

just added userName as a dependency and it fixed it. The problem was that without the dependency, it was throwing an infinite loop.

Body:
I'm using React.js and firebase to build a web app. Using firebase, when the auth state changes as the user signs in with google, the pages is supposed to be redirected to the "/home" route. instead, it signs in and then "freezes". The page becomes unresponsive. I have checked the console logs on the localhost:3000 page. It keeps throwing a warning multiple times. see below
Kindly help me fix this.

Throttling navigation to prevent the browser from hanging. See https://crbug.com/1038223. Command line switch --disable-ipc-flooding-protection can be used to bypass the protection

below is my code.

//Header.js component
import { signInWithPopup } from "firebase/auth";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { selectUserEmail, selectUserName, selectUserPhoto, setSignOutState, setUserLoginDetails } from "../features/user/userSlice";
import { auth, provider } from "../firebase";

//header component.
const Header = (props) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const userEmail = useSelector(selectUserEmail);
  const userName = useSelector(selectUserName);
  const userPhoto = useSelector(selectUserPhoto);

  // moniter auth state. if user signs in , redirect him to homepage
  useEffect(() => {
    auth.onAuthStateChanged(
      async (user) => {
        if (user) {
          setUser(user);
          navigate("/home");
        }
      },
      [userName, userEmail, userPhoto]
    );
  });
  //handle auth ftn
  const handleAuth = async () => {
    provider.addScope("profile");
    provider.addScope("email");
    if (!userName) {
      const result = await signInWithPopup(auth, provider);
      setUser(result.user).catch((error) => {
        alert(error.message);
      });
      console.log(result);
    } else if (userName) {
      auth
        .signOut()
        .then(() => {
          dispatch(setSignOutState());
          navigate("/");
        })
        .catch((error) => {
          alert(error.message);
        });
    }
  };

  //dispatch ftn
  const setUser = (user) => {
    dispatch(
      setUserLoginDetails({
        name: user.displayName,
        email: user.email,
        photo: user.photoURL,
      })
    );
  };

  //UI of the COMPONENT
  return (

      <Logo>

      </Logo>
      {!userName ? (
        <Login onClick={handleAuth}>LOGIN</Login>
      ) : (
        <>
          <NavMenu>

              HOME

              SEARCH

              WATCHLIST

              ORIGINALS

              MOVIES

              SERIES

          </NavMenu>
          <Signout>
            <UserImg src={userPhoto} alt={userName} />
            <DropDown>
              Sign out
            </DropDown>
          </Signout>
        </>
      )}

  );
};

//App.js code

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./App.css";
import Header from "./components/Header";
import Home from "./components/Home";
import Login from "./components/Login";
function App() {
  return (

      <Router>

        <Routes>
          <Route path="/" element={<Login />}></Route>
          <Route path="/home" element={<Home />}></Route>
        </Routes>
      </Router>

  );
}

export default App;

Body:
useEffect(() => {
    auth.onAuthStateChanged(async (user) => {
      if (user) {
        setUser(user);
        navigate("/home");
      }
    });
  }, [userName]);

just added userName as a dependency and it fixed it. The problem was that without the dependency, it was throwing an infinite loop.


问:
While loop in Freemarker
How do I create a similar loop in Freemarker(FTL)
In freemarker I have this statement:

```<code><#if myVariable?? >
  // do stuff
</#if>
</code>```

and I want to convert it to a while loop is it possible?

Javascript-code I want to replicate

```<code>while (myVariable != null) {
  // do stuff
}
</code>```

If not possible how is the recursive approach in Freemarker?

答:
You could use a macro with  recursion:

```<code><#macro doStuff>
  <#if myVariable?? >
    // do stuff
    <@doStuff/>
  </#if>
</#macro>

<@doStuff/>
</code>```

Title: While loop in Freemarker

Body:
How do I create a similar loop in Freemarker(FTL)
In freemarker I have this statement:

<#if myVariable?? >
  // do stuff
</#if>

and I want to convert it to a while loop is it possible?

Javascript-code I want to replicate

while (myVariable != null) {
  // do stuff
}

If not possible how is the recursive approach in Freemarker?

Body:
You could use a macro with  recursion:

<#macro doStuff>
  <#if myVariable?? >
    // do stuff
    <@doStuff/>
  </#if>
</#macro>

<@doStuff/>


问:
How to replace only missing value of specific column from datafarm 1 by value matched from data frame 2
I have two dataframes as shown below:

```<code>structure(list(ID = c("a", "a", "c", "d", "a", "f"), a1 = c("2001",
"2000", "2000", "1998", "2006", "2002"), value = c("100", NA,
"200", NA, "400", "500")), class = "data.frame", row.names = c(NA,
-6L))

ID2 <- c("x","a","c","d","n","f","g","m")
a2 <- c(2000,2000,2000,2000,2000,2000,2000,2000)
value2 <- c(100, 1000, 20000, 1000, 400,500,1,1)

  ID   a1 value
1  a 2001   100
2  a 2000  <NA>
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500

  ID2   a2 value2
1   x 2000    100
2   a 2000   1000
3   c 2000  20000
4   d 2000   1000
5   n 2000    400
6   f 2000    500
7   g 2000      1
8   m 2000      1
</code>```

what I want to do: I want to replace only missing value in column value of data frame 1 by corresponding value from value2 column of dataframe 2. the year and ID should match. I tried the following code using left_join; however, this gave me the wrong result

```<code>r <- left_join(data, data2, by=c("ID"="ID2","a1"="a2"))
</code>```

Any suggetsion?

expected result

```<code>  ID   a1 value
1  a 2001   100
2  a 2000  **1000**
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500
</code>```

Body:
I have two dataframes as shown below:

structure(list(ID = c("a", "a", "c", "d", "a", "f"), a1 = c("2001",
"2000", "2000", "1998", "2006", "2002"), value = c("100", NA,
"200", NA, "400", "500")), class = "data.frame", row.names = c(NA,
-6L))

ID2 <- c("x","a","c","d","n","f","g","m")
a2 <- c(2000,2000,2000,2000,2000,2000,2000,2000)
value2 <- c(100, 1000, 20000, 1000, 400,500,1,1)

  ID   a1 value
1  a 2001   100
2  a 2000  <NA>
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500

  ID2   a2 value2
1   x 2000    100
2   a 2000   1000
3   c 2000  20000
4   d 2000   1000
5   n 2000    400
6   f 2000    500
7   g 2000      1
8   m 2000      1

what I want to do: I want to replace only missing value in column value of data frame 1 by corresponding value from value2 column of dataframe 2. the year and ID should match. I tried the following code using left_join; however, this gave me the wrong result

r <- left_join(data, data2, by=c("ID"="ID2","a1"="a2"))

Any suggetsion?

expected result

  ID   a1 value
1  a 2001   100
2  a 2000  **1000**
3  c 2000   200
4  d 1998  <NA>
5  a 2006   400
6  f 2002   500

Body:
Using just base R.

merge(df1, df2, by.x=c('ID', 'a1'), by.y=c('ID2', 'a2'), all.x=TRUE) |>
  transform(value=ifelse(is.na(value), value2, value), value2=NULL)
#   ID   a1 value
# 1  a 2000  1000
# 2  a 2001   100
# 3  a 2006   400
# 4  c 2000   200
# 5  d 1998    NA
# 6  f 2002   500

Data:

df1 <- structure(list(ID = c("a", "a", "c", "d", "a", "f"), a1 = c(2001L,
2000L, 2000L, 1998L, 2006L, 2002L), value = c(100L, NA, 200L,
NA, 400L, 500L)), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6"))
df2 <- structure(list(ID2 = c("x", "a", "c", "d", "n", "f", "g", "m"
), a2 = c(2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L
), value2 = c(100L, 1000L, 20000L, 1000L, 400L, 500L, 1L, 1L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))


问:
Using XPath to select button inside HTML with content of tag instead of numbered list
I am using python + selenium to automate common behavior through a website. I have now arrived at a point where there is a div
 with a number of
 inside href> tags. Please find a snippet of the HTML page below to clarify.

```<code><div class="teetime-grid" data-baan="1">
    <a href="#">

        <div class="btn btn-success teetime has-bookings " data-time="1645165200"
             title="Er zijn nog 3 beschikbare plaatsen op deze starttijd">
            <span class="time">07:20</span>
            <div class="icons">
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon vrij"> </span>
                <span class="icon vrij"> </span>
                <span class="icon vrij"> </span>

            </div>
        </div>
    </a>

    <a href="#">

        <div class="btn btn-success teetime has-bookings " data-time="1645165800"
             title="Er zijn nog 1 beschikbare plaatsen op deze starttijd">
            <span class="time">07:30</span>
            <div class="icons">
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon bezet geslacht-m"> </span>
                <span class="icon vrij"> </span>

            </div>
        </div>
    </a>
</div>
</code>```

I need to access specific
 inside the grid. In Selenium, I know I can do this by using:

```<code>driver = webdriver.Chrome()
driver.find_element_by_xpath("//a[2]/div")
</code>```

To select the second  tag in my above example, which in this case has a corresponding time of 07:30 associated with it (it's defined in the 07:30).

Is there also a way to access these elements by the contents of the  instead of specifying the number in the list of href> tags? Because now I still have to know which a[?] number corresponds to a certain time. If I have to look this up manually every time time there is no point in automating this browser action to begin with.

答:
This will find the div, which contains a specific span child 1 level down.

```<code>//span[@class='time'][text()='07:30']/..
</code>```

And if you'll add one more /.., you'll find the a (the div parent).

Body:
I am using python + selenium to automate common behavior through a website. I have now arrived at a point where there is a div
 with a number of
 inside  tags. Please find a snippet of the HTML page below to clarify.

            07:20

            07:30

I need to access specific
 inside the grid. In Selenium, I know I can do this by using:

driver = webdriver.Chrome()
driver.find_element_by_xpath("//a[2]/div")

To select the second  tag in my above example, which in this case has a corresponding time of 07:30 associated with it (it's defined in the 07:30).

Is there also a way to access these elements by the contents of the  instead of specifying the number in the list of  tags? Because now I still have to know which a[?] number corresponds to a certain time. If I have to look this up manually every time time there is no point in automating this browser action to begin with.

Body:
This will find the div, which contains a specific span child 1 level down.

//span[@class='time'][text()='07:30']/..

And if you'll add one more /.., you'll find the a (the div parent).