问:
how to make phone number clickable in classifield wordpress
I tried everything to make the phone number clickable but for some reason it didn't work

```<code>    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>
    <li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><?php echo $post_phone; ?></li>
</code>```

I added this and it still didn't work :

```<code><a href="tel:$post_phone"> $post_phone</a>
</code>```

and this

```<code><li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?></a></li>
                        <?php }?>
</code>```

Thank you so much for your help

答:
Easier to do it all in PHP:   </p>

```<code> <?php
      echo '<a href="tel:' . $post_phone . '">' . $post_phone . '</a>';
      echo '<li><span>' . esc_html_e( 'Phone', 'classiera' ) . '</span><a href="callto://' . $post_phone . '">' . $post_phone . '</a>'
 ?>
</code>```

Body:
I tried everything to make the phone number clickable but for some reason it didn't work

    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>

<?php esc_html_e( 'Phone', 'classiera' ); ?><?php echo $post_phone; ?>

I added this and it still didn't work :

 $post_phone

and this

<?php esc_html_e( 'Phone', 'classiera' ); ?><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?>

                        <?php }?>

Thank you so much for your help

Body:
Easier to do it all in PHP:

 <?php
      echo '<a href="tel:' . $post_phone . '">' . $post_phone . '</a>';
      echo '<li><span>' . esc_html_e( 'Phone', 'classiera' ) . '</span><a href="callto://' . $post_phone . '">' . $post_phone . '</a>'
 ?>


来源: stackexchange

问:
Why does my code run twice in the completion block
I have some code that connects to a firebase and when it gets to a certain part of the code it runs it twice it also does not remove my waitAlertController it is causing my code to crash because it runs it twice then the second time there are no values because the first time it ran it deleted them here is my code

this is my table view where I add the wait view controller and start the completion methods.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)

    let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
    })

    let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
        // let them know to wait a second or the bet won't go through
        var waitController = UIAlertController(title: "Please Wait", message: "Your bet is being processed", preferredStyle: .alert)

        self.present(waitController, animated: true, completion: nil)
        //take away the usersMoney
        self.takeAwayMoney(self.amountBets[indexPath.row],index: indexPath.row, completion: { (result: Bool?) in

            guard let boolResult = result else {
                return
            }
            var getResult = ""
            print("You have taken away the users money")

                print("you made it this far almost there")
                //let delayInSeconds = 3.0 // 1
                //DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
        })
        if (self.userHasMoney == true) {
        self.updateBet(indexPath.row, completion: { (result: Bool?) in

            guard let checkRes = result else {
                return
            }

        })

        self.getOpoosingUserNames(self.userName, indexPath.row, completion: { (anothaResult: Bool?) in

            guard let value = anothaResult else {
                return print("didn't work")
            }
                    //wait for the first view to load in case it uploads to fast
                    sleep(1)
                    self.dismiss(animated: true, completion: nil)
                    let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames!, preferredStyle: .alert)
                    let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
                    successController.addAction(okButt)
                    self.present(successController, animated: true, completion: nil)
                    //lastly delete the opposing UserName
                    self.amountBets.remove(at: indexPath.row)
                    self.tableView.reloadData()
                    print("Second")

        })
        } else {
            //display a alert that lets the user know hes broke
            let brokeController = UIAlertController(title: "Failed", message: "Reason: You don't have enough money!", preferredStyle: .alert)
            let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
            brokeController.addAction(okButt)
            self.present(brokeController, animated: true, completion: nil)
        }

    return
    })

    alertController.addAction(okButton)
    alertController.addAction(yesButton)
    present(alertController, animated: true, completion: nil)
}
</code>```

and this is my takeMoneyAway method

```<code>func takeAwayMoney(_ howMuch: String, index: Int, completion: @escaping (Bool)-> ()) -> Void{
        if let notMuch = Int(howMuch) {

            let userID = FIRAuth.auth()?.currentUser?.uid

            datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let money = value?["money"] as? String ?? ""

                //convert money to int
                if let conMoney = Int(money) {
                    var conMoreMoney = conMoney
                    if conMoreMoney < notMuch {
                        print(" You don't have enough money")
                        completion(false)
                        return
                    } else {
                        conMoreMoney -= notMuch
                        let values = ["money": String(conMoreMoney)]

                        //update the users money
                        self.datRef.child("User").child(userID!).updateChildValues(values)
                        completion(true)
                        /*
                        self.updateBet(index, completion: { (result: Bool?) in
                            guard let checkResult = result else {
                                return print("Failed to get result")
                            }
                            if checkResult == true {
                                completion(true)
                            } else {
                                completion(false)
                            }
                        })
 */

                    }

                }
                // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }
    }
</code>```

and my final method goes to my database updates the values and grabs the person they made a bet against.

```<code> func updateBet(_ index: Int, completion: @escaping (_ something: Bool?) -> Void) {
        let userID = FIRAuth.auth()?.currentUser?.uid
        datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            // ...

            self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
                //
                // this is the unique identifier of the bet.  eg, -Kfx81GvUxoHpmmMwJ9P
                guard let dict = snapshot.value as? [String: AnyHashable] else {
                    print("failed to get dictionary from Bets.\(self.userName)")
                    return
                }
                let values = ["OpposingUsername": self.userName,"Show": "no"]

                self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)
                let checkTheCodeWentHere = "Success"
                // now get the opposing username which is just the Username registered to that specific bet

                self.datRef.child("Bets").child(self.tieBetToUser[index]).observeSingleEvent(of: .value, with: { snapshot in
                    let thisValue = snapshot.value as? NSDictionary
                    if let username = thisValue?["Username"] as? String {
                        self.opposingUserNames = username
                        completion(true)
                    } else {
                        completion(false)
                    }

                })

            })

        }) { (error) in
            print(error.localizedDescription)
        }

    }
</code>```

so in the tableview method there is a block of code that says if checkRes == true {}
all of the code in the curly braces runs twice I checked this with break points can some one tell me why this is?

答:
Without being able to actually run the code and test it, and based solely on your comments above, I believe the part you were talking about was this:

```<code>//take away the usersMoney
self.takeAwayMoney(self.amountBets[indexPath.row],index: indexPath.row, completion:{(result) in
    if result {
        // User has money
    } else {
        // User does not have money
    }
    var getResult = ""
    print("You have taken away the users money")

        print("you made it this far almost there")
        //let delayInSeconds = 3.0 // 1
        //DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
})
</code>```

The takeAwayMoney method returns whether the user has money or not via the result parameter of the closure and that parameter wsan't an optional in the method definition. However, in the above code, for some reason it was declared an optional. I have changed the code to remove that bit of code and added an if condition indicating how you would proceed after takeAwayMoney has been executed.

Basically, you first call takeAwayMoney, wait for that method to return its results via the closure, and then look at the results of the closure and do any subsequent processing. So, it looks as if you really need all the code within the if (self.userHasMoney == true) { condition to be moved to be within the takeAwayMoney completion closure.

Hope this makes sense. If not, feel free to ping me and I'll try to clarify.

ContentLicense: CC BY-SA 3.0

Body:
I have some code that connects to a firebase and when it gets to a certain part of the code it runs it twice it also does not remove my waitAlertController it is causing my code to crash because it runs it twice then the second time there are no values because the first time it ran it deleted them here is my code

this is my table view where I add the wait view controller and start the completion methods.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)

    let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
    })

    let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
        // let them know to wait a second or the bet won't go through
        var waitController = UIAlertController(title: "Please Wait", message: "Your bet is being processed", preferredStyle: .alert)

        self.present(waitController, animated: true, completion: nil)
        //take away the usersMoney
        self.takeAwayMoney(self.amountBets[indexPath.row],index: indexPath.row, completion: { (result: Bool?) in

            guard let boolResult = result else {
                return
            }
            var getResult = ""
            print("You have taken away the users money")

                print("you made it this far almost there")
                //let delayInSeconds = 3.0 // 1
                //DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
        })
        if (self.userHasMoney == true) {
        self.updateBet(indexPath.row, completion: { (result: Bool?) in

            guard let checkRes = result else {
                return
            }

        })

        self.getOpoosingUserNames(self.userName, indexPath.row, completion: { (anothaResult: Bool?) in

            guard let value = anothaResult else {
                return print("didn't work")
            }
                    //wait for the first view to load in case it uploads to fast
                    sleep(1)
                    self.dismiss(animated: true, completion: nil)
                    let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames!, preferredStyle: .alert)
                    let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
                    successController.addAction(okButt)
                    self.present(successController, animated: true, completion: nil)
                    //lastly delete the opposing UserName
                    self.amountBets.remove(at: indexPath.row)
                    self.tableView.reloadData()
                    print("Second")

        })
        } else {
            //display a alert that lets the user know hes broke
            let brokeController = UIAlertController(title: "Failed", message: "Reason: You don't have enough money!", preferredStyle: .alert)
            let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
            brokeController.addAction(okButt)
            self.present(brokeController, animated: true, completion: nil)
        }

    return
    })

    alertController.addAction(okButton)
    alertController.addAction(yesButton)
    present(alertController, animated: true, completion: nil)
}

and this is my takeMoneyAway method

func takeAwayMoney(_ howMuch: String, index: Int, completion: @escaping (Bool)-> ()) -> Void{
        if let notMuch = Int(howMuch) {

            let userID = FIRAuth.auth()?.currentUser?.uid

            datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let money = value?["money"] as? String ?? ""

                //convert money to int
                if let conMoney = Int(money) {
                    var conMoreMoney = conMoney
                    if conMoreMoney < notMuch {
                        print(" You don't have enough money")
                        completion(false)
                        return
                    } else {
                        conMoreMoney -= notMuch
                        let values = ["money": String(conMoreMoney)]

                        //update the users money
                        self.datRef.child("User").child(userID!).updateChildValues(values)
                        completion(true)
                        /*
                        self.updateBet(index, completion: { (result: Bool?) in
                            guard let checkResult = result else {
                                return print("Failed to get result")
                            }
                            if checkResult == true {
                                completion(true)
                            } else {
                                completion(false)
                            }
                        })
 */

                    }

                }
                // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }
    }

and my final method goes to my database updates the values and grabs the person they made a bet against.

 func updateBet(_ index: Int, completion: @escaping (_ something: Bool?) -> Void) {
        let userID = FIRAuth.auth()?.currentUser?.uid
        datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            // ...

            self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
                //
                // this is the unique identifier of the bet.  eg, -Kfx81GvUxoHpmmMwJ9P
                guard let dict = snapshot.value as? [String: AnyHashable] else {
                    print("failed to get dictionary from Bets.\(self.userName)")
                    return
                }
                let values = ["OpposingUsername": self.userName,"Show": "no"]

                self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)
                let checkTheCodeWentHere = "Success"
                // now get the opposing username which is just the Username registered to that specific bet

                self.datRef.child("Bets").child(self.tieBetToUser[index]).observeSingleEvent(of: .value, with: { snapshot in
                    let thisValue = snapshot.value as? NSDictionary
                    if let username = thisValue?["Username"] as? String {
                        self.opposingUserNames = username
                        completion(true)
                    } else {
                        completion(false)
                    }

                })

            })

        }) { (error) in
            print(error.localizedDescription)
        }

    }

so in the tableview method there is a block of code that says if checkRes == true {}
all of the code in the curly braces runs twice I checked this with break points can some one tell me why this is?

Body:
Without being able to actually run the code and test it, and based solely on your comments above, I believe the part you were talking about was this:

//take away the usersMoney
self.takeAwayMoney(self.amountBets[indexPath.row],index: indexPath.row, completion:{(result) in
    if result {
        // User has money
    } else {
        // User does not have money
    }
    var getResult = ""
    print("You have taken away the users money")

        print("you made it this far almost there")
        //let delayInSeconds = 3.0 // 1
        //DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
})

The takeAwayMoney method returns whether the user has money or not via the result parameter of the closure and that parameter wsan't an optional in the method definition. However, in the above code, for some reason it was declared an optional. I have changed the code to remove that bit of code and added an if condition indicating how you would proceed after takeAwayMoney has been executed.

Basically, you first call takeAwayMoney, wait for that method to return its results via the closure, and then look at the results of the closure and do any subsequent processing. So, it looks as if you really need all the code within the if (self.userHasMoney == true) { condition to be moved to be within the takeAwayMoney completion closure.

Hope this makes sense. If not, feel free to ping me and I'll try to clarify.


问:
How to run batch file using powershell
I am trying to run one batch file using powershell. It required property file to start the APP as without it is failing.

Below are the commands which i have tried but dint get success.

```<code>cmd.exe /c ' C:\designer\5.7\bin\designer.bat -p C:\designer\5.7\bin\designer.prop
</code>```

or

```<code>& "C:\designer\5.7\bin\designer.exe" "C:\designer\5.7\bin\designer.prop"
</code>```

or

```<code>& "C:\designer\5.7\bin\designer.exe" C:\designer\5.7\bin\designer.prop
</code>```

Could someone suggest more on it?

答:
x.vbs file content following:

```<code>Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd /K CD **path** & **x.bat** **parameter**"
Set oShell = Nothing
</code>```

powershell script following :

```<code>Start-Process x.vbs
</code>```

Title: How to run batch file using powershell

Body:
I am trying to run one batch file using powershell. It required property file to start the APP as without it is failing.

Below are the commands which i have tried but dint get success.

cmd.exe /c ' C:\designer\5.7\bin\designer.bat -p C:\designer\5.7\bin\designer.prop

or

& "C:\designer\5.7\bin\designer.exe" "C:\designer\5.7\bin\designer.prop"

or

& "C:\designer\5.7\bin\designer.exe" C:\designer\5.7\bin\designer.prop

Could someone suggest more on it?

Body:
x.vbs file content following:

Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd /K CD **path** & **x.bat** **parameter**"
Set oShell = Nothing

powershell script following :

Start-Process x.vbs


问:
Show ObservableCollection items in CommandLineTool
I have a class library called something.mvvm there are some classes and folders.

Previously it was used for an mvvm project with an UI.

Now I've added an CommandLineProject. And in the CommandLineProject I want to use the functions from the class library.
In the class library is a function which gets user and set them to an observablecollection.

Now I want to display the users in the console instead of de View(like before).

So my question is, how can I use an observableCollection in a CommandLineTool?

答:
From Wikipedia: Console application

A console application is a computer program designed to be used via a text-only computer interface

You can't show any graphic elements in a console application.
If you want to show e.g. all items in your ObservableCollection you can loop through the collection and via Console.WriteLine you can print your items.

Something like

```<code>foreach(var item in MyObservableCollection)
{
    var text = <build your string from the properties you want to show>;
    Console.WriteLine(text);
}
</code>```

Body:
From Wikipedia: Console application

A console application is a computer program designed to be used via a text-only computer interface

You can't show any graphic elements in a console application.
If you want to show e.g. all items in your ObservableCollection you can loop through the collection and via Console.WriteLine you can print your items.

Something like

foreach(var item in MyObservableCollection)
{
    var text = <build your string from the properties you want to show>;
    Console.WriteLine(text);
}


问:
Swift - Implementing multiple scrollViews
I am creating a photo album app, in which a page should consist of multiple imageViews, each one within a scrollView, so each image placed within the page can be scrolled and zoomed (kind of like Instagram's Layout).
What is the best way of implementing this? using CollectionView seems a bit complicated as the spaces may vary, based on the template selected, but when I try using multiple scrollViews I have troubles referencing to each one within the delegate viewForZooming function. I have tried using an array of scrollViews, but the delegate function isn't being called.

```<code>func drawPage(pageID: Int) {

    var tempImagesArray = [UIImage]()
    var tempImageLocationsArray: [CGRect] = []

    var scrollView: UIScrollView!
    var imageView = UIImageView()

    if pageID == 1 {
        tempImagesArray = imagesArrayLeft
        tempImageLocationsArray = imageLocationsArrayLeft
    }
    else {
        tempImagesArray = imagesArrayRight
        tempImageLocationsArray = imageLocationsArrayRight
    }

    for i in 0...tempImagesArray.count - 1 {

        scrollView = UIScrollView(frame: tempImageLocationsArray[i])
        scrollView.delegate = self

        let image = tempImagesArray[i]
        imageView.image = image
        imageView.frame = tempImageLocationsArray[i]
        scrollView.addSubview(imageView)
        scrollView.contentSize = image.size
        scrollView.clipsToBounds = true
        scrollView.layer.borderColor = UIColor.white.cgColor
        scrollView.layer.borderWidth = 4.0

        let scrollViewFrame = scrollView.frame
        let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
        let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
        let minScale = min(scaleWidth, scaleHeight)
        scrollView.minimumZoomScale = 1.0

        scrollView.maximumZoomScale = 4.0
        scrollView.zoomScale = minScale

        scrollViewsArray.append(scrollView)
        imageViewsArray.append(imageView)

        scrollViewsArray[scrollViewsArray.count - 1].delegate = self

        self.pageFrameView.addSubview(scrollView)

    }
}
</code>```

And the delegate function:

```<code>func viewForZooming(in scrollView: UIScrollView) -> UIView? {

    if scrollViewsArray.count > 0 {
        if scrollView == scrollViewsArray[0] {
            return self.imageViewsArray[0]
        }
        else {
            return self.imageViewsArray[0]
            }
    }

    return nil

}
</code>```

答:
SORRY!!! But your question is the bit complex to understand. What I'll suggest you the best, for now, is that to USE tag for every scroll views rather than putting them in array.

Regards,
  Code Blizzard

Body:
I am creating a photo album app, in which a page should consist of multiple imageViews, each one within a scrollView, so each image placed within the page can be scrolled and zoomed (kind of like Instagram's Layout).
What is the best way of implementing this? using CollectionView seems a bit complicated as the spaces may vary, based on the template selected, but when I try using multiple scrollViews I have troubles referencing to each one within the delegate viewForZooming function. I have tried using an array of scrollViews, but the delegate function isn't being called.

func drawPage(pageID: Int) {

    var tempImagesArray = [UIImage]()
    var tempImageLocationsArray: [CGRect] = []

    var scrollView: UIScrollView!
    var imageView = UIImageView()

    if pageID == 1 {
        tempImagesArray = imagesArrayLeft
        tempImageLocationsArray = imageLocationsArrayLeft
    }
    else {
        tempImagesArray = imagesArrayRight
        tempImageLocationsArray = imageLocationsArrayRight
    }

    for i in 0...tempImagesArray.count - 1 {

        scrollView = UIScrollView(frame: tempImageLocationsArray[i])
        scrollView.delegate = self

        let image = tempImagesArray[i]
        imageView.image = image
        imageView.frame = tempImageLocationsArray[i]
        scrollView.addSubview(imageView)
        scrollView.contentSize = image.size
        scrollView.clipsToBounds = true
        scrollView.layer.borderColor = UIColor.white.cgColor
        scrollView.layer.borderWidth = 4.0

        let scrollViewFrame = scrollView.frame
        let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
        let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
        let minScale = min(scaleWidth, scaleHeight)
        scrollView.minimumZoomScale = 1.0

        scrollView.maximumZoomScale = 4.0
        scrollView.zoomScale = minScale

        scrollViewsArray.append(scrollView)
        imageViewsArray.append(imageView)

        scrollViewsArray[scrollViewsArray.count - 1].delegate = self

        self.pageFrameView.addSubview(scrollView)

    }
}

And the delegate function:

func viewForZooming(in scrollView: UIScrollView) -> UIView? {

    if scrollViewsArray.count > 0 {
        if scrollView == scrollViewsArray[0] {
            return self.imageViewsArray[0]
        }
        else {
            return self.imageViewsArray[0]
            }
    }

    return nil

}


问:
Trying to understand extern in C
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

```<code>extern int global_counter;

int file_counter;
</code>```

extern.c

```<code>#include "extern.h"

int global_counter = 5;
</code>```

incrementor1.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

incrementor2.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

```<code>void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}
</code>```

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

```<code>CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o
</code>```

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

```<code>From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2
</code>```

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.

答:
You're experiencing the problem due to tentative definition.

Quoting C11, chapter §6.9.2

A declaration of an identifier for an object that has file scope without an initializer, and
  without a storage-class specifier or with the storage-class specifier static, constitutes a
  tentative definition. If a translation unit contains one or more tentative definitions for an
  identifier, and the translation unit contains no external definition for that identifier, then
  the behavior is exactly as if the translation unit contains a file scope declaration of that
  identifier, with the composite type as of the end of the translation unit, with an initializer
  equal to 0.

Try compiling with -fno-common flag and it should throw the error related to redefinition for file_counter.

Quoting the online manual

-fno-common

In C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with the extern keyword, which do not allocate storage.

Unix C compilers have traditionally allocated storage for uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This is the behavior specified by -fcommon, and is the default for GCC on most targets. On the other hand, this behavior is not required by ISO C, and on some targets may carry a speed or code size penalty on variable references.

The -fno-common option specifies that the compiler should instead place uninitialized global variables in the data section of the object file. This inhibits the merging of tentative definitions by the linker so you get a multiple-definition error if the same variable is defined in more than one compilation unit. Compiling with -fno-common is useful on targets for which it provides better performance, or if you wish to verify that the program will work on other systems that always treat uninitialized variable definitions this way.

Title: Trying to understand extern in C

Body:
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

extern int global_counter;

int file_counter;

extern.c

#include "extern.h"

int global_counter = 5;

incrementor1.c

#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}

incrementor2.c

#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.


问:
How to connect two stages of circles using CSS
Folks,

We are trying to connect two lines with different stages but it seems stage2 is moving to different line.

How to connect these two stages(circles) with lines so that they appear on same line. As of now always it is coming to new line.

Code below :

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><font face="Times New Roman" size="1">stage1</font>
<span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
</span>
<hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
<font face="Times New Roman" size="1">stage2</font>
</span>
<span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
</span>
<hr style="height:1px; margin-top:-11px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px"></code>```

答:
Like this?

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display:inline-block;">
  <font face="Times New Roman" size="1">stage1</font>
  <span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div><!--
--><div style="display:inline-block;">
  <font face="Times New Roman" size="1">stage2</font>
  <span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-11px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div></code>```

Body:
Folks,

We are trying to connect two lines with different stages but it seems stage2 is moving to different line.

How to connect these two stages(circles) with lines so that they appear on same line. As of now always it is coming to new line.

Code below :

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}

stage1

stage2

Body:
Like this?

.circle {
  width: 10px;
  height: 10px;
  border-radius: 15px 15px 15px 15px;
  padding: 5px;
  background: white;
  border: 1px solid green;
}

.circle-inner {
  width: 10px;
  height: 10px;
  border-radius: 10px 10px 10px 10px;
  background: green;
}

<div style="display:inline-block;">
  <font face="Times New Roman" size="1">stage1</font>
  <span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-10px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div><!--
--><div style="display:inline-block;">
  <font face="Times New Roman" size="1">stage2</font>
  <span class="circle" style="display:block">
 <span class="circle-inner" style="display:block"></span>
  </span>
  <hr style="height:1px; margin-top:-11px; border:none; color:#000; background-color:#000;width:80px;margin-left:22px">
</div>


问:
looping through csv file
I'm very new to R and Rstudio. What I'm trying to do is loop through a csv file.

The file has 3 columns. 1) user 2) event (success or fail) 3) randNum

So basically every user starts off with a fail and once they reach a success it moves on to the next user.

Ex:

```<code>user:   |  event:  | randNum

user1  |   fail    |  6

user1  |   fail    |  4

user1  |  fail     |  1

user1   | success  |  2

user2 | ...        |
</code>```

Basically what I need to do is this. I need to store the first random number (6) and than the last random number (2) which will be whenever the user succeeds. How would I do that? And i need to do this for each user because I will be doing something with these numbers.

答:
If every user eventually succeeds and you want to consider the first and last row of every user try following code:

```<code>df<-split(df,df$user)
df<-lapply(df,function(x){
     x<-rbind(head(x,1),tail(x,1))
     x
})

df<-do.call("rbind",df)
</code>```

From this, you will get the first fail and success of each user

Title: looping through csv file

Body:
I'm very new to R and Rstudio. What I'm trying to do is loop through a csv file.

The file has 3 columns. 1) user 2) event (success or fail) 3) randNum

So basically every user starts off with a fail and once they reach a success it moves on to the next user.

Ex:

user:   |  event:  | randNum

user1  |   fail    |  6

user1  |   fail    |  4

user1  |  fail     |  1

user1   | success  |  2

user2 | ...        |

Basically what I need to do is this. I need to store the first random number (6) and than the last random number (2) which will be whenever the user succeeds. How would I do that? And i need to do this for each user because I will be doing something with these numbers.

Body:
If every user eventually succeeds and you want to consider the first and last row of every user try following code:

df<-split(df,df$user)
df<-lapply(df,function(x){
     x<-rbind(head(x,1),tail(x,1))
     x
})

df<-do.call("rbind",df)

From this, you will get the first fail and success of each user


问:
Junit test hangs up on my async thread
I am fork a new thread on my service's @Postconstruct method, and in the new thread, a infinite loop is running.

My test is just invoke the service using spring mvc test:

```<code>ResultActions result = this.mockMvc.perform(post("/test").with(httpBasic(user, pwd)).contentType("application/json").content(test))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(status().isOk());
</code>```

And the test just hangs there, waiting for the infinite loop thread to stop. but when the service is started normally, the test is fine. Any idea why? And how to fix it.

here is the code in my service java:

```<code>@Postconstruct
private void init() {
   invoke();
}

private void invoke() {

 Runnable task = () -> {
     while(true) { ... }
  }
 Thread t;
 for(int i=0; i<3; i++) {
     t = new Thread(task);
     t.setName("test-" + i);
     t.start();
  }
 }
</code>```

答:
Suggestion: step back from using "bare metal" Threads. There are nice abstraction concepts, like ExecutorService and things like Futures and Promises.

The point is: one can use dependency injection to provide such an ExecutorService to the production code; and then you can define your own service ... that does everything on the same thread.

Meaning: avoid unit tests that deal with multiple threads - as that often leads to additional waiting, or "flakiness" as you never now exactly how long your test will be running.

Title: Junit test hangs up on my async thread

Body:
I am fork a new thread on my service's @Postconstruct method, and in the new thread, a infinite loop is running.

My test is just invoke the service using spring mvc test:

ResultActions result = this.mockMvc.perform(post("/test").with(httpBasic(user, pwd)).contentType("application/json").content(test))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(status().isOk());

And the test just hangs there, waiting for the infinite loop thread to stop. but when the service is started normally, the test is fine. Any idea why? And how to fix it.

here is the code in my service java:

@Postconstruct
private void init() {
   invoke();
}

private void invoke() {

 Runnable task = () -> {
     while(true) { ... }
  }
 Thread t;
 for(int i=0; i<3; i++) {
     t = new Thread(task);
     t.setName("test-" + i);
     t.start();
  }
 }


问:
Parse variable number of differently typed integers from a line in C
I have a file with lines separated by '\n' where each line looks like either

```<code>10010 0 19 7 18
</code>```

or

```<code>10014 -1 -1 -1 11 10db8 1
</code>```

That is, every line will always either have 5 or 7 space separated values and the type of every value is also known beforehand. I want to read the file line by line and parse each line to extract inttypes (SCNi32, SCNu32, SCNx32..) and store in corresponding inttype variables. What is the easiest way to do this? I am new to C.

答:
You should probably create a struct to store them in, for example:

```<code>typedef struct
{
  int16_t   a;
  uint32_t  b;
  int8_t    c;
  ...
} int_stuff_t;
</code>```

Then you can just write a long list such as

```<code>#define GET_FORMAT_SPECIFIER(type) _Generic((type), \
  int16_t:  "%"SCNd16, \
  uint32_t: "%"SCNu32, \
  int8_t:   "%"SCNd8)

fscanf(fp, GET_FORMAT_SPECIFIER(int_stuff.a), &int_stuff.a);
fscanf(fp, GET_FORMAT_SPECIFIER(int_stuff.b), &int_stuff.b);
...
</code>```

Now if you have a whole lot of these and they have all kinds of names and formats, then this might be one of the few valid cases where you should consider using X macros, to make the code easy to maintain.

Example:

```<code>#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <assert.h>

// X macro (type, name, format)
#define INT_STUFF_LIST     \
  X(int16_t,  a, SCNd16)   \
  X(uint32_t, b, SCNu32)   \
  X(int8_t,   c, SCNd8)

typedef struct
{
  #define X(type, name, format) \
  type name;
  INT_STUFF_LIST
  #undef X
} int_stuff_t;

int main()
{
  FILE* fp = fopen("something.txt", "r");
  assert(fp != NULL);

  int_stuff_t int_stuff;

  #define X(type, name, format) \
  fscanf(fp, "%" format, &int_stuff.name);
  INT_STUFF_LIST
  #undef X

  fclose(fp);
}
</code>```

Though this is just a quick & dirty example, the real code should continuously check the result of each fscanf call to ensure it isn't EOF.

Body:
I have a file with lines separated by '\n' where each line looks like either

10010 0 19 7 18

or

10014 -1 -1 -1 11 10db8 1

That is, every line will always either have 5 or 7 space separated values and the type of every value is also known beforehand. I want to read the file line by line and parse each line to extract inttypes (SCNi32, SCNu32, SCNx32..) and store in corresponding inttype variables. What is the easiest way to do this? I am new to C.

Body:
You should probably create a struct to store them in, for example:

typedef struct
{
  int16_t   a;
  uint32_t  b;
  int8_t    c;
  ...
} int_stuff_t;

Then you can just write a long list such as

#define GET_FORMAT_SPECIFIER(type) _Generic((type), \
  int16_t:  "%"SCNd16, \
  uint32_t: "%"SCNu32, \
  int8_t:   "%"SCNd8)

fscanf(fp, GET_FORMAT_SPECIFIER(int_stuff.a), &int_stuff.a);
fscanf(fp, GET_FORMAT_SPECIFIER(int_stuff.b), &int_stuff.b);
...

Now if you have a whole lot of these and they have all kinds of names and formats, then this might be one of the few valid cases where you should consider using X macros, to make the code easy to maintain.

Example:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <assert.h>

// X macro (type, name, format)
#define INT_STUFF_LIST     \
  X(int16_t,  a, SCNd16)   \
  X(uint32_t, b, SCNu32)   \
  X(int8_t,   c, SCNd8)

typedef struct
{
  #define X(type, name, format) \
  type name;
  INT_STUFF_LIST
  #undef X
} int_stuff_t;

int main()
{
  FILE* fp = fopen("something.txt", "r");
  assert(fp != NULL);

  int_stuff_t int_stuff;

  #define X(type, name, format) \
  fscanf(fp, "%" format, &int_stuff.name);
  INT_STUFF_LIST
  #undef X

  fclose(fp);
}

Though this is just a quick & dirty example, the real code should continuously check the result of each fscanf call to ensure it isn't EOF.


问:
Microsoft ADAL Signout
I am using Microsoft ADAL library in one of my project. I am using the library method acquireTokenWithResource:clientId:redirectUri:completionBlock: for the sign in purpose, and upon sign out I am just clearing the token cache and all the other cookies.Everything is working as expected.But it seems like token is not getting expired upon sign out, as I've checked by using the same token in Postman.

So how I can inform Microsoft that user has signed out?
Do I need to call any API upon sign out?

答:
The lifetime of the access_token is independent of the login session of a user who grants access to a client.So even user logout ,access token still available in it's lifetime .

AFAIK, azure ad doesn't provide an effective way to revoke the access token, you could config the appropriate lifetime of access token to reduce risks. It has a relatively short validity (default is 1 hour) and as soon as it expires it must be refreshed with a refresh token.

Any feedback about Azure AD , you could post to here.

Title: Microsoft ADAL Signout


问:
WP7 page background image
I plan to use a background image for each of my pages in WP7 and not keep the background transparent.

Any suggestions or issues I need to be aware of?

Also, I noticed a CacheMode property.

Can I use that to improve performance if each of the pages will have the same background stretching across the entire page?

答:
You can create an Image control sized to full the display and lay your other controls in front of it.

If there is a reason you expect this control to be redrawn, then bitmap caching will save you the overhead of rasterising the control repeatedly.

Title: WP7 page background image

ContentLicense: CC BY-SA 2.5


问:
Matching against ID and copying cells of other column as a block to another sheet
I got a Sheet1 looking like this:

And what I want to do is that I copy the amounts where the ID matches the ID I am looking for (here 3) into another Sheet.
So my result in Sheet 2 would look like this:

Any ideas on how to do that? I think Excel VBA is necessary (would be awesome if its not needed though) and I also thought about using SQL expression in VBA.

Thanks

答:
When ids are on B2:B10 and amounts are on D2:D10 and the value to find is on B13, this array formula will get multiple matches:

```<code>{=IFERROR(INDEX(D$3:D$10, SMALL(IF(B$3:B$10=$B$13, ROW(B$3:B$10)-MIN(ROW(B$3:B$10))+1), ROW(E$3:E$10)-2)), "")}
</code>```

Note that the last E$3:E$10 can be an any column. This method is from this article, which explains the formula very kindly.

Also, as I commented, in Google Sheets, you can achieve this by more simple query() function:

```<code>=query($B:$D, "select D where B = "&$B$13)
</code>```

Body:
When ids are on B2:B10 and amounts are on D2:D10 and the value to find is on B13, this array formula will get multiple matches:

{=IFERROR(INDEX(D$3:D$10, SMALL(IF(B$3:B$10=$B$13, ROW(B$3:B$10)-MIN(ROW(B$3:B$10))+1), ROW(E$3:E$10)-2)), "")}

Note that the last E$3:E$10 can be an any column. This method is from this article, which explains the formula very kindly.

Also, as I commented, in Google Sheets, you can achieve this by more simple query() function:

=query($B:$D, "select D where B = "&$B$13)


问:
Moodle installation 2.7? are there any known login vulnerabilities?
Guys I am planning to use moodle 2.7 as the lms in my organization..could you please let me know if there are any know vulnerabilities which could grant a user a higher order privilege?? if yes then how do I make sure I fix it...I have to use moodle 2.7 only..cannot upgrade that</p>

答: Moodle 2.7 is out of support in about 6 weeks.  It's patched (security wise) as of this point in time, but if someone discovers something 3 months from now, it won't be fixed and you'll have to upgrade anyway.  It's a really, really bad idea to use it for a new site when you might as well use 3.1 (LTS) or 3.2


问:
Java: how to compare two strings in order to obtain the portions where they differ?
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

```<code>String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";
</code>```

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

```<code>private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}
</code>```

Calling getAllSubsequences on these two strings:

```<code>String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"
</code>```

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

答:
This is the solution I found, thanks to this link posted by @aUserHimself.

```<code>private static int[][] lcs(String s, String t) {
        int m, n;
        m = s.length();
        n = t.length();
        int[][] table = new int[m+1][n+1];
        for (int i=0; i < m+1; i++)
            for (int j=0; j<n+1; j++)
                table[i][j] = 0;
        for (int i = 1; i < m+1; i++)
            for (int j = 1; j < n+1; j++)
                if (s.charAt(i-1) == t.charAt(j-1))
                        table[i][j] = table[i-1][j-1] + 1;
                else
                    table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
        return table;
    }

private static List<List<String>> getDiffs(int[][] table, String s, String t, int i, int j,
                                           int indexS, int indexT, List<List<String>> diffs){
    List<String> sList, tList;
    sList = diffs.get(0);
    tList = diffs.get(1);
    if (i > 0 && j > 0 && (s.charAt(i-1) == t.charAt(j-1)))
        return getDiffs(table, s, t, i-1, j-1, indexS, indexT, diffs);
    else if (i > 0 || j > 0) {
            if (i > 0 && (j == 0 || table[i][j-1] < table[i-1][j])){
                if (i == indexS)
                    sList.set(sList.size()-1, String.valueOf(s.charAt(i-1)) + sList.get(sList.size() - 1));
                else
                    sList.add(String.valueOf(s.charAt(i-1)));
                diffs.set(0, sList);
                return getDiffs(table, s, t, i-1, j, i-1, indexT, diffs);
            }
            else if (j > 0 && (i == 0 || table[i][j-1] >= table[i-1][j])){
                if (j == indexT)
                    tList.set(tList.size() - 1, String.valueOf(t.charAt(j-1)) + tList.get(tList.size()-1));
                else
                    tList.add(String.valueOf(t.charAt(j-1)));
                diffs.set(1, tList);
                return getDiffs(table, s, t, i, j-1, indexS, j-1, diffs);
            }
        }
    return diffs;
}

private static List<List<String>> getAllDiffs(String s, String t){
    List<List<String>> diffs = new ArrayList<List<String>>();
    List<String> l1, l2;
    l1 = new ArrayList<>();
    l2 = new ArrayList<>();
    diffs.add(l1);
    diffs.add(l2);
    return getDiffs(lcs(s, t), s, t, s.length(), t.length(), 0,  0, diffs);
}
</code>```

I posted because maybe it could be interesting for someone.

Body:
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}

Calling getAllSubsequences on these two strings:

String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

Body:
This is the solution I found, thanks to this link posted by @aUserHimself.

private static int[][] lcs(String s, String t) {
        int m, n;
        m = s.length();
        n = t.length();
        int[][] table = new int[m+1][n+1];
        for (int i=0; i < m+1; i++)
            for (int j=0; j<n+1; j++)
                table[i][j] = 0;
        for (int i = 1; i < m+1; i++)
            for (int j = 1; j < n+1; j++)
                if (s.charAt(i-1) == t.charAt(j-1))
                        table[i][j] = table[i-1][j-1] + 1;
                else
                    table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
        return table;
    }

private static List<List<String>> getDiffs(int[][] table, String s, String t, int i, int j,
                                           int indexS, int indexT, List<List<String>> diffs){
    List<String> sList, tList;
    sList = diffs.get(0);
    tList = diffs.get(1);
    if (i > 0 && j > 0 && (s.charAt(i-1) == t.charAt(j-1)))
        return getDiffs(table, s, t, i-1, j-1, indexS, indexT, diffs);
    else if (i > 0 || j > 0) {
            if (i > 0 && (j == 0 || table[i][j-1] < table[i-1][j])){
                if (i == indexS)
                    sList.set(sList.size()-1, String.valueOf(s.charAt(i-1)) + sList.get(sList.size() - 1));
                else
                    sList.add(String.valueOf(s.charAt(i-1)));
                diffs.set(0, sList);
                return getDiffs(table, s, t, i-1, j, i-1, indexT, diffs);
            }
            else if (j > 0 && (i == 0 || table[i][j-1] >= table[i-1][j])){
                if (j == indexT)
                    tList.set(tList.size() - 1, String.valueOf(t.charAt(j-1)) + tList.get(tList.size()-1));
                else
                    tList.add(String.valueOf(t.charAt(j-1)));
                diffs.set(1, tList);
                return getDiffs(table, s, t, i, j-1, indexS, j-1, diffs);
            }
        }
    return diffs;
}

private static List<List<String>> getAllDiffs(String s, String t){
    List<List<String>> diffs = new ArrayList<List<String>>();
    List<String> l1, l2;
    l1 = new ArrayList<>();
    l2 = new ArrayList<>();
    diffs.add(l1);
    diffs.add(l2);
    return getDiffs(lcs(s, t), s, t, s.length(), t.length(), 0,  0, diffs);
}

I posted because maybe it could be interesting for someone.


问:
" 'NSData' is not convertible to 'Data' " - while building project in swift on xcode Version 8.3 (8E162)
I have been getting this strange error while build in a project, after resent updating of xcode. Any help will be appreciated.

Thankx and Regards
Sanjay.

```<code>if let dataFromFilePathString = NSData(contentsOfFile: DataJsonFilePath) {
            var dictionary:[String:Any]? = [:]
            let data = (data: dataFromFilePathString as Data) // ERROR
</code>```

答:
With the hint from @Martin R , I could correct the code as under.

```<code>        let url = NSURL(string: DataJsonFilePath)
        let dataFromFilePathString = NSData(contentsOf: url! as URL) as Data?
        var dictionary:[String:Any]? = [:]
        if let data = dataFromFilePathString {
</code>```

Thankx..

Body:
I have been getting this strange error while build in a project, after resent updating of xcode. Any help will be appreciated.

Thankx and Regards
Sanjay.

if let dataFromFilePathString = NSData(contentsOfFile: DataJsonFilePath) {
            var dictionary:[String:Any]? = [:]
            let data = (data: dataFromFilePathString as Data) // ERROR

Body:
With the hint from @Martin R , I could correct the code as under.

        let url = NSURL(string: DataJsonFilePath)
        let dataFromFilePathString = NSData(contentsOf: url! as URL) as Data?
        var dictionary:[String:Any]? = [:]
        if let data = dataFromFilePathString {

Thankx..


问:
Find the most frequent items among the arrays - PHP
I have 3 arrays in my code.

```<code>array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];
</code>```

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

```<code>array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];
</code>```

答:
You can use the function array_count_values like this:

```<code> print_r(array_count_values($array));
</code>```

More info in the manual: http://php.net/manual/en/function.array-count-values.php

Body:
I have 3 arrays in my code.

array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];

Body:
You can use the function array_count_values like this:

 print_r(array_count_values($array));

More info in the manual: http://php.net/manual/en/function.array-count-values.php


问:
Catch/guard crash earlier for [SCNSpriteKitEventHandler touchesCancelled:withEvent:]?
Can someone help me identify why my app is crashing or how I can better catch the crash earlier to know what line of code is causing it?

This is the crash log from Crashlytics:

```<code>#0
Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000010

Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x188ecef70 objc_msgSend + 16
1  SceneKit                       0x19a486324 -[SCNSpriteKitEventHandler touchesCancelled:withEvent:] + 528
2  SceneKit                       0x19a5666c8 -[SCNView touchesCancelled:withEvent:] + 60
3  UIKit                          0x1904cde04 __98-[UIApplication _cancelViewProcessingOfTouches:withEvent:sendingTouchesCancelledToViewsOfTouches:]_block_invoke + 552
4  UIKit                          0x1903c4b44 -[UIApplication _cancelTouches:withEvent:includingGestures:notificationBlock:] + 908
5  UIKit                          0x1904cdb84 -[UIApplication _cancelViewProcessingOfTouches:withEvent:sendingTouchesCancelledToViewsOfTouches:] + 172
6  UIKit                          0x1908f76ec _UIGestureEnvironmentCancelTouches + 628
7  UIKit                          0x1908f7464 -[UIGestureEnvironment _cancelTouches:event:] + 52
8  UIKit                          0x19036c438 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 1604
9  UIKit                          0x1908f6680 _UIGestureEnvironmentUpdate + 1100
10 CoreFoundation                 0x18a4320c0 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
11 CoreFoundation                 0x18a42fcf0 __CFRunLoopDoObservers + 372
12 CoreFoundation                 0x18a430180 __CFRunLoopRun + 1024
13 CoreFoundation                 0x18a35e2b8 CFRunLoopRunSpecific + 444
14 GraphicsServices               0x18be12198 GSEventRunModal + 180
15 UIKit                          0x1903a57fc -[UIApplication _run] + 684
16 UIKit                          0x1903a0534 UIApplicationMain + 208
17 activeMaze                     0x1000f4b08 main (ArchiveKeys.swift:9)
18 libdispatch.dylib              0x1893415b8 (Missing)
</code>```

This crash is only happening in distributed apps and I can't replicate when debugging so "Enable Zombie Objects" does not appear to be helping.

Thanks

Greg

答:
The crash was from the way I was removing an SKScene (.overlaySKScene) from an SCNView:

I was setting it to nil, this works 99% of the time and always works on the sim but it is not correct:

```<code>    maze3DScene.overlaySKScene = nil
</code>```

I should have been removing the SKScene from the parent SCNView the same way you remove a SCNNode:

```<code>    maze3DScene.overlaySKScene?.removeFromParent()
</code>```

Hopefully this helps someone else who might make the same mistake.

Body:
Can someone help me identify why my app is crashing or how I can better catch the crash earlier to know what line of code is causing it?

This is the crash log from Crashlytics:

#0
Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000010

Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x188ecef70 objc_msgSend + 16
1  SceneKit                       0x19a486324 -[SCNSpriteKitEventHandler touchesCancelled:withEvent:] + 528
2  SceneKit                       0x19a5666c8 -[SCNView touchesCancelled:withEvent:] + 60
3  UIKit                          0x1904cde04 __98-[UIApplication _cancelViewProcessingOfTouches:withEvent:sendingTouchesCancelledToViewsOfTouches:]_block_invoke + 552
4  UIKit                          0x1903c4b44 -[UIApplication _cancelTouches:withEvent:includingGestures:notificationBlock:] + 908
5  UIKit                          0x1904cdb84 -[UIApplication _cancelViewProcessingOfTouches:withEvent:sendingTouchesCancelledToViewsOfTouches:] + 172
6  UIKit                          0x1908f76ec _UIGestureEnvironmentCancelTouches + 628
7  UIKit                          0x1908f7464 -[UIGestureEnvironment _cancelTouches:event:] + 52
8  UIKit                          0x19036c438 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 1604
9  UIKit                          0x1908f6680 _UIGestureEnvironmentUpdate + 1100
10 CoreFoundation                 0x18a4320c0 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
11 CoreFoundation                 0x18a42fcf0 __CFRunLoopDoObservers + 372
12 CoreFoundation                 0x18a430180 __CFRunLoopRun + 1024
13 CoreFoundation                 0x18a35e2b8 CFRunLoopRunSpecific + 444
14 GraphicsServices               0x18be12198 GSEventRunModal + 180
15 UIKit                          0x1903a57fc -[UIApplication _run] + 684
16 UIKit                          0x1903a0534 UIApplicationMain + 208
17 activeMaze                     0x1000f4b08 main (ArchiveKeys.swift:9)
18 libdispatch.dylib              0x1893415b8 (Missing)

This crash is only happening in distributed apps and I can't replicate when debugging so "Enable Zombie Objects" does not appear to be helping.

Thanks

Greg

Body:
The crash was from the way I was removing an SKScene (.overlaySKScene) from an SCNView:

I was setting it to nil, this works 99% of the time and always works on the sim but it is not correct:

    maze3DScene.overlaySKScene = nil

I should have been removing the SKScene from the parent SCNView the same way you remove a SCNNode:

    maze3DScene.overlaySKScene?.removeFromParent()

Hopefully this helps someone else who might make the same mistake.


问:
How can I adjust the .init event for TinyMCE in EpiServer 8.0?
We need to get to the .init event for TinyMCE in the CMS to be able to adjust some of the settings.  How can we do this?  Here is an example of something we'd like to be able to perform.

```<code>tinymce.init({
    some_property : 'do something'
});
</code>```

This is so we can adjust content filtering in TinyMCE.  My understanding is that this version of EpiServer uses TinyMCE 3.9.3. Thanks for your help.

答:
You could have your custom JavaScript execute whenever the CMS UI is loaded by adding something like the following to your module.config file in the site root:

```<code><?xml version="1.0" encoding="utf-8"?>
<module>
  <clientResources>
    <add name="tinymce.custominit" path="/Path/To/Script/YourScriptFile.js" resourceType="Script" />
  </clientResources>

  <clientModule>
    <moduleDependencies>
      <add dependency="CMS" type="RunAfter" />
    </moduleDependencies>
    <requiredResources>
      <add name="tinymce.custominit" />
    </requiredResources>
  </clientModule>

</module>
</code>```

In YourScriptFile.js you can put whatever script you need to wire up TinyMCE events.

Your other option would be to create a plugin for TinyMCE, to allow your custom initialization code to be enabled/disabled for different Episerver properties.

Body:
We need to get to the .init event for TinyMCE in the CMS to be able to adjust some of the settings.  How can we do this?  Here is an example of something we'd like to be able to perform.

tinymce.init({
    some_property : 'do something'
});

This is so we can adjust content filtering in TinyMCE.  My understanding is that this version of EpiServer uses TinyMCE 3.9.3. Thanks for your help.

Body:
You could have your custom JavaScript execute whenever the CMS UI is loaded by adding something like the following to your module.config file in the site root:

<?xml version="1.0" encoding="utf-8"?>
<module>
  <clientResources>
    <add name="tinymce.custominit" path="/Path/To/Script/YourScriptFile.js" resourceType="Script" />
  </clientResources>

  <clientModule>
    <moduleDependencies>
      <add dependency="CMS" type="RunAfter" />
    </moduleDependencies>
    <requiredResources>
      <add name="tinymce.custominit" />
    </requiredResources>
  </clientModule>

</module>

In YourScriptFile.js you can put whatever script you need to wire up TinyMCE events.

Your other option would be to create a plugin for TinyMCE, to allow your custom initialization code to be enabled/disabled for different Episerver properties.


问:
Rails elastic Beanstalk cannot deploy -
Error says cannot allocate memory but lots of googling has shown native gems are troubling on beanstalk.

```<code> Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

      /opt/rubies/ruby-2.1.10/bin/ruby extconf.rb
  Cannot allocate memory - /opt/rubies/ruby-2.1.10/bin/ruby extconf.rb 2>&1

  Gem files will remain installed in /opt/rubies/ruby-2.1.10/lib/ruby/gems/2.1.0/gems/json-1.8.3 for inspection.
  Results logged to /opt/rubies/ruby-2.1.10/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0-static/json-1.8.3/gem_make.out
</code>```

is there a way to verify beanstalk can install this gem without problems?

答:
Letting the build system package all the dependencies take up more resources than the default EC2 instance can handle.

Increase the size of your EC2 instance/ Swapfile during ElasticBeanstalk deployment to fix this issue.

check my previous response here

Title: Rails elastic Beanstalk cannot deploy -

Body:
Error says cannot allocate memory but lots of googling has shown native gems are troubling on beanstalk.

 Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

      /opt/rubies/ruby-2.1.10/bin/ruby extconf.rb
  Cannot allocate memory - /opt/rubies/ruby-2.1.10/bin/ruby extconf.rb 2>&1

  Gem files will remain installed in /opt/rubies/ruby-2.1.10/lib/ruby/gems/2.1.0/gems/json-1.8.3 for inspection.
  Results logged to /opt/rubies/ruby-2.1.10/lib/ruby/gems/2.1.0/extensions/x86_64-linux/2.1.0-static/json-1.8.3/gem_make.out

is there a way to verify beanstalk can install this gem without problems?


问:
Avoid printing table name in column name while using beeline
While using hive in beeline an using simple select query I would like to return table without table name in column name as a default.

Example

Data

On example of a simple table (TutorialsPoint):

```<code>CREATE TABLE IF NOT EXISTS employee ( eid int, name String,
salary String, destination String)
COMMENT 'Employee details'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE;
</code>```

The SELECT query returns:

```<code>SELECT * FROM employee;
+---------------+----------------+------------------+-----------------------+--+
| employee.eid  | employee.name  | employee.salary  | employee.destination  |
+---------------+----------------+------------------+-----------------------+--+
+---------------+----------------+------------------+-----------------------+--+
</code>```

Desired results

The desired results are achieved with use of AS:

```<code>SELECT eid AS eid, name AS name, salary AS salary,
       destination AS destination FROM employee;

+------+-------+---------+--------------+--+
| eid  | name  | salary  | destination  |
+------+-------+---------+--------------+--+
+------+-------+---------+--------------+--+
</code>```

Problem

I would like to avoid typing AS each time I run select query and return results without table names in column names as default behaviour.

答:
set hive.resultset.use.unique.column.names=false

Configuration Properties

Demo

```<code>hive> create table t (i int,j int,k int);
hive> select * from t;
</code>```

```<code>t.i t.j t.k
</code>```

```<code>hive> set hive.resultset.use.unique.column.names=false;
hive> select * from t;
</code>```

```<code>i   j   k
</code>```

Body:
While using hive in beeline an using simple select query I would like to return table without table name in column name as a default.

Example

Data

On example of a simple table (TutorialsPoint):

CREATE TABLE IF NOT EXISTS employee ( eid int, name String,
salary String, destination String)
COMMENT 'Employee details'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE;

The SELECT query returns:

SELECT * FROM employee;
+---------------+----------------+------------------+-----------------------+--+
| employee.eid  | employee.name  | employee.salary  | employee.destination  |
+---------------+----------------+------------------+-----------------------+--+
+---------------+----------------+------------------+-----------------------+--+

Desired results

The desired results are achieved with use of AS:

SELECT eid AS eid, name AS name, salary AS salary,
       destination AS destination FROM employee;

+------+-------+---------+--------------+--+
| eid  | name  | salary  | destination  |
+------+-------+---------+--------------+--+
+------+-------+---------+--------------+--+

Problem

I would like to avoid typing AS each time I run select query and return results without table names in column names as default behaviour.

Body:
set hive.resultset.use.unique.column.names=false

Configuration Properties

Demo

hive> create table t (i int,j int,k int);
hive> select * from t;

t.i t.j t.k

hive> set hive.resultset.use.unique.column.names=false;
hive> select * from t;

i   j   k


问:
Weird NetworkStream reading issue
Goal: execute Read() method of NetworkStream / SslStream only when it wouldn't block.

Here's what I have and it's a workaround:

```<code>    /// <summary>
    /// Blocks the current thread until this stream has data available for reading or the token is canceled.
    /// </summary>
    /// <param name="token">The object that allows this operation to be canceled.</param>
    /// <returns>True if data is available to be read, false if canceled.</returns>
    public bool WaitDataAvailable(CancellationToken token) {
        lock (Socket) {
            while (!Socket.Poll(PollingInterval, SelectMode.SelectRead) && !token.IsCancellationRequested) ;
            Thread.Sleep(1); // THIS IS A ONE CRAZY HACK HERE!!! Why is it necessary?
            return !token.IsCancellationRequested && Socket.Connected;
        }
    }
</code>```

It took me 2 weeks of banging my head against the wall to figure out the Thread.Sleep(1) workaround. Without this, my communication code just died right after establishing the connection and exchanging a couple of initial messages. I couldn't even figure out why. My code was supposed to just receive the message from one end point, inspect it and pass it to the other end point. Without 1ms wait the client just froze. Then, after I killed my app, the client worked normally as it would received ALL data, no error detected whatsoever.

After a thorough investigation I ruled out all thread synchronization issues in my code. BTW, the code uses blocking operation, only synchronous methods and as few threads as possible. BTW this yielded far better benchmark results than any asynchronous versions, since task creation is quite expensive compared to just directly exchanging messages mostly shorter than 1KB.

So my traffic inspection tool works stable, it's tested and benchmarked, however it drives me crazy I don't understand WHY it works. Without Thread.Sleep(1) it doesn't. All the data is exchanged properly, but the client app freezes until my app is killed.

I also found out ca 5 microseconds of waiting is enough for it to work properly most of the time.

You would probably think why didn't I just check if my code enter the blocking read operation and freezes. Heisenberg. Any debugging like Debug.WriteLine or Console.WriteLine makes it work. Well, sometimes it even work properly when run with Visual Studio Diagnostic Tools, but freezes when run without debugging.

This issue here is very hard to reproduce, because it happens randomly and only when no debugging is involved. It was impossible to reproduce using any test code, only with real world client applications. When I tried to test it connecting .NET based clients I wrote for testing purposes it never froze.

So, why should I wait before reading the stream and what am I waiting for?

BTW, the protocol I transmit uses TLV encoding, so I don't read greedy, I read messages, first the header  telling how long the message will be, then the data, which can be incomplete, if I read less than specified in header, I wait for more data to complete the message. I noticed that the freezes I described happen only if I get incomplete messages - the ones that need to be read in more than one read operation. But then again - if there's a bug in my message handling, why does it work perfectly when 1ms lag is introduced?

I understand this problem is very esoteric and probably described vaguely, some would miss the whole source code. But this is what it is. It is not a simple case and cannot be reduced to one. I already tried to test individual parts of the system and found out that this problem exists only in this particular case: TLV message encoding, reading non-greedy, real live LDAP client reading directory tree. If I change anything, like for example the reads to greedy (always maximum avalilable number of bytes) - the issue won't occur. If I try to read the directory with my own .NET application - the issue won't occur. If I insert any debug instructions before reading the stream - the issue won't occur.

The simplest possible case I tested it is using my code as LDAP proxy and reading directory tree with LdapAdmin. I know it's not this particular client fault, because LDP freezes too, but not always.

答: I hate to say it, but waiting (blocking) on a socket to become available is a terrible terrible idea. Did you know that you can do a zero-length async read, and it will invoke the callback for you when data is available, without you having to give it a buffer in advance? (or at least you can share and re-use a static readonly byte[] ZeroLengthBuffer = new byte[0];) Then when data is available, you get a sensible buffer and do some actual reading (sync or async, up to you) - perhaps keeping an eye on .Available on the socket. This zero-length read trick works for either of the Socket async read methods, IIRC - so Socket.BeginReceive or Socket.ReceiveAsync (which despite the name, is not async in the async/await sense, and may complete synchronously).

Title: Weird NetworkStream reading issue

Body:
Goal: execute Read() method of NetworkStream / SslStream only when it wouldn't block.

Here's what I have and it's a workaround:

    ///
    /// Blocks the current thread until this stream has data available for reading or the token is canceled.
    ///
    /// <param name="token">The object that allows this operation to be canceled.</param>
    /// <returns>True if data is available to be read, false if canceled.</returns>
    public bool WaitDataAvailable(CancellationToken token) {
        lock (Socket) {
            while (!Socket.Poll(PollingInterval, SelectMode.SelectRead) && !token.IsCancellationRequested) ;
            Thread.Sleep(1); // THIS IS A ONE CRAZY HACK HERE!!! Why is it necessary?
            return !token.IsCancellationRequested && Socket.Connected;
        }
    }

It took me 2 weeks of banging my head against the wall to figure out the Thread.Sleep(1) workaround. Without this, my communication code just died right after establishing the connection and exchanging a couple of initial messages. I couldn't even figure out why. My code was supposed to just receive the message from one end point, inspect it and pass it to the other end point. Without 1ms wait the client just froze. Then, after I killed my app, the client worked normally as it would received ALL data, no error detected whatsoever.

After a thorough investigation I ruled out all thread synchronization issues in my code. BTW, the code uses blocking operation, only synchronous methods and as few threads as possible. BTW this yielded far better benchmark results than any asynchronous versions, since task creation is quite expensive compared to just directly exchanging messages mostly shorter than 1KB.

So my traffic inspection tool works stable, it's tested and benchmarked, however it drives me crazy I don't understand WHY it works. Without Thread.Sleep(1) it doesn't. All the data is exchanged properly, but the client app freezes until my app is killed.

I also found out ca 5 microseconds of waiting is enough for it to work properly most of the time.

You would probably think why didn't I just check if my code enter the blocking read operation and freezes. Heisenberg. Any debugging like Debug.WriteLine or Console.WriteLine makes it work. Well, sometimes it even work properly when run with Visual Studio Diagnostic Tools, but freezes when run without debugging.

This issue here is very hard to reproduce, because it happens randomly and only when no debugging is involved. It was impossible to reproduce using any test code, only with real world client applications. When I tried to test it connecting .NET based clients I wrote for testing purposes it never froze.

So, why should I wait before reading the stream and what am I waiting for?

BTW, the protocol I transmit uses TLV encoding, so I don't read greedy, I read messages, first the header  telling how long the message will be, then the data, which can be incomplete, if I read less than specified in header, I wait for more data to complete the message. I noticed that the freezes I described happen only if I get incomplete messages - the ones that need to be read in more than one read operation. But then again - if there's a bug in my message handling, why does it work perfectly when 1ms lag is introduced?

I understand this problem is very esoteric and probably described vaguely, some would miss the whole source code. But this is what it is. It is not a simple case and cannot be reduced to one. I already tried to test individual parts of the system and found out that this problem exists only in this particular case: TLV message encoding, reading non-greedy, real live LDAP client reading directory tree. If I change anything, like for example the reads to greedy (always maximum avalilable number of bytes) - the issue won't occur. If I try to read the directory with my own .NET application - the issue won't occur. If I insert any debug instructions before reading the stream - the issue won't occur.

The simplest possible case I tested it is using my code as LDAP proxy and reading directory tree with LdapAdmin. I know it's not this particular client fault, because LDP freezes too, but not always.


问:
HTML Send selected option to PHP via Ajax on same page
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

```<code><div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <tr>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </tr>
                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "<tr>";
                            echo "<th>" . $i . "</th>";
                            echo "<th>" . $row['userName'] . "</th>";
                            echo "<th>" . $row['score'] . "</th>";
                            echo "</tr>";
                        }
                    ?>
                </table>
            </div>
        </div>
</code>```

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

答:
you can make another page by the name of highscores.php and get all  the code there.then make a call on page load to get the scores dynamically in this div.</p>

```<code>  $(document.ready(function(){
//on page load,for the first time.
$('#highscore').load('http://site_url/highscores.php');
//on selectbox change
$('#selectbox').change(function(){
 $.post("highscores.php", {sort: val}, function(data){
    //perform sorting and return the data div.
 $('#highscore').html(data);
});
 })
});
//// homepage section where the scores load,add a div by the id
<div id="highscore"></div>

//////// highscore page
<div class="third third-center">
        <h2>Highscores</h2>
        <div class="sortby">
            <form id="" method="post" action="home.php">
                <select id="selectForm" name="sort">
                  <option value="score ASC">Score Ascending</option>
                  <option value="score DESC">Score Descending</option>
                  <option value="userName ASC">Name Ascending</option>
                  <option value="userName DESC">Name Descending</option>
                </select>
            </form>
        </div>
        <div class="inner">
            <table>
                <tr>
                    <th style="font-size: 20px">Position</th>
                    <th style="font-size: 20px">Name</th>
                    <th style="font-size: 20px">Score</th>
                </tr>
                <?php
                    $i = 0;

                    $choice = "score ASC";

                    $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                    while($row = mysqli_fetch_array($search)){
                        $i++;
                        echo "<tr>";
                        echo "<th>" . $i . "</th>";
                        echo "<th>" . $row['userName'] . "</th>";
                        echo "<th>" . $row['score'] . "</th>";
                        echo "</tr>";
                    }
                ?>
            </table>
        </div>
    </div>
</code>```

Body:
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

Highscores

                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>

                        Position
                        Name
                        Score

                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "
";
                            echo "" . $i . "	";
                            echo "" . $row['userName'] . "	";
                            echo "" . $row['score'] . "	";
                            echo "
";
                        }
                    ?>

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

Body:
you can make another page by the name of highscores.php and get all  the code there.then make a call on page load to get the scores dynamically in this div.

  $(document.ready(function(){
//on page load,for the first time.
$('#highscore').load('http://site_url/highscores.php');
//on selectbox change
$('#selectbox').change(function(){
 $.post("highscores.php", {sort: val}, function(data){
    //perform sorting and return the data div.
 $('#highscore').html(data);
});
 })
});
//// homepage section where the scores load,add a div by the id
<div id="highscore"></div>

//////// highscore page
<div class="third third-center">
        <h2>Highscores</h2>
        <div class="sortby">
            <form id="" method="post" action="home.php">
                <select id="selectForm" name="sort">
                  <option value="score ASC">Score Ascending</option>
                  <option value="score DESC">Score Descending</option>
                  <option value="userName ASC">Name Ascending</option>
                  <option value="userName DESC">Name Descending</option>
                </select>
            </form>
        </div>
        <div class="inner">
            <table>
                <tr>
                    <th style="font-size: 20px">Position</th>
                    <th style="font-size: 20px">Name</th>
                    <th style="font-size: 20px">Score</th>
                </tr>
                <?php
                    $i = 0;

                    $choice = "score ASC";

                    $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                    while($row = mysqli_fetch_array($search)){
                        $i++;
                        echo "<tr>";
                        echo "<th>" . $i . "</th>";
                        echo "<th>" . $row['userName'] . "</th>";
                        echo "<th>" . $row['score'] . "</th>";
                        echo "</tr>";
                    }
                ?>
            </table>
        </div>
    </div>


问:
PHP: SoapClient Response code from HTTP headers
I'm trying to extract the Soap response's HTTP status code.
So for instance i have :

```<code>$client = new SoapClient($wsdl);
$client->__setSoapHeaders(
    new SoapHeader(
        $nameSpace,
        'Security',
        $secHeaderValue,
        true
    )
);

// The actual call
$response = $client->Complete($paramswebservice)
</code>```

So now i'm getting the response headers, this way :

```<code>$responseHeaders = $client->__getLastResponseHeaders();
var_dump($responseHeaders);
</code>```

This is the result of the vardump : a string formatted this way (web browser - page source code)

What i am doing right now to extract the http status code '200' :

```<code>/**
 * Returns the HTTP Status code of $response
 * @param string $response
 * @return string
 */
function extract_response_http_code($response) {
    $tmp = explode('\n', $response);
    $array = explode(' ', $tmp[0]);

    return $array[1];
}
</code>```

I really don't like this solution. I would like a more robust / consistent one. Any suggestions ?

EDIT 1

As asked in the comments :

```
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Length: 1315
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Thu, 30 Mar 2017 08:52:15 GMT ```

答:
PHP code demo

```<code><?php
$result="HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Length: 1315
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Thu, 30 Mar 2017 08:52:15 GMT";
preg_match("/HTTP\/\d\.\d\s*\K[\d]+/", $result,$matches);
print_r($matches);
</code>```

Output:

```<code>Array
(
    [0] => 200
)
</code>```

Body:
I'm trying to extract the Soap response's HTTP status code.
So for instance i have :

$client = new SoapClient($wsdl);
$client->__setSoapHeaders(
    new SoapHeader(
        $nameSpace,
        'Security',
        $secHeaderValue,
        true
    )
);

// The actual call
$response = $client->Complete($paramswebservice)

So now i'm getting the response headers, this way :

$responseHeaders = $client->__getLastResponseHeaders();
var_dump($responseHeaders);

This is the result of the vardump : a string formatted this way (web browser - page source code)

What i am doing right now to extract the http status code '200' :

/**
 * Returns the HTTP Status code of $response
 * @param string $response
 * @return string
 */
function extract_response_http_code($response) {
    $tmp = explode('\n', $response);
    $array = explode(' ', $tmp[0]);

    return $array[1];
}

I really don't like this solution. I would like a more robust / consistent one. Any suggestions ?

EDIT 1

As asked in the comments :

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Length: 1315
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Thu, 30 Mar 2017 08:52:15 GMT

Body:
PHP code demo

<?php
$result="HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Length: 1315
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Thu, 30 Mar 2017 08:52:15 GMT";
preg_match("/HTTP\/\d\.\d\s*\K[\d]+/", $result,$matches);
print_r($matches);

Output:

Array
(
    [0] => 200
)