问:
The resize function loads the page
For the side menu there is a recalculation for the height: adaptive, for the tablet and for the desktop. It seems to be working more and less, but when I started testing on real devices, I noticed that everything is working too slowly because of the function of what is written in the function of resize. Do not tell me how refactor the code in a normal way, so that the speed of work on devices is faster? Thank you!

https://codepen.io/malinosky/pen/JOVdOG

```<code> //расчет высоты body
var calcHeightFilter = function calcHeightFilter() {
    var bodyHeight = $(document).outerHeight(true);
    var asideHeight = $('.section--aside').height();

    if (($(document).width()) < 768) {
        if ($('.section--aside').hasClass('open-aside')) {
            $('.js-anchor-top').css("display", "none");
            if (bodyHeight > asideHeight) {
                $('body').css("overflow", "hidden");
                $('body').height(asideHeight + 169); // Значение 169 - это хеадер + футер
            }
        }
    }

    if (($(document).width()) >= 768 && ($(document).width()) <= 1023 ) {
        var tabletFilterHeight = $('.wrap-main').height();
        $(".section--aside").height(tabletFilterHeight);
        $(".section--aside").css("overflow-y", "auto");

        $(".section--aside").css("height", function(){
            return $('.wrap-main').height() + 70;
        });

        var newwTabletFilterHeight = $('.section--content').height() + 112 + $('.footer').height(); // 112 - это шапка
            var asideNewwHeightH = $(".section--aside").height(newwTabletFilterHeight - 70);
            $('body').height(newwTabletFilterHeight);

        $(window).scroll(function() {
            if ($(window).scrollTop() >= $(document).height() - $(window).height()) {
                calcHeightFilter();
                $('.button_more').css('box-shadow', '0px 0px 13px 0px rgba(0, 0, 0, 0.2)');
            } else {
                $('.button_more').css('box-shadow', 'none');
            }
        });
    }

    if (($(document).width()) > 1023) {
        $('body').css("overflow-y", "visible");
        $('section--aside').css("overflow-y", "visible");
    }

        $(window).on('resize', function(){

            if (($(document).width()) < 768) {
                if ($('.section--aside').hasClass('open-aside')) {
                    $('.js-anchor-top').css("display", "none");
                        $('body').css("overflow", "hidden");
                        $('.section--aside').css("overflow", "hidden");
                        $('.section--aside').css("height", "auto");
                        $("body").css("height", function(){
                            return $('.section--aside').height() + 169;
                        });
                        $('.section--aside__close').css("display", "block");
                        $('.section-empty').remove();
                }
            }

            if (($(document).width()) >= 768 && ($(document).width()) <= 1023 ) {
                var newTabletFilterHeight = $('.section--content').height() + 112 + $('.footer').height();
                var asideNewHeightH = $(".section--aside").height(newTabletFilterHeight);
                $('body').height(newTabletFilterHeight);
                $(".section--aside").css("overflow-y", "auto");
                if ($('.section--aside').hasClass('open-aside')) {
                    $('.section--aside__close').css("display", "block");
                    $(".wrap-main").append('<div class="section-empty">');
                    $('body').height(newTabletFilterHeight + $('.section-empty').height());
                }
            }

            if (($(document).width()) > 1023) {
                $('body').css("height", "inherit");
                $('.section-empty').remove();
                $(".footer").css("margin-bottom", "0");
                $('.section--aside__close').css("display", "none");
                $('body').css("overflow", "visible");
                $('.section--aside').css("overflow", "visible");
                $('.section--aside').css("height", "auto");
            }
        });

}

// Открытие/закрытие фильтра в каталоге
$(document).on('click', '.js-filter_show', function(){
    $(".section--aside").addClass("open-aside");
    $(".section--catalog").addClass("overlay-section");
    $('.section--aside__close').css("display", "block");

    if (($(document).width()) >= 768 && ($(document).width()) <= 1023 ) {
        $(".wrap-main").append('<div class="section-empty">');
    }

    calcHeightFilter();
});

$(document).on('click', '.section--aside__close', function(){
    $(".section--aside").removeClass("open-aside");
    $('.section--aside__close').css("display", "none");
    $(".section--catalog").removeClass("overlay-section");
    $('.section-empty').remove();
    $('body').css("overflow", "visible");
    $('body').css("height", "100%");
});
</code>```

答:
The $(window).on('resize') callback can be called many times in quick succession. Instead of recalculating everything immediately, I would suggest debouncing the calculations:

```<code>$(window).on('resize', _debounce);

// Time to wait before calling resize in milliseconds
var DEBOUNCE_DELAY = 250;

var timeout = null;
function _debounce() {
    timeout = setTimeout(function() {
        timeout = null;
        resize();
    }, DEBOUNCE_DELAY);
}

function resize() {
    // perform all calculations here.
}
</code>```

How this works is the _debounce function sets up a timer which waits DEBOUNCE_DELAY milliseconds before calling the resize function. If _debounce is called and there is an existing timer, the timer gets cancelled so that _resize is only called once, after the last call to _debounce

Title: The resize function loads the page

Body:
For the side menu there is a recalculation for the height: adaptive, for the tablet and for the desktop. It seems to be working more and less, but when I started testing on real devices, I noticed that everything is working too slowly because of the function of what is written in the function of resize. Do not tell me how refactor the code in a normal way, so that the speed of work on devices is faster? Thank you!

https://codepen.io/malinosky/pen/JOVdOG

 //расчет высоты body
var calcHeightFilter = function calcHeightFilter() {
    var bodyHeight = $(document).outerHeight(true);
    var asideHeight = $('.section--aside').height();

    if (($(document).width()) < 768) {
        if ($('.section--aside').hasClass('open-aside')) {
            $('.js-anchor-top').css("display", "none");
            if (bodyHeight > asideHeight) {
                $('body').css("overflow", "hidden");
                $('body').height(asideHeight + 169); // Значение 169 - это хеадер + футер
            }
        }
    }

    if (($(document).width()) >= 768 && ($(document).width()) <= 1023 ) {
        var tabletFilterHeight = $('.wrap-main').height();
        $(".section--aside").height(tabletFilterHeight);
        $(".section--aside").css("overflow-y", "auto");

        $(".section--aside").css("height", function(){
            return $('.wrap-main').height() + 70;
        });

        var newwTabletFilterHeight = $('.section--content').height() + 112 + $('.footer').height(); // 112 - это шапка
            var asideNewwHeightH = $(".section--aside").height(newwTabletFilterHeight - 70);
            $('body').height(newwTabletFilterHeight);

        $(window).scroll(function() {
            if ($(window).scrollTop() >= $(document).height() - $(window).height()) {
                calcHeightFilter();
                $('.button_more').css('box-shadow', '0px 0px 13px 0px rgba(0, 0, 0, 0.2)');
            } else {
                $('.button_more').css('box-shadow', 'none');
            }
        });
    }

    if (($(document).width()) > 1023) {
        $('body').css("overflow-y", "visible");
        $('section--aside').css("overflow-y", "visible");
    }

        $(window).on('resize', function(){

            if (($(document).width()) < 768) {
                if ($('.section--aside').hasClass('open-aside')) {
                    $('.js-anchor-top').css("display", "none");
                        $('body').css("overflow", "hidden");
                        $('.section--aside').css("overflow", "hidden");
                        $('.section--aside').css("height", "auto");
                        $("body").css("height", function(){
                            return $('.section--aside').height() + 169;
                        });
                        $('.section--aside__close').css("display", "block");
                        $('.section-empty').remove();
                }
            }

            if (($(document).width()) >= 768 && ($(document).width()) <= 1023 ) {
                var newTabletFilterHeight = $('.section--content').height() + 112 + $('.footer').height();
                var asideNewHeightH = $(".section--aside").height(newTabletFilterHeight);
                $('body').height(newTabletFilterHeight);
                $(".section--aside").css("overflow-y", "auto");
                if ($('.section--aside').hasClass('open-aside')) {
                    $('.section--aside__close').css("display", "block");
                    $(".wrap-main").append('
');
                    $('body').height(newTabletFilterHeight + $('.section-empty').height());
                }
            }

            if (($(document).width()) > 1023) {
                $('body').css("height", "inherit");
                $('.section-empty').remove();
                $(".footer").css("margin-bottom", "0");
                $('.section--aside__close').css("display", "none");
                $('body').css("overflow", "visible");
                $('.section--aside').css("overflow", "visible");
                $('.section--aside').css("height", "auto");
            }
        });

}

// Открытие/закрытие фильтра в каталоге
$(document).on('click', '.js-filter_show', function(){
    $(".section--aside").addClass("open-aside");
    $(".section--catalog").addClass("overlay-section");
    $('.section--aside__close').css("display", "block");

    if (($(document).width()) >= 768 && ($(document).width()) <= 1023 ) {
        $(".wrap-main").append('
');
    }

    calcHeightFilter();
});

$(document).on('click', '.section--aside__close', function(){
    $(".section--aside").removeClass("open-aside");
    $('.section--aside__close').css("display", "none");
    $(".section--catalog").removeClass("overlay-section");
    $('.section-empty').remove();
    $('body').css("overflow", "visible");
    $('body').css("height", "100%");
});

Body:
The $(window).on('resize') callback can be called many times in quick succession. Instead of recalculating everything immediately, I would suggest debouncing the calculations:

$(window).on('resize', _debounce);

// Time to wait before calling resize in milliseconds
var DEBOUNCE_DELAY = 250;

var timeout = null;
function _debounce() {
    timeout = setTimeout(function() {
        timeout = null;
        resize();
    }, DEBOUNCE_DELAY);
}

function resize() {
    // perform all calculations here.
}

How this works is the _debounce function sets up a timer which waits DEBOUNCE_DELAY milliseconds before calling the resize function. If _debounce is called and there is an existing timer, the timer gets cancelled so that _resize is only called once, after the last call to _debounce


来源: stackexchange

问:
Displaying a Json on a CollectionViewCell inside a TableViewCell. Swift 3
I'm trying to parse a Json and display it as a collection view item which is inside a table view cell . So the hierarchy  would be like:

MainTableVIew -> TableViewCell -> CollectionView -> CollectionViewCell

So I have the json

```<code>"payments":[{
    "type":"card",
    "title":"Card"
}, {
    "type":"sms",
    "title":"SMS",
    "max_amount":24
},{
    "type":"account",
    "title":"Account",
    "disabled":true,
    "max_amount":-1
}]
</code>```

which i parsed it.
The next thing which i did is in

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "NewPaymentCell") as! NewPaymentTableViewCell
            cell.package?.title = payments[indexPath.row].title
            return cell}
</code>```

which package is

```<code>var package : PromoPayment? {
        didSet {
            collectionView.reloadData()
        }
    }
</code>```

and PromoPayment the class where i get the dictionary.

In the NewPaymentCollectionView class i also populate the cell like :

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewPaymentCollectionCell", for: indexPath) as! NewPaymentCollectionViewCell
        cell.paymentIcon.image = UIImage(named: iconImage[indexPath.row])
        cell.kidPayment?.title = (package?.title)!
        return cell
    }
</code>```

where kidPayment is

```<code>var kidPayment : PromoPayment? {
    didSet{
        namePaymentTypeLabel.text = kidPayment?.title
        }
    }
</code>```

and it s modeled in class NewPaymentCollectionViewCell: UICollectionViewCell

When i debug it returns me nil..

Appreciate your help.

答:
You can try this one, design a custom cell of tableview and add colletion view inside it. Create an outlet for collection view and try reloading the collection view as per given code.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "NewPaymentCell") as! NewPaymentTableViewCell
            cell.package?.title = payments[indexPath.row].title
            **cell.collectionView.reloadData()**
            return cell
}
</code>```

Instead of using a didset method use this.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to parse a Json and display it as a collection view item which is inside a table view cell . So the hierarchy  would be like:

MainTableVIew -> TableViewCell -> CollectionView -> CollectionViewCell

So I have the json

"payments":[{
    "type":"card",
    "title":"Card"
}, {
    "type":"sms",
    "title":"SMS",
    "max_amount":24
},{
    "type":"account",
    "title":"Account",
    "disabled":true,
    "max_amount":-1
}]

which i parsed it.
The next thing which i did is in

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "NewPaymentCell") as! NewPaymentTableViewCell
            cell.package?.title = payments[indexPath.row].title
            return cell}

which package is

var package : PromoPayment? {
        didSet {
            collectionView.reloadData()
        }
    }

and PromoPayment the class where i get the dictionary.

In the NewPaymentCollectionView class i also populate the cell like :

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewPaymentCollectionCell", for: indexPath) as! NewPaymentCollectionViewCell
        cell.paymentIcon.image = UIImage(named: iconImage[indexPath.row])
        cell.kidPayment?.title = (package?.title)!
        return cell
    }

where kidPayment is

var kidPayment : PromoPayment? {
    didSet{
        namePaymentTypeLabel.text = kidPayment?.title
        }
    }

and it s modeled in class NewPaymentCollectionViewCell: UICollectionViewCell

When i debug it returns me nil..

Appreciate your help.

Body:
You can try this one, design a custom cell of tableview and add colletion view inside it. Create an outlet for collection view and try reloading the collection view as per given code.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "NewPaymentCell") as! NewPaymentTableViewCell
            cell.package?.title = payments[indexPath.row].title
            **cell.collectionView.reloadData()**
            return cell
}

Instead of using a didset method use this.


问:
Transposing query results
I have select statement that returns two values (one column, two rows). I'd like to change them so that I have two columns and one row. I know there is something like pivot but I'm not sure how to used that, as it requires aggregation values and I do not aggregate here anything. What would be the most performant way to accomplish this task? Thank you!</p>

答:
A simple way is to use min() and max():

```<code>select min(col), max(col)
from (<your query here>) t;
</code>```

Title: Transposing query results

Body:
A simple way is to use min() and max():

select min(col), max(col)
from (<your query here>) t;


问:
When to use "return result" and when to use "self.result"
Is there any good rules or practices for when you should return something from the function and when you should set the result as a variable(self.result)?

Say you have class where the main objective is to do some calculations, maybe something like:

```<code>class Calculations:
    def __init__(var1, var2, var3):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3

    def calc1(self):
        self.result1 = self.var1 + self.var2

    def calc2(self):
        self.result2 = self.var2 + self.var3

    def final_calc(self):
        self.calc1()
        self.calc2()
        return self.result1 / self.result2

if __name__ == '__main__':
    calcObject = Calculations(10, 15, 20)
    result = calcObject.final_calc()
</code>```

Is this considered very bad practice? I agree that it don't make much sense in this specific example, but as the calculations grows more complex, I use the results and variables from one functions in several other functions – and I find myself passing lots variables back and forth between functions.

答:
To decide whether a method should store data in properties and/or return it, use some heuristics:

Is the method supposed to modify the object's state? Properties are not merely things to store calculation results on to pass them between methods; any value stored in a property contributes to the state of the object. Does it make sense for the method to change that state?

Is the method expected to produce a value? A method like set_foo(...) is probably not supposed to produce any new values, a method like get_foo() or calculate() probably is.

Do you have logical dependencies between methods? For your final_calc, you must call calc1 and calc2 first before result1 and result2 are available. There is no obvious connection between these method calls and those properties. That would all be a lot more explicit and less error prone like this:

```<code>def final_calc(self):
    result1 = self.calc1()
    result2 = self.calc2()
    return result1 / result2
</code>```

You're even freeing yourself up to write return self.calc1() / self.calc2().

All the properties which will ever exist should be declared in __init__, methods should merely change the values of those properties. Your object shouldn't suddenly sprout new properties after calling a method.

Body:
Is there any good rules or practices for when you should return something from the function and when you should set the result as a variable(self.result)?

Say you have class where the main objective is to do some calculations, maybe something like:

class Calculations:
    def __init__(var1, var2, var3):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3

    def calc1(self):
        self.result1 = self.var1 + self.var2

    def calc2(self):
        self.result2 = self.var2 + self.var3

    def final_calc(self):
        self.calc1()
        self.calc2()
        return self.result1 / self.result2

if __name__ == '__main__':
    calcObject = Calculations(10, 15, 20)
    result = calcObject.final_calc()

Is this considered very bad practice? I agree that it don't make much sense in this specific example, but as the calculations grows more complex, I use the results and variables from one functions in several other functions – and I find myself passing lots variables back and forth between functions.

Body:
To decide whether a method should store data in properties and/or return it, use some heuristics:

Is the method supposed to modify the object's state? Properties are not merely things to store calculation results on to pass them between methods; any value stored in a property contributes to the state of the object. Does it make sense for the method to change that state?

Is the method expected to produce a value? A method like set_foo(...) is probably not supposed to produce any new values, a method like get_foo() or calculate() probably is.

Do you have logical dependencies between methods? For your final_calc, you must call calc1 and calc2 first before result1 and result2 are available. There is no obvious connection between these method calls and those properties. That would all be a lot more explicit and less error prone like this:

def final_calc(self):
    result1 = self.calc1()
    result2 = self.calc2()
    return result1 / result2

You're even freeing yourself up to write return self.calc1() / self.calc2().

All the properties which will ever exist should be declared in __init__, methods should merely change the values of those properties. Your object shouldn't suddenly sprout new properties after calling a method.


问:
Does each pub/sub topics require its own connection GCP?
We start using pub/sub for tracking data. On pub sub we have 600+ topics.

Our developer said that each topics require dedicated connection to GCP thus application require additional file descriptors equal to number of topics. Is this correct? I cannot find any pub/sub documentation mentioning this. Thank you.

答: It depends on what you mean by "connection to GCP." If you are using the Google Cloud Pub/Sub client libraries, then you will need to instantiate a publisher client for each topic. </p>


问:
(movieclip1).gotoAndPlay from inside another movieclip(movieclip2) not working
I have a movieclip on stage that is a black screen and nothing else. Just a black rectangle with frames that have frame instance names. The overall instance name of this black screen is simply "BlackScreen".

What I am trying to do is do BlackScreen.gotoAndPlay("BSL") from another movieclip that's on the same stage in a different layer of the stage. The "BSL" is one of the frame instance names.

This seems like it would work, as all I am trying to do is play some frames. But whenever I test the project, it gives me this for all the instances I use BlackScreen.gotoAndPlay("BSL"):

Symbol 'Darkened Code', Layer 'Head', Frame 1119, Line 1, Column 1    1120: Access of undefined property BlackScreen.

What I'm assuming is that a movieclip can't detect other movieclips? Or am I just doing something wrong?

答:
You need to access BlackScreen through _root (as2) or root (as3). When you write code on the timeline of a movieclip, the "scope" of the code is that of the movieclip and not the main stage. By trying to access BlackScreen here, it will look for BlackScreen inside the Darkened Code movieclip, you need to tell it explicitly to look on the main stage using root

eg.

```<code>root.BlackScreen.gotoAndPlay("BSL")
</code>```

Body:
You need to access BlackScreen through _root (as2) or root (as3). When you write code on the timeline of a movieclip, the "scope" of the code is that of the movieclip and not the main stage. By trying to access BlackScreen here, it will look for BlackScreen inside the Darkened Code movieclip, you need to tell it explicitly to look on the main stage using root

eg.

root.BlackScreen.gotoAndPlay("BSL")


问:
find the min and max values of nested list by index of element in nested list
I have a nested list like the following:

```<code>x = [[1,  5, 3,  4],
     [5, 10, 7,  8],
     [9,  9, 2, 12]]
</code>```

I need to find to find the min and max values of the nested list transposed such that the result for min is:

```<code>1, 5, 2, 4  # 1 is the min of first column (1, 5, 9) a.s.o
</code>```

and the max should be:

```<code>9, 10, 7, 12
</code>```

I tried to convert it into a dataframe first and then doing max and min on the different axis but all doesn't come up as the result I want.

Body:
I have a nested list like the following:

x = [[1,  5, 3,  4],
     [5, 10, 7,  8],
     [9,  9, 2, 12]]

I need to find to find the min and max values of the nested list transposed such that the result for min is:

1, 5, 2, 4  # 1 is the min of first column (1, 5, 9) a.s.o

and the max should be:

9, 10, 7, 12

I tried to convert it into a dataframe first and then doing max and min on the different axis but all doesn't come up as the result I want.

Body:
Simply with numpy module:

import numpy as np

x = np.array([[1,  5, 3,  4], [5, 10, 7,  8], [9,  9, 2, 12]])
print(np.min(x, 0))    # [1 5 2 4]
print(np.max(x, 0))    # [ 9 10  7 12]


问:
MEDIA_INFO_BUFFERING_START not found in xamarin android?
I am currently working with Mediaplayer in Xamarin android. There are MediaPlayer.MEDIA_INFO_BUFFERING_START and MediaPlayer.MEDIA_INFO_BUFFERING_END in native android(java). But I cannot find these MEDIA_INFO_BUFFERING_START and MEDIA_INFO_BUFFERING_START for Xamarin. My code in android studio:

```<code>  mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            switch (what) {
                case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                    AppLog.showLogE(TAG,"Buffering...");
                    progressView.setVisibility(View.VISIBLE);
                    break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                    AppLog.showLogE(TAG,"Buffering End");
                    progressView.setVisibility(View.GONE);
                    break;
            }
            return false;
        }
    });
</code>```

In Xamarin Android I am stuck here:

```<code>    public bool OnInfo(MediaPlayer mp, [GeneratedEnum] MediaInfo what, int extra)
    {
        switch (what)
        {
            case MediaPlayer. //not found

                    break;
        }
        return false;
    }
</code>```

答:
Well, this is how you do it on xamarin android,
I hope this is what you are looking for  :

```<code> switch (what) {
            case Android.Media.MediaInfo.BufferingStart:
                //AppLog.showLogE(TAG,"Buffering...");
                progressView.Visibility=(ViewStates.Visible);
                break;
            case Android.Media.MediaInfo.BufferingEnd:
                //AppLog.showLogE(TAG,"Buffering End");
                progressView.Visibility=(ViewStates.Gone);
                break;
        }
</code>```

Goodluck!
Happy coding.

Body:
I am currently working with Mediaplayer in Xamarin android. There are MediaPlayer.MEDIA_INFO_BUFFERING_START and MediaPlayer.MEDIA_INFO_BUFFERING_END in native android(java). But I cannot find these MEDIA_INFO_BUFFERING_START and MEDIA_INFO_BUFFERING_START for Xamarin. My code in android studio:

  mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            switch (what) {
                case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                    AppLog.showLogE(TAG,"Buffering...");
                    progressView.setVisibility(View.VISIBLE);
                    break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                    AppLog.showLogE(TAG,"Buffering End");
                    progressView.setVisibility(View.GONE);
                    break;
            }
            return false;
        }
    });

In Xamarin Android I am stuck here:

    public bool OnInfo(MediaPlayer mp, [GeneratedEnum] MediaInfo what, int extra)
    {
        switch (what)
        {
            case MediaPlayer. //not found

                    break;
        }
        return false;
    }

Body:
Well, this is how you do it on xamarin android,
I hope this is what you are looking for  :

 switch (what) {
            case Android.Media.MediaInfo.BufferingStart:
                //AppLog.showLogE(TAG,"Buffering...");
                progressView.Visibility=(ViewStates.Visible);
                break;
            case Android.Media.MediaInfo.BufferingEnd:
                //AppLog.showLogE(TAG,"Buffering End");
                progressView.Visibility=(ViewStates.Gone);
                break;
        }

Goodluck!
Happy coding.


问:
Removing substring between two words including the words, which are repeating in a string
I have to remove substrings between two words from a string which are repeating in the string.

For example, for the input:

People consider that cats and dogs are good friends but the fact is that dogs have got a problem with cats. Dogs always chase cats and bark at them.

I want the output:

People consider that are good friends but the fact is that.and bark at them.

Here "cats" and "dogs" are repeating and I have to remove all the substring between "cats" and "dogs" including "cats" and "dogs".

答:
You can try this:</p>

```<code>private static String getWithoutRepetitions(String sentence){
    String result = sentence;
    String[] allWords = (sentence.replaceAll(",", " ").replaceAll("\\.", " ")).split(" ");
    HashMap<String, Integer> pairs = new HashMap<>();
    for(String s : allWords){
        if(pairs.get(s) == null && s != null){
            pairs.put(s, 1);
        }else{
            pairs.put(s, pairs.get(s)+1);
        }
    }
    for (Entry<String, Integer> entry : pairs.entrySet()) {
        String key = entry.getKey();
        Integer value = (Integer) entry.getValue();
        if(value > 1){
            result = result.replaceAll(key, "");
        }
    }
    result = result.trim().replaceAll(" +", " ");
    return result;
}
</code>```

Body:
You can try this:

private static String getWithoutRepetitions(String sentence){
    String result = sentence;
    String[] allWords = (sentence.replaceAll(",", " ").replaceAll("\\.", " ")).split(" ");
    HashMap<String, Integer> pairs = new HashMap<>();
    for(String s : allWords){
        if(pairs.get(s) == null && s != null){
            pairs.put(s, 1);
        }else{
            pairs.put(s, pairs.get(s)+1);
        }
    }
    for (Entry<String, Integer> entry : pairs.entrySet()) {
        String key = entry.getKey();
        Integer value = (Integer) entry.getValue();
        if(value > 1){
            result = result.replaceAll(key, "");
        }
    }
    result = result.trim().replaceAll(" +", " ");
    return result;
}


问:
Python3 Replace module call with variable
I am writing a script to query a mongoDB collection using pymongo.

My database has three collections and I am asking the user to pick a collection and then want to return all confirmed guests from that collection.

Currently, I have:

```<code>collectiontosearch = input("What event would you like to display? : ")
collection = db.collectiontosearch
print(collection)

for people in collection.find({"Confirmed": "Yes"}):
            pprint.pprint(people)
</code>```

But instead of searching on the assigned value of 'collectiontosearch', it is searching on the plain text 'collectiontosearch' which obviously is not a collection in my database.  Any idea how I can get pymongo to take my variable value here instead of the strict text of my variable name?  I realize this is probably pretty basic stuff.

答:
Collection is accessible on MongoClient instance by indexing or by get_database instance method.

Use:

```<code>collectiontosearch = input("What event would you like to display? : ")
collection = db[collectiontosearch]
...
</code>```

Or:

```<code>collection = db.get_database(collectiontosearch)
</code>```

Body:
I am writing a script to query a mongoDB collection using pymongo.

My database has three collections and I am asking the user to pick a collection and then want to return all confirmed guests from that collection.

Currently, I have:

collectiontosearch = input("What event would you like to display? : ")
collection = db.collectiontosearch
print(collection)

for people in collection.find({"Confirmed": "Yes"}):
            pprint.pprint(people)

But instead of searching on the assigned value of 'collectiontosearch', it is searching on the plain text 'collectiontosearch' which obviously is not a collection in my database.  Any idea how I can get pymongo to take my variable value here instead of the strict text of my variable name?  I realize this is probably pretty basic stuff.

Body:
Collection is accessible on MongoClient instance by indexing or by get_database instance method.

Use:

collectiontosearch = input("What event would you like to display? : ")
collection = db[collectiontosearch]
...

Or:

collection = db.get_database(collectiontosearch)


问:
Data entered offline does not synchronize when going back online
Some users report that they create offline content and when they go online they lose their data. They just disappear.

I do not know where to start, in my tests this does not occur.

Is there an authentication problem? I use today the form E-mail and password.

I'm using minSdkVersion 16 and compile 'com.google.firebase: firebase-auth: 10.2.1'

I mentioned Auth, why it is not clear how the firebase behaves when the user loses authentication. Let's assume that it loses authentication and inserts new data (after losing authentication), what does firebase do?

1 - Block the insertion - if this is the behavior, my problem will not be the tightening, because the data is inserted and I can see it in the APP.

2 - Does not block the insertion, but when it is online this data will be lost (it is my suspicion)

3 - Does not block the insertion, puts the insert in the queue and updates the base (this is what I hope, because if the user for an unexpected reason lose the offline authentication I will not have to authenticate again until it goes online).

答:
```<code>FirebaseDatabase.getInstance().setPersistenceEnabled(true);
</code>```

try -
Enabling Offline Capabilities on Android

Body:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);

try -
Enabling Offline Capabilities on Android


问:
Pandas: Join results from extractall
I've got a dataframe, and I want to extract all occurences of a pattern and then join them as a single string to become a new column of my original dataframe.

Example:

```<code>original = pd.DataFrame(["bonjour bonjour", "au revoir bonjour", "lala"])

                   0
0    bonjour bonjour
1  au revoir bonjour
2               lala
</code>```

expected result :

```<code>                   0                 1
0    bonjour bonjour  bonjour, bonjour
1  au revoir bonjour           bonjour
2               lala
</code>```

Where I'm stuck:

```<code>extracted = original[0].str.extractall("(bonjour)")

               0
  match
0 0      bonjour
  1      bonjour
1 0      bonjour
</code>```

I can't manage this result, I really don't get how to work with the structure. It seems simple but, depending on how I access it, I don't get what I want.

答:
You need to use findall rather than extract all i.e

```<code>original['new'] = original[0].str.findall('bonjour').apply(','.join)

          0                  new
0    bonjour bonjour   bonjour, bonjour
1  au revoir bonjour            bonjour
2               lala
</code>```

Title: Pandas: Join results from extractall

Body:
I've got a dataframe, and I want to extract all occurences of a pattern and then join them as a single string to become a new column of my original dataframe.

Example:

original = pd.DataFrame(["bonjour bonjour", "au revoir bonjour", "lala"])

                   0
0    bonjour bonjour
1  au revoir bonjour
2               lala

expected result :

                   0                 1
0    bonjour bonjour  bonjour, bonjour
1  au revoir bonjour           bonjour
2               lala

Where I'm stuck:

extracted = original[0].str.extractall("(bonjour)")

               0
  match
0 0      bonjour
  1      bonjour
1 0      bonjour

I can't manage this result, I really don't get how to work with the structure. It seems simple but, depending on how I access it, I don't get what I want.

Body:
You need to use findall rather than extract all i.e

original['new'] = original[0].str.findall('bonjour').apply(','.join)

          0                  new
0    bonjour bonjour   bonjour, bonjour
1  au revoir bonjour            bonjour
2               lala


问:
Specify source ip using fsockopen
On a server with multiple IPs routed to it, I'd like to use PHP's fsockopen to open from a non-primary-interface ip (or a comparable method to be able to make fread and fwrites from a different ip)</p>

答:
This is not possible with fsockopen. You have to use the sockets wrapper:

```<code>$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, '192.168.1.100');
socket_connect($sock, 'stackoverflow.com', 80);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Specify source ip using fsockopen

Body:
This is not possible with fsockopen. You have to use the sockets wrapper:

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, '192.168.1.100');
socket_connect($sock, 'stackoverflow.com', 80);


问:
Python Created Object Attribute
I would like to create attributes of an object based on a dictionary passed in as an argument. Here is the code. But it does not work as

```<code>class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for k in di.keys():
            name = 'k' + '_' + 'series'
            self.name = None

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series
</code>```

I get the following error: 'Obj' object has no attribute 'c'

The code read "name" as a literal, and not as the variable defined.

答:
Use setattr

```<code>class Obj(object):
    def __init__(self, di):
        for key, value in di.items():
            setattr(self, key, value)
</code>```

Some additional advice:

Your code is very strange. I'm not sure why you expect self.name to evaluate as self.(eval('name')) when that clearly doens't happen elsewhere in python

```<code> lower = str.upper
 str.lower('Hello')  # -> still returns 'hello'
</code>```

There is no need to iterate over dictionary.keys(), especially in python 2. for k in dictionary: works just fine. If you want both keys and values use dictionary.items() (or dictionary.iteritems() in python 2).

name = 'k' + '_' + 'series' just makes the string 'k_series'. You need to be able to tell the difference between a string and a variable name. I think you mean k + '_' + series but series is never defined. Don't use + to concatenate strings like that anyway, use .format.

Title: Python Created Object Attribute

Body:
I would like to create attributes of an object based on a dictionary passed in as an argument. Here is the code. But it does not work as

class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for k in di.keys():
            name = 'k' + '_' + 'series'
            self.name = None

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series

I get the following error: 'Obj' object has no attribute 'c'

The code read "name" as a literal, and not as the variable defined.

Body:
Use setattr

class Obj(object):
    def __init__(self, di):
        for key, value in di.items():
            setattr(self, key, value)

Some additional advice:

Your code is very strange. I'm not sure why you expect self.name to evaluate as self.(eval('name')) when that clearly doens't happen elsewhere in python

 lower = str.upper
 str.lower('Hello')  # -> still returns 'hello'

There is no need to iterate over dictionary.keys(), especially in python 2. for k in dictionary: works just fine. If you want both keys and values use dictionary.items() (or dictionary.iteritems() in python 2).

name = 'k' + '_' + 'series' just makes the string 'k_series'. You need to be able to tell the difference between a string and a variable name. I think you mean k + '_' + series but series is never defined. Don't use + to concatenate strings like that anyway, use .format.


问:
Declaring a class inline of ASPX-age
I'm trying to set up a receive-page to collect data, which is formatted as a JSON-string, being sent to us from an external service and which we have to add to our database.

For the sake of simplicity, I would like to keep all the code in one page which is linked to this external service.

I can receive the JSON-string, but I can't seem to deserialize it because it won't accept my class.

My code is shown below.
For debugging reasons I'm also exporting the data to an external log.
If some date would not be added, I can try to see the log if there is anything special in that message which is causing issues.

If I remove my class from the code the page will load correctly.
If I put the class in it, it will throw an error (which I can't see because I'm using an online webserver).

Does anyone know what is wrong with this code?

```<code><%@ Page Language="C#" %>
<%@ import namespace="System.Data"%>
<%@ import namespace="System.Data.SqlClient"%>
<%@ import namespace="System.IO" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.Script.Serialization" %>

<%

public class MessageClass
{
    public string type;
    public string text;
    public string url;
    public string user_name;
    public int timestamp;
}

// GET THE CONTENT THAT WAS POSTED
//StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
//string requestFromPost = reader.ReadToEnd();
string requestFromPost = "{type:'image',url:'https://someservice.com/picture.jpg',user_name:'user',timestamp:1511772572733}";

Response.Write(requestFromPost);

// BACKUP THE MESSAGE IN A LOG
StreamWriter sw;
try
{
  sw = File.AppendText(Server.MapPath(".\\") + "test.log");
  sw.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss") +"] " + requestFromPost);
  sw.Flush();
  sw.Close();
}
catch(Exception ex)
{
  // IGNORE
}

StringBuilder sb = new StringBuilder();
JavaScriptSerializer ser = new JavaScriptSerializer();
//var response = ser.Deserialize<MessageClass>(requestFromPost);

//Response.Write(response.url);

// DATABASE STUFF GOES BELOW

%>
</code>```

答: You will need to changes the data type for timestamp to long since it is not a valid integer</p>

Title: Declaring a class inline of ASPX-age

Body:
I'm trying to set up a receive-page to collect data, which is formatted as a JSON-string, being sent to us from an external service and which we have to add to our database.

For the sake of simplicity, I would like to keep all the code in one page which is linked to this external service.

I can receive the JSON-string, but I can't seem to deserialize it because it won't accept my class.

My code is shown below.
For debugging reasons I'm also exporting the data to an external log.
If some date would not be added, I can try to see the log if there is anything special in that message which is causing issues.

If I remove my class from the code the page will load correctly.
If I put the class in it, it will throw an error (which I can't see because I'm using an online webserver).

Does anyone know what is wrong with this code?

<%@ Page Language="C#" %>
<%@ import namespace="System.Data"%>
<%@ import namespace="System.Data.SqlClient"%>
<%@ import namespace="System.IO" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.Script.Serialization" %>

<%

public class MessageClass
{
    public string type;
    public string text;
    public string url;
    public string user_name;
    public int timestamp;
}

// GET THE CONTENT THAT WAS POSTED
//StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
//string requestFromPost = reader.ReadToEnd();
string requestFromPost = "{type:'image',url:'https://someservice.com/picture.jpg',user_name:'user',timestamp:1511772572733}";

Response.Write(requestFromPost);

// BACKUP THE MESSAGE IN A LOG
StreamWriter sw;
try
{
  sw = File.AppendText(Server.MapPath(".\\") + "test.log");
  sw.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss") +"] " + requestFromPost);
  sw.Flush();
  sw.Close();
}
catch(Exception ex)
{
  // IGNORE
}

StringBuilder sb = new StringBuilder();
JavaScriptSerializer ser = new JavaScriptSerializer();
//var response = ser.Deserialize<MessageClass>(requestFromPost);

//Response.Write(response.url);

// DATABASE STUFF GOES BELOW

%>


问:
Prevent hover effect from looping
I made a hover effect which toggles a top block to slide up/down at the same time the bottom block slides up / down.

As you can see in the Fiddle: https://jsfiddle.net/wmaL1pm5/1/

However, if you swipe your mouse fast on and off the block the hover effects keeps repeating even if you are not on that block anymore.

In my HTML I have 2 row's with each 3 row containing 3 of these blocks. If you swipe your mouse of these rows all of the blocks are repeating their hover effect.

How can I prevent the hover effect from looping if you hover another block or if your mouse is on the current block.

Below my current jQuery code:

```<code>$(".usp-hover").mouseenter( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).removeClass("usp-block-hidden");
     $( this ).find( ".usp-block-hover" ).slideDown('slow')
});

$(".usp-hover").mouseleave( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).slideToggle('slow')
});
</code>```

答:
You can stop the previous animation by using the .stop() method:

```<code>$(".usp-hover").mouseenter( function(){
    $( this ).find( ".usp-block-title" ).stop().slideToggle('slow')
    $( this ).find( ".usp-block-hover" ).removeClass("usp-block-hidden");
    $( this ).find( ".usp-block-hover" ).stop().slideDown('slow')
});

$(".usp-hover").mouseleave( function(){
    $( this ).find( ".usp-block-title" ).stop().slideToggle('slow')
    $( this ).find( ".usp-block-hover" ).stop().slideToggle('slow')
});
</code>```

This will stop queuing up your animations and only display the latest and thus prevent the loop.

Title: Prevent hover effect from looping

Body:
I made a hover effect which toggles a top block to slide up/down at the same time the bottom block slides up / down.

As you can see in the Fiddle: https://jsfiddle.net/wmaL1pm5/1/

However, if you swipe your mouse fast on and off the block the hover effects keeps repeating even if you are not on that block anymore.

In my HTML I have 2 row's with each 3 row containing 3 of these blocks. If you swipe your mouse of these rows all of the blocks are repeating their hover effect.

How can I prevent the hover effect from looping if you hover another block or if your mouse is on the current block.

Below my current jQuery code:

$(".usp-hover").mouseenter( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).removeClass("usp-block-hidden");
     $( this ).find( ".usp-block-hover" ).slideDown('slow')
});

$(".usp-hover").mouseleave( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).slideToggle('slow')
});

Body:
You can stop the previous animation by using the .stop() method:

$(".usp-hover").mouseenter( function(){
    $( this ).find( ".usp-block-title" ).stop().slideToggle('slow')
    $( this ).find( ".usp-block-hover" ).removeClass("usp-block-hidden");
    $( this ).find( ".usp-block-hover" ).stop().slideDown('slow')
});

$(".usp-hover").mouseleave( function(){
    $( this ).find( ".usp-block-title" ).stop().slideToggle('slow')
    $( this ).find( ".usp-block-hover" ).stop().slideToggle('slow')
});

This will stop queuing up your animations and only display the latest and thus prevent the loop.


问:
Building Dictionary in Python as a Function
Hi everyone~~ :) I have an Arduino Uno sending sensor data over USB to PyCharm (Python IDE), after which I have to compile these data and write to a CSV file for machine learning later.

I am trying to build a dictionary in Python as a function as seen below:

```<code>def readData():  # reads inputs from Arduino
   try:
     datastring = arduino.readline()
   except:
     pass
 return datastring

def build_dictionary(): # function to build dictionary
     incomingdata = readData()

    for incomingdata in arduino:
      incomingdata = incomingdata.strip()

    if incomingdata:
        datasplit = incomingdata.split(',')
        i = 0
        temperature = datasplit[i]
        i = i + 1
        humidity = datasplit[i]
        i = i + 1
        light = datasplit[i]
        i = 0
        dic = {'Temp': temperature, 'Humidity': humidity, 'Light': light}
</code>```

When I printed some parts of the dictionary, "dic", immediately after "dic = {...}, as in:

```<code>print "dic['Temp']: ", dic['Temp']
</code>```

I was able to obtain output normally (i.e. PyCharm printed everything Arduino sent to it). However, when I did the following:

```<code>def build_dictionary(): # function to build dictionary
     incomingdata = readData()

    for incomingdata in arduino:
      incomingdata = incomingdata.strip()

    if incomingdata:
        datasplit = incomingdata.split(',')
        i = 0
        temperature = datasplit[i]
        i = i + 1
        humidity = datasplit[i]
        i = i + 1
        light = datasplit[i]
        i = 0
        global dic
        dic = {'Temp': temperature, 'Humidity': humidity, 'Light': light}
   return dic

while True:
    print "dic['Temp']: ", dic['Temp']
</code>```

the output became:

```<code>dic['Temp']:  24.00
dic['Temp']:  25.00
</code>```

Only the first 2 outputs were printed strangely. A check on the Arduino board showed that it was still sending information to PyCharm (Python) but they were just not getting printed out.

May I ask where did I go wrong here?

Thank you so much! :)

答:
It sounds like you need to read a line from the serial port and then process that line, and then go back and get a new line and so on:

```<code>def readData(): # read just one line from arduino
    # simplified
    return arduino.readline()

def build_dictionary(incomingdata): # function to build dictionary
    dic = {}
    incomingdata = incomingdata.strip()
    if incomingdata:
        datasplit = incomingdata.split(',')
        temperature = datasplit[0]
        humidity = datasplit[1]
        light = datasplit[2]
        dic = {'Temp': temperature, 'Humidity': humidity, 'Light': light}
   return dic

while True:
    dic = build_dictionary(readData())
    print(dic)
</code>```

Note:

This code loops round forever. It has no way to stop (unless you press ctrl-C)

Update:

Using a counter to break after a number of samples:

```<code>for _ in range(9999):
    dic = build_dictionary(readData())
    print(dic)
</code>```

Body:
Hi everyone~~ :) I have an Arduino Uno sending sensor data over USB to PyCharm (Python IDE), after which I have to compile these data and write to a CSV file for machine learning later.

I am trying to build a dictionary in Python as a function as seen below:

def readData():  # reads inputs from Arduino
   try:
     datastring = arduino.readline()
   except:
     pass
 return datastring

def build_dictionary(): # function to build dictionary
     incomingdata = readData()

    for incomingdata in arduino:
      incomingdata = incomingdata.strip()

    if incomingdata:
        datasplit = incomingdata.split(',')
        i = 0
        temperature = datasplit[i]
        i = i + 1
        humidity = datasplit[i]
        i = i + 1
        light = datasplit[i]
        i = 0
        dic = {'Temp': temperature, 'Humidity': humidity, 'Light': light}

When I printed some parts of the dictionary, "dic", immediately after "dic = {...}, as in:

print "dic['Temp']: ", dic['Temp']

I was able to obtain output normally (i.e. PyCharm printed everything Arduino sent to it). However, when I did the following:

def build_dictionary(): # function to build dictionary
     incomingdata = readData()

    for incomingdata in arduino:
      incomingdata = incomingdata.strip()

    if incomingdata:
        datasplit = incomingdata.split(',')
        i = 0
        temperature = datasplit[i]
        i = i + 1
        humidity = datasplit[i]
        i = i + 1
        light = datasplit[i]
        i = 0
        global dic
        dic = {'Temp': temperature, 'Humidity': humidity, 'Light': light}
   return dic

while True:
    print "dic['Temp']: ", dic['Temp']

the output became:

dic['Temp']:  24.00
dic['Temp']:  25.00

Only the first 2 outputs were printed strangely. A check on the Arduino board showed that it was still sending information to PyCharm (Python) but they were just not getting printed out.

May I ask where did I go wrong here?

Thank you so much! :)

Body:
It sounds like you need to read a line from the serial port and then process that line, and then go back and get a new line and so on:

def readData(): # read just one line from arduino
    # simplified
    return arduino.readline()

def build_dictionary(incomingdata): # function to build dictionary
    dic = {}
    incomingdata = incomingdata.strip()
    if incomingdata:
        datasplit = incomingdata.split(',')
        temperature = datasplit[0]
        humidity = datasplit[1]
        light = datasplit[2]
        dic = {'Temp': temperature, 'Humidity': humidity, 'Light': light}
   return dic

while True:
    dic = build_dictionary(readData())
    print(dic)

Note:

This code loops round forever. It has no way to stop (unless you press ctrl-C)

Update:

Using a counter to break after a number of samples:

for _ in range(9999):
    dic = build_dictionary(readData())
    print(dic)


问:
header not being set in storage promise
I am trying to add a header to my api call however, i need to get auth token and set that to the header. But when i try and run the bellow code it doesn't set it, only sets the Content-Type.

```<code>import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [HttpClient]
})
export class DataProvider {
  public token:string;

constructor(public http: HttpClient, public storage: Storage) {}

getsomething(){

 let headers = new HttpHeaders();
 headers = headers.set('Content-Type', 'application/json');
 this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
   headers = headers.set('AuthToken', this.token);
 });

 console.log(headers);

 return this.http.get('http://localhost:54951/getfarms', {
   headers: headers
 });
</code>```

}

答:
The header.set() function does not return a header instance so do the following

```<code>headers = header.set('AuthToken', this.token); //change the line
headers.set('AuthToken', this.token); //do not reassign the headers object
</code>```

Title: header not being set in storage promise

Body:
I am trying to add a header to my api call however, i need to get auth token and set that to the header. But when i try and run the bellow code it doesn't set it, only sets the Content-Type.

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';

@Injectable()
@Component({
  providers: [HttpClient]
})
export class DataProvider {
  public token:string;

constructor(public http: HttpClient, public storage: Storage) {}

getsomething(){

 let headers = new HttpHeaders();
 headers = headers.set('Content-Type', 'application/json');
 this.storage.get('token').then((val) => {
   this.token = val;
   console.log(this.token);
   headers = headers.set('AuthToken', this.token);
 });

 console.log(headers);

 return this.http.get('http://localhost:54951/getfarms', {
   headers: headers
 });

}

Body:
The header.set() function does not return a header instance so do the following

headers = header.set('AuthToken', this.token); //change the line
headers.set('AuthToken', this.token); //do not reassign the headers object


问:
Default Option not selected dropdown in angularjs
I am struggling with dropdown list, Please refer bellow code

My Controller

```<code>(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);
</code>```

My UI

```<code><body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>
</code>```

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

答:
change value in your select with ng-value

```<code><select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  <option ng-repeat="option in data.availableOptions" ng-value="{{option.id}}">{{option.name}}</option>
</select>
</code>```

Updated Plunker

Body:
I am struggling with dropdown list, Please refer bellow code

My Controller

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);

My UI

  <form name="myForm">
     Repeat select:
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>

  <tt>model = {{data.model}}</tt>

Here is an demo, In this demo i am setting $scope.data.model as 1 , then why my Dropdown list showing blank ..

I had searched and tried lot, but no luck, Please help.
Thanks in advance, and sorry for my bad English.

Edit Note : I had tried this before, But still facing this issue.

Body:
change value in your select with ng-value

<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  <option ng-repeat="option in data.availableOptions" ng-value="{{option.id}}">{{option.name}}</option>
</select>

Updated Plunker


问:
Selenium WD / Java | Cannot create 'if' & 'else if' statement
I have a web page that have an indicator if a specific stock is opened/closed.
For that I want to set a if & else if statement. For some reason I get an error in eclipse.

*Note: Don't know if it helps, but if I copy/paste the code to a new empty class that is a 'Main' one, it works without any errors - so the structure of the code is Ok I guess.

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class TestClock {

public static void chromeMethod(WebDriver driver) {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
}

public static void runTestClock(WebDriver driver)
{

    WebElement Status = null;
    if( Status == driver.findElement(By.cssSelector(".redClockBigIcon")));
    {
        System.out.println("Stock is closed");
        driver.navigate().back();
    }

    else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
    {
        System.out.println("Stock is open");

        driver.navigate().back();
    }

}
}
</code>```

I get a syntax error under 'else' :

Syntax error on token "else", delete this token

答:
```<code>else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
</code>```

Here is your mistake: the last ; has to be deletet

Body:
I have a web page that have an indicator if a specific stock is opened/closed.
For that I want to set a if & else if statement. For some reason I get an error in eclipse.

*Note: Don't know if it helps, but if I copy/paste the code to a new empty class that is a 'Main' one, it works without any errors - so the structure of the code is Ok I guess.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class TestClock {

public static void chromeMethod(WebDriver driver) {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
}

public static void runTestClock(WebDriver driver)
{

    WebElement Status = null;
    if( Status == driver.findElement(By.cssSelector(".redClockBigIcon")));
    {
        System.out.println("Stock is closed");
        driver.navigate().back();
    }

    else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
    {
        System.out.println("Stock is open");

        driver.navigate().back();
    }

}
}

I get a syntax error under 'else' :

Syntax error on token "else", delete this token

Body:
else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );

Here is your mistake: the last ; has to be deletet


问:
jquery .on is not working
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

```<code>$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});
</code>```

答:
So what is the issue with this

```<code>tabs[i].on("click", switchTab);
</code>```

In this case you are using bracket notation which is short for jQuery's tabs.get(i). The get(index) method returns the DOM object, it does not return an jQuery object. Since DOM does not have on() it throws an error.

So how can you fix it? You could use eq() which returns a jQuery object

```<code>tabs.eq(i).on("click", switchTab);
</code>```

BUT why loop over the elements yourself when jQuery does it for you.

```<code>tabs.on("click", switchTab);
</code>```

Title: jquery .on is not working

Body:
When using $(document).on('ready', function(){////}) nothing is happens so I changed to $(document).ready(function(){////}).

When using .on function its not working and throwing error and exeption as follows:

Warning:

jQuery.Deferred exception: tabs[i].on is not a function TypeError:
  tabs[i].on is not a function
      at HTMLDocument. (https://animesh.dev/wp-content/plugins/hyparticles/assests/script.js?ver=4.9.1:7:11)
      at j (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:29999)
      at k (https://animesh.dev/wp-content/plugins/hyparticles/assests/jquery-3.2.1.min.js?ver=4.9.1:2:30313)
  undefined

Error:

Uncaught TypeError: tabs[i].on is not a function
      at HTMLDocument. (script.js?ver=4.9.1:7)
      at j (jquery-3.2.1.min.js?ver=4.9.1:2)
      at k (jquery-3.2.1.min.js?ver=4.9.1:2)

note: tabs is a variable defined by me inside script.js

note: I'm using jquery v3.2.1(latest) in minify version

why the error coming out

My script.js:

$(document).ready(function() {
    alert("ready");
    var tabs = $("ul.nav-tabs > li");

    for (i = 0; i < tabs.length; i++) {
        tabs[i].on("click", switchTab);
    }

    function switchTab(event) {
        event.preventDefault();
        console.log(event);
    }

});

Body:
So what is the issue with this

tabs[i].on("click", switchTab);

In this case you are using bracket notation which is short for jQuery's tabs.get(i). The get(index) method returns the DOM object, it does not return an jQuery object. Since DOM does not have on() it throws an error.

So how can you fix it? You could use eq() which returns a jQuery object

tabs.eq(i).on("click", switchTab);

BUT why loop over the elements yourself when jQuery does it for you.

tabs.on("click", switchTab);


问:
Task automation software on Windows servers
We currently have Java program which runs a multitude of tasks on our Windows servers, we are planning to replace that with an open source task automation software for efficiency and maintainability reasons.

The following are the features we are looking for:

Ability to run tasks/scripts in any language (Java, C#, Python etc..)

Schedule the tasks at any instant (12:00 AM 12/16/2010) or run them at specific intervals (Every 10 minutes).

Ability to notify the admin if a task execution failed and preventing them to run again.

Parallel execution of independent tasks and ability to set dependencies between tasks.

Ability to priortize and preempt the tasks when needed without restarting the software.

Reporting capabilities on how long each task took etc.

Remotely adding, deleting and monitoring the progress of tasks which are being executed

Please let me know if you know of any great open source solutions which address all or most of these needs. Thanks for your help!

答:
You can try using Hudson, the opensource Continuous Integration system for doing this. It provides most if not all of the features you are asking for. Each task (or call it "project" in the Hudson lingo) can be scheduled periodically, or via a SCM trigger, or a curl call using the tokenizer URL. You can interlink jobs as downstream projects, and can also execute them parallelly among various boxes. It has great error reporting capabilities, and archives all the build logs, error reports and supports various formats like junit to generate you colorful plots showing the trends of your job success rate, test metrics etc.

Refer this to get started off:

http://wiki.hudson-ci.org/display/HUDSON/Use+Hudson

You can schedule the tasks by creating them as Maven targets (or ant, Makefiles anything for that reason; it can run any script so it is quite flexible) The email notification is quite useful to notify is the jobs are failing or unstable.

Moreover, Hudson comes with a bunch of opensource plugins, and is very useful. Hope that helps.


问:
java.lang.NoSuchMethodError: No direct method at com.google.android.gms.iid.InstanceID.zza
Error :

java.lang.NoSuchMethodError: No direct method
  (Landroid/content/Context;)V in class
  Lcom/google/android/gms/iid/zzd; or its super classes (declaration of
  'com.google.android.gms.iid.zzd' appears in
  /data/app/com.app-1/base.apk:classes33.dex)
                                                         at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
                                                         at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
                                                         at com.quickblox.messages.services.a.c.(Unknown Source)

Gradle

```<code>qbSdkVersion = '3.3.1'

versionName = '3.3.0'

testRunnerVersion = "0.4.1"

// Dependency versions
playServicesVersion = '10.2.1'
supportV4Version = '23.1.1'
appcompatV7Version = '23.1.1'
recyclerviewV7Version = '23.2.1'
supportAnnotationsVersion = '23.1.1'
designVersion = '23.1.1'

uilVersion = '1.9.0'
glideVersion = '3.6.1'
pullToRefreshVersion = '3.2.3'
stickyListHeaders = '2.7.0'
robotoTextViewVersion = '2.4.3'
stickersVersion = '0.7.3'
crashlyticsVersion = '2.2.2'
</code>```

答: I had similar issue when I used in my project android-support libs or play-services libs with different versions, check it in your project (you can see it in Android Studio in part 'External Libraries'). In QuickBlox Android SDK (v3.3.1) used play-services version 10.2.1 and support libs version 23.1.1. If you use firebase in your project, it version must be same with play-services version. Additionally check versions this libs in others modules in your project. Also check, maybe other libs from your dependencies use support libs or play-services libs with different versions with your project.</p>

Body:
Error :

java.lang.NoSuchMethodError: No direct method
  (Landroid/content/Context;)V in class
  Lcom/google/android/gms/iid/zzd; or its super classes (declaration of
  'com.google.android.gms.iid.zzd' appears in
  /data/app/com.app-1/base.apk:classes33.dex)
                                                         at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
                                                         at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
                                                         at com.quickblox.messages.services.a.c.(Unknown Source)

Gradle

qbSdkVersion = '3.3.1'

versionName = '3.3.0'

testRunnerVersion = "0.4.1"

// Dependency versions
playServicesVersion = '10.2.1'
supportV4Version = '23.1.1'
appcompatV7Version = '23.1.1'
recyclerviewV7Version = '23.2.1'
supportAnnotationsVersion = '23.1.1'
designVersion = '23.1.1'

uilVersion = '1.9.0'
glideVersion = '3.6.1'
pullToRefreshVersion = '3.2.3'
stickyListHeaders = '2.7.0'
robotoTextViewVersion = '2.4.3'
stickersVersion = '0.7.3'
crashlyticsVersion = '2.2.2'


问:
Why immutable objects allow to comply the Liskov Substitution Principle?
I want to show an example with Rectangles and Squares:

```<code>    class Rectangle {

private int width;
private int height;

public int getWidth() {
    return width;
}

public void setWidth(int width) {
    this.width = width;
}

public int getHeight() {
    return height;
}

public void setHeight(int height) {
    this.height = height;
}

public int area() {
    return width * height;
}

}

class Square extends Rectangle{

@Override
public void setWidth(int width){
    super.setWidth(width);
    super.setHeight(width);
}

@Override
public void setHeight(int height){
    super.setHeight(height);
    super.setWidth(height);
}

}

public class Use {

public static void main(String[] args) {
    Rectangle sq = new Square();
    LSPTest(sq);
}

public static void LSPTest(Rectangle rec) {
    rec.setWidth(5);
    rec.setHeight(4);

    if (rec.area() == 20) {
        // do Something
    }
}

}
</code>```

If I substitute an instance of Square instead of Rectangle in method LSPTest the behaviour of my programm will be changed. This is contrary to the LSP.

I heard, that immutable object allow to solve this problem. But why?

I changed example.
I add constructor in Rectangle:

```<code>public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
</code>```

Then, I changed setters:

```<code>    public Rectangle setWidth(int width) {
    return new Rectangle(width, this.height);
}

public Rectangle setHeight(int height) {
    return new Rectangle(this.width, height);
}
</code>```

Now, Square looks like:

```<code>class Square{
public Square() {

}

public Square(int width, int height) {
    super(width, height);
}

@Override
public Rectangle setWidth(int width) {
    return new Rectangle(width, width);
}

@Override
public Rectangle setHeight(int height) {
    return new Rectangle(height, height);
}

}
</code>```

And here is the client code:

```<code> public class Use {

public static void main(String[] args) {
    Rectangle sq = new Square(4, 4);
    LSPTest(sq);
}

public static void LSPTest(Rectangle rec) {
    rec = rec.setHeight(5);

    if (rec.area() == 20) {
        System.out.println("yes");
    }
}

}
</code>```

The same problems remain. What's the difference whether the object itself is changed or a new object is returned. The program still behaves differently for the base class and subclass.

答:
The issue is with the contracts, i.e. the expectations of the programmers that use your Rectangle.

The contract is that you can do a setWidth(15) and afterwards getWidth() will return 15 until you do another setWidth with a different value.

From the perspective of setHeight, this means it must not change height. Continue that line of thought, and the contract for a setter is "update this property to the parameter value and leave all other properties unchanged".

Now in Square, the new invariant getWidth() == getHeight() forces setWidth to also set the height, and voilà: the contract of setHeight is violated.

Of course you could explicitly state in Rectangle.setWidth()'s contract (i.e. the method documentation) that the width may change if setHeight() is called.

But now your contract on setWidth is pretty useless: it will set the width, which may or may not stay constant after a call to setHeight, depending on whatever a subclass may decide to do.

Things can get worse. Assume you roll out your Rectangle, people complain a bit about the unusual contract on the setters but otherwise everything is fine.

But now somebody comes and wants to add a new subclass, OriginCenteredRectangle. Now changing the width also needs to update x and y. Have fun explaining your users that you had to modify the contract of the base class so that another subclass (that only 10% of your users need) could be added.

Practice has shown that the OriginCenteredRectangle problem is far more common than the silliness of that example indicates.

Also, practice has shown that programmers typically are not aware of the full contract, and start writing updateable subclasses that fly in the face of expectations, causing subtle bugs.

So most programming language community finally decides that you need value classes; from what I have seen in C++ and Java, this process takes a decade or two.

Now with immutable classes, your setters suddenly look different:
void setWidth(width) becomes Rectangle setWidth(width). I.e. you don't write setters, you write functions that return a new object with a different width.

And that's perfectly acceptable in Square: setWidth remains unchanged and still returns a Rectangle as it must.
Of course you will want a function to get back a different square, so Square adds the function Square Square.setSize(size).

You still want a MutableRectangle class just to construct Rectangles without having to create a new copy - you'll have Rectangle toRectangle() which does the constructor call. (The other name for MutableRectangle would be RectangleBuilder, which describes a somewhat more limited recommended use of the class. Pick your style - personally, I think MutableRectangle is fine, it is just that most subclassing attempts will fail so I'd consider making it final.)

Body:
I want to show an example with Rectangles and Squares:

    class Rectangle {

private int width;
private int height;

public int getWidth() {
    return width;
}

public void setWidth(int width) {
    this.width = width;
}

public int getHeight() {
    return height;
}

public void setHeight(int height) {
    this.height = height;
}

public int area() {
    return width * height;
}

}

class Square extends Rectangle{

@Override
public void setWidth(int width){
    super.setWidth(width);
    super.setHeight(width);
}

@Override
public void setHeight(int height){
    super.setHeight(height);
    super.setWidth(height);
}

}

public class Use {

public static void main(String[] args) {
    Rectangle sq = new Square();
    LSPTest(sq);
}

public static void LSPTest(Rectangle rec) {
    rec.setWidth(5);
    rec.setHeight(4);

    if (rec.area() == 20) {
        // do Something
    }
}

}

If I substitute an instance of Square instead of Rectangle in method LSPTest the behaviour of my programm will be changed. This is contrary to the LSP.

I heard, that immutable object allow to solve this problem. But why?

I changed example.
I add constructor in Rectangle:

public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}

Then, I changed setters:

    public Rectangle setWidth(int width) {
    return new Rectangle(width, this.height);
}

public Rectangle setHeight(int height) {
    return new Rectangle(this.width, height);
}

Now, Square looks like:

class Square{
public Square() {

}

public Square(int width, int height) {
    super(width, height);
}

@Override
public Rectangle setWidth(int width) {
    return new Rectangle(width, width);
}

@Override
public Rectangle setHeight(int height) {
    return new Rectangle(height, height);
}

}

And here is the client code:

 public class Use {

public static void main(String[] args) {
    Rectangle sq = new Square(4, 4);
    LSPTest(sq);
}

public static void LSPTest(Rectangle rec) {
    rec = rec.setHeight(5);

    if (rec.area() == 20) {
        System.out.println("yes");
    }
}

}

The same problems remain. What's the difference whether the object itself is changed or a new object is returned. The program still behaves differently for the base class and subclass.


问:
xmlpull can not load any factory class

I am trying to use apktool to decompile apk files using the command shown below but it is not able to decode the Android manifest and throws an exception. I have tested it with different apps and get the same exception always. I have the jar of xmlpull-1.1.3.1, xmlpull_1_0_5, and kxml2 in my jre lib path (i.e., /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext/) and I have included these paths in the CLASSPATH. How do I resolve this please?

```<code>apktool d uk.co.houseoffraser.apk
</code>```

I: Using Apktool 2.3.0 on uk.co.houseoffraser.apk

  I: Loading resource table...

  I: Decoding AndroidManifest.xml with resources...

  Exception in thread "main" brut.androlib.AndrolibException: Could not decode XML
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decode(XmlPullStreamDecoder.java:145)
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decodeManifest(XmlPullStreamDecoder.java:153)
      at brut.androlib.res.decoder.ResFileDecoder.decodeManifest(ResFileDecoder.java:140)
      at brut.androlib.res.AndrolibResources.decodeManifestWithResources(AndrolibResources.java:209)
      at brut.androlib.Androlib.decodeManifestWithResources(Androlib.java:137)
      at brut.androlib.ApkDecoder.decode(ApkDecoder.java:113)
      at brut.apktool.Main.cmdDecode(Main.java:160)
      at brut.apktool.Main.main(Main.java:72)

  Caused by: org.xmlpull.v1.XmlPullParserException: could not load any factory class (even small or full default implementation); nested exception is:
      org.kxml2.io.XmlReader
      at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:225)
      at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:76)
      at org.xmlpull.v1.wrapper.XmlPullWrapperFactory.(XmlPullWrapperFactory.java:52)
      at org.xmlpull.v1.wrapper.XmlPullWrapperFactory.newInstance(XmlPullWrapperFactory.java:29)
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decode(XmlPullStreamDecoder.java:49)
      ... 7 more

答: I finally discovered that the xmlpull jar e.g., xmlpull-1.1.3.1.jar, xmlpull_1_0_5.jar is the default xml parser that is always used even if you only have the KXML2 parser in your CLASSPATH. Removing the xmlpull parser from the jre extended library (e.g., /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext/) fixes the problem. Even if the CLASSPATH have other xml parsers, as long as only the KXML2 jar is in the jre library, it works.</p>

Title: xmlpull can not load any factory class

Body:
I am trying to use apktool to decompile apk files using the command shown below but it is not able to decode the Android manifest and throws an exception. I have tested it with different apps and get the same exception always. I have the jar of xmlpull-1.1.3.1, xmlpull_1_0_5, and kxml2 in my jre lib path (i.e., /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/ext/) and I have included these paths in the CLASSPATH. How do I resolve this please?

apktool d uk.co.houseoffraser.apk

I: Using Apktool 2.3.0 on uk.co.houseoffraser.apk

  I: Loading resource table...

  I: Decoding AndroidManifest.xml with resources...

  Exception in thread "main" brut.androlib.AndrolibException: Could not decode XML
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decode(XmlPullStreamDecoder.java:145)
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decodeManifest(XmlPullStreamDecoder.java:153)
      at brut.androlib.res.decoder.ResFileDecoder.decodeManifest(ResFileDecoder.java:140)
      at brut.androlib.res.AndrolibResources.decodeManifestWithResources(AndrolibResources.java:209)
      at brut.androlib.Androlib.decodeManifestWithResources(Androlib.java:137)
      at brut.androlib.ApkDecoder.decode(ApkDecoder.java:113)
      at brut.apktool.Main.cmdDecode(Main.java:160)
      at brut.apktool.Main.main(Main.java:72)

  Caused by: org.xmlpull.v1.XmlPullParserException: could not load any factory class (even small or full default implementation); nested exception is:
      org.kxml2.io.XmlReader
      at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:225)
      at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:76)
      at org.xmlpull.v1.wrapper.XmlPullWrapperFactory.(XmlPullWrapperFactory.java:52)
      at org.xmlpull.v1.wrapper.XmlPullWrapperFactory.newInstance(XmlPullWrapperFactory.java:29)
      at brut.androlib.res.decoder.XmlPullStreamDecoder.decode(XmlPullStreamDecoder.java:49)
      ... 7 more


问:
C++ Square Root with recursion
My square root program for some reason gets an answer that is a little off from what it should get for most inputs. I'm not sure why this is. Only certain inputs are wrong. I also get a segmentation fault at then very end after the answer is given and am not sure why that is either.</p>

```<code>#include<iostream>
#include<cmath>
#include<cfloat>
#include<string>
#include <cstdlib>
using namespace std;

//declare sqroot function calls recursive function newton
double sqroot1(double num );
double newton(double num, double guess);
int main(int argc, char **argv)
{

    for( int i = 0 ; i < argc ; i++)
    {
       cout<<"sqroot("<<argv[i+1]<<") is "<< sqroot1(atoi(argv[i+1]))     <<endl;
    }
}

double newton(double num, double a)
{
    if ((abs(a*a - num) <= FLT_EPSILON))
    {
        return a;
    }
    else
    {
        newton(num, (a+num/a)/2 );
    }
}

double sqroot1(double num)
{
    double sqrt = newton(num,num/2);
    return sqrt;
}
</code>```

答:
Adding to 1201ProgramAlarm's answer, why is the following so bad?

```<code>if ((abs(a*a - num) <= eps))
</code>```

Let's say eps is 1e-15, a bit bigger than DBL_EPSILON. Well, if a is even moderately large (something like 5 or greater) then the unit in the last place (ulp) of a*a is bigger than eps and the condition can only be true if a*a == num. There's a risk, with rounding, that this won't be reached and you end up with infinite recursion and a crash.

Now let's say that num is very small such that for the initial guess

```<code>abs(num/2*num/2 - num) <= eps
</code>```

So for instance, sqroot1(1e-20) will evaluate

```<code>abs(1e-40/4 - 1e-20)   <= 1e-15
</code>```

which is true and you will get 5e-21 as the square root of 1e-20. This is atrocious precision.

Title: C++ Square Root with recursion

Body:
My square root program for some reason gets an answer that is a little off from what it should get for most inputs. I'm not sure why this is. Only certain inputs are wrong. I also get a segmentation fault at then very end after the answer is given and am not sure why that is either.

#include<iostream>
#include<cmath>
#include<cfloat>
#include<string>
#include <cstdlib>
using namespace std;

//declare sqroot function calls recursive function newton
double sqroot1(double num );
double newton(double num, double guess);
int main(int argc, char **argv)
{

    for( int i = 0 ; i < argc ; i++)
    {
       cout<<"sqroot("<<argv[i+1]<<") is "<< sqroot1(atoi(argv[i+1]))     <<endl;
    }
}

double newton(double num, double a)
{
    if ((abs(a*a - num) <= FLT_EPSILON))
    {
        return a;
    }
    else
    {
        newton(num, (a+num/a)/2 );
    }
}

double sqroot1(double num)
{
    double sqrt = newton(num,num/2);
    return sqrt;
}

Body:
Adding to 1201ProgramAlarm's answer, why is the following so bad?

if ((abs(a*a - num) <= eps))

Let's say eps is 1e-15, a bit bigger than DBL_EPSILON. Well, if a is even moderately large (something like 5 or greater) then the unit in the last place (ulp) of a*a is bigger than eps and the condition can only be true if a*a == num. There's a risk, with rounding, that this won't be reached and you end up with infinite recursion and a crash.

Now let's say that num is very small such that for the initial guess

abs(num/2*num/2 - num) <= eps

So for instance, sqroot1(1e-20) will evaluate

abs(1e-40/4 - 1e-20)   <= 1e-15

which is true and you will get 5e-21 as the square root of 1e-20. This is atrocious precision.


问:
Linq Sql Int null equal to null. Not returning rows
I have a linq query with a where clause as below

```<code>var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
                               join pd1 in dbContext.XXXXXXXXXXX on ppatg.ScheduleID equals pd1.ScheduleID
                               where  pd1.GroupID == null
                               select
                               new
                               {
                                FinishPDI = pd1.ProductionDateID,
                                FinishingDate = pd1.WorkFlowDate,
                                ppatg.GroupName,
                                ppatg.PNTGroupID
                               });
</code>```

In the database GroupID is an int that can be null. The linq query returns rows without the filtered where clause but none when I include the where clause. There are null values in the GroupId column in the database.

It is definitely this statement that produces no results. All the literature on the subject online says that this is equivalent to

```<code>pd1.GroupID is null // in sql
</code>```

I am getting results that contradict this

Sql code is

```<code> select pd1.ProductionDateID as FinishPDI, pd1.WorkflowDate as FinishingDate,GroupName ,PNTGroupId
 from XXXXXXXXXXXX
 inner join XXXXXXXXXXXX pd1 on
 XXXXXXXXXXXX.ScheduleId = pd1.ScheduleID
 where pd1.GroupID is null
</code>```

答:
You can combine your where with the join, which should give you the expected results:

```<code>var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
                               join pd1 in dbContext.XXXXXXXXXXX.Where(p => !p.GroupId.HasValue) on ppatg.ScheduleID equals pd1.ScheduleID
                               select
                               new
                               {
                                FinishPDI = pd1.ProductionDateID,
                                FinishingDate = pd1.WorkFlowDate,
                                ppatg.GroupName,
                                ppatg.PNTGroupID
                               });
</code>```

Body:
I have a linq query with a where clause as below

var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
                               join pd1 in dbContext.XXXXXXXXXXX on ppatg.ScheduleID equals pd1.ScheduleID
                               where  pd1.GroupID == null
                               select
                               new
                               {
                                FinishPDI = pd1.ProductionDateID,
                                FinishingDate = pd1.WorkFlowDate,
                                ppatg.GroupName,
                                ppatg.PNTGroupID
                               });

In the database GroupID is an int that can be null. The linq query returns rows without the filtered where clause but none when I include the where clause. There are null values in the GroupId column in the database.

It is definitely this statement that produces no results. All the literature on the subject online says that this is equivalent to

pd1.GroupID is null // in sql

I am getting results that contradict this

Sql code is

 select pd1.ProductionDateID as FinishPDI, pd1.WorkflowDate as FinishingDate,GroupName ,PNTGroupId
 from XXXXXXXXXXXX
 inner join XXXXXXXXXXXX pd1 on
 XXXXXXXXXXXX.ScheduleId = pd1.ScheduleID
 where pd1.GroupID is null

Body:
You can combine your where with the join, which should give you the expected results:

var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
                               join pd1 in dbContext.XXXXXXXXXXX.Where(p => !p.GroupId.HasValue) on ppatg.ScheduleID equals pd1.ScheduleID
                               select
                               new
                               {
                                FinishPDI = pd1.ProductionDateID,
                                FinishingDate = pd1.WorkFlowDate,
                                ppatg.GroupName,
                                ppatg.PNTGroupID
                               });


问:
PyQT force update textEdit before calling other function
My question concerns PyQT5.
I try to have a dialog window with a button that when clicked

updates some text of a QTextEdit field

calls a function (which needs much time to terminate)

Something like this:

```<code>class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    run_lengthy_function(self)
</code>```

However, when I run my GUI I notice that the text is updated only after the lengthy function has terminated, although the QTextEdit.append is called before the lengthy function. How can I enforce that the text is updated in advance?

What I tried so far (but didn't work) was to let Python wait some time before triggering the lengthy function call, i.e.

```<code>from time import sleep

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    sleep(5)
    run_lengthy_function(self)
</code>```

答:
The repaint is called in event loop so sleep the whole thread does not change anything.

You can call repaint manually by:

```<code>self.startDialogTextEdit.repaint()
</code>```

or call static method:

```<code>QCoreApplication.processEvents()
</code>```

which also call repaint internally

Body:
My question concerns PyQT5.
I try to have a dialog window with a button that when clicked

updates some text of a QTextEdit field

calls a function (which needs much time to terminate)

Something like this:

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    run_lengthy_function(self)

However, when I run my GUI I notice that the text is updated only after the lengthy function has terminated, although the QTextEdit.append is called before the lengthy function. How can I enforce that the text is updated in advance?

What I tried so far (but didn't work) was to let Python wait some time before triggering the lengthy function call, i.e.

from time import sleep

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    sleep(5)
    run_lengthy_function(self)

Body:
The repaint is called in event loop so sleep the whole thread does not change anything.

You can call repaint manually by:

self.startDialogTextEdit.repaint()

or call static method:

QCoreApplication.processEvents()

which also call repaint internally