问:
Bootstrap mr-auto doesn't work
i am using bootstrap4 , and this is my code, I add  class mr-auto in the checkbox line, so i think the New use?Sign up now! should be at the right ,but it doesn't , what's the problem?

```<code><h1 class="text-center">Log in</h1>
<div class="row">
<div class="col-md-6 offset-md-3">
  <form action="/login" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="bhbKzszsGeADlAPkfoW4U58mGd9zfOy9mIl62R/gODqAFXevFsmTj//StPsLnrf8XpNlpkR+BHY6pgxlSlh8Og==" />
    <div class="form-group">
      <input type="text" name="email" id="email" class="form-control" placeholder="用户名/Email" autofocus="autofocus" />
    </div>
    <div class="form-group">
      <input type="password" name="password" id="password" class="form-control" placeholder="password" />
    </div>
    <input type="submit" name="commit" value="login" class="btn btn-primary btn-block" data-disable-with="login" />

    <div class="form-check mt-2 mr-auto d-inline-block">
      <label class="form-check-label p-0">
        <input type="checkbox" name="remember_me" id="remember_me" value="{:class=>"form-check-input "}" /> Remember me
      </label>
    </div>
    <p class=" d-inline-block">New user?<a href="/signup">Sign up now!</a></p>
    </form>
  </div>
</div>
</code>```

答:
It doesn't align because the auto margins won't work on inline-block elements.
Use float-right instead..

```<code><form action="/login" accept-charset="UTF-8" method="post">
    <input name="utf8" type="hidden" value="✓">
    <input type="hidden" name="authenticity_token" value="bhbKzszsGeADlAPkfoW4U58mGd9zfOy9mIl62R/gODqAFXevFsmTj//StPsLnrf8XpNlpkR+BHY6pgxlSlh8Og==">
    <div class="form-group">
        <input type="text" name="email" id="email" class="form-control" placeholder="用户名/Email" autofocus="autofocus">
    </div>
    <div class="form-group">
        <input type="password" name="password" id="password" class="form-control" placeholder="password">
    </div>
    <input type="submit" name="commit" value="login" class="btn btn-primary btn-block" data-disable-with="login">

    <div class="form-check mt-2 d-inline-block">
        <label class="form-check-label p-0">
            <input type="checkbox" name="remember_me" id="remember_me" value="{:class=>"form-check-input "}"> Remember me
        </label>
    </div>
    <p class="float-right mt-2 d-inline-block">New user?<a href="/signup">Sign up now!</a></p>
</form>
</code>```

http://www.codeply.com/go/0XCESDWKdG

Title: Bootstrap mr-auto doesn't work

Body:
i am using bootstrap4 , and this is my code, I add  class mr-auto in the checkbox line, so i think the New use?Sign up now! should be at the right ,but it doesn't , what's the problem?

Log in

  <form action="/login" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="bhbKzszsGeADlAPkfoW4U58mGd9zfOy9mIl62R/gODqAFXevFsmTj//StPsLnrf8XpNlpkR+BHY6pgxlSlh8Og==" />

      <input type="text" name="email" id="email" class="form-control" placeholder="用户名/Email" autofocus="autofocus" />

      <input type="password" name="password" id="password" class="form-control" placeholder="password" />

    <input type="submit" name="commit" value="login" class="btn btn-primary btn-block" data-disable-with="login" />

        <input type="checkbox" name="remember_me" id="remember_me" value="{:class=>"form-check-input "}" /> Remember me

New user?Sign up now!

    </form>

Body:
It doesn't align because the auto margins won't work on inline-block elements.
Use float-right instead..

<form action="/login" accept-charset="UTF-8" method="post">
    <input name="utf8" type="hidden" value="✓">
    <input type="hidden" name="authenticity_token" value="bhbKzszsGeADlAPkfoW4U58mGd9zfOy9mIl62R/gODqAFXevFsmTj//StPsLnrf8XpNlpkR+BHY6pgxlSlh8Og==">
    <div class="form-group">
        <input type="text" name="email" id="email" class="form-control" placeholder="用户名/Email" autofocus="autofocus">
    </div>
    <div class="form-group">
        <input type="password" name="password" id="password" class="form-control" placeholder="password">
    </div>
    <input type="submit" name="commit" value="login" class="btn btn-primary btn-block" data-disable-with="login">

    <div class="form-check mt-2 d-inline-block">
        <label class="form-check-label p-0">
            <input type="checkbox" name="remember_me" id="remember_me" value="{:class=>&quot;form-check-input &quot;}"> Remember me
        </label>
    </div>
    <p class="float-right mt-2 d-inline-block">New user?<a href="/signup">Sign up now!</a></p>
</form>

http://www.codeply.com/go/0XCESDWKdG


来源: stackexchange

问:
WCF REST GET returns "Endpoint not found"
So I am trying to create a very basic WCF service with REST GET but there is only "Endpoint not found". I am sending GET via Postman App to address:

```<code>http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/json
</code>```

Service is hosted by IIS; Here's all my code:

```<code>namespace RESTfulTest
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        string GetText();
    }
}

namespace RESTfulTest
{
    [ServiceBehavior(InstanceContextMode =InstanceContextMode.Single)]
    public class Service1 : IService1
    {
        public string GetText()
        {
            return "Hello REST";
        }
    }

}
</code>```

And App.config file:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RESTfulTest.Service1">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/" />
          </baseAddresses>
        </host>
        <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="RESTfulTest.IService1"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

  </system.serviceModel>

</configuration>
</code>```

What am I missing here?

答:
Are you going to be using ASP.NET Ajax to call the service? If not, you should not be using the <enableWebScript> behavior, but rather the <webHttp> behavior.

Also, you should probably remove the <serviceMetadata> behavior, since you won't be exposing WSDL from your service.

ContentLicense: CC BY-SA 3.0

Body:
So I am trying to create a very basic WCF service with REST GET but there is only "Endpoint not found". I am sending GET via Postman App to address:

http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/json

Service is hosted by IIS; Here's all my code:

namespace RESTfulTest
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        string GetText();
    }
}

namespace RESTfulTest
{
    [ServiceBehavior(InstanceContextMode =InstanceContextMode.Single)]
    public class Service1 : IService1
    {
        public string GetText()
        {
            return "Hello REST";
        }
    }

}

And App.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RESTfulTest.Service1">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8733/Design_Time_Addresses/RESTfulTest/Service1/" />
          </baseAddresses>
        </host>
        <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="RESTfulTest.IService1"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

  </system.serviceModel>

</configuration>

What am I missing here?


问:
How to create a universal jquery validate and reset function call
I am using the jquery validate plugin to create a validation method for all forms in an application. Using the jquery each() function to cycle each form and applyt the method. I want to achieve the reset using the same each method. how can i accomplish this?

This is the code that works:

```<code> $("form").each(function () {
        $(this).validate();
    });
</code>```

This is the code that doesn't

```<code>   $("form").each(function () {
        validator = $(this).validate();
        validator.resetForm();
        $("#reset").click(function () {
            validator.resetForm();
        });
    });
</code>```

Please advise..

答:
Without the var keyword, you're setting validator as a global variable, and changing what it's set to with each loop (so it'll be set the to the validator of the last form at the end), just add var when declaring it, like this:

```<code>$("form").each(function () {
   var validator = $(this).validate();  //add var here
   validator.resetForm();
   $("#reset").click(function () {
       validator.resetForm();
   });
});
</code>```

This will correct it so you'll reset each <form> once, rater than the last <form> n times.

ContentLicense: CC BY-SA 2.5

Body:
I am using the jquery validate plugin to create a validation method for all forms in an application. Using the jquery each() function to cycle each form and applyt the method. I want to achieve the reset using the same each method. how can i accomplish this?

This is the code that works:

 $("form").each(function () {
        $(this).validate();
    });

This is the code that doesn't

   $("form").each(function () {
        validator = $(this).validate();
        validator.resetForm();
        $("#reset").click(function () {
            validator.resetForm();
        });
    });

Please advise..

Body:
Without the var keyword, you're setting validator as a global variable, and changing what it's set to with each loop (so it'll be set the to the validator of the last form at the end), just add var when declaring it, like this:

$("form").each(function () {
   var validator = $(this).validate();  //add var here
   validator.resetForm();
   $("#reset").click(function () {
       validator.resetForm();
   });
});

This will correct it so you'll reset each <form> once, rater than the last <form> n times.


问:
trigger state of parent component
I have a modal wrapper and within it it has react-modal which is an npm module.

In the render method it open base on the this.props.isOpen

```<code><ReactModal
    contentLabel="modal-big"
    className="modal-big"
    isOpen={this.props.isOpen}
    shouldCloseOnOverlayClick={true}
>
    {this.content()}
</ReactModal>
</code>```

and within this.content I have button that should close the modal. But how to change the state of the parent? I can't call this.props.isOpen = false;

答:
You would need to define a function in the parent component that would set its state to closed for the modal and then pass not only the prop of open but also the function that will change the modal to be closed.

```<code>class ParentComponent extends Component {
  constructor() {
    super();

    this.state = {
      open: true
    }
  }

  _closeModal = () => {
    this.setState({
      open: false
    })
  }

  render() {
    return <ChildComponent closeModal={this._closeModal}

  }
}
</code>```

in your child component you would just executed this.props.closeModal and it would update the parents state and close the modal

Title: trigger state of parent component

Body:
I have a modal wrapper and within it it has react-modal which is an npm module.

In the render method it open base on the this.props.isOpen

<ReactModal
    contentLabel="modal-big"
    className="modal-big"
    isOpen={this.props.isOpen}
    shouldCloseOnOverlayClick={true}
>
    {this.content()}
</ReactModal>

and within this.content I have button that should close the modal. But how to change the state of the parent? I can't call this.props.isOpen = false;

Body:
You would need to define a function in the parent component that would set its state to closed for the modal and then pass not only the prop of open but also the function that will change the modal to be closed.

class ParentComponent extends Component {
  constructor() {
    super();

    this.state = {
      open: true
    }
  }

  _closeModal = () => {
    this.setState({
      open: false
    })
  }

  render() {
    return <ChildComponent closeModal={this._closeModal}

  }
}

in your child component you would just executed this.props.closeModal and it would update the parents state and close the modal


问:
bootstrap: how to active a menu?
I have a menu in my header.jsp file. like this:

```<code><ul class="nav nav-pills">

<li  class="active"><a href="index.jsp">home</a></li>

<li><a href="product.jsp">product</a></li>

</ul>
</code>```

Both index.jsp and product.jsp include header.jsp. By default, the Home item is selected and it is active. When I click product menu, it is navigated to product.jsp page, the product item should be active, my question is how to set the
Product
 as class="active"?

Your answer is appreciated. Great thanks.

答:
I know this is an old question, but if you are looking for a jQuery-based front-end solution you could do something like:

```<code>$(function() {
    $('ul.nav li a[href$="' + window.location.pathname+ '"]').parent().addClass("active");
});
</code>```

This will dynamically add an active class to the parent (in your case
) of the  element if the href attribute matches the URL path. The change you will need to make is to write the full path - so:

```<code><ul class="nav nav-pills">
  <li id="home"><a href="/actual/site/path/index.jsp">home</a></li>
  <li id="product"><a href="/actual/site/path/product.jsp">product</a></li>
</ul>
</code>```

This solution is not effected by hash or query parameters appended to the link as it only checks the path.

Title: bootstrap: how to active a menu?

Body:
I have a menu in my header.jsp file. like this:

home

product

Both index.jsp and product.jsp include header.jsp. By default, the Home item is selected and it is active. When I click product menu, it is navigated to product.jsp page, the product item should be active, my question is how to set the
Product
 as class="active"?

Your answer is appreciated. Great thanks.

Body:
I know this is an old question, but if you are looking for a jQuery-based front-end solution you could do something like:

$(function() {
    $('ul.nav li a[href$="' + window.location.pathname+ '"]').parent().addClass("active");
});

This will dynamically add an active class to the parent (in your case <li>) of the <a> element if the href attribute matches the URL path. The change you will need to make is to write the full path - so:

<ul class="nav nav-pills">
  <li id="home"><a href="/actual/site/path/index.jsp">home</a></li>
  <li id="product"><a href="/actual/site/path/product.jsp">product</a></li>
</ul>

This solution is not effected by hash or query parameters appended to the link as it only checks the path.


问:
Debugging Arduino Uno code running on Arduino MKR1000
So, I am an amateur programmer at Arduino, and have never used Arduino MKR1000 before. I used an Arduino Uno and wrote the attached code that detects heart beat and temperature using the Grove Ear clip heart beat sensor and the Grove Temperature sensor and then prints them in the console every 20 seconds. Previously, this code was written to show in an Grove OLED screen but later simplified it back to using it by reading on just the console.

Because of the wearable nature of my project I have to switch to using a MKR1000 instead. I know the MKR1000 uses the same Arduino code and should work the same way as it did on my Arduino Uno, but I have been having some issues with using the MKR1000 with the same code.

The issue is that the code only runs once and stops after that. While I am aware of the for loops and how it works to certain extent, I cannot find the exact issue why it stops looping instead of taking the data constantly and publishing it on the console, like it did previously with my Uno.

Just for the heads up, following is how my code reacted to Arduino Uno:

The result in the console shows:

  Please be ready
  This will now begin
```

<p>then it prints number 1 to 20 every second followed by sensor readings. After publishing this, it repeats this process again. </p>

<p>Again sorry for the inconvenience and thank you for your help.</p>

<p>I used direct codes from the documentation blog of the sensors (bottom of the page of the linked page):</p>

<p>Grove heart bear sensor</p>

<p>Grove Temperature sensor</p>

<pre class="lang-cpp prettyprint-override"><code>#define LED 4//indicator, Grove - LED is connected with D4 of Arduino
boolean led_state = LOW;//state of LED, each time an external interrupt
                                //will change the state of LED
float tempa;
int tempPin = 0;
unsigned char counter;
unsigned long temp[21];
unsigned long sub;
bool data_effect=true;
unsigned int heart_rate;//the measurement result of heart rate

const int max_heartpluse_duty = 2000;//you can change it follow your system's request.
                        //2000 meams 2 seconds. System return error
                        //if the duty overtrip 2 second.
void setup()
{

    pinMode(LED, OUTPUT);
    Serial.begin(9600);
 while (!Serial){
  ;
  }
    Serial.println("Please be ready");
    delay(5000);
    arrayInit();
    Serial.println("This will now begin.");
    attachInterrupt(0, interrupt, RISING);//set interrupt 0,digital port 2
}
void loop()
{
    digitalWrite(LED, led_state);//Update the state of the indicator
}
/*Function: calculate the heart rate*/

void sum()
{
 if(data_effect)
    {
        heart_rate=1200000/(temp[20]-temp[0]);//60*20*1000/20_total_time
        Serial.print("Heart_rate_is:\t");
        Serial.println(heart_rate);
        tempa = analogRead(tempPin);
        tempa = tempa * 0.11;
         Serial.print("Body Temperature = ");
         Serial.print(tempa);
         Serial.print("*C");
         Serial.println();
         delay(1000);
    }
   data_effect=1;//sign bit
}
/*Function: Interrupt service routine.Get the sigal from the external interrupt*/
void interrupt()
{
    temp[counter]=millis();
    Serial.println(counter,DEC);
    switch(counter)
    {
        case 0:
            sub=temp[counter]-temp[20];

            break;
        default:
            sub=temp[counter]-temp[counter-1];

            break;
    }
    if(sub>max_heartpluse_duty)//set 2 seconds as max heart pluse duty
    {
        data_effect=0;//sign bit
        counter=0;
        Serial.println("measurement error,test will restart!" );
        arrayInit();
    }
    else if (counter==20&&data_effect)
    {
      counter=0;
      sum();
    }
    else if(counter!=20&&data_effect)
    {
    counter++;
    }
    else
    {
        counter=0;
        data_effect=1;
    }

}
/*Function: Initialization for the array(temp)*/
void arrayInit()
{
    for(unsigned char i=0;i < 20;i ++)
    {
        temp[i]=0;
    }
    temp[20]=millis();
}
</code>```

答:
Your problem is the interrupt pin. On the Arduino UNO the digital pin D2 is interrupt pin 0, as you have done in your code. On the Arduino MKR1000 the interrupt pin is tha same as the physical pin number, so if you'r connecting to pin 2, change attachInterrupt(0, interrupt, RISING); to attachInterrupt(2, interrupt, RISING);

If you wanna be sure to use the right pin you can use digitalPinToInterrupt(pin) to get the correct interrupt number on any Arduino board. Like this attachInterrupt(digitalPinToInterrupt(pin), interrupt, RISING); where pin is the physical pin number.

Info

On the Arduino MKR1000 you can use pin 0, 1, 4, 5, 6, 7, 8, 9, A1 and A2 as interrupt

Body:
So, I am an amateur programmer at Arduino, and have never used Arduino MKR1000 before. I used an Arduino Uno and wrote the attached code that detects heart beat and temperature using the Grove Ear clip heart beat sensor and the Grove Temperature sensor and then prints them in the console every 20 seconds. Previously, this code was written to show in an Grove OLED screen but later simplified it back to using it by reading on just the console.

Because of the wearable nature of my project I have to switch to using a MKR1000 instead. I know the MKR1000 uses the same Arduino code and should work the same way as it did on my Arduino Uno, but I have been having some issues with using the MKR1000 with the same code.

The issue is that the code only runs once and stops after that. While I am aware of the for loops and how it works to certain extent, I cannot find the exact issue why it stops looping instead of taking the data constantly and publishing it on the console, like it did previously with my Uno.

Just for the heads up, following is how my code reacted to Arduino Uno:

The result in the console shows:

  Please be ready
  This will now begin

then it prints number 1 to 20 every second followed by sensor readings. After publishing this, it repeats this process again.

Again sorry for the inconvenience and thank you for your help.

I used direct codes from the documentation blog of the sensors (bottom of the page of the linked page):

Grove heart bear sensor

Grove Temperature sensor

#define LED 4//indicator, Grove - LED is connected with D4 of Arduino
boolean led_state = LOW;//state of LED, each time an external interrupt
                                //will change the state of LED
float tempa;
int tempPin = 0;
unsigned char counter;
unsigned long temp[21];
unsigned long sub;
bool data_effect=true;
unsigned int heart_rate;//the measurement result of heart rate

const int max_heartpluse_duty = 2000;//you can change it follow your system's request.
                        //2000 meams 2 seconds. System return error
                        //if the duty overtrip 2 second.
void setup()
{

    pinMode(LED, OUTPUT);
    Serial.begin(9600);
 while (!Serial){
  ;
  }
    Serial.println("Please be ready");
    delay(5000);
    arrayInit();
    Serial.println("This will now begin.");
    attachInterrupt(0, interrupt, RISING);//set interrupt 0,digital port 2
}
void loop()
{
    digitalWrite(LED, led_state);//Update the state of the indicator
}
/*Function: calculate the heart rate*/

void sum()
{
 if(data_effect)
    {
        heart_rate=1200000/(temp[20]-temp[0]);//60*20*1000/20_total_time
        Serial.print("Heart_rate_is:\t");
        Serial.println(heart_rate);
        tempa = analogRead(tempPin);
        tempa = tempa * 0.11;
         Serial.print("Body Temperature = ");
         Serial.print(tempa);
         Serial.print("*C");
         Serial.println();
         delay(1000);
    }
   data_effect=1;//sign bit
}
/*Function: Interrupt service routine.Get the sigal from the external interrupt*/
void interrupt()
{
    temp[counter]=millis();
    Serial.println(counter,DEC);
    switch(counter)
    {
        case 0:
            sub=temp[counter]-temp[20];

            break;
        default:
            sub=temp[counter]-temp[counter-1];

            break;
    }
    if(sub>max_heartpluse_duty)//set 2 seconds as max heart pluse duty
    {
        data_effect=0;//sign bit
        counter=0;
        Serial.println("measurement error,test will restart!" );
        arrayInit();
    }
    else if (counter==20&&data_effect)
    {
      counter=0;
      sum();
    }
    else if(counter!=20&&data_effect)
    {
    counter++;
    }
    else
    {
        counter=0;
        data_effect=1;
    }

}
/*Function: Initialization for the array(temp)*/
void arrayInit()
{
    for(unsigned char i=0;i < 20;i ++)
    {
        temp[i]=0;
    }
    temp[20]=millis();
}


问:
Cannot exit emacs within terminal in ubuntu 14.04
I'm running emacs in my terminal on ubuntu 14.04:

```<code>$ emacs -nw
</code>```

If I try to exit with C-x C-c, I see this in the chord space at the bottom:

```<code>C-x-
</code>```

I'm an Emacs newb but this looks like its trying to make a joined chord with the c key even though I lift my finger way up over the Ctrl key. If I just hit c I get

```<code>C-x c is undefined
</code>```

Now if I run emacs normally in the pop up editor, I'm able to exit just fine. What am I doing wrong?

答:
You might have overloaded the C-c command.

The default shortcut in ubuntu for the copy command is C-Shift-c, but some users change it to C-c in their settings.
If you've done that, emacs won't close at C-x C-c cause it's recognizing the C-c as the copy command.

Body:
I'm running emacs in my terminal on ubuntu 14.04:

$ emacs -nw

If I try to exit with C-x C-c, I see this in the chord space at the bottom:

C-x-

I'm an Emacs newb but this looks like its trying to make a joined chord with the c key even though I lift my finger way up over the Ctrl key. If I just hit c I get

C-x c is undefined

Now if I run emacs normally in the pop up editor, I'm able to exit just fine. What am I doing wrong?


问:
Divide the navbar into 3 equal parts
I have 3 menu items in my navbar. I want the entire nav to be divided into 3 parts for my 3 menus. I tried with the following code but the last menu item takes bit extra space than others. How do i fix it?

 .navbar {
         border : 1px solid #ffffff;
     }
     #intr1, #intr2 {
         border-right: 1px solid #ffffff;
     }
     .menuLabel {
         text-align: center;
         font-size: 17px;
         font-weight: bold;
         color: #ffffff;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <html>
    <head>
     <title></title>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    </head>
    <body>
    <div class="container-fluid">
     <div class="navbar navbar-inverse">
      <div class="navbar-header ">
             <ul class="nav navbar-nav container">
              <li class="col-md-4" id="intr1"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
              <li class="col-md-4" id="intr2"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
              <li class="col-md-4" id="intr3"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
             </ul>
           </div>
     </div>
    </div>

    </body>
    </html></code>```

答: Just remove the .container class on the .navbar-nav because that is causing you to have 15px right padding which throws off the evenness.

Title: Divide the navbar into 3 equal parts

Body:
I have 3 menu items in my navbar. I want the entire nav to be divided into 3 parts for my 3 menus. I tried with the following code but the last menu item takes bit extra space than others. How do i fix it?

 .navbar {
         border : 1px solid #ffffff;
     }
     #intr1, #intr2 {
         border-right: 1px solid #ffffff;
     }
     .menuLabel {
         text-align: center;
         font-size: 17px;
         font-weight: bold;
         color: #ffffff;
     }

     <title></title>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

INTERIOR DESIGN

INTERIOR DESIGN

INTERIOR DESIGN


问:
Xamarin PCL IllegalStateException when pressing back button to go out the app
I am having this error and I have tried to set a break point but unable to find which part of my code caused the problem. This problem will occur when I pressed the back button to go out the application. The stack trace below didn't show anything of my code either. Does anyone seen this problem before or how do i debug this type of problem.</p>

```<code>   Java.Lang.IllegalStateException: Activity has been destroyed
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3511/77cb8568/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method) [0x00084] in /Users/builder/data/lanes/3511/ce955cc0/source/Java.Interop/src/Java.Interop/Java.Interop/JniEnvironment.g.cs:11464
  at Android.Runtime.JNIEnv.CallIntMethod (System.IntPtr jobject, System.IntPtr jmethod) [0x00000] in /Users/builder/data/lanes/3511/ce955cc0/source/monodroid/src/Mono.Android/JNIEnv.g.cs:186
  at Android.Support.V4.App.FragmentTransactionInvoker.CommitAllowingStateLoss () [0x00033] in <27c17fe440cf491ba8255bcefade6e02>:0
  at Xamarin.Forms.Platform.Android.AppCompat.MasterDetailContainer.Dispose (System.Boolean disposing) [0x00042] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\MasterDetailContainer.cs:130
  at Java.Lang.Object.Dispose () [0x00000] in /Users/builder/data/lanes/3511/ce955cc0/source/xamarin-android/src/Mono.Android/Java.Lang/Object.cs:203
  at Xamarin.Forms.Platform.Android.AppCompat.MasterDetailPageRenderer.Dispose (System.Boolean disposing) [0x00046] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\MasterDetailPageRenderer.cs:192
  at Java.Lang.Object.Dispose () [0x00000] in /Users/builder/data/lanes/3511/ce955cc0/source/xamarin-android/src/Mono.Android/Java.Lang/Object.cs:203
  at Xamarin.Forms.Platform.Android.AppCompat.Platform.SetPage (Xamarin.Forms.Page newRoot) [0x0003f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:226
  at Xamarin.Forms.Platform.Android.AppCompat.Platform.Dispose () [0x00010] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:52
  at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.OnDestroy () [0x0002f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:195
  at Android.App.Activity.n_OnDestroy (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in /Users/builder/data/lanes/3511/ce955cc0/source/monodroid/src/Mono.Android/platforms/android-24/src/generated/Android.App.Activity.cs:2981
  at at (wrapper dynamic-method) System.Object:3a1f2dcb-839c-41c3-88f3-3ca5ed8f0b6f (intptr,intptr)
  at java.lang.IllegalStateException: Activity has been destroyed
  at at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
  at at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:638)
  at at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:621)
  at at md5b60ffeb829f638581ab2bb9b1a7f4f3f.FormsAppCompatActivity.n_onDestroy(Native Method)
  at at md5b60ffeb829f638581ab2bb9b1a7f4f3f.FormsAppCompatActivity.onDestroy(FormsAppCompatActivity.java:80)
  at at android.app.Activity.performDestroy(Activity.java:5603)
  at at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1135)
  at at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3670)
  at at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3701)
  at at android.app.ActivityThread.access$1500(ActivityThread.java:161)
  at at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1318)
  at at android.os.Handler.dispatchMessage(Handler.java:102)
  at at android.os.Looper.loop(Looper.java:157)
  at at android.app.ActivityThread.main(ActivityThread.java:5356)
  at at java.lang.reflect.Method.invokeNative(Native Method)
  at at java.lang.reflect.Method.invoke(Method.java:515)
  at at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
  at at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
  at at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I can confirm this is fixed in  Xamarin.Forms 2.3.4.221-pre6 dated 27/3/2017

Enter:
PM> Install-Package Xamarin.Forms -Pre

Delete bin and obj folders in your projects, clean and build the solution.

Body:
I am having this error and I have tried to set a break point but unable to find which part of my code caused the problem. This problem will occur when I pressed the back button to go out the application. The stack trace below didn't show anything of my code either. Does anyone seen this problem before or how do i debug this type of problem.

   Java.Lang.IllegalStateException: Activity has been destroyed
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3511/77cb8568/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method) [0x00084] in /Users/builder/data/lanes/3511/ce955cc0/source/Java.Interop/src/Java.Interop/Java.Interop/JniEnvironment.g.cs:11464
  at Android.Runtime.JNIEnv.CallIntMethod (System.IntPtr jobject, System.IntPtr jmethod) [0x00000] in /Users/builder/data/lanes/3511/ce955cc0/source/monodroid/src/Mono.Android/JNIEnv.g.cs:186
  at Android.Support.V4.App.FragmentTransactionInvoker.CommitAllowingStateLoss () [0x00033] in <27c17fe440cf491ba8255bcefade6e02>:0
  at Xamarin.Forms.Platform.Android.AppCompat.MasterDetailContainer.Dispose (System.Boolean disposing) [0x00042] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\MasterDetailContainer.cs:130
  at Java.Lang.Object.Dispose () [0x00000] in /Users/builder/data/lanes/3511/ce955cc0/source/xamarin-android/src/Mono.Android/Java.Lang/Object.cs:203
  at Xamarin.Forms.Platform.Android.AppCompat.MasterDetailPageRenderer.Dispose (System.Boolean disposing) [0x00046] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\MasterDetailPageRenderer.cs:192
  at Java.Lang.Object.Dispose () [0x00000] in /Users/builder/data/lanes/3511/ce955cc0/source/xamarin-android/src/Mono.Android/Java.Lang/Object.cs:203
  at Xamarin.Forms.Platform.Android.AppCompat.Platform.SetPage (Xamarin.Forms.Page newRoot) [0x0003f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:226
  at Xamarin.Forms.Platform.Android.AppCompat.Platform.Dispose () [0x00010] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:52
  at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.OnDestroy () [0x0002f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:195
  at Android.App.Activity.n_OnDestroy (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in /Users/builder/data/lanes/3511/ce955cc0/source/monodroid/src/Mono.Android/platforms/android-24/src/generated/Android.App.Activity.cs:2981
  at at (wrapper dynamic-method) System.Object:3a1f2dcb-839c-41c3-88f3-3ca5ed8f0b6f (intptr,intptr)
  at java.lang.IllegalStateException: Activity has been destroyed
  at at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
  at at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:638)
  at at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:621)
  at at md5b60ffeb829f638581ab2bb9b1a7f4f3f.FormsAppCompatActivity.n_onDestroy(Native Method)
  at at md5b60ffeb829f638581ab2bb9b1a7f4f3f.FormsAppCompatActivity.onDestroy(FormsAppCompatActivity.java:80)
  at at android.app.Activity.performDestroy(Activity.java:5603)
  at at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1135)
  at at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3670)
  at at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3701)
  at at android.app.ActivityThread.access$1500(ActivityThread.java:161)
  at at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1318)
  at at android.os.Handler.dispatchMessage(Handler.java:102)
  at at android.os.Looper.loop(Looper.java:157)
  at at android.app.ActivityThread.main(ActivityThread.java:5356)
  at at java.lang.reflect.Method.invokeNative(Native Method)
  at at java.lang.reflect.Method.invoke(Method.java:515)
  at at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
  at at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
  at at dalvik.system.NativeStart.main(Native Method)


问:
CONTACT_ID - Keeping it in sync
I am interested in your opinions on the best way to keep a robust reference to a contact starting android 2.0. I have read a lot regarding this issue but i don't know which technique is advisable and if there's any new ones. Below are the 3 options i found so far:

1- Don't use your own db. Extend the contacts.contract to write your data

2 - Use ContentObserver to keep track of any changes made to the contacts. This technique would however require your application to be running

3- Store all RAW contact IDs related to a CONTACT_ID in your db and infer the content of the aggregate contact from all its constituent RAW contacts

In my case i need to keep a separate db and i was wondering if there's any other new technique of keeping the CONTACT_ID current after aggregations and dis-aggregations...

Please advise

答:
I am playing with the new Contacts API at the moment, writing an app which is also a source of contact data. I can't recommend #3 at all. To get all of "my" contact data I simply store them with a magic value in the RawContacts.SYNC1 field and query the contacts content provider for that when my app starts up.

Re. your question, don't use CONTACT_IDs, as they are volatile. Use the lookup API, i.e. if you have a raw contact ID, use RawContacts.getContactLookupUri() to get to the Contact. Likewise if some API gives you a  contact ID, use Contacts.getLookupUri() to get a persistent identifier you can use later on.

Title: CONTACT_ID - Keeping it in sync


问:
Not possible to set Filter value using data binding?
This issue came forth from drilling down the original question: How to set filter in table dropdown based on table row data

Background

I want to use a filter on a SAPUI5 dropdown control, where I set the filter value based on a model property (data binding)

The issue

If I use a filter where the filter value value1 is specified by data binding:

new sap.ui.model.Filter({
    path     : "division",
    operator : sap.ui.model.FilterOperator.EQ,
    value1   : "{/someProperty}"
})
```

<p>then the dropdown does not render any items</p>

<p>However, if I <strong>hardcode</strong> a value at property <code>value1</code>:</p>

<pre class="lang-js prettyprint-override"><code>new sap.ui.model.Filter({
    path     : "division",
    operator : sap.ui.model.FilterOperator.EQ,
    value1   : "Test"
})
</code>```

Then the filter works as expected.

The Question

Is it true we can't use data binding for specifying a filter value? Or should I implement it in another way?

A small part of me can actually understand that setting a filter on a control's model using a value from that same model could induce some referential issues, but this behavior also occurs when using two distinct named models (one for the dropdown, and one for the filter value)

Any help is greatly appreciated!

答: No, it is not currently possible to set Filter value using data binding.  However, there is an approved enhancement issue in the OpenUI5 repository labeled "contribution welcome". This means that it is planned to add this functionality, and once added it will be possible to set the Filter value using data binding.</p>

Body:
This issue came forth from drilling down the original question: How to set filter in table dropdown based on table row data

Background

I want to use a filter on a SAPUI5 dropdown control, where I set the filter value based on a model property (data binding)

The issue

If I use a filter where the filter value value1 is specified by data binding:

new sap.ui.model.Filter({
    path     : "division",
    operator : sap.ui.model.FilterOperator.EQ,
    value1   : "{/someProperty}"
})

then the dropdown does not render any items

However, if I hardcode a value at property value1:

new sap.ui.model.Filter({
    path     : "division",
    operator : sap.ui.model.FilterOperator.EQ,
    value1   : "Test"
})

Then the filter works as expected.

The Question

Is it true we can't use data binding for specifying a filter value? Or should I implement it in another way?

A small part of me can actually understand that setting a filter on a control's model using a value from that same model could induce some referential issues, but this behavior also occurs when using two distinct named models (one for the dropdown, and one for the filter value)

Any help is greatly appreciated!


问:
How do you specify different dependencies and symbols when multi targeting a .NET Standard class library?
With project.json, it was possible to target different target frameworks, specifying different dependencies and conditional compilation symbols for each target framework.

I need to do the same thing with a .NET Standard class library using the .csproj project format. I know how to target multiple frameworks, but how do you specify different dependencies and conditional compilation symbols for each?

(In case "conditional compilation" is not clear, I need the ability to specify preprocessor directives in code such as #if NET452.)

A good example where this is useful is when dealing with appsettings. With the full .NET Framework, you need to reference System.Configuration.dll and work through ConfigurationManager. .NET Core configuration is a totally different beast.

答:
The accepted answer from your previous question which you linked to already has the answer: use <ItemGroup>s with Conditions testing for $(TargetFramework). Slightly modified code from that answer:

<ItemGroup Condition="'$(TargetFramework)' == 'net452'">
  <PackageReference Include="Microsoft.Azure.DocumentDB" Version="1.12.0" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.6'">
  <PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="1.1.0" />
</ItemGroup>
```

For preprocessor directives, you don't need to do anything. Directives like NET452 or NETSTANDARD1_6 are defined automatically.

Body:
The accepted answer from your previous question which you linked to already has the answer: use <ItemGroup>s with Conditions testing for $(TargetFramework). Slightly modified code from that answer:

<ItemGroup Condition="'$(TargetFramework)' == 'net452'">
  <PackageReference Include="Microsoft.Azure.DocumentDB" Version="1.12.0" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.6'">
  <PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="1.1.0" />
</ItemGroup>

For preprocessor directives, you don't need to do anything. Directives like NET452 or NETSTANDARD1_6 are defined automatically.


问:
start the service when app gets closed
I want to start a service when I press the home button or just press back (when the app is in the background but not killed)
how can I do a function that checks that ?
thanks to all</p>

答:
You need a BaseActivity,and all other Activities must extend this BaseActivity:

as @Shoad said but the method that triggers is

```<code>    public class BaseActivity extends Activity {
     @Override
    protected void onPause() {

//Start Service or do what you want

    }
    }
</code>```

Couldn't succed comment down

Title: start the service when app gets closed

Body:
You need a BaseActivity,and all other Activities must extend this BaseActivity:

as @Shoad said but the method that triggers is

    public class BaseActivity extends Activity {
     @Override
    protected void onPause() {

//Start Service or do what you want

    }
    }

Couldn't succed comment down


问:
How to disable a tooltip for a specific dataset in ChartJS
I displaying a chart where two types are included. Now I want to hide the toolbar for one dataset. I saw some discussion like this on GitHub, but this doesn't bring me further.

Here is an example of my Chart:

Chart.defaults.global.legend.display = false;
var ctx = document.getElementById("chart").getContext("2d");
var data = {
  labels: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],
  datasets: [
     {
       label: "Test",
       type: 'bar',
       backgroundColor: "#F29220",
       borderColor: "#F29220",
       data: [4,1,1,2,2,2,2,2,2,2,2,1]
     },
     {
       label: "Test2",
       type: 'bar',
       backgroundColor: "#F29220",
       borderColor: "#F29220",
       data: [4,0,0,0,0,0,0,0,0,0,0,0]
     },
     {
       label: "",
       type: 'line',
       fillColor: "rgba(220,220,220,0)",
       pointColor: "rgba(220,220,220,0)",
       borderColor: "#FF0000",
       tooltip: false,
       data: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
     }]
  };
  var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
       scales: {
          xAxes: [{
             stacked: true,
             ticks: {
                fontColor: '#000',
             }
          }],
          yAxes: [{
             stacked: true,
             ticks: {
                beginAtZero: true,
                fontColor: '#000',
                callback: function(label, index, labels) {
                   return label + '%';
                }
             },
          }]
       },
       elements: {
          point:{
             radius: 0
          }
       },
       tooltips: {
          enabled: true,
          mode: 'single',
          callbacks: {
             label: function(tooltipItems, data) {
                 return data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.yLabel + ' %';
          }
       }
    }
 }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" width="740" height="370"></canvas></code>```

How can I hide the tooltip just for the line chart? As you can see in the code, I already tried to insert the attribute "tooltip", but this doesn't work.

答:
As you already concluded, there isn't a way to configure chart.js out of the box to only show tooltips of specific datasets.  However, you can use the plugin interface to create a plugin that can provide this functionality.

Here is a plugin that I created for your scenario that let's you configure which datasets you want the tooltip to display for.

```<code>Chart.plugins.register({
  // need to manipulate tooltip visibility before its drawn (but after update)
  beforeDraw: function(chartInstance, easing) {
    // check and see if the plugin is active (its active if the option exists)
    if (chartInstance.config.options.tooltips.onlyShowForDatasetIndex) {
      // get the plugin configuration
      var tooltipsToDisplay = chartInstance.config.options.tooltips.onlyShowForDatasetIndex;

      // get the active tooltip (if there is one)
      var active = chartInstance.tooltip._active || [];

      // only manipulate the tooltip if its just about to be drawn
      if (active.length > 0) {
        // first check if the tooltip relates to a dataset index we don't want to show
        if (tooltipsToDisplay.indexOf(active[0]._datasetIndex) === -1) {
          // we don't want to show this tooltip so set it's opacity back to 0
          // which causes the tooltip draw method to do nothing
          chartInstance.tooltip._model.opacity = 0;
        }
      }
    }
  }
});
</code>```

With the new plugin in place, you can now use a new property in the tooltips config called onlyShowForDatasetIndex that accepts an array of dataset indexes that the tooltip should display for.

```<code>tooltips: {
  enabled: true,
  mode: 'single',
  // new property from our plugin
  // configure with an array of datasetIndexes that the tooltip should display for
  // to get the datasetIndex, just use it's position in the dataset [] above in the data property
  onlyShowForDatasetIndex: [0, 1],
  callbacks: {
    label: function(tooltipItems, data) {
      return data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.yLabel + ' %';
    }
  }
}
</code>```

Where the index value maps to the position of the dataset in the datasets property.

Take a look at this codepen to see this in action.  Notice the tooltips only show on the bar charts but not the line (since we did not include this dataset in the new configuration property).

Body:
I displaying a chart where two types are included. Now I want to hide the toolbar for one dataset. I saw some discussion like this on GitHub, but this doesn't bring me further.

Here is an example of my Chart:

Chart.defaults.global.legend.display = false;
var ctx = document.getElementById("chart").getContext("2d");
var data = {
  labels: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],
  datasets: [
     {
       label: "Test",
       type: 'bar',
       backgroundColor: "#F29220",
       borderColor: "#F29220",
       data: [4,1,1,2,2,2,2,2,2,2,2,1]
     },
     {
       label: "Test2",
       type: 'bar',
       backgroundColor: "#F29220",
       borderColor: "#F29220",
       data: [4,0,0,0,0,0,0,0,0,0,0,0]
     },
     {
       label: "",
       type: 'line',
       fillColor: "rgba(220,220,220,0)",
       pointColor: "rgba(220,220,220,0)",
       borderColor: "#FF0000",
       tooltip: false,
       data: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
     }]
  };
  var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
       scales: {
          xAxes: [{
             stacked: true,
             ticks: {
                fontColor: '#000',
             }
          }],
          yAxes: [{
             stacked: true,
             ticks: {
                beginAtZero: true,
                fontColor: '#000',
                callback: function(label, index, labels) {
                   return label + '%';
                }
             },
          }]
       },
       elements: {
          point:{
             radius: 0
          }
       },
       tooltips: {
          enabled: true,
          mode: 'single',
          callbacks: {
             label: function(tooltipItems, data) {
                 return data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.yLabel + ' %';
          }
       }
    }
 }
 });

<canvas id="chart" width="740" height="370"></canvas>

How can I hide the tooltip just for the line chart? As you can see in the code, I already tried to insert the attribute "tooltip", but this doesn't work.

Body:
As you already concluded, there isn't a way to configure chart.js out of the box to only show tooltips of specific datasets.  However, you can use the plugin interface to create a plugin that can provide this functionality.

Here is a plugin that I created for your scenario that let's you configure which datasets you want the tooltip to display for.

Chart.plugins.register({
  // need to manipulate tooltip visibility before its drawn (but after update)
  beforeDraw: function(chartInstance, easing) {
    // check and see if the plugin is active (its active if the option exists)
    if (chartInstance.config.options.tooltips.onlyShowForDatasetIndex) {
      // get the plugin configuration
      var tooltipsToDisplay = chartInstance.config.options.tooltips.onlyShowForDatasetIndex;

      // get the active tooltip (if there is one)
      var active = chartInstance.tooltip._active || [];

      // only manipulate the tooltip if its just about to be drawn
      if (active.length > 0) {
        // first check if the tooltip relates to a dataset index we don't want to show
        if (tooltipsToDisplay.indexOf(active[0]._datasetIndex) === -1) {
          // we don't want to show this tooltip so set it's opacity back to 0
          // which causes the tooltip draw method to do nothing
          chartInstance.tooltip._model.opacity = 0;
        }
      }
    }
  }
});

With the new plugin in place, you can now use a new property in the tooltips config called onlyShowForDatasetIndex that accepts an array of dataset indexes that the tooltip should display for.

tooltips: {
  enabled: true,
  mode: 'single',
  // new property from our plugin
  // configure with an array of datasetIndexes that the tooltip should display for
  // to get the datasetIndex, just use it's position in the dataset [] above in the data property
  onlyShowForDatasetIndex: [0, 1],
  callbacks: {
    label: function(tooltipItems, data) {
      return data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.yLabel + ' %';
    }
  }
}

Where the index value maps to the position of the dataset in the datasets property.

Take a look at this codepen to see this in action.  Notice the tooltips only show on the bar charts but not the line (since we did not include this dataset in the new configuration property).


问:
XDebug Helper IDE Key for Atom
I cannot find a list of IDE Keys for the Google Chrome extension XDebug Helper.  What would the IDE key for Atom be? </p>

答: When using the php-debug Atom package, the IDE key does not matter. </p>

Title: XDebug Helper IDE Key for Atom


问:
Does SEO read the data loaded from AJAX?
I loaded the title, description and keywords with Ajax, after loading the program, the datas are loaded from my database with php. The question is, Does the SEO read the title, description and keywords, from my code?

here is my JS function to load the head elements

```<code>function addHead(page)
{
$.ajax({
   url:"php/content_head.php",
   type:"POST",
   data:"page="+page,

    success: function(reponse){
        result = JSON.parse(reponse);
        $("title").text(result["Title"]);
        var headL = document.getElementById("head");
        headL.innerHTML+='<meta name="description" content="'+result["Desc"]+'">';
        headL.innerHTML+='<meta name="keywords" content="'+result["Keywords"]+'">';
        headL.innerHTML+='<meta name="author" content="Softmagazin">';
    }
});
}
</code>```

and this is the PHP data

```<code><?php

include "connect.php";
include "config.php";
include "functions.php";

$data = array();

$page = $_POST["page"];
$tabel = $GLOBALS['tabel_pagini'];
$sql = "SELECT * FROM $tabel WHERE Pagina = '$page'";

$result = $conn->query($sql);
$row = $result->fetch_assoc();

$data["Title"] = $row["Titlu"];
$data["Desc"] = $row["Descriere"];
$data["Keywords"] = $row["CuvinteCheie"];

echo json_encode($data);

?>
</code>```

答:
While that used to be the case, Google's bots have gotten a lot 'smarter' recently.  Their crawlers should be able to see your page just fine.  If you are still concerned or just want to see for yourself, try downloading Lynx and take a look at how your page renders.

From the Google Webmaster Help site Crawling and Indexing FAQ:

Q: My website uses pages made with PHP, ASP, CGI, JSP, CFM, etc. Will these still get indexed?

A: Yes! Provided these technologies serve pages that are visible in a browser, Googlebot will generally be able to crawl, index and rank them without problems. We have no preference, they're all equivalent in terms of crawling, indexing and ranking as long as we can crawl them. One way to double-check how a search engine crawler might see your page is to use a text-only browser such as Lynx to view your pages.

Body:
I loaded the title, description and keywords with Ajax, after loading the program, the datas are loaded from my database with php. The question is, Does the SEO read the title, description and keywords, from my code?

here is my JS function to load the head elements

function addHead(page)
{
$.ajax({
   url:"php/content_head.php",
   type:"POST",
   data:"page="+page,

    success: function(reponse){
        result = JSON.parse(reponse);
        $("title").text(result["Title"]);
        var headL = document.getElementById("head");
        headL.innerHTML+='<meta name="description" content="'+result["Desc"]+'">';
        headL.innerHTML+='<meta name="keywords" content="'+result["Keywords"]+'">';
        headL.innerHTML+='<meta name="author" content="Softmagazin">';
    }
});
}

and this is the PHP data

<?php

include "connect.php";
include "config.php";
include "functions.php";

$data = array();

$page = $_POST["page"];
$tabel = $GLOBALS['tabel_pagini'];
$sql = "SELECT * FROM $tabel WHERE Pagina = '$page'";

$result = $conn->query($sql);
$row = $result->fetch_assoc();

$data["Title"] = $row["Titlu"];
$data["Desc"] = $row["Descriere"];
$data["Keywords"] = $row["CuvinteCheie"];

echo json_encode($data);

?>


问:
preferred way of accessing child class members from base class
What is the best way to access child class properties in the base class. It seems that if  I am using inheritance I need to solely depend on methods instead of properties [because separate set of properties exists for separate classes]. Is there any recommended,safe way of accessing child class properties from base class. or is this any preferred way of refactoring the code, so that I can access child class members via a base class. i know the use of virtual functions but I don't know how to use it to set values for the child class members variables.</p>

```<code>class Abc
{
  public int Abc_1 {get;set;}
  private int _abc;

  virtual int DoCalculationonAbc(int a)
  {
    return abc_1 * a;
  }

  virtual void SetValueToPrivate(int a)
  {
    _abc = a;
  }
}

class Def:Abc
{
  private int _def;
  private int _def2;
  public int Def_2{get;set;} // what is the preferred way to set values this property

  override public void SetValueToPrivate(int a)
  {
     _def = a;
     //_def2 = ??
  }
}

Main()
{
  Abc ab = new Def();
}
</code>```

答:
You can try:</p>

```<code>var testDerived = (Derived)new Derived(); //casting to derived class required to access its members.

testBase.a = testDerived.b;
</code>```

Body:
What is the best way to access child class properties in the base class. It seems that if  I am using inheritance I need to solely depend on methods instead of properties [because separate set of properties exists for separate classes]. Is there any recommended,safe way of accessing child class properties from base class. or is this any preferred way of refactoring the code, so that I can access child class members via a base class. i know the use of virtual functions but I don't know how to use it to set values for the child class members variables.

class Abc
{
  public int Abc_1 {get;set;}
  private int _abc;

  virtual int DoCalculationonAbc(int a)
  {
    return abc_1 * a;
  }

  virtual void SetValueToPrivate(int a)
  {
    _abc = a;
  }
}

class Def:Abc
{
  private int _def;
  private int _def2;
  public int Def_2{get;set;} // what is the preferred way to set values this property

  override public void SetValueToPrivate(int a)
  {
     _def = a;
     //_def2 = ??
  }
}

Main()
{
  Abc ab = new Def();
}

Body:
You can try:

var testDerived = (Derived)new Derived(); //casting to derived class required to access its members.

testBase.a = testDerived.b;


问:
Spring Boot not reading application.properties for DataSource
I've put my DataSource details in /resources/application.properties file:

```<code>spring.datasource.url = jdbc:mysql://localhost:3306/dsm
spring.datasource.username = root
spring.datasource.password = admin123
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
</code>```

I've tried adding a direct reference to the properties file, this this didn't make any difference.

```<code>@PropertySource("classpath:application.properties")
</code>```

The error being generated is:

```<code>2015-11-23 14:44:30.232  INFO 54329 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2015-11-23 14:44:31.522  INFO 54329 --- [on(2)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2015-11-23 14:44:31.535  INFO 54329 --- [on(2)-127.0.0.1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2015-11-23 14:44:31.629  INFO 54329 --- [on(2)-127.0.0.1] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.11.Final}
2015-11-23 14:44:31.632  INFO 54329 --- [on(2)-127.0.0.1] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2015-11-23 14:44:31.636  INFO 54329 --- [on(2)-127.0.0.1] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2015-11-23 14:44:31.824  INFO 54329 --- [on(2)-127.0.0.1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
23-Nov-2015 14:44:32.005 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver Not loading a JDBC driver as driverClassName property is null.
23-Nov-2015 14:44:32.008 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.tomcat.jdbc.pool.ConnectionPool.init Unable to create initial connections of pool.
 java.sql.SQLException: The url cannot be null
</code>```

Looking at my properties file, both the dialect and the url are defined, and they're not being picked up, which is leading me to believe that the file isn't being ready.

My application class incase it helps:

```<code>@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

}
</code>```

答: I had the same problem, turned out I put the properties file in /resources/META-INF. Changed the package to /resources/<default-package> and it was fixed.

Body:
I've put my DataSource details in /resources/application.properties file:

spring.datasource.url = jdbc:mysql://localhost:3306/dsm
spring.datasource.username = root
spring.datasource.password = admin123
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

I've tried adding a direct reference to the properties file, this this didn't make any difference.

@PropertySource("classpath:application.properties")

The error being generated is:

2015-11-23 14:44:30.232  INFO 54329 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2015-11-23 14:44:31.522  INFO 54329 --- [on(2)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2015-11-23 14:44:31.535  INFO 54329 --- [on(2)-127.0.0.1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2015-11-23 14:44:31.629  INFO 54329 --- [on(2)-127.0.0.1] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.11.Final}
2015-11-23 14:44:31.632  INFO 54329 --- [on(2)-127.0.0.1] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2015-11-23 14:44:31.636  INFO 54329 --- [on(2)-127.0.0.1] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2015-11-23 14:44:31.824  INFO 54329 --- [on(2)-127.0.0.1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
23-Nov-2015 14:44:32.005 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver Not loading a JDBC driver as driverClassName property is null.
23-Nov-2015 14:44:32.008 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.tomcat.jdbc.pool.ConnectionPool.init Unable to create initial connections of pool.
 java.sql.SQLException: The url cannot be null

Looking at my properties file, both the dialect and the url are defined, and they're not being picked up, which is leading me to believe that the file isn't being ready.

My application class incase it helps:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

}


问:
Materialize links do not fit inside navigation
Problem:

Fitting five links inside a navigation using Materialize CSS. Right now, three links fit and I can even add a fourth. But when I add five links in total, the last two break.

Minimal Working Example (MWE):

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
    <title>Materialize</title>
    <!-- CSS  -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.1/css/materialize.min.css" rel="stylesheet">
</head>
<body>
    <header>
        <nav class="indigo" role="navigation">
            <div class="nav-wrapper container">
                <a id="logo-container" href="#" class="brand-logo"><i class="material-icons md-36">flight_takeoff</i> Logo</a>
                <ul class="right hide-on-med-and-down">
                    <li class="active"><a href="javascript:void(0)">Home</a></li>
                    <li><a href="javascript:void(0)">About</a></li>
                    <li><a href="javascript:void(0)">Contact</li>
                    <li><a href="javascript:void(0)"><i class="material-icons left">add_circle</i> Registration</a></li>
                    <li><a href="javascript:void(0)"><i class="material-icons left">account_circle</i> Login</a></li>
                </ul>
            </div>
        </nav>
    </header>
</body>
</html>
</code>```

Desired output:

To get all five links to fit inside the navigation on the right side.

答:
It's because your href="#">Contact is missing the close tag.
Here's the updated code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
    <title>Materialize</title>
    <!-- CSS  -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.1/css/materialize.min.css" rel="stylesheet">
</head>
<body>
    <header>
        <nav class="indigo" role="navigation">
            <div class="nav-wrapper container">
                <a id="logo-container" href="#" class="brand-logo"><i class="material-icons md-36">flight_takeoff</i> Logo</a>
                <ul class="right hide-on-med-and-down">
                    <li class="active"><a href="javascript:void(0)">Home</a></li>
                    <li><a href="javascript:void(0)">About</a></li>
                    <li><a href="javascript:void(0)">Contact</a></li> <!-- Note the </a> closing tag -->
                    <li><a href="javascript:void(0)"><i class="material-icons left">add_circle</i> Registration</a></li>
                    <li><a href="javascript:void(0)"><i class="material-icons left">account_circle</i> Login</a></li>
                </ul>
            </div>
        </nav>
    </header>
</body>
</html>
</code>```

Body:
Problem:

Fitting five links inside a navigation using Materialize CSS. Right now, three links fit and I can even add a fourth. But when I add five links in total, the last two break.

Minimal Working Example (MWE):

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
    <title>Materialize</title>

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.1/css/materialize.min.css" rel="stylesheet">

                flight_takeoff Logo

Home

About

Contact

add_circle Registration

account_circle Login

Desired output:

To get all five links to fit inside the navigation on the right side.

Body:
It's because your <a href="#">Contact is missing the close tag.
Here's the updated code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
    <title>Materialize</title>
    <!-- CSS  -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.1/css/materialize.min.css" rel="stylesheet">
</head>
<body>
    <header>
        <nav class="indigo" role="navigation">
            <div class="nav-wrapper container">
                <a id="logo-container" href="#" class="brand-logo"><i class="material-icons md-36">flight_takeoff</i> Logo</a>
                <ul class="right hide-on-med-and-down">
                    <li class="active"><a href="javascript:void(0)">Home</a></li>
                    <li><a href="javascript:void(0)">About</a></li>
                    <li><a href="javascript:void(0)">Contact</a></li> <!-- Note the </a> closing tag -->
                    <li><a href="javascript:void(0)"><i class="material-icons left">add_circle</i> Registration</a></li>
                    <li><a href="javascript:void(0)"><i class="material-icons left">account_circle</i> Login</a></li>
                </ul>
            </div>
        </nav>
    </header>
</body>
</html>


问:
Angular2: HammerJS swipe for md-tab-group
I've implemented HammerJS in my Angular2 webapp and I've also tested the example code out. This code uses an Array of objects and seems to work flawlessly. However, I've been trying to implement the same system for @angular2-material/tabs. Therefore I have a <md-tab-group> with multiple <md-tab>'s which should swipe from tab to tab. Problem is that I can't even trigger the swipe function.

HTML-File:

```<code><md-tab-group md-stretch-tabs [(selectedIndex)]="selectedIndex" (selectedIndexChange)="selectChange()">
      <div class="swipe-box" (swipeleft)="swipe(idx, $event.type)" (swiperight)="swipe(idx, $event.type)">
        <md-tab>
           (...) //Content Tab 1
        </md-tab>
        <md-tab>
           (...) //Content Tab 2
        </md-tab>
      </div>
</md-tab-group>
</code>```

In the example can be seen that *ngFor is used like *ngFor="let avatar of avatars; let idx=index" for the  swipe-box-
. But since I'm getting my index from the <md-tab-group> it doesn't seem neccesary and even when I include it, my event isn't triggered but my <md-tab>-content becomes hidden. Therefore I left it out. I did leave the idx parameter in the function because the swipe method expects a number (second parameter is optional). Documentation

For the TypeScript-file I've implemented the following code (some code might not work but haven't been able to test it since the swipe method doesn't get called).

TS-File:

```<code>export class HomeComponent {

  selectedIndex: number = 1;

  selectChange(): void{
    console.log("event triggered INDEX: " + this.selectedIndex);
  }

  SWIPE_ACTION = { LEFT: 'swipeleft', RIGHT: 'swiperight' };

  // Action triggered when user swipes
  swipe(selectedIndex: number, action = this.SWIPE_ACTION.RIGHT) {
    console.log("swiped"); //DOES NOT GET TRIGGERD
    // Out of range
    if (selectedIndex < 0 || selectedIndex > 1 ) return;

    let nextIndex = 0;
    // Swipe right, next tab
    if (action === this.SWIPE_ACTION.RIGHT) {
      const isLast = selectedIndex === 1;
      nextIndex = isLast ? 0 : selectedIndex + 1;
      console.log("swipe right");
    }

    // Swipe left, previous tab
    if (action === this.SWIPE_ACTION.LEFT) {
      const isFirst = selectedIndex === 0;
      nextIndex = isFirst ? 1 : selectedIndex - 1;
      console.log("swipe left");
    }
  }
}
</code>```

Live demo of what HammerJS does and yes, I've implemented the script needed in the index.html

```<code><!-- Hammer JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js"></script>
</code>```

答:
You need the swipe detection on each tab, not the container.  </p>

```<code>  <div class="swipe-box">
    <md-tab (swipeleft)="swipe(1, $event.type)"
            (swiperight)="swipe(1, $event.type)">
       (...) //Content Tab 1
    </md-tab>
    <md-tab (swipeleft)="swipe(2, $event.type)"
            (swiperight)="swipe(2, $event.type)">
       (...) //Content Tab 2
    </md-tab>
  </div>
</code>```

Body:
I've implemented HammerJS in my Angular2 webapp and I've also tested the example code out. This code uses an Array of objects and seems to work flawlessly. However, I've been trying to implement the same system for @angular2-material/tabs. Therefore I have a <md-tab-group> with multiple <md-tab>'s which should swipe from tab to tab. Problem is that I can't even trigger the swipe function.

HTML-File:

<md-tab-group md-stretch-tabs [(selectedIndex)]="selectedIndex" (selectedIndexChange)="selectChange()">

        <md-tab>
           (...) //Content Tab 1
        </md-tab>
        <md-tab>
           (...) //Content Tab 2
        </md-tab>

</md-tab-group>

In the example can be seen that *ngFor is used like *ngFor="let avatar of avatars; let idx=index" for the  swipe-box-
. But since I'm getting my index from the <md-tab-group> it doesn't seem neccesary and even when I include it, my event isn't triggered but my <md-tab>-content becomes hidden. Therefore I left it out. I did leave the idx parameter in the function because the swipe method expects a number (second parameter is optional). Documentation

For the TypeScript-file I've implemented the following code (some code might not work but haven't been able to test it since the swipe method doesn't get called).

TS-File:

export class HomeComponent {

  selectedIndex: number = 1;

  selectChange(): void{
    console.log("event triggered INDEX: " + this.selectedIndex);
  }

  SWIPE_ACTION = { LEFT: 'swipeleft', RIGHT: 'swiperight' };

  // Action triggered when user swipes
  swipe(selectedIndex: number, action = this.SWIPE_ACTION.RIGHT) {
    console.log("swiped"); //DOES NOT GET TRIGGERD
    // Out of range
    if (selectedIndex < 0 || selectedIndex > 1 ) return;

    let nextIndex = 0;
    // Swipe right, next tab
    if (action === this.SWIPE_ACTION.RIGHT) {
      const isLast = selectedIndex === 1;
      nextIndex = isLast ? 0 : selectedIndex + 1;
      console.log("swipe right");
    }

    // Swipe left, previous tab
    if (action === this.SWIPE_ACTION.LEFT) {
      const isFirst = selectedIndex === 0;
      nextIndex = isFirst ? 1 : selectedIndex - 1;
      console.log("swipe left");
    }
  }
}

Live demo of what HammerJS does and yes, I've implemented the script needed in the index.html

Body:
You need the swipe detection on each tab, not the container.

  <div class="swipe-box">
    <md-tab (swipeleft)="swipe(1, $event.type)"
            (swiperight)="swipe(1, $event.type)">
       (...) //Content Tab 1
    </md-tab>
    <md-tab (swipeleft)="swipe(2, $event.type)"
            (swiperight)="swipe(2, $event.type)">
       (...) //Content Tab 2
    </md-tab>
  </div>


问:
Creating a Custom Fold Function for Custom Tree
I'm attempting to create my own fold function which I can then use on my custom tree.

My Tree is simple like so:

```<code>data Stem a = Node (Stem a) (Stem a) | Leaf a
</code>```

I want to be able to build a foldTree function which works much in the same way as foldr would.

I've manage to get it to work for when n=1 or just a leaf with the following

```<code>foldTree :: (x -> u -> u) -> u -> Stem x -> u
foldTree f a (Leaf o) = f o a
</code>```

But I can't seem to work out the next line (IE for when there are nodes and leafs), I understand I need to recursively call foldTree but I'm not sure how I can do it. I've tried the following but I'm not having much luck.

```<code>foldTree f a (Node l r) = f a (foldTree f a l) (foldTree f a r)
</code>```

This doesn't work as I know my parameters are x -> u  -> u and so I've got one too many parameters. Although this is where I am stuck I'm not sure how to traverse both paths correctly.

So all together I have

```<code>foldTree :: (x -> u -> u) -> u -> Stem x -> u
foldTree f a (Leaf o) = f o a
foldTree f a (Node l r) = f a (foldTree f a l) (foldTree f a r) <-- Not working
</code>```

How can I update this second line (or possibly something else in the method to get it to work?

Thanks for the help!

答:
Work on the simple, specific cases first, and then extend the logic to the general cases.  You have the easy one, for Leaf:

```<code>foldTree f a (Leaf o) = f o a
</code>```

Then think about what you want to happen where there's a Node with only two Leafs:

```<code>foldTree f a (Node (Leaf x) (Leaf y)) = _
</code>```

Here we know that f will have to be applied twice, but in what order?  Let's just start with the Leaf in the first slot of Node:

```<code>foldTree f a (Node (Leaf x) (Leaf y)) = _ (f x a)
</code>```

I've left the hole (_) in the expression because GHC will actually tell you what type of thing needs to go there when you try to compile.  In this case, it'll say that you need something of type u -> u since f x a :: u.  Well, we know that f :: x -> u -> u, so we can write

```<code>foldTree f a (Node (Leaf x) (Leaf y)) = f _ (f x a)
</code>```

Now the only thing that can fill this hole is y from the right leaf, so

```<code>foldTree f a (Node (Leaf x) (Leaf y)) = f y (f x a)
</code>```

But we know that f x a is the same as foldTree f a (Leaf x), so we can substitute that in:

```<code>foldTree f a (Node (Leaf x) (Leaf y)) = f y (foldTree f a (Leaf x))
</code>```

Then replace Leaf x with just a single variable:

```<code>foldTree f a (Node left (Leaf y)) = f y (foldTree f a left)
</code>```

If you squint your eyes and look closely, you'll see the same pattern a second time.  Just do a quick substitution

```<code>foldTree f a (Node left (Leaf y)) = f y a'
  where a' = foldTree f a left
</code>```

Now you can do the substitution

```<code>foldTree f a (Node left right) = foldTree f a' right
  where a' = foldTree f a left
</code>```

And the whole definition is

```<code>foldTree f a (Leaf x) = f x a
foldTree f a (Node left right) = foldTree f (foldTree f a left) right
</code>```

Body:
I'm attempting to create my own fold function which I can then use on my custom tree.

My Tree is simple like so:

data Stem a = Node (Stem a) (Stem a) | Leaf a

I want to be able to build a foldTree function which works much in the same way as foldr would.

I've manage to get it to work for when n=1 or just a leaf with the following

foldTree :: (x -> u -> u) -> u -> Stem x -> u
foldTree f a (Leaf o) = f o a

But I can't seem to work out the next line (IE for when there are nodes and leafs), I understand I need to recursively call foldTree but I'm not sure how I can do it. I've tried the following but I'm not having much luck.

foldTree f a (Node l r) = f a (foldTree f a l) (foldTree f a r)

This doesn't work as I know my parameters are x -> u  -> u and so I've got one too many parameters. Although this is where I am stuck I'm not sure how to traverse both paths correctly.

So all together I have

foldTree :: (x -> u -> u) -> u -> Stem x -> u
foldTree f a (Leaf o) = f o a
foldTree f a (Node l r) = f a (foldTree f a l) (foldTree f a r) <-- Not working

How can I update this second line (or possibly something else in the method to get it to work?

Thanks for the help!

Body:
Work on the simple, specific cases first, and then extend the logic to the general cases.  You have the easy one, for Leaf:

foldTree f a (Leaf o) = f o a

Then think about what you want to happen where there's a Node with only two Leafs:

foldTree f a (Node (Leaf x) (Leaf y)) = _

Here we know that f will have to be applied twice, but in what order?  Let's just start with the Leaf in the first slot of Node:

foldTree f a (Node (Leaf x) (Leaf y)) = _ (f x a)

I've left the hole (_) in the expression because GHC will actually tell you what type of thing needs to go there when you try to compile.  In this case, it'll say that you need something of type u -> u since f x a :: u.  Well, we know that f :: x -> u -> u, so we can write

foldTree f a (Node (Leaf x) (Leaf y)) = f _ (f x a)

Now the only thing that can fill this hole is y from the right leaf, so

foldTree f a (Node (Leaf x) (Leaf y)) = f y (f x a)

But we know that f x a is the same as foldTree f a (Leaf x), so we can substitute that in:

foldTree f a (Node (Leaf x) (Leaf y)) = f y (foldTree f a (Leaf x))

Then replace Leaf x with just a single variable:

foldTree f a (Node left (Leaf y)) = f y (foldTree f a left)

If you squint your eyes and look closely, you'll see the same pattern a second time.  Just do a quick substitution

foldTree f a (Node left (Leaf y)) = f y a'
  where a' = foldTree f a left

Now you can do the substitution

foldTree f a (Node left right) = foldTree f a' right
  where a' = foldTree f a left

And the whole definition is

foldTree f a (Leaf x) = f x a
foldTree f a (Node left right) = foldTree f (foldTree f a left) right


问:
Css fonts are not working in IE after I disabled cache in Node JS
Css fonts are not working in IE after I disabled cache in Node JS.

When the user navigates to some page and navigates back to previous page by clicking on back button, the previous page font styles are not working in IE 11.

'koa-no-cache' Code to disable cache

```<code>app.use(noCache({global: true}));
</code>```

I used the above code to disable cache for my node application.

Any Solution ?

答: With the cache disabled the browser should not cache assets - including fonts. The solution would be to host the fonts from a different location where the cache is not disabled, if you want the fonts to be cached, or to disable the cache only for certain types of assets.</p>

Body:
Css fonts are not working in IE after I disabled cache in Node JS.

When the user navigates to some page and navigates back to previous page by clicking on back button, the previous page font styles are not working in IE 11.

'koa-no-cache' Code to disable cache

app.use(noCache({global: true}));

I used the above code to disable cache for my node application.

Any Solution ?


问:
Create a LayerDrawable object programmatically
How can I create this drawable programmatically? </p>

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
  <bitmap android:src="@drawable/android_red"
    android:gravity="center" />
</item>
<item android:top="10dp" android:left="10dp">
  <bitmap android:src="@drawable/android_green"
    android:gravity="center" />
</item>
<item android:top="20dp" android:left="20dp">
  <bitmap android:src="@drawable/android_blue"
    android:gravity="center" />
</item>
</layer-list>
</code>```

答: It is pretty much completely described here. Just create a new instance of LayerDrawable by passing its constructor an array of Drawable objects.

ContentLicense: CC BY-SA 4.0

Body:
How can I create this drawable programmatically?

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
  <bitmap android:src="@drawable/android_red"
    android:gravity="center" />
</item>
<item android:top="10dp" android:left="10dp">
  <bitmap android:src="@drawable/android_green"
    android:gravity="center" />
</item>
<item android:top="20dp" android:left="20dp">
  <bitmap android:src="@drawable/android_blue"
    android:gravity="center" />
</item>
</layer-list>


问:
insert from phpmyadmin to table in HTML
I created a game which sends scores to phpmyadmin. And up to this point code is working good, but later when I try to "SELECT score FROM..."  and put it to table at the bottom on the screen I have problems, syntax etc. I simply want to create table with 5 the highest scores

first part is working good, but problems starts from line:

$query = "SELECT score FROM score_fish ORDER BY ID ASC";
code below:

```<code>    //<link rel="stylesheet" href="css/style1.css">
   // <script src="js/apps1.js"></script>
    //<script
        //src="https://code.jquery.com/jquery-2.2.4.js"
      //  integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
        //crossorigin="anonymous">
    //</script>
    <?php

    $name = $_POST['scores'];
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "scores";
    //  $table = "top scores";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    // Check connection
    if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
    }
    //  $sql = "CREATE TABLE score_fish (
    //      id MEDIUMINT NOT NULL AUTO_INCREMENT,
    //      name CHAR(30) NOT NULL,
    //      score MEDIUMINT,
    //      PRIMARY KEY (id)
    //  )";
    $sql = "INSERT INTO score_fish(score) VALUES ($name)";

    if ($conn->query($sql) === TRUE) {
       echo "www.Rados.com.pl";
    } else {
       echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $query = "SELECT score FROM score_fish ORDER BY `ID` ASC";
    if ($conn->query($query) === TRUE) {
        $conn->query($query);
       echo "Error: ";
    } else {
       print ($conn->query($query));
    }

    // $sql = mysql> SELECT id, score FROM score_fish ORDER BY score DESC;

    $conn->close();

    ?>
    <table>
       <tr>
         <th class="gameScore">No.</th>
         <th class="gameScore">Top Scores</th>
       </tr>
       <tr>
         <th class="gameScore" class="gameScore"><?php echo $query ?></th>
         <th class="gameScore"></th>
       </tr>
       <tr>
         <th class="gameScore" class="gameScore"><?php echo $query ?></th>
         <th class="gameScore"></th>
       </tr>
       <tr>
         <th class="gameScore" class="gameScore"><?php echo $query ?></th>
         <th class="gameScore"></th>
       </tr>
       <tr>
         <th class="gameScore" class="gameScore"><?php echo $query ?></th>
         <th class="gameScore"></th>
       </tr>
       <tr>
         <th class="gameScore" class="gameScore"><?php echo $query ?></th>
         <th class="gameScore"></th>
       </tr>
    </table>
    </section>
</code>```

答:
```<code>$name = $_POST['scores'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "scores";
//  $table = "top scores";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
//  $sql = "CREATE TABLE score_fish (
//      id MEDIUMINT NOT NULL AUTO_INCREMENT,
//      name CHAR(30) NOT NULL,
//      score MEDIUMINT,
//      PRIMARY KEY (id)
//  )";
$sql = "INSERT INTO score_fish(score) VALUES ($name)";

if ($conn->query($sql) === TRUE) {
   echo "www.Rados.com.pl";
} else {
   echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
<table>
   <tr>
     <th class="gameScore">No.</th>
     <th class="gameScore">Top Scores</th>
   </tr>
<?php
$query = "SELECT score FROM score_fish ORDER BY score DESC LIMIT 5;";
if ($conn->query($query) === TRUE) {
    $score_no = 0;
    foreach($conn->query($query) as $row){
        $score_no += 1;
?>
   <tr>
     <th class="gameScore"><?php echo $score_no; ?></th>
     <th class="gameScore" class="gameScore"><?php echo $row['score']; ?></th>
   </tr>
<?php
    } //end foreach

    } else {
        print ($conn->query($query));
        echo "Error: ";
    }

    $conn->close();
?>

</table>
</section>
</code>```

Title: insert from phpmyadmin to table in HTML

Body:
I created a game which sends scores to phpmyadmin. And up to this point code is working good, but later when I try to "SELECT score FROM..."  and put it to table at the bottom on the screen I have problems, syntax etc. I simply want to create table with 5 the highest scores

first part is working good, but problems starts from line:

$query = "SELECT score FROM score_fish ORDER BY ID ASC";
code below:

    //<link rel="stylesheet" href="css/style1.css">
   //
    //
    <?php

    $name = $_POST['scores'];
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "scores";
    //  $table = "top scores";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    // Check connection
    if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
    }
    //  $sql = "CREATE TABLE score_fish (
    //      id MEDIUMINT NOT NULL AUTO_INCREMENT,
    //      name CHAR(30) NOT NULL,
    //      score MEDIUMINT,
    //      PRIMARY KEY (id)
    //  )";
    $sql = "INSERT INTO score_fish(score) VALUES ($name)";

    if ($conn->query($sql) === TRUE) {
       echo "www.Rados.com.pl";
    } else {
       echo "Error: " . $sql . "
" . $conn->error;
    }

    $query = "SELECT score FROM score_fish ORDER BY `ID` ASC";
    if ($conn->query($query) === TRUE) {
        $conn->query($query);
       echo "Error: ";
    } else {
       print ($conn->query($query));
    }

    // $sql = mysql> SELECT id, score FROM score_fish ORDER BY score DESC;

    $conn->close();

    ?>

         No.
         Top Scores

         <?php echo $query ?>

         <?php echo $query ?>

         <?php echo $query ?>

         <?php echo $query ?>

         <?php echo $query ?>


问:
Can using eval to dynamically build an associative array be made secure?
I know that using eval to execute user-input strings is dangerous. From another question, and tests so far, it seems that the only way to dynamically initialize an associate array is to use eval.

Considering the following example (say hash_test.sh), it is clear that user input could be used to inject and run arbitrary commands.

```<code>#!/bin/bash

key0="a"
value0="b"
key1='c]="d"); echo "You were hacked on $(date)"; #'
value2="2"
input=$(cat - <<EOF
[$key0]="$value0"
[$key1]="$value1"
EOF
)

eval "declare -A hash=( ${input[@]} )"
echo "keys";
for key in "${!hash[@]}"; do
    echo "Key: $key Value: ${hash[$key]}";
done;
</code>```

Running hash_test.sh demonstrates the problem.

Is there a technique that could safely escape the user input to make this secure?

答:
First -- the eval given in the linked answer was redundant with behavior of declare without it:

```<code>string='["key1"]="value1" ["key2"]="value2"'
declare -A assoc_array="($string)"
echo "Value of key1 is ${assoc_array[key1]}"
</code>```

However, this does have the same security risks:

```<code>string='["key1"]="$(touch /tmp/i-am-insecure)"'
declare -A assoc_array="($string)"
ls -l /tmp/i-am-insecure ## guess what, it exists
</code>```

You could quote the values being generated by printf %q, if you really insisted:

```<code>printf -v string '[%q]=%q' "key1" '$(touch /tmp/i-am-insecure)'
declare -A assoc_array="($string)"
ls -l /tmp/i-am-insecure ## not found!
</code>```

But best-practice is to iteratively populate your array. To serialize in an entirely unambiguous format:

```<code>for key in "${!array[@]}"; do printf '%s\0' "$key" "${array[$key]}"; done >file
</code>```

...and to deserialize from that format:

```<code>declare -A array
while IFS= read -r -d '' key && IFS= read -r -d '' value; do array[$key]=$value; done <file
</code>```

Body:
I know that using eval to execute user-input strings is dangerous. From another question, and tests so far, it seems that the only way to dynamically initialize an associate array is to use eval.

Considering the following example (say hash_test.sh), it is clear that user input could be used to inject and run arbitrary commands.

#!/bin/bash

key0="a"
value0="b"
key1='c]="d"); echo "You were hacked on $(date)"; #'
value2="2"
input=$(cat - <<EOF
[$key0]="$value0"
[$key1]="$value1"
EOF
)

eval "declare -A hash=( ${input[@]} )"
echo "keys";
for key in "${!hash[@]}"; do
    echo "Key: $key Value: ${hash[$key]}";
done;

Running hash_test.sh demonstrates the problem.

Is there a technique that could safely escape the user input to make this secure?

Body:
First -- the eval given in the linked answer was redundant with behavior of declare without it:

string='["key1"]="value1" ["key2"]="value2"'
declare -A assoc_array="($string)"
echo "Value of key1 is ${assoc_array[key1]}"

However, this does have the same security risks:

string='["key1"]="$(touch /tmp/i-am-insecure)"'
declare -A assoc_array="($string)"
ls -l /tmp/i-am-insecure ## guess what, it exists

You could quote the values being generated by printf %q, if you really insisted:

printf -v string '[%q]=%q' "key1" '$(touch /tmp/i-am-insecure)'
declare -A assoc_array="($string)"
ls -l /tmp/i-am-insecure ## not found!

But best-practice is to iteratively populate your array. To serialize in an entirely unambiguous format:

for key in "${!array[@]}"; do printf '%s\0' "$key" "${array[$key]}"; done >file

...and to deserialize from that format:

declare -A array
while IFS= read -r -d '' key && IFS= read -r -d '' value; do array[$key]=$value; done <file


问:
Google maps transit_station also shows bus stations
I'm trying to display all METRO STOPS and TRAM STOPS on a map. I'm doing so via the Radar Search API. It gives back all locations matching a type within a given radius. These types are possible.

So I'm basically doing a search on the types subway_station for metro and transit_station for tram stops.

The problem is that transit_station also returns bus stations (which also has its separate type bus_station so I would expect them not to be returned via the transit_station type).

This is the URL I'm making the request to:

```<code>https://maps.googleapis.com/maps/api/place/radarsearch/json?type=transit_station&location=51.055154,3.726752&radius=5000&key=[MY_API_KEY]
</code>```

So I wonder if I'm doing something wrong or my request is simply not possible via Google Maps?

答:
My understanding is that transit_station is a generic type that includes train_station, bus_station, subway_station and light_rail_station.

I think you should use a separate light_rail_station type for trams:

https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.055154%2C3.726752&radius=5000&type=light_rail_station&key=YOUR_API_KEY

Also, I figured out that many stations are marked as a bus_station and light_rail_station at the same time.

Hope it helps!

Body:
I'm trying to display all METRO STOPS and TRAM STOPS on a map. I'm doing so via the Radar Search API. It gives back all locations matching a type within a given radius. These types are possible.

So I'm basically doing a search on the types subway_station for metro and transit_station for tram stops.

The problem is that transit_station also returns bus stations (which also has its separate type bus_station so I would expect them not to be returned via the transit_station type).

This is the URL I'm making the request to:

https://maps.googleapis.com/maps/api/place/radarsearch/json?type=transit_station&location=51.055154,3.726752&radius=5000&key=[MY_API_KEY]

So I wonder if I'm doing something wrong or my request is simply not possible via Google Maps?