问:
Change toggle state for multiple elements and need to keep in localstorage when page refresh
There are multiple collapsible panels and a particular panel gets collapsed when a button placed on a that panel is clicked.This button is toggled as plus and minus icon when clicked over.Collapsed panels and button icon should remain in the same state on page refresh. Panel part is working fine but toggle button does not remain in the same state i.e. plus icon is toggled to minus icon on click but when clicked again it remains as minus icon only instead of changing back to plus icon. I am using localstorage for saving the state for both panel and button. But I am missing the right approach for button somewhere. I am new to jquery and tried all answers given here and on other platform but not able to make out the exact issue. Please help to point out what is going wrong. if need any other info,please let me know.

```<code><div class="row">
<div class="col-md-8 col-sm-6 col-xs-12">
<div class="panel panel-primary">
<div class="panel panel-heading" style="height: 45px;">
<h4 class="text-center" ><span class="glyphicon glyphicon-film" aria-hidden="true" style="padding-right: 10px;"></span>Name
<span data-toggle="collapse" data-target="#{{ template }}">
<span class="more-less pull-right" aria-hidden="true" id="{{ icon }}" ><i class="glyphicon glyphicon-plus-sign"></i></span>
</span>
</h4>
</div>
<div class="panel-collapse collapse" id="{{ template }}">
<div class="panel-body">
<div class="row">
<div class="col-md-4 col-sm-6 col-xs-12"><p class="lead"><b>Duration : </b> 1 Hour</p></div>
<div class="col-md-1 col-sm-6 col-xs-12"></div>
<div class="col-md-4 col-sm-6 col-xs-12"><h4 class="text-muted "><code>Module Topics</code></h4></div>
<div class="col-md-1 col-sm-6 col-xs-12"></div>
<div class="col-md-2 col-sm-6 col-xs-12">
</div>
</div>
</code>```

Jquery:

```<code>    $(".more-less").click(function ()
    {
        $(this).find('i').toggleClass('glyphicon-plus-sign').toggleClass('glyphicon-minus-sign');
        var active = $(this).attr('id');
        var activeclass = $(this).find('i').attr('class');
        var gicon= localStorage.gicon === undefined ? new Array() : JSON.parse(localStorage.gicon);
        if ($.inArray(active,gicon)==-1) //check that the element is not in the array
            gicon.push(active);
            gicon.push(activeclass);
        localStorage.gicon=JSON.stringify(gicon);
    });

    $(document).ready(function() {
    var gicon=localStorage.gicon === undefined ? new Array() : JSON.parse(localStorage.gicon);
        for (var i in gicon){
            if ($("#"+gicon[i]).find('i').hasClass('glyphicon-plus-sign'))
            {
                $("#"+gicon[i]).html('<i  class="glyphicon glyphicon-minus-sign"></i>');

            }
        }
    });
</code>```

答:
Here is working example https://jsfiddle.net/sL2tmrsd/ - use this to test.
I refactored your code.

Please keep in mind to never use new Array() use [] instead.

Stackoverflow's code snippet is not working with localStorage so don't bother clicking "Run code snippet".

   $(document).ready(function() {

  function expandPanelOnInit() {
   var activePanel = localStorage.getItem('activePanel');

   // We exit function if activePanel is not set yet
   if (activePanel === null) {
    return;
   }

   $('a[aria-controls="' + activePanel + '"]')
    .removeClass('collapsed')
    .attr('aria-expanded', true)
    .find('i').toggleClass('glyphicon-plus-sign glyphicon-minus-sign');

   $('#' + activePanel).addClass('in');

  }

  expandPanelOnInit();

        $('a[role="button"]').click(function() {
          var id = $(this).attr('aria-controls');
    var _thisIcon = $(this).find('i');

    localStorage.setItem('activePanel', id);

    $('#accordion i.glyphicon').not(_thisIcon)
   .removeClass('glyphicon-minus-sign')
   .addClass('glyphicon-plus-sign');

    _thisIcon.toggleClass('glyphicon-plus-sign glyphicon-minus-sign');

        });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingOne">
      <h4 class="panel-title">

          <i class="glyphicon glyphicon-plus-sign"></i>

      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingTwo">
      <h4 class="panel-title">

          <i class="glyphicon glyphicon-plus-sign"></i>

      </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingThree">
      <h4 class="panel-title">

          <i class="glyphicon glyphicon-plus-sign"></i>

      </h4>
    </div>
    <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>
  </code>```

Body:
There are multiple collapsible panels and a particular panel gets collapsed when a button placed on a that panel is clicked.This button is toggled as plus and minus icon when clicked over.Collapsed panels and button icon should remain in the same state on page refresh. Panel part is working fine but toggle button does not remain in the same state i.e. plus icon is toggled to minus icon on click but when clicked again it remains as minus icon only instead of changing back to plus icon. I am using localstorage for saving the state for both panel and button. But I am missing the right approach for button somewhere. I am new to jquery and tried all answers given here and on other platform but not able to make out the exact issue. Please help to point out what is going wrong. if need any other info,please let me know.

Name

Duration :  1 Hour

Module Topics

Jquery:

    $(".more-less").click(function ()
    {
        $(this).find('i').toggleClass('glyphicon-plus-sign').toggleClass('glyphicon-minus-sign');
        var active = $(this).attr('id');
        var activeclass = $(this).find('i').attr('class');
        var gicon= localStorage.gicon === undefined ? new Array() : JSON.parse(localStorage.gicon);
        if ($.inArray(active,gicon)==-1) //check that the element is not in the array
            gicon.push(active);
            gicon.push(activeclass);
        localStorage.gicon=JSON.stringify(gicon);
    });

    $(document).ready(function() {
    var gicon=localStorage.gicon === undefined ? new Array() : JSON.parse(localStorage.gicon);
        for (var i in gicon){
            if ($("#"+gicon[i]).find('i').hasClass('glyphicon-plus-sign'))
            {
                $("#"+gicon[i]).html('');

            }
        }
    });

Body:
Here is working example https://jsfiddle.net/sL2tmrsd/ - use this to test.
I refactored your code.

Please keep in mind to never use new Array() use [] instead.

Stackoverflow's code snippet is not working with localStorage so don't bother clicking "Run code snippet".

   $(document).ready(function() {

  function expandPanelOnInit() {
   var activePanel = localStorage.getItem('activePanel');

   // We exit function if activePanel is not set yet
   if (activePanel === null) {
    return;
   }

   $('a[aria-controls="' + activePanel + '"]')
    .removeClass('collapsed')
    .attr('aria-expanded', true)
    .find('i').toggleClass('glyphicon-plus-sign glyphicon-minus-sign');

   $('#' + activePanel).addClass('in');

  }

  expandPanelOnInit();

        $('a[role="button"]').click(function() {
          var id = $(this).attr('aria-controls');
    var _thisIcon = $(this).find('i');

    localStorage.setItem('activePanel', id);

    $('#accordion i.glyphicon').not(_thisIcon)
   .removeClass('glyphicon-minus-sign')
   .addClass('glyphicon-plus-sign');

    _thisIcon.toggleClass('glyphicon-plus-sign glyphicon-minus-sign');

        });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingOne">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
          <i class="glyphicon glyphicon-plus-sign"></i>
        </a>
      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingTwo">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          <i class="glyphicon glyphicon-plus-sign"></i>
        </a>
      </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingThree">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          <i class="glyphicon glyphicon-plus-sign"></i>
        </a>
      </h4>
    </div>
    <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
Simple.OData.Client returns no results
I trying to use Simple.OData.Client within PCL Xamarin.Forms project, but it doesn't return anything.

This is my code:

```<code>Simple.OData.Client.ODataClient clientOData = new Simple.OData.Client.ODataClient("http://services.odata.org/Northwind/Northwind.svc/");

var cust = await clientOData.For("Customers").FindEntriesAsync();
</code>```

答: This code is similar to what the library has in its integration tests (which pass). What do you mean by that it doesn't return anything? Does it fail? Returns an empty result?</p>

ContentLicense: CC BY-SA 3.0

Title: Simple.OData.Client returns no results

Body:
I trying to use Simple.OData.Client within PCL Xamarin.Forms project, but it doesn't return anything.

This is my code:

Simple.OData.Client.ODataClient clientOData = new Simple.OData.Client.ODataClient("http://services.odata.org/Northwind/Northwind.svc/");

var cust = await clientOData.For("Customers").FindEntriesAsync();


问:
How to use createWindow in my code [Qt5.8]
In the following code , when new tab or window is requested by the site then it doesn't prints anything . How do I make my code working ? Please Help , I am too confused . Thanks !</p>

```<code>class WebView:public QWebEngineView{
protected:
    QWebEngineView* createWindow(QWebEnginePage::WebWindowType type){
        switch(type){
        case QWebEnginePage::WebBrowserTab: {
                std::cout<<"Tab Requested"<<std::endl;
                return new QWebEngineView();
            }
            case QWebEnginePage::WebBrowserBackgroundTab: {
                std::cout<<"Background Tab Requested"<<std::endl;
                return new QWebEngineView();
            }
            case QWebEnginePage::WebBrowserWindow: {
                std::cout<<"window Requested"<<std::endl;
                return new QWebEngineView();
            }
            case QWebEnginePage::WebDialog: {
                std::cout<<"popup Requested"<<std::endl;
                return new QWebEngineView();
            }
            }
            return nullptr;
        }
public:
    QString home_page;
    QWebEngineView* view=new QWebEngineView();
    WebView(QString page=QString("https://google.com")){
        this->home_page=page;
        this->view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);
        createWebView();
    }
    void createWebView(){
        this->view->load(QUrl(this->home_page));
    }
</code>```

答:
The createWindow function is implemented for members of the WebView class, not for the view member.

```<code>#include <QApplication>

#include <QWebEngineView>
#include <QWebEngineSettings>
#include <iostream>

class WebView : public QWebEngineView
{
public:
    WebView(QString page=QString("https://google.com"), QWidget *parent = Q_NULLPTR):QWebEngineView(parent)
    {
        home_page = page;
        settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
    }

    void createWebView(){
        load(QUrl(home_page));
    }

protected:
    QWebEngineView* createWindow(QWebEnginePage::WebWindowType type){
        switch(type){
        case QWebEnginePage::WebBrowserTab: {
            std::cout<<"Tab Requested"<<std::endl;
            return new QWebEngineView();
        }
        case QWebEnginePage::WebBrowserBackgroundTab: {
            std::cout<<"Background Tab Requested"<<std::endl;
            return new QWebEngineView();
        }
        case QWebEnginePage::WebBrowserWindow: {
            std::cout<<"window Requested"<<std::endl;
            return new QWebEngineView();
        }
        case QWebEnginePage::WebDialog: {
            std::cout<<"popup Requested"<<std::endl;
            return new QWebEngineView();
        }
        }
        return nullptr;
    }

private:
    QString home_page;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    WebView web;
    web.createWebView();
    web.show();

    return a.exec();
}
</code>```

Body:
In the following code , when new tab or window is requested by the site then it doesn't prints anything . How do I make my code working ? Please Help , I am too confused . Thanks !

class WebView:public QWebEngineView{
protected:
    QWebEngineView* createWindow(QWebEnginePage::WebWindowType type){
        switch(type){
        case QWebEnginePage::WebBrowserTab: {
                std::cout<<"Tab Requested"<<std::endl;
                return new QWebEngineView();
            }
            case QWebEnginePage::WebBrowserBackgroundTab: {
                std::cout<<"Background Tab Requested"<<std::endl;
                return new QWebEngineView();
            }
            case QWebEnginePage::WebBrowserWindow: {
                std::cout<<"window Requested"<<std::endl;
                return new QWebEngineView();
            }
            case QWebEnginePage::WebDialog: {
                std::cout<<"popup Requested"<<std::endl;
                return new QWebEngineView();
            }
            }
            return nullptr;
        }
public:
    QString home_page;
    QWebEngineView* view=new QWebEngineView();
    WebView(QString page=QString("https://google.com")){
        this->home_page=page;
        this->view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);
        createWebView();
    }
    void createWebView(){
        this->view->load(QUrl(this->home_page));
    }

Body:
The createWindow function is implemented for members of the WebView class, not for the view member.

#include <QApplication>

#include <QWebEngineView>
#include <QWebEngineSettings>
#include <iostream>

class WebView : public QWebEngineView
{
public:
    WebView(QString page=QString("https://google.com"), QWidget *parent = Q_NULLPTR):QWebEngineView(parent)
    {
        home_page = page;
        settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
    }

    void createWebView(){
        load(QUrl(home_page));
    }

protected:
    QWebEngineView* createWindow(QWebEnginePage::WebWindowType type){
        switch(type){
        case QWebEnginePage::WebBrowserTab: {
            std::cout<<"Tab Requested"<<std::endl;
            return new QWebEngineView();
        }
        case QWebEnginePage::WebBrowserBackgroundTab: {
            std::cout<<"Background Tab Requested"<<std::endl;
            return new QWebEngineView();
        }
        case QWebEnginePage::WebBrowserWindow: {
            std::cout<<"window Requested"<<std::endl;
            return new QWebEngineView();
        }
        case QWebEnginePage::WebDialog: {
            std::cout<<"popup Requested"<<std::endl;
            return new QWebEngineView();
        }
        }
        return nullptr;
    }

private:
    QString home_page;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    WebView web;
    web.createWebView();
    web.show();

    return a.exec();
}


问:
making all input fields borders red when no one at least was filled in
I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.

HTML

```<code><form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form>
</code>```

JavaScript

```<code>$(function(){
  $("#myform").submit(function(){

    var valid=0;
    $(this).find('input[type=text]').each(function(){
        if($(this).val() != "") valid+=1;
    });

    if(valid){
        return true;
    }
    else {
        alert("error: you must fill in at least one field");
        return false;
    }
  });
});
</code>```

Thanks

答:
How about this ?

$(function(){
  $("#myform").submit(function(){
    var dirty = false;
    $('input[type=text]').each(function(){
        if($(this).val().length){
          dirty = true;
        }
    });
    if(!dirty){
      $('input[type=text]').each(function(){
        $(this).css('border','1px solid red');
      });
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form></code>```

Body:
I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.

HTML

<form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form>

JavaScript

$(function(){
  $("#myform").submit(function(){

    var valid=0;
    $(this).find('input[type=text]').each(function(){
        if($(this).val() != "") valid+=1;
    });

    if(valid){
        return true;
    }
    else {
        alert("error: you must fill in at least one field");
        return false;
    }
  });
});

Thanks

Body:
How about this ?

$(function(){
  $("#myform").submit(function(){
    var dirty = false;
    $('input[type=text]').each(function(){
        if($(this).val().length){
          dirty = true;
        }
    });
    if(!dirty){
      $('input[type=text]').each(function(){
        $(this).css('border','1px solid red');
      });
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form>


问:
Configuring frequency of notifications for requesting location updates
I'm trying to resolve a small problem:

```<code>mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, mLocationListener);
</code>```

So I assumed that mLocationListener should wait for 2 mainutes before calling it's onLocationChanged method. However, the method is called right after I send geo fix updates to emulator, every time I do it. Did I misunderstand the android developers guide, and do I have to to use timers or anything similar for organizing update rate I need?

答: I think you're confused as to how the updates work. You can't tell the GPS hardware to send you an update at a specific time in the future. You can only give it guidelines on when you'd like to be updated. With the minTime you're saying you don't want updates more frequently than every 2 minutes, but then you're using a min distance of zero when you setup your listener. That tells the underlying GPS driver to send you an update whenever the location changes distance by any amount. That's why you're getting updates immediately when you send in a new point.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to resolve a small problem:

mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, mLocationListener);

So I assumed that mLocationListener should wait for 2 mainutes before calling it's onLocationChanged method. However, the method is called right after I send geo fix updates to emulator, every time I do it. Did I misunderstand the android developers guide, and do I have to to use timers or anything similar for organizing update rate I need?


问:
regex select not commented statements
```<code>echo '```'; print_r(1); echo '```';  <- select this

 echo '```'; print_r($temp); echo '```';  <- select this without space

// echo '```'; print_r($temp); echo '```';  <- skip this

echo '```'; print_r($temp3); echo '```';  <- select this

print_r($temp1);  <- select this

// print_r($temp11);  <- skip this

    print_r($temp2);  <- select this without spaces

    if (true) {
        print_r($temp4);  <- select this without spaces

    }
</code>```

I have a code with print statements I need to select only non commented statements

here is a regex

```<code>^((?!\/\/\s?))(echo '```';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?
```

DEMO

how to skip spaces ?'      print_r($temp4);'
or how can I change regex to make it work ?

答:
```<code>import re

rgx = re.compile('^[ \t]*((echo|print_r).*;)', re.MULTILINE)
for line in rgx.finditer(code):
    print line.group(1)

# echo '```'; print_r(1); echo '```';
# echo '```'; print_r($temp); echo '```';
# echo '```'; print_r($temp3); echo '```';
# print_r($temp1);
# print_r($temp2);
# print_r($temp4);
</code>```

Title: regex select not commented statements

Body:
echo '
'; print_r(1); echo '
';  <- select this

 echo '
'; print_r($temp); echo '
';  <- select this without space

// echo '
'; print_r($temp); echo '
';  <- skip this

echo '
'; print_r($temp3); echo '
';  <- select this

print_r($temp1);  <- select this

// print_r($temp11);  <- skip this

    print_r($temp2);  <- select this without spaces

    if (true) {
        print_r($temp4);  <- select this without spaces

    }

I have a code with print statements I need to select only non commented statements

here is a regex

^((?!\/\/\s?))(echo '
';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?

DEMO

how to skip spaces ?'      print_r($temp4);'
or how can I change regex to make it work ?

Body:
import re

rgx = re.compile('^[ \t]*((echo|print_r).*;)', re.MULTILINE)
for line in rgx.finditer(code):
    print line.group(1)

# echo '<pre>'; print_r(1); echo '</pre>';
# echo '<pre>'; print_r($temp); echo '</pre>';
# echo '<pre>'; print_r($temp3); echo '</pre>';
# print_r($temp1);
# print_r($temp2);
# print_r($temp4);


问:
Vue equivalent of setTimeout?
I'm making a shopping cart system with Laravel and Vue. When I add an item to the basket, I display a confirmation message by toggling a Vue variable being watched by a v-if:

```<code><div class="alert alert-success" v-if="basketAddSuccess" transition="expand">Added to the basket</div>
</code>```

And the JS:

```<code>addToBasket: function(){
                item = this.product;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
            }
</code>```

(And yes, I will be adding this in a then-catch shortly).

This works fine and the message appears. However, I'd like the message to disappear again after a certain time, say a few seconds. How can I do this with Vue? I've tried setTimeOut but Vue doesn't seem to like it, saying it's undefined.

EDIT: I was misspelling setTimeout like an idiot. However, it still doesn't work:

My function is now:

```<code>addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                setTimeout(function(){
                    this.basketAddSuccess = false;
                }, 2000);
            }
</code>```

答:
after encountering the same issue, I ended up on this thread. For future generation's sake: The current up-most voted answer, attempts to bind "this" to a variable in order to avoid changing the context when invoking the function which is defined in the setTimeout.

An alternate and more recommended approach(using Vue.JS 2.2 & ES6) is to use an arrow function in order to bind the context to the parent (Basically "addToBasket"'s "this" and the "setTimeout"'s "this" would still refer to the same object):

```<code>addToBasket: function(){
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        setTimeout(() => {
            this.basketAddSuccess = false;
        }, 2000);
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Vue equivalent of setTimeout?

Body:
I'm making a shopping cart system with Laravel and Vue. When I add an item to the basket, I display a confirmation message by toggling a Vue variable being watched by a v-if:

Added to the basket

And the JS:

addToBasket: function(){
                item = this.product;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
            }

(And yes, I will be adding this in a then-catch shortly).

This works fine and the message appears. However, I'd like the message to disappear again after a certain time, say a few seconds. How can I do this with Vue? I've tried setTimeOut but Vue doesn't seem to like it, saying it's undefined.

EDIT: I was misspelling setTimeout like an idiot. However, it still doesn't work:

My function is now:

addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                setTimeout(function(){
                    this.basketAddSuccess = false;
                }, 2000);
            }

Body:
after encountering the same issue, I ended up on this thread. For future generation's sake: The current up-most voted answer, attempts to bind "this" to a variable in order to avoid changing the context when invoking the function which is defined in the setTimeout.

An alternate and more recommended approach(using Vue.JS 2.2 & ES6) is to use an arrow function in order to bind the context to the parent (Basically "addToBasket"'s "this" and the "setTimeout"'s "this" would still refer to the same object):

addToBasket: function(){
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        setTimeout(() => {
            this.basketAddSuccess = false;
        }, 2000);
    }


问:
Java Bukkit API - Get LastDamageCause Entity in PlayerMoveMent Event
So I am trying to figure out how to get the last damage cause when a player reaches the void in minecraft. However, I cannot find a way how to get the damager.

So here is my event handler

```<code>@EventHandler
public void on(PlayerMoveEvent event)
{
    Player player = (Player)event.getPlayer();

    if (event.getTo().getY() <= 20.0)
    {
        Entity damager = (Player) event.getPlayer().getLastDamageCause().getEntity();

        if(damager instanceof Player)
        {
            if(player.getLastDamageCause().getEntity().equals(damager))
            {
                damager.sendMessage("KILLER WORKING");
                player.sendMessage("WOKRING!!!!");
            }
        }
    }
}
</code>```

Somehow when I got damaged (player), it gives both messages. Can anyone help me? Thanks!

答:
You recieve both messages since both the player and damager are the same at that time.

You get the entity from getLastDamageCause().getEntity(), store it into the damager object. Then check if the damager is equals to the getLastDamageCause().getEntity(), which always will returns true.

To solve your problem, according to this topic "getEntity() returns the subject of the DamageEvent, not the damager. To get the damager, you need to check:"

```<code>if(player.getLastDamageCause() instanceof EntityDamageByEntityEvent)
    Player damager = ((EntityDamageByEntityEvent) player.getLastDamageCause()).getDamager();
</code>```

That code returns the player who damages a player, for an entity I do not know. But it seems you only need to check it if it's a player anyway.

By the way there is no need to cast event.getPlayer() into a player, since it's already a player.

Body:
So I am trying to figure out how to get the last damage cause when a player reaches the void in minecraft. However, I cannot find a way how to get the damager.

So here is my event handler

@EventHandler
public void on(PlayerMoveEvent event)
{
    Player player = (Player)event.getPlayer();

    if (event.getTo().getY() <= 20.0)
    {
        Entity damager = (Player) event.getPlayer().getLastDamageCause().getEntity();

        if(damager instanceof Player)
        {
            if(player.getLastDamageCause().getEntity().equals(damager))
            {
                damager.sendMessage("KILLER WORKING");
                player.sendMessage("WOKRING!!!!");
            }
        }
    }
}

Somehow when I got damaged (player), it gives both messages. Can anyone help me? Thanks!

Body:
You recieve both messages since both the player and damager are the same at that time.

You get the entity from getLastDamageCause().getEntity(), store it into the damager object. Then check if the damager is equals to the getLastDamageCause().getEntity(), which always will returns true.

To solve your problem, according to this topic "getEntity() returns the subject of the DamageEvent, not the damager. To get the damager, you need to check:"

if(player.getLastDamageCause() instanceof EntityDamageByEntityEvent)
    Player damager = ((EntityDamageByEntityEvent) player.getLastDamageCause()).getDamager();

That code returns the player who damages a player, for an entity I do not know. But it seems you only need to check it if it's a player anyway.

By the way there is no need to cast event.getPlayer() into a player, since it's already a player.


问:
PHP Search multidimensional array for value & get corresponding element value
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

```<code>Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)
</code>```

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

I've tried using array_search(31, $myArray) but it does not work...

答:
One-line solution using array_column and array_search functions:

```<code>$result = array_search(31, array_column($arr, 'key', 'field'));

print_r($result);   // CONSTRUCTN
</code>```

Or with simple foreach loop:

```<code>$search_key = 31;
$result = "";
foreach ($arr as $item) {   // $arr is your initial array
    if ($item['key'] == $search_key) {
        $result = $item['field'];
        break;
    }
}

print_r($result);   // CONSTRUCTN
</code>```

Body:
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

I've tried using array_search(31, $myArray) but it does not work...

Body:
One-line solution using array_column and array_search functions:

$result = array_search(31, array_column($arr, 'key', 'field'));

print_r($result);   // CONSTRUCTN

Or with simple foreach loop:

$search_key = 31;
$result = "";
foreach ($arr as $item) {   // $arr is your initial array
    if ($item['key'] == $search_key) {
        $result = $item['field'];
        break;
    }
}

print_r($result);   // CONSTRUCTN


问:
Firebase Retrieving data always null
I am using this method to retrieve data on Android, and it always returns null. Inside the ondatachange the listFinalBus is not null, but when the return comes, I get a null value.

Here is my code:

```<code>   public List<Bus> findAllBus() {
    // Read from the database
    myRef.child("Bus").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
            for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {

                Bus bus = userDataSnapshot.getValue(Bus.class);
                Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());

                listFinalBus.add(bus);
                Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

    Log.d(TAG, "onDataChange: list  firas return" + listFinalBus.size());
    //return is null
    return listFinalBus;
}
</code>```

答:
Your .addValueEventListener(listener) works async. So you will return your field fisrt which is null and after the call is done, your listener get called. But your field is already returned.
So to fix this, whether you write your own listener like:

```<code>interface MyCallback{
    void onSuccess(List<Bus> bus)
}
</code>```

and your code could be like:

```<code>public void findAllBus(MyCallback callback) {
// Read from the database
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
        for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {

            Bus bus = userDataSnapshot.getValue(Bus.class);
            Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());

            listFinalBus.add(bus);
            Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
        }
        callback.onSuccess(List<Bus> bus);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }

});

}
</code>```

So you can get your List no matter where you like.And just implements the Callback and pass it to your repository.

Or if you familiar with RxJava. You can pass an Observable which gonna like

```<code>public Observable<Bus> findAllBus(){
        return Observable.create(new ObservableOnSubscribe<Bus>() {
        @Override
        public void subscribe(ObservableEmitter<Bus> e) throws Exception {
            myRef.child("Bus").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
                    for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {

                        Bus bus = userDataSnapshot.getValue(Bus.class);
                        Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());

                        e.onNext(bus);
                        Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
                    }
                    e.onComplete();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    e.onError(error);
                }

            }
    });
}
</code>```

Title: Firebase Retrieving data always null

Body:
I am using this method to retrieve data on Android, and it always returns null. Inside the ondatachange the listFinalBus is not null, but when the return comes, I get a null value.

Here is my code:

   public List<Bus> findAllBus() {
    // Read from the database
    myRef.child("Bus").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
            for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {

                Bus bus = userDataSnapshot.getValue(Bus.class);
                Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());

                listFinalBus.add(bus);
                Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

    Log.d(TAG, "onDataChange: list  firas return" + listFinalBus.size());
    //return is null
    return listFinalBus;
}

Body:
Your .addValueEventListener(listener) works async. So you will return your field fisrt which is null and after the call is done, your listener get called. But your field is already returned.
So to fix this, whether you write your own listener like:

interface MyCallback{
    void onSuccess(List<Bus> bus)
}

and your code could be like:

public void findAllBus(MyCallback callback) {
// Read from the database
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
        for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {

            Bus bus = userDataSnapshot.getValue(Bus.class);
            Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());

            listFinalBus.add(bus);
            Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
        }
        callback.onSuccess(List<Bus> bus);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }

});

}

So you can get your List no matter where you like.And just implements the Callback and pass it to your repository.

Or if you familiar with RxJava. You can pass an Observable which gonna like

public Observable<Bus> findAllBus(){
        return Observable.create(new ObservableOnSubscribe<Bus>() {
        @Override
        public void subscribe(ObservableEmitter<Bus> e) throws Exception {
            myRef.child("Bus").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
                    for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {

                        Bus bus = userDataSnapshot.getValue(Bus.class);
                        Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());

                        e.onNext(bus);
                        Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
                    }
                    e.onComplete();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    e.onError(error);
                }

            }
    });
}


问:
is using eval() to run the contents of an html attribute safe?
So i'm simply trying to mimic some angular syntax and create some functionality of my own where I can add an html attribute: m-click="navigate('/signup')" and then evaluate the javascript inside.

var $scope = {};

$scope.navigate = function(url) {
  console.log('go to: "' + url + '"');
};

$('[m-click]').on('click', function(item) {
  eval('$scope.' + $(this).attr('m-click'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button m-click="navigate('/signup');">
  Sign Up
</button></code>```

What I'm wondering is:

is this how this is done with Angular and ng-click?

Is there another way to do this?

Is this safe, or is it prone to attacks?

答:
Is there another way to do this?

If you split the arguments, you could do it without an eval:

var $scope = {};

$scope.navigate = function(url) {
  console.log('go to: "' + url + '"');
};

$('[m-click]').on('click', function(item) {
  var $this = $(this);
  var func = $this.attr('m-click');
  var to = $this.attr('m-to');
  $scope[func](to);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button m-click="navigate" m-to="/signup">
  Sign Up
</button></code>```

Is this safe, or is it prone to attacks?

Not directly, but eval is in general unsafe. If you make a mistake in another place, every script code could be injected.

Body:
So i'm simply trying to mimic some angular syntax and create some functionality of my own where I can add an html attribute: m-click="navigate('/signup')" and then evaluate the javascript inside.

var $scope = {};

$scope.navigate = function(url) {
  console.log('go to: "' + url + '"');
};

$('[m-click]').on('click', function(item) {
  eval('$scope.' + $(this).attr('m-click'));
});

<button m-click="navigate('/signup');">
  Sign Up
</button>

What I'm wondering is:

is this how this is done with Angular and ng-click?

Is there another way to do this?

Is this safe, or is it prone to attacks?

Body:
Is there another way to do this?

If you split the arguments, you could do it without an eval:

var $scope = {};

$scope.navigate = function(url) {
  console.log('go to: "' + url + '"');
};

$('[m-click]').on('click', function(item) {
  var $this = $(this);
  var func = $this.attr('m-click');
  var to = $this.attr('m-to');
  $scope[func](to);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button m-click="navigate" m-to="/signup">
  Sign Up
</button>

Is this safe, or is it prone to attacks?

Not directly, but eval is in general unsafe. If you make a mistake in another place, every script code could be injected.


问:
using enable_if to specialize on return type from a base class
I'm porting a large code base to clang (builds with g++ and intel c++). Code similar to the following snippet compiles and works on g++ 4.8 - 6.2  but fails to compile with clang 3.8 and 3.9. The second invocation of the MinOp should (AFAICT) get the base class specialization ("Don't call me!"), but clang attempts to instantiate the std::min version and fails:

```<code>#include <algorithm>
#include <iostream>
#include <type_traits>

template <typename T> class Vector
{
public:
    Vector() : xyz{} {}
    Vector(T const &x, T const &y, T const &z) : xyz{y, y, z} {}
    Vector<T> min(Vector<T> const &v) { return Vector<T>(std::min(xyz[0], v.xyz[0]), std::min(xyz[1], v.xyz[1]), std::min(xyz[2], v.xyz[2])); }
    T xyz[3];
};

class MinOpBase
{
public:
    template <class T> typename std::enable_if<!std::is_fundamental<T>::value>::type
    operator()(Vector<T> &left, Vector<T> const &right) const { std::cout << "Don't call me!" << std::endl; }
};

class MinOp : public MinOpBase
{
public:
    template <typename T> void operator()(T &left, T const &right) const
    { left = std::min(left, right); }

    // Support component-wise min on vectors of fundamental types
    template <typename T> typename std::enable_if<std::is_fundamental<T>::value>::type
    operator() (Vector<T>  &left, Vector<T>  const &right) const
    {  left.min(right); }

    using MinOpBase::operator();
};

int main()
{
    Vector<double> v1, v2;
    Vector<Vector<double>> vv1, vv2;
    MinOp m;
    m(v1,v2);
    m(vv1,vv2);
}
</code>```

Note that if there is no base class (MinOpBase), and the "Don't call me!" specialization is directly in the MinOp class, clang works too.

Is this use of a using statement to bring in the specialization from the base class valid?

This looks to me like a whole bunch of machinery for not very much value (although of course this has been simplified almost to the point of pointlessness). Better ideas?

答:
A colleague pointed out that my question is a duplicate of
SFINAE not working on llvm/clang

I think the conclusion that clang is doing the "right" thing according to the standard is correct. From Johannes Schaub - litb's answer:

7.3.3 p15 of C++11 (the using declaration of the inherited function template is ignored because it has the same name and parameters as a
  member function template of the derived class)

Although the other compilers are doing what probably ought to be the "right" thing. I don't know if this has been reported as a defect in the standard.

Work-arounds include putting all specializations into base classes or modifying one of the argument types of one of the specializations.

Body:
I'm porting a large code base to clang (builds with g++ and intel c++). Code similar to the following snippet compiles and works on g++ 4.8 - 6.2  but fails to compile with clang 3.8 and 3.9. The second invocation of the MinOp should (AFAICT) get the base class specialization ("Don't call me!"), but clang attempts to instantiate the std::min version and fails:

#include <algorithm>
#include <iostream>
#include <type_traits>

template <typename T> class Vector
{
public:
    Vector() : xyz{} {}
    Vector(T const &x, T const &y, T const &z) : xyz{y, y, z} {}
    Vector<T> min(Vector<T> const &v) { return Vector<T>(std::min(xyz[0], v.xyz[0]), std::min(xyz[1], v.xyz[1]), std::min(xyz[2], v.xyz[2])); }
    T xyz[3];
};

class MinOpBase
{
public:
    template <class T> typename std::enable_if<!std::is_fundamental<T>::value>::type
    operator()(Vector<T> &left, Vector<T> const &right) const { std::cout << "Don't call me!" << std::endl; }
};

class MinOp : public MinOpBase
{
public:
    template <typename T> void operator()(T &left, T const &right) const
    { left = std::min(left, right); }

    // Support component-wise min on vectors of fundamental types
    template <typename T> typename std::enable_if<std::is_fundamental<T>::value>::type
    operator() (Vector<T>  &left, Vector<T>  const &right) const
    {  left.min(right); }

    using MinOpBase::operator();
};

int main()
{
    Vector<double> v1, v2;
    Vector<Vector<double>> vv1, vv2;
    MinOp m;
    m(v1,v2);
    m(vv1,vv2);
}

Note that if there is no base class (MinOpBase), and the "Don't call me!" specialization is directly in the MinOp class, clang works too.

Is this use of a using statement to bring in the specialization from the base class valid?

This looks to me like a whole bunch of machinery for not very much value (although of course this has been simplified almost to the point of pointlessness). Better ideas?


问:
How can I search through an array using a limit on the number of digits considered?
I have a function that searches a tuple of the format [(Double, Double)]. It finds a given x-value and if found, returns the corresponding y-value.

I need to alter it so that instead of searching for an exact x-value in the list of (x,y) pairs, it searches only up to the same number of digits after the decimal point of the given search term.

Example:

```<code>var a: [(Double, Double)] = [(0.0,0.0)]

a = [(0.1234, 0.0), (0.12345, 1.0), (0.123456, 2.0), (0.1234567, 3.0)]

//the current version of the function, this is what I need to change
func getValueFromTuples(tupleArr:[(Double,Double)],n:Double)->Double?{

    for tuple in tupleArr{

        if tuple.0 == n{

            return tuple.1

        }
    }

    return nil

}

print("Value:", getValueFromTuples(tupleArr: a, n: 0.1234)!)
//needs to return 0.0

print("Value:", getValueFromTuples(tupleArr: a, n: 0.12345)!)
//needs to return 1.0

print("Value:", getValueFromTuples(tupleArr: a, n: 0.123456)!)
//needs to return 2.0
</code>```

答:
One possible solution is to convert each number to a string and see if the "x" string begins with the "n" string.

```<code>func getValueFromTuples(tupleArr: [(Double,Double)], n: Double) -> Double? {
    let nStr = "\(n)"
    for tuple in tupleArr {
        let xStr = "\(tuple.0)"
        if xStr.hasPrefix(nStr) {
            return tuple.1
        }
    }

    return nil
}
</code>```

Note that this really only works if the "x" values of your tuple array are sorted correctly.

Body:
I have a function that searches a tuple of the format [(Double, Double)]. It finds a given x-value and if found, returns the corresponding y-value.

I need to alter it so that instead of searching for an exact x-value in the list of (x,y) pairs, it searches only up to the same number of digits after the decimal point of the given search term.

Example:

var a: [(Double, Double)] = [(0.0,0.0)]

a = [(0.1234, 0.0), (0.12345, 1.0), (0.123456, 2.0), (0.1234567, 3.0)]

//the current version of the function, this is what I need to change
func getValueFromTuples(tupleArr:[(Double,Double)],n:Double)->Double?{

    for tuple in tupleArr{

        if tuple.0 == n{

            return tuple.1

        }
    }

    return nil

}

print("Value:", getValueFromTuples(tupleArr: a, n: 0.1234)!)
//needs to return 0.0

print("Value:", getValueFromTuples(tupleArr: a, n: 0.12345)!)
//needs to return 1.0

print("Value:", getValueFromTuples(tupleArr: a, n: 0.123456)!)
//needs to return 2.0

Body:
One possible solution is to convert each number to a string and see if the "x" string begins with the "n" string.

func getValueFromTuples(tupleArr: [(Double,Double)], n: Double) -> Double? {
    let nStr = "\(n)"
    for tuple in tupleArr {
        let xStr = "\(tuple.0)"
        if xStr.hasPrefix(nStr) {
            return tuple.1
        }
    }

    return nil
}

Note that this really only works if the "x" values of your tuple array are sorted correctly.


问:
small python project - not sure if it's me or visual studio
I'm receiving an error in my code "name 'sales_total' is not defined" I'm working in python 3.6 in visual studio but not sure if it's me or visual studio. This is just my first type of project trying to get my feet wet in the basics but this is throwing me off. The code is below if anyone who has worked with visual studio could help.</p>

```<code>def sixerstix(sell_price, sales_total):

    sell_price = eval(input("What is the average sale price per ticket: "))
    sales_total = sell_price * 43

print("The total made for the season is ", sales_total)

sixerstix()
</code>```

答:
Your mistake is simply one of scope. The variable sales_total is defined inside the sixerstix() function; however you attempt to use the variable outside the function. A simple solution would be get rid of the function altogether, define the sell price and sales_total variables at the beginning of your code, and moving the body of the function outside.

```<code>sell_price = eval(input("What is the average sale price per ticket: "))
sales_total = sell_price * 43
print("The total made for the season is ", sales_total)
</code>```

Now the variable sales_total is defined globally and you can use it in your print() statement.

Body:
I'm receiving an error in my code "name 'sales_total' is not defined" I'm working in python 3.6 in visual studio but not sure if it's me or visual studio. This is just my first type of project trying to get my feet wet in the basics but this is throwing me off. The code is below if anyone who has worked with visual studio could help.

def sixerstix(sell_price, sales_total):

    sell_price = eval(input("What is the average sale price per ticket: "))
    sales_total = sell_price * 43

print("The total made for the season is ", sales_total)

sixerstix()

Body:
Your mistake is simply one of scope. The variable sales_total is defined inside the sixerstix() function; however you attempt to use the variable outside the function. A simple solution would be get rid of the function altogether, define the sell price and sales_total variables at the beginning of your code, and moving the body of the function outside.

sell_price = eval(input("What is the average sale price per ticket: "))
sales_total = sell_price * 43
print("The total made for the season is ", sales_total)

Now the variable sales_total is defined globally and you can use it in your print() statement.


问:
Change color of resource
I have a resource png of a house linked if you want to view it. It's basically just a dark home button.

I have it included and imported as an image asset as a drawable.

I'm attempting to set it as a button, but change it to be a white color programmatically.

Here's how I'm attempting to change the color to be white:

```<code>        ImageButton txtbtnAccept = new ImageButton(this);
        this._surveyHomeButton = txtbtnAccept;
        txtbtnAccept.setId(this.generateViewId());
        txtbtnAccept.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        layoutParams = (RelativeLayout.LayoutParams) txtbtnAccept.getLayoutParams();
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        layoutParams.height = 200;
        layoutParams.width = 200;
        txtbtnAccept.setScaleType(ImageView.ScaleType.FIT_CENTER);
        txtbtnAccept.setAdjustViewBounds(true);

        txtbtnAccept.setLayoutParams(layoutParams);

        txtbtnAccept.setBackgroundResource(0);
        txtbtnAccept.setVisibility(View.GONE);

        Bitmap homeImage = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_home);
        Drawable whiteImg = new BitmapDrawable(getResources(), homeImage);

        whiteImg.setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
        txtbtnAccept.setImageDrawable(whiteImg);
        txtbtnAccept.setImageBitmap(homeImage);
</code>```

Any idea where I'm going wrong?

答: What you want is called tinting. Have a look at DrawableCompat.setTint(Drawable, int).</p>

Title: Change color of resource

Body:
I have a resource png of a house linked if you want to view it. It's basically just a dark home button.

I have it included and imported as an image asset as a drawable.

I'm attempting to set it as a button, but change it to be a white color programmatically.

Here's how I'm attempting to change the color to be white:

        ImageButton txtbtnAccept = new ImageButton(this);
        this._surveyHomeButton = txtbtnAccept;
        txtbtnAccept.setId(this.generateViewId());
        txtbtnAccept.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        layoutParams = (RelativeLayout.LayoutParams) txtbtnAccept.getLayoutParams();
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        layoutParams.height = 200;
        layoutParams.width = 200;
        txtbtnAccept.setScaleType(ImageView.ScaleType.FIT_CENTER);
        txtbtnAccept.setAdjustViewBounds(true);

        txtbtnAccept.setLayoutParams(layoutParams);

        txtbtnAccept.setBackgroundResource(0);
        txtbtnAccept.setVisibility(View.GONE);

        Bitmap homeImage = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_home);
        Drawable whiteImg = new BitmapDrawable(getResources(), homeImage);

        whiteImg.setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
        txtbtnAccept.setImageDrawable(whiteImg);
        txtbtnAccept.setImageBitmap(homeImage);

Any idea where I'm going wrong?


问:
Handling Back button in Parent Activity
I have my main activity which contains 2 fragments:

MainActivity

```<code>public class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            FragmentOne fragmentOne = new FragmentOne ();

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragmentOne ).commit();

        }

    }
</code>```

This activity initially display fragment one.

Fragment one has a button which listens and when clicked it will replace itself with fragment two. When the button is clicked the interface in fragment one gets

```<code>//Main acitivty has this method which is a a method the interface in fragment one requires
@Override
    public void goToFragmentTwo() {

        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //  setSupportActionBar(toolbar);

        // Create fragment and give it an argument specifying the article it should show
         FragmentTwo fragmentTwo = new FragmentTwo ();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, fragmentTwo );
        transaction.addToBackStack(FragmentTwo.BACKSTACK_TAG);

        // Commit the transaction
        transaction.commit();
    }
</code>```

If the android back button or the back button in the toolbar gets called the fragments need to have a confirm dialog which asks are you sure you want to leave. If Ok then I have a second activity called the HomeActivity (this activity is the parent activity of MainActivity) which it needs to go to, or if cancel it needs to just close the dialog and stay in the current fragment.

So in the MainActivity I have overrode the onBackPressed method which displays a :

@Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

```<code>    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
                finish();
        }
    });
    builder.show();
}
</code>```

I am experiencing two problems with this code:

1) Pressing the back button in the toolbar doesn't display a dialog
2) The dialog's OK and Cancel features are not working correctly.

Essentially what I am trying to accomplish is I have a HomeActivity which has a button to navigate to the MainActivity. When the MainActivity gets called I will start a workflow where each fragment is a section of that workflow. If the back button is pressed this workflow needs to be discarded and the user should be returned back to the HomeActivty.

答:
i am assuming you are using ActionBar.

Try adding this in your activity:

```<code> @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return false;
}

 @Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            finish();
        }
    });
    builder.show();
}
</code>```

Title: Handling Back button in Parent Activity

Body:
I have my main activity which contains 2 fragments:

MainActivity

public class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentOneInteractionListener, FragmentTwo.OnFragmentTwoInteractionListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            FragmentOne fragmentOne = new FragmentOne ();

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, fragmentOne ).commit();

        }

    }

This activity initially display fragment one.

Fragment one has a button which listens and when clicked it will replace itself with fragment two. When the button is clicked the interface in fragment one gets

//Main acitivty has this method which is a a method the interface in fragment one requires
@Override
    public void goToFragmentTwo() {

        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //  setSupportActionBar(toolbar);

        // Create fragment and give it an argument specifying the article it should show
         FragmentTwo fragmentTwo = new FragmentTwo ();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, fragmentTwo );
        transaction.addToBackStack(FragmentTwo.BACKSTACK_TAG);

        // Commit the transaction
        transaction.commit();
    }

If the android back button or the back button in the toolbar gets called the fragments need to have a confirm dialog which asks are you sure you want to leave. If Ok then I have a second activity called the HomeActivity (this activity is the parent activity of MainActivity) which it needs to go to, or if cancel it needs to just close the dialog and stay in the current fragment.

So in the MainActivity I have overrode the onBackPressed method which displays a :

@Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
                finish();
        }
    });
    builder.show();
}

I am experiencing two problems with this code:

1) Pressing the back button in the toolbar doesn't display a dialog
2) The dialog's OK and Cancel features are not working correctly.

Essentially what I am trying to accomplish is I have a HomeActivity which has a button to navigate to the MainActivity. When the MainActivity gets called I will start a workflow where each fragment is a section of that workflow. If the back button is pressed this workflow needs to be discarded and the user should be returned back to the HomeActivty.

Body:
i am assuming you are using ActionBar.

Try adding this in your activity:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return false;
}

 @Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Do you want to leave? ");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MainActivity.super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            finish();
        }
    });
    builder.show();
}


问:
Unable to deserialize my json
This is my class

Initial one which actually needs to be transformed to good json data.
This is the initial bad one

```<code>{
    "channels": {
        "heart-rate": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.HeartRateChannelEvent, LTF.MyPlan.ActivityUtil",
                        "beatsPerMinute": 40,
                        "offset": 0
                    }
                ]
            }
        },
        "location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
                    }
                ]
            }
        }
    }
}

public class LocationChannelEvent : Activity.Channel.Event
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float? Distance { get; set; }
    public float? Altitude { get; set; }

    /// <summary>
    /// Speed in m/s
    /// </summary>
    public float? Speed { get; set; }
</code>```

This is my json data, which i am unable to deserialize. I keep receiving the default values, even when i change

```<code>{

"location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
            ]
        }
    }
}
</code>```

My Custom Coverter

```<code>public class CompactListConverter : JsonConverter
    {
        public const string TypeKey = "type";
        public const string StructureKey = "structure";
        public const string ListKey = "list";

    /// <summary>
    /// Only convert lists of non-enumerable class types.
    /// </summary>
    /// <param name="objectType"></param>
    /// <returns></returns>
    public override bool CanConvert(Type objectType)
    {
        var objectTypeInfo = objectType.GetTypeInfo();

        if (objectTypeInfo.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List<>))
        {
            var itemTypeInfo = objectTypeInfo.GenericTypeArguments.Single().GetTypeInfo();
            if (itemTypeInfo.IsClass && !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(itemTypeInfo))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    ///  Generates a wrapper object containing type, structure, and the condensed list.
    /// </summary>
    /// <param name="writer"></param>
    /// <param name="value"></param>
    /// <param name="serializer"></param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (IList)value;
        if (list.Count > 0)
        {
            var array = new JArray();
            var wrapper = GetWrapper(list, serializer);

            foreach (var item in list)
            {
                var obj = JObject.FromObject(item, serializer);
                var itemValues = new JArray();
                foreach (var prop in obj.Properties())
                {
                    itemValues.Add(prop.Value);
                }
                array.Add(itemValues);
            }

            wrapper.Add(ListKey, array);
            wrapper.WriteTo(writer);
        }
        else
        {
            new JObject().WriteTo(writer);
        }
    }

    private JObject GetWrapper(IList list, JsonSerializer serializer)
    {
        var wrapper = new JObject {{TypeKey, list[0].GetType().AssemblyQualifiedName}};

        var keys = new JArray();

        var first = JObject.FromObject(list[0], serializer);
        foreach (var prop in first.Properties())
        {
            keys.Add(new JValue(prop.Name));
        }

        wrapper.Add(StructureKey, keys);

        return wrapper;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var wrapper = JObject.Load(reader);
        var itemType = Type.GetType(wrapper.GetValue(TypeKey).ToObject<string>());
        var array = wrapper.GetValue(ListKey) as JArray;

        var list = existingValue as IList ?? (IList) Activator.CreateInstance(typeof (List<>).MakeGenericType(new[] {itemType}));

        if (array != null && array.Count > 0)
        {
            var keys = wrapper.GetValue(StructureKey) as JArray ?? new JArray();
            foreach (var itemValues in array.Children<JArray>())
            {
                var item = new JObject();
                for (var i = 0; i < keys.Count; i++)
                {
                    item.Add(new JProperty(keys[i].ToString(), itemValues[i]));
                }

                list.Add(item.ToObject(itemType, serializer));
            }
        }
        return list;
    }
}

public class ChannelCompactingConverter : CompactListConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return base.CanConvert(objectType)
                && typeof(IList<Activity.Channel.Event>).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
    }
</code>```

答:
You can use json.net to deserialize and re-serialize a List<LocationChannelEvent> in the format shown as long as you use a custom JsonConverer.  This is required because, by default, a collection of objects is serialized from and to a JSON array, but in your JSON, a collection of objects is being serialized in a slightly more compact form of a single object where the object property names are serialized only once in an array of strings called "structure", and the objects themselves are represented as an array of array of values, the inner arrays being in 1-1 correspondence to the structure array.

Thus, if you create the following converter:

```<code>public class StructuredListConverter<T> : JsonConverter
{
    const string typeName = "type";
    const string structureName = "structure";
    const string listName = "list";

    public override bool CanConvert(Type objectType)
    {
        if (!typeof(ICollection<T>).IsAssignableFrom(objectType))
            return false;
        // This converter is only implemented for read/write collections.  So no arrays.
        if (objectType.IsArray)
            return false;
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var collection = existingValue as ICollection<T> ?? (ICollection<T>) serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
        var root = JObject.Load(reader);
        var structure = root[structureName] == null ? null : root[structureName].ToObject<string []>();
        if (structure == null)
            throw new JsonSerializationException("structure not found.");
        var listToken = root[listName];
        if (listToken == null || listToken.Type == JTokenType.Null)
            return collection;
        var list = listToken as JArray;
        if (list == null)
            throw new JsonSerializationException("list was not an array.");
        if (list == null || list.Count == 0)
            return collection;
        foreach (var item in list)
        {
            if (item == null || item.Type == JTokenType.Null)
                collection.Add(default(T));
            else if (item.Type != JTokenType.Array)
                throw new JsonSerializationException(string.Format("Item was not an array: {0}", item));
            else
                collection.Add(new JObject(item.Zip(structure, (i, n) => new JProperty(n, i))).ToObject<T>());
        }
        return collection;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var contract = serializer.ContractResolver.ResolveContract(typeof(T)) as JsonObjectContract;
        if (contract == null)
            throw new JsonSerializationException(string.Format("Type {0} is not mapped to a JSON object.", typeof(T)));

        var collection = (ICollection<T>)value;
        writer.WriteStartObject();

        // Write item type
        writer.WritePropertyName(typeName);
        serializer.Serialize(writer, typeof(T));

        // Write structure (property names)
        var structure = contract.Properties.Where(p => p.Readable && !p.Ignored).Select(p => p.PropertyName).ToList();
        writer.WritePropertyName(structureName);
        serializer.Serialize(writer, structure);

        // Write array of array of values
        var query = collection
            .Select(i => i == null ? null : contract.Properties.Where(p => p.Readable && !p.Ignored).Select(p => p.ValueProvider.GetValue(i)));
        writer.WritePropertyName(listName);
        serializer.Serialize(writer, query);

        writer.WriteEndObject();
    }
}
</code>```

And define your data model as follows:

```<code>public class LocationChannelEvent : Activity.Channel.Event
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float? Distance { get; set; }
    public float? Altitude { get; set; }

    /// <summary>
    /// Speed in m/s
    /// </summary>
    public float? Speed { get; set; }
}

public class Location
{
    [JsonConverter(typeof(StructuredListConverter<LocationChannelEvent>))]
    public List<LocationChannelEvent> events { get; set; }
}

public class RootObject
{
    public Location location { get; set; }
}
</code>```

You will be able to deserialize and re-serialize the JSON shown.

Prototype fiddle.

Title: Unable to deserialize my json

Body:
This is my class

Initial one which actually needs to be transformed to good json data.
This is the initial bad one

{
    "channels": {
        "heart-rate": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.HeartRateChannelEvent, LTF.MyPlan.ActivityUtil",
                        "beatsPerMinute": 40,
                        "offset": 0
                    }
                ]
            }
        },
        "location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
                    }
                ]
            }
        }
    }
}

public class LocationChannelEvent : Activity.Channel.Event
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float? Distance { get; set; }
    public float? Altitude { get; set; }

    ///
    /// Speed in m/s
    ///
    public float? Speed { get; set; }

This is my json data, which i am unable to deserialize. I keep receiving the default values, even when i change

{

"location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
            ]
        }
    }
}

My Custom Coverter

public class CompactListConverter : JsonConverter
    {
        public const string TypeKey = "type";
        public const string StructureKey = "structure";
        public const string ListKey = "list";

    ///
    /// Only convert lists of non-enumerable class types.
    ///
    /// <param name="objectType"></param>
    /// <returns></returns>
    public override bool CanConvert(Type objectType)
    {
        var objectTypeInfo = objectType.GetTypeInfo();

        if (objectTypeInfo.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List<>))
        {
            var itemTypeInfo = objectTypeInfo.GenericTypeArguments.Single().GetTypeInfo();
            if (itemTypeInfo.IsClass && !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(itemTypeInfo))
            {
                return true;
            }
        }
        return false;
    }

    ///
    ///  Generates a wrapper object containing type, structure, and the condensed list.
    ///
    /// <param name="writer"></param>
    /// <param name="value"></param>
    /// <param name="serializer"></param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (IList)value;
        if (list.Count > 0)
        {
            var array = new JArray();
            var wrapper = GetWrapper(list, serializer);

            foreach (var item in list)
            {
                var obj = JObject.FromObject(item, serializer);
                var itemValues = new JArray();
                foreach (var prop in obj.Properties())
                {
                    itemValues.Add(prop.Value);
                }
                array.Add(itemValues);
            }

            wrapper.Add(ListKey, array);
            wrapper.WriteTo(writer);
        }
        else
        {
            new JObject().WriteTo(writer);
        }
    }

    private JObject GetWrapper(IList list, JsonSerializer serializer)
    {
        var wrapper = new JObject {{TypeKey, list[0].GetType().AssemblyQualifiedName}};

        var keys = new JArray();

        var first = JObject.FromObject(list[0], serializer);
        foreach (var prop in first.Properties())
        {
            keys.Add(new JValue(prop.Name));
        }

        wrapper.Add(StructureKey, keys);

        return wrapper;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var wrapper = JObject.Load(reader);
        var itemType = Type.GetType(wrapper.GetValue(TypeKey).ToObject<string>());
        var array = wrapper.GetValue(ListKey) as JArray;

        var list = existingValue as IList ?? (IList) Activator.CreateInstance(typeof (List<>).MakeGenericType(new[] {itemType}));

        if (array != null && array.Count > 0)
        {
            var keys = wrapper.GetValue(StructureKey) as JArray ?? new JArray();
            foreach (var itemValues in array.Children<JArray>())
            {
                var item = new JObject();
                for (var i = 0; i < keys.Count; i++)
                {
                    item.Add(new JProperty(keys[i].ToString(), itemValues[i]));
                }

                list.Add(item.ToObject(itemType, serializer));
            }
        }
        return list;
    }
}

public class ChannelCompactingConverter : CompactListConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return base.CanConvert(objectType)
                && typeof(IList<Activity.Channel.Event>).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
    }

Body:
You can use json.net to deserialize and re-serialize a List<LocationChannelEvent> in the format shown as long as you use a custom JsonConverer.  This is required because, by default, a collection of objects is serialized from and to a JSON array, but in your JSON, a collection of objects is being serialized in a slightly more compact form of a single object where the object property names are serialized only once in an array of strings called "structure", and the objects themselves are represented as an array of array of values, the inner arrays being in 1-1 correspondence to the structure array.

Thus, if you create the following converter:

public class StructuredListConverter<T> : JsonConverter
{
    const string typeName = "type";
    const string structureName = "structure";
    const string listName = "list";

    public override bool CanConvert(Type objectType)
    {
        if (!typeof(ICollection<T>).IsAssignableFrom(objectType))
            return false;
        // This converter is only implemented for read/write collections.  So no arrays.
        if (objectType.IsArray)
            return false;
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var collection = existingValue as ICollection<T> ?? (ICollection<T>) serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
        var root = JObject.Load(reader);
        var structure = root[structureName] == null ? null : root[structureName].ToObject<string []>();
        if (structure == null)
            throw new JsonSerializationException("structure not found.");
        var listToken = root[listName];
        if (listToken == null || listToken.Type == JTokenType.Null)
            return collection;
        var list = listToken as JArray;
        if (list == null)
            throw new JsonSerializationException("list was not an array.");
        if (list == null || list.Count == 0)
            return collection;
        foreach (var item in list)
        {
            if (item == null || item.Type == JTokenType.Null)
                collection.Add(default(T));
            else if (item.Type != JTokenType.Array)
                throw new JsonSerializationException(string.Format("Item was not an array: {0}", item));
            else
                collection.Add(new JObject(item.Zip(structure, (i, n) => new JProperty(n, i))).ToObject<T>());
        }
        return collection;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var contract = serializer.ContractResolver.ResolveContract(typeof(T)) as JsonObjectContract;
        if (contract == null)
            throw new JsonSerializationException(string.Format("Type {0} is not mapped to a JSON object.", typeof(T)));

        var collection = (ICollection<T>)value;
        writer.WriteStartObject();

        // Write item type
        writer.WritePropertyName(typeName);
        serializer.Serialize(writer, typeof(T));

        // Write structure (property names)
        var structure = contract.Properties.Where(p => p.Readable && !p.Ignored).Select(p => p.PropertyName).ToList();
        writer.WritePropertyName(structureName);
        serializer.Serialize(writer, structure);

        // Write array of array of values
        var query = collection
            .Select(i => i == null ? null : contract.Properties.Where(p => p.Readable && !p.Ignored).Select(p => p.ValueProvider.GetValue(i)));
        writer.WritePropertyName(listName);
        serializer.Serialize(writer, query);

        writer.WriteEndObject();
    }
}

And define your data model as follows:

public class LocationChannelEvent : Activity.Channel.Event
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float? Distance { get; set; }
    public float? Altitude { get; set; }

    /// <summary>
    /// Speed in m/s
    /// </summary>
    public float? Speed { get; set; }
}

public class Location
{
    [JsonConverter(typeof(StructuredListConverter<LocationChannelEvent>))]
    public List<LocationChannelEvent> events { get; set; }
}

public class RootObject
{
    public Location location { get; set; }
}

You will be able to deserialize and re-serialize the JSON shown.

Prototype fiddle.


问:
Time complexity recurrence relation
I need to find the recurrence relation:

```<code>int search(int[] a, int l, int h, int goal) {
    if (low == high) return 0;
    int tg = target(a, l, h);
    if (goal < target)
        return search(a, l, tg-1, goal);
    else if (goal > target)
        return search(a, tg +1, h, goal);
    else
        return a[tg];
}
</code>```

What would be the initial way to approach this question? I'm not asking for a solution, but just an initial way to approach it. Thanks!

答:
Since you are not asking about an exact solution (however, I can provide that if you want), I'm going to give you a hint, which is a very simple, yet not a well-known method of approaching such problems.

The crucial idea is to modify your function to a function which has probably worst complexity, but its expected complexity can be measured easily, let's call this modified function findTarget2:

```<code>public static int findTarget2 (int[] a, int low, int high, int goal) {
    if (low == high) return 0;
    int len = high - low + 1; //length of the array range, i.e. input size
    while (true) {
       int target = selectTarget(a, low, high);
       if (goal < target && target-low <= 3/4 * len)
          return findTarget2(a, low, target-1, goal);
       else if (goal > target && high-target <= 3/4 * len)
          return findTarget2(a, target+1, high, goal);
       else if (goal == target)
          return a[target];
    }

}
</code>```

Now, let f(n) be the time complexity of the original, and g(n) be the time complexity of the findTarget2 function, where n is the size of their input, i.e. the length of the array range equal high-low+1.

Now, let's say that selectTarget results in a bad execution if and only if it doesn't cause any return call inside the while's body.

The first observation is that g(n) >= f(n), because in a case of a bad execution, findTarget2 basically calls itself on the same input, while the original function reduces the size of input by at least 1. Thus, if have an upper bound for g(n), then the same bound applies to f(n).

Next, the expected time complexity of g(n) can be written as follows:

```<code>EX[g(n)] <= EX[g(3/4 * n) + X * O(n)]
</code>```

which can be written as follows using linearity of expected value:

```<code>EX[g(n)] <= EX[g(3/4 * n)] + EX[X] * O(n)
</code>```

where X is the random variable denoting the number of while loop executions until it results in return call, and the last O(n) is the non-recursive time spent in findTarget2 function, and it's O(n), because it is said that selectTarget function runs in that time.

Now your task is just to compute EX[X] and then you can use Master theorem to get the final expected time complexity of g(n), which is also an upper bound for the expected time complexity of f(n), so the upper bound of the complexity of the original function.

Title: Time complexity recurrence relation

Body:
I need to find the recurrence relation:

int search(int[] a, int l, int h, int goal) {
    if (low == high) return 0;
    int tg = target(a, l, h);
    if (goal < target)
        return search(a, l, tg-1, goal);
    else if (goal > target)
        return search(a, tg +1, h, goal);
    else
        return a[tg];
}

What would be the initial way to approach this question? I'm not asking for a solution, but just an initial way to approach it. Thanks!

Body:
Since you are not asking about an exact solution (however, I can provide that if you want), I'm going to give you a hint, which is a very simple, yet not a well-known method of approaching such problems.

The crucial idea is to modify your function to a function which has probably worst complexity, but its expected complexity can be measured easily, let's call this modified function findTarget2:

public static int findTarget2 (int[] a, int low, int high, int goal) {
    if (low == high) return 0;
    int len = high - low + 1; //length of the array range, i.e. input size
    while (true) {
       int target = selectTarget(a, low, high);
       if (goal < target && target-low <= 3/4 * len)
          return findTarget2(a, low, target-1, goal);
       else if (goal > target && high-target <= 3/4 * len)
          return findTarget2(a, target+1, high, goal);
       else if (goal == target)
          return a[target];
    }

}

Now, let f(n) be the time complexity of the original, and g(n) be the time complexity of the findTarget2 function, where n is the size of their input, i.e. the length of the array range equal high-low+1.

Now, let's say that selectTarget results in a bad execution if and only if it doesn't cause any return call inside the while's body.

The first observation is that g(n) >= f(n), because in a case of a bad execution, findTarget2 basically calls itself on the same input, while the original function reduces the size of input by at least 1. Thus, if have an upper bound for g(n), then the same bound applies to f(n).

Next, the expected time complexity of g(n) can be written as follows:

EX[g(n)] <= EX[g(3/4 * n) + X * O(n)]

which can be written as follows using linearity of expected value:

EX[g(n)] <= EX[g(3/4 * n)] + EX[X] * O(n)

where X is the random variable denoting the number of while loop executions until it results in return call, and the last O(n) is the non-recursive time spent in findTarget2 function, and it's O(n), because it is said that selectTarget function runs in that time.

Now your task is just to compute EX[X] and then you can use Master theorem to get the final expected time complexity of g(n), which is also an upper bound for the expected time complexity of f(n), so the upper bound of the complexity of the original function.