问:
How to move camera using joystick in Unity?
I have a problem with camera movement using joystick in Unity. I wrote this code to my joystick

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {

private Image bgImg;
private Image joystickImg;
private Vector2 pos;

private void Start()
{
    bgImg = GetComponent<Image>();
    joystickImg = transform.GetChild(0).GetComponent<Image>();
}

public virtual void OnDrag(PointerEventData ped)
{
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {
        pos.x = (pos.x * 2 + 1) / bgImg.rectTransform.sizeDelta.x;
        pos.y = (pos.y * 2 - 1) / bgImg.rectTransform.sizeDelta.y;

        pos = (pos.magnitude > 1.0f) ? pos.normalized : pos;

        // Move Joystrick IMG
        joystickImg.rectTransform.anchoredPosition = new Vector2(pos.x * (bgImg.rectTransform.sizeDelta.x / 3), pos.y * (bgImg.rectTransform.sizeDelta.y / 3));
    }
}

public virtual void OnPointerDown(PointerEventData ped)
{
    OnDrag(ped);
}

public virtual void OnPointerUp(PointerEventData ped)
{
    pos = Vector2.zero;
    joystickImg.rectTransform.anchoredPosition = Vector2.zero;
}

public float Horizontal()
{
    if (pos.x != 0)
    {
        return pos.x;
    }
    else
    {
        return Input.GetAxis("Horizontal");
    }
}

public float Vertical()
{
    if (pos.y != 0)
    {
        return pos.y;
    }
    else
    {
        return Input.GetAxis("Vertical");
    }
}
}
</code>```

This code works well and return dynamicly Vector2(x,y). So, now I want to move camera (change position X,Y) using this joystick and these coordinates. Do you have any idea how to do it? Everyones show how to move cube or sphere and nowhere how to translate a camera...

答:
This can be easily be done with the Translate function

```<code>Camera.main.transform.Translate(pos, Space.World);
</code>```

You need to also multiply it a number(speed) and Time.deltaTime to make sure the movement is the-same on every devices.

So, this is how the code should look like:

```<code>private Vector2 pos;
public float moveSpeed = 100f;
</code>```

Then, in your OnDrag or Update function:

```<code>Vector3 newPos = new Vector3(pos.x * moveSpeed, pos.y * moveSpeed, 0);
newPos *= Time.deltaTime;

Camera.main.transform.Translate(newPos, Space.World);
</code>```

Body:
I have a problem with camera movement using joystick in Unity. I wrote this code to my joystick

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {

private Image bgImg;
private Image joystickImg;
private Vector2 pos;

private void Start()
{
    bgImg = GetComponent<Image>();
    joystickImg = transform.GetChild(0).GetComponent<Image>();
}

public virtual void OnDrag(PointerEventData ped)
{
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {
        pos.x = (pos.x * 2 + 1) / bgImg.rectTransform.sizeDelta.x;
        pos.y = (pos.y * 2 - 1) / bgImg.rectTransform.sizeDelta.y;

        pos = (pos.magnitude > 1.0f) ? pos.normalized : pos;

        // Move Joystrick IMG
        joystickImg.rectTransform.anchoredPosition = new Vector2(pos.x * (bgImg.rectTransform.sizeDelta.x / 3), pos.y * (bgImg.rectTransform.sizeDelta.y / 3));
    }
}

public virtual void OnPointerDown(PointerEventData ped)
{
    OnDrag(ped);
}

public virtual void OnPointerUp(PointerEventData ped)
{
    pos = Vector2.zero;
    joystickImg.rectTransform.anchoredPosition = Vector2.zero;
}

public float Horizontal()
{
    if (pos.x != 0)
    {
        return pos.x;
    }
    else
    {
        return Input.GetAxis("Horizontal");
    }
}

public float Vertical()
{
    if (pos.y != 0)
    {
        return pos.y;
    }
    else
    {
        return Input.GetAxis("Vertical");
    }
}
}

This code works well and return dynamicly Vector2(x,y). So, now I want to move camera (change position X,Y) using this joystick and these coordinates. Do you have any idea how to do it? Everyones show how to move cube or sphere and nowhere how to translate a camera...

Body:
This can be easily be done with the Translate function

Camera.main.transform.Translate(pos, Space.World);

You need to also multiply it a number(speed) and Time.deltaTime to make sure the movement is the-same on every devices.

So, this is how the code should look like:

private Vector2 pos;
public float moveSpeed = 100f;

Then, in your OnDrag or Update function:

Vector3 newPos = new Vector3(pos.x * moveSpeed, pos.y * moveSpeed, 0);
newPos *= Time.deltaTime;

Camera.main.transform.Translate(newPos, Space.World);


来源: stackexchange

问:
Group consecutive rows of same value using time spans
Sorry for the vague title (I just don't know how to describe this conundrum)

Give the following schedule table for a classroom:

```<code>╔═══════════╦════════════╦═══════════╦═══════════╦═════════╗
║ Classroom ║ CourseName ║  Lesson   ║ StartTime ║ EndTime ║
╠═══════════╬════════════╬═══════════╬═══════════╬═════════╣
║      1001 ║ Course 1   ║ Lesson 1  ║      0800 ║    0900 ║
║      1001 ║ Course 1   ║ Lesson 2  ║      0900 ║    1000 ║
║      1001 ║ Course 1   ║ Lesson 3  ║      1000 ║    1100 ║
║      1001 ║ Course 2   ║ Lesson 10 ║      1100 ║    1200 ║
║      1001 ║ Course 2   ║ Lesson 11 ║      1200 ║    1300 ║
║      1001 ║ Course 1   ║ Lesson 4  ║      1300 ║    1400 ║
║      1001 ║ Course 1   ║ Lesson 5  ║      1400 ║    1500 ║
╚═══════════╩════════════╩═══════════╩═══════════╩═════════╝
</code>```

I would like to group the table to display this:

```<code>╔═══════════╦════════════╦═══════════╦═════════╗
║ Classroom ║ CourseName ║ StartTime ║ EndTime ║
╠═══════════╬════════════╬═══════════╬═════════╣
║      1001 ║ Course 1   ║      0800 ║    1100 ║
║      1001 ║ Course 2   ║      1100 ║    1300 ║
║      1001 ║ Course 1   ║      1300 ║    1500 ║
╚═══════════╩════════════╩═══════════╩═════════╝
</code>```

Basically we are looking at a schedule that show which crouse is using what classroom during a certain timespan...

My initial thought was:
Group by Classroom and CourseName and take Max and Min for start\end time but that will not give me the time spans it will show as if Course 1 is using the Classroom from 08:00 - 16:00 with no break in the middle.

答:
```<code>     CREATE TABLE Classroom(Classroom VARCHAR(100), CourseName  VARCHAR(100),  Lesson    VARCHAR(100), StartTime  VARCHAR(100), EndTime  VARCHAR(100))
 INSERT INTO Classroom
SELECT '1001','Course 1','Lesson 1 ','0800','0900'
UNION SELECT '1001','Course 1','Lesson 2 ','0900','1000'
UNION SELECT '1001','Course 1','Lesson 3 ','1000','1100'
UNION SELECT '1001','Course 2','Lesson 10','1100','1200'
UNION SELECT '1001','Course 2','Lesson 11','1200','1300'
UNION SELECT '1001','Course 1','Lesson 4 ','1300','1400'
UNION SELECT '1001','Course 1','Lesson 5 ','1400','1500'

SELECT * FROM Classroom

;WITH CTE_ClassRooms AS (
SELECT *,ROW_NUMBER() over(partition by classroom,CourseName order by StartTime) AS R FROM Classroom A
WHERE NOT EXISTS(SELECT 1 FROM Classroom B WHERE B.Classroom = A.Classroom AND B.CourseName = A.CourseName AND B.StartTime = A.EndTime)
UNION ALL
SELECT B.*,R fROM CTE_ClassRooms A JOIN Classroom B ON B.Classroom = A.Classroom AND B.CourseName = A.CourseName AND A.StartTime = B.EndTime
)

--SELECT * FROM CTE_ClassRooms order by Classroom,CourseName,R

SELECT Classroom,CourseName,MIN(StartTime),MAX(EndTime)
FROM CTE_ClassRooms
GROUP BY Classroom,CourseName,R
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Sorry for the vague title (I just don't know how to describe this conundrum)

Give the following schedule table for a classroom:

╔═══════════╦════════════╦═══════════╦═══════════╦═════════╗
║ Classroom ║ CourseName ║  Lesson   ║ StartTime ║ EndTime ║
╠═══════════╬════════════╬═══════════╬═══════════╬═════════╣
║      1001 ║ Course 1   ║ Lesson 1  ║      0800 ║    0900 ║
║      1001 ║ Course 1   ║ Lesson 2  ║      0900 ║    1000 ║
║      1001 ║ Course 1   ║ Lesson 3  ║      1000 ║    1100 ║
║      1001 ║ Course 2   ║ Lesson 10 ║      1100 ║    1200 ║
║      1001 ║ Course 2   ║ Lesson 11 ║      1200 ║    1300 ║
║      1001 ║ Course 1   ║ Lesson 4  ║      1300 ║    1400 ║
║      1001 ║ Course 1   ║ Lesson 5  ║      1400 ║    1500 ║
╚═══════════╩════════════╩═══════════╩═══════════╩═════════╝

I would like to group the table to display this:

╔═══════════╦════════════╦═══════════╦═════════╗
║ Classroom ║ CourseName ║ StartTime ║ EndTime ║
╠═══════════╬════════════╬═══════════╬═════════╣
║      1001 ║ Course 1   ║      0800 ║    1100 ║
║      1001 ║ Course 2   ║      1100 ║    1300 ║
║      1001 ║ Course 1   ║      1300 ║    1500 ║
╚═══════════╩════════════╩═══════════╩═════════╝

Basically we are looking at a schedule that show which crouse is using what classroom during a certain timespan...

My initial thought was:
Group by Classroom and CourseName and take Max and Min for start\end time but that will not give me the time spans it will show as if Course 1 is using the Classroom from 08:00 - 16:00 with no break in the middle.


问:
unable to understand docker cp command

I am trying to copy file from docker container to host. I have attached the snapshot in which I listed all the containers as well as container file structure. But when I execute docker cp, it says it could not find the file. Can anyone tell me what wrong am I doing or if I am missing something. I am very new to docker so please guide me through.

答:
I think you need to absolute path to the file inside the container. See the following.

Copying files from Docker container to host

```<code>docker cp <CONTAINER>:/<ABS_PATH>/procfile .
</code>```

Title: unable to understand docker cp command

Body:
I think you need to absolute path to the file inside the container. See the following.

Copying files from Docker container to host

docker cp <CONTAINER>:/<ABS_PATH>/procfile .


问:
Changing the value of a single node in XML
I have the following XML document:

```<code><People>
  <Person>
    <Name>Dylan</Name>
    <Email>email</Email>
    <Age>4</Age>
  </Person>
  <Person>
    <Name>Name</Name>
    <Email>name</Email>
    <Age>16</Age>
  </Person>
  <Person>
    <Name>ok</Name>
    <Email>name</Email>
    <Age>16</Age>
  </Person>
</People>
</code>```

This is the code used to create the file, hope that helps.
I'm trying to be able to select a certain Person via their name and change update their age to another value. I've managed to compare a user entered name with one in the document but have no idea how to go about updating the age after this.

```<code>XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Dylan\\Desktop\\people.xml");
string name = textBox1.Text;
bool correct = false;

foreach (XmlNode node in doc.SelectNodes("//Person"))
{
    string Name = node.SelectSingleNode("Name").InnerText;
    if (Name == name)
    {
        //code to change age
    }
    if (correct == true) break;
 }
</code>```

This is the code used to create the file:

```<code>     XmlTextWriter x = new XmlTextWriter("C:\\Users\\Dylan\\Desktop\\people.xml", Encoding.UTF8);
        x.Formatting = Formatting.Indented;
        x.WriteStartElement("People");
        x.WriteStartElement("Person");
        x.WriteStartElement("Name");
        x.WriteString(textBox1.Text);
        x.WriteEndElement();
        x.WriteStartElement("Email");
        x.WriteString(textBox2.Text);
        x.WriteEndElement();
        x.WriteStartElement("Age");
        x.WriteString(numericUpDown1.Value.ToString());
        x.WriteEndElement();
        x.WriteEndElement();
        x.WriteEndElement();
        x.Close();
        MessageBox.Show("Created!");
</code>```

答:
You should be able to update the age as follows:</p>

```<code>XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Dylan\\Desktop\\people.xml");
string name = textBox1.Text;
bool correct = false;

foreach (XmlNode node in doc.SelectNodes("//Person"))
{
    string Name = node.SelectSingleNode("Name").InnerText;
    if (Name == name)
    {
        // Using the Person node, select the Age node
        XmlNode ageNode = node.SelectSingleNode("Age");

        // Update the value with whatever new value is required
        ageNode.InnerText = "10";
    }

    if (correct == true) break;
}

// Remember to save the changes!
doc.Save("C:\\Users\\Dylan\\Desktop\\people.xml");
</code>```

Body:
I have the following XML document:

<People>
  <Person>
    <Name>Dylan</Name>
    <Email>email</Email>
    <Age>4</Age>
  </Person>
  <Person>
    <Name>Name</Name>
    <Email>name</Email>
    <Age>16</Age>
  </Person>
  <Person>
    <Name>ok</Name>
    <Email>name</Email>
    <Age>16</Age>
  </Person>
</People>

This is the code used to create the file, hope that helps.
I'm trying to be able to select a certain Person via their name and change update their age to another value. I've managed to compare a user entered name with one in the document but have no idea how to go about updating the age after this.

XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Dylan\\Desktop\\people.xml");
string name = textBox1.Text;
bool correct = false;

foreach (XmlNode node in doc.SelectNodes("//Person"))
{
    string Name = node.SelectSingleNode("Name").InnerText;
    if (Name == name)
    {
        //code to change age
    }
    if (correct == true) break;
 }

This is the code used to create the file:

     XmlTextWriter x = new XmlTextWriter("C:\\Users\\Dylan\\Desktop\\people.xml", Encoding.UTF8);
        x.Formatting = Formatting.Indented;
        x.WriteStartElement("People");
        x.WriteStartElement("Person");
        x.WriteStartElement("Name");
        x.WriteString(textBox1.Text);
        x.WriteEndElement();
        x.WriteStartElement("Email");
        x.WriteString(textBox2.Text);
        x.WriteEndElement();
        x.WriteStartElement("Age");
        x.WriteString(numericUpDown1.Value.ToString());
        x.WriteEndElement();
        x.WriteEndElement();
        x.WriteEndElement();
        x.Close();
        MessageBox.Show("Created!");

Body:
You should be able to update the age as follows:

XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Dylan\\Desktop\\people.xml");
string name = textBox1.Text;
bool correct = false;

foreach (XmlNode node in doc.SelectNodes("//Person"))
{
    string Name = node.SelectSingleNode("Name").InnerText;
    if (Name == name)
    {
        // Using the Person node, select the Age node
        XmlNode ageNode = node.SelectSingleNode("Age");

        // Update the value with whatever new value is required
        ageNode.InnerText = "10";
    }

    if (correct == true) break;
}

// Remember to save the changes!
doc.Save("C:\\Users\\Dylan\\Desktop\\people.xml");


问:
MongoDB: Get single document with specific parent id and highest order value
My documents have the key order, which is an ascending numeric value.

Now I would like to get the highest order value of all documents which has a specific parent value.

What I am doing is (I'm using mongo native driver)

find all documents with the specific parent id

sort the result in descending order

limit to 1 document

I'm doing this, as I think findOne can't sort the documents. Am I right with that?

```<code>const last = await Content.find({ parent: parentID }).sort({ order: -1 }).limit(1).toArray()
console.log(last[0].order)
</code>```

Now I get an array with a single document. But is it possible to get only the document itself without returning the result as an array?

答:
You want to use findOne like this:</p>

```<code>var options = {
    "sort": [['order','desc']]
};

Content.findOne({ parent: parentID }, options, function(err, result) {
    if (err) throw err;
    console.log(result);
});
</code>```

Body:
My documents have the key order, which is an ascending numeric value.

Now I would like to get the highest order value of all documents which has a specific parent value.

What I am doing is (I'm using mongo native driver)

find all documents with the specific parent id

sort the result in descending order

limit to 1 document

I'm doing this, as I think findOne can't sort the documents. Am I right with that?

const last = await Content.find({ parent: parentID }).sort({ order: -1 }).limit(1).toArray()
console.log(last[0].order)

Now I get an array with a single document. But is it possible to get only the document itself without returning the result as an array?

Body:
You want to use findOne like this:

var options = {
    "sort": [['order','desc']]
};

Content.findOne({ parent: parentID }, options, function(err, result) {
    if (err) throw err;
    console.log(result);
});


问:
SQL Count Error
I am trying to use a count function to show me how many employees have the title "Sales"

```<code>if( !$connect)
{
die("ERROR: Cannot connect to database $db on server $server
using user name $user (".mysqli_connect_errno().
", ".mysqli_connect_error().")");
}
else
{
$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";

$result = mysqli_query($connect, $userQuery);

if (!$result)
{
    die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}

if (mysqli_num_rows($result) == 0)
{
    print("No records found with query $userQuery");
}
else
{
     print("<h1>SALES STAFF REPORT</h1>");
     while ($row = mysqli_fetch_assoc($result))
    {
        print("<p>There are
        ".$row['COUNT(empID)']."</p>");
    }

}
 mysqli_close($connect);   // close the connection
}
?>
</code>```

I am getting this error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'COUNT(empID) FROM personnel WHERE jobTitle='Sales'' at line 1

on this line:

```<code>$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";
</code>```

I am unsure of what I am doing incorrectly, but any help would be appreciated.

End result should read "There are 4 sales staff".

My professor did include this in the assignment, not sure if that will help.

```<code>"There are two different MySQL functions that you can use here: you can
modify the SELECT statement to use a MySQL aggregation function,
or you can use the MySQL function that returns the number of records in the
result set. "
</code>```

答:
You are missing the SELECT keyword when making the statement.

You have:
$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";

It should be:
$userQuery = "SELECT COUNT(empID) FROM personnel WHERE jobTitle='Sales'";

Title: SQL Count Error

Body:
I am trying to use a count function to show me how many employees have the title "Sales"

if( !$connect)
{
die("ERROR: Cannot connect to database $db on server $server
using user name $user (".mysqli_connect_errno().
", ".mysqli_connect_error().")");
}
else
{
$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";

$result = mysqli_query($connect, $userQuery);

if (!$result)
{
    die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}

if (mysqli_num_rows($result) == 0)
{
    print("No records found with query $userQuery");
}
else
{
     print("
SALES STAFF REPORT
");
     while ($row = mysqli_fetch_assoc($result))
    {
        print("
There are
        ".$row['COUNT(empID)']."
");
    }

}
 mysqli_close($connect);   // close the connection
}
?>

I am getting this error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'COUNT(empID) FROM personnel WHERE jobTitle='Sales'' at line 1

on this line:

$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";

I am unsure of what I am doing incorrectly, but any help would be appreciated.

End result should read "There are 4 sales staff".

My professor did include this in the assignment, not sure if that will help.

"There are two different MySQL functions that you can use here: you can
modify the SELECT statement to use a MySQL aggregation function,
or you can use the MySQL function that returns the number of records in the
result set. "


问:
How do I write an update statement when the attribute I am updating is user input?
```<code>def updateNurseSpecification():

    nurse_lname = input("\nEnter the last name of the nurse "
                    "you would to update: \n")

    query = c.execute('SELECT fname, lname, specification FROM Nurses '
                  'WHERE lname LIKE ?', (nurse_lname,))

    new_spec = input("\nEnter the updated specification of this employee: \n")

    query1 = c.execute('UPDATE Nurses SET specification = ', (new_spec,)
                  ' WHERE lname LIKE ?', (nurse_lname,))
</code>```

I do not know the syntax in order to update the record with the variable "new_spec".

```<code>    print("Your update is as shown: \t")

    query2 = c.execute('SELECT fname, lname, specification FROM Nurses'
                 'WHERE lname LIKE ?', (nurse_lname,))
</code>```

答:
execute takes two parameters - an SQL string and a tuple of arguments:

```<code>c.execute('UPDATE Nurses SET specification = %s WHERE lname LIKE %s',
          (new_spec, nurse_lname))
</code>```

Body:
def updateNurseSpecification():

    nurse_lname = input("\nEnter the last name of the nurse "
                    "you would to update: \n")

    query = c.execute('SELECT fname, lname, specification FROM Nurses '
                  'WHERE lname LIKE ?', (nurse_lname,))

    new_spec = input("\nEnter the updated specification of this employee: \n")

    query1 = c.execute('UPDATE Nurses SET specification = ', (new_spec,)
                  ' WHERE lname LIKE ?', (nurse_lname,))

I do not know the syntax in order to update the record with the variable "new_spec".

    print("Your update is as shown: \t")

    query2 = c.execute('SELECT fname, lname, specification FROM Nurses'
                 'WHERE lname LIKE ?', (nurse_lname,))

Body:
execute takes two parameters - an SQL string and a tuple of arguments:

c.execute('UPDATE Nurses SET specification = %s WHERE lname LIKE %s',
          (new_spec, nurse_lname))


问:
Enable validation for Hidden elements
Hi I want to validate hidden field value in MVC 5. Below is the view side code

```<code>@Html.HiddenFor(m => m.DecalLogoFileName, new { id = "hdImageName" })
@Html.ValidationMessageFor(model => model.DecalLogoFileName)
</code>```

I have many editor control for which validation is getting fire but any how this validation control is not getting fire on submit click

```<code><img id="DecalLogo" name="DecalLogo" class="photo" ImageUrl="" />
@Html.HiddenFor(m => m.DecalLogoFileName, new { id = "hdImageName" })
@Html.ValidationMessageFor(model => model.DecalLogoFileName)
<label for="imgInp" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i>Upload Logo
</label>
<input type='file' id="imgInp" name="image" />

<script type="text/javascript">
//Preview & Update an image before it is uploaded
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#DecalLogo').attr('src', e.target.result);
            $('#hdImageName').val(e.target.result);//Here I am filling my Hidden field control
        }
        reader.readAsDataURL(input.files[0]);
    }
}
$("#imgInp").change(function () {
    readURL(this);
});
</code>```

From above script code I am filling the value of hidden field control and I want to validate luike if this script is not fired then validation should get display.

How can I validate in MVC that on submit click that Image is upload or not.

答:
Basically jQuery validate ignores hidden fields,display:none and any element with has invisible parent what you can do is override default behavior by applying

$("#yourformid").data("validator").settings.ignore = "";

OR

$.validator.setDefaults({ ignore: [] });

This should not in document.ready

Above line of code will validate all hidden fields in form which you have passed in some of the cases it's not quite good in some case you just want to validate only hidden field which has a particular class XYZ then do it like below

$.validator.setDefaults({ ignore: ':hidden:not(.XYZ)' });,

Above line of code set a validator as a way to ignore all hiddenfields but validate hiddenfield whose class is XYZ

UPDATE

Validate Fields with particular class even if it's hidden.

$(document).ready(function() {
  $.validator.setDefaults({
    ignore: ":hidden:not('.Validateclass')" // validate all hidden fields with specified class
  });
  $('form').valid();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<form id="form">
  <input class="Validateclass" name="hoge1" type="hidden" data-val-required="The field is required." data-val="true" required />
  <span data-valmsg-for="hoge1" data-valmsg-replace="true"></span>
  <input name="hoge2" type="hidden" data-val-required="The field is required." data-val="true" required/>
  <span data-valmsg-for="hoge2" data-valmsg-replace="true"></span>
  <input type="submit" />
</form></code>```

ContentLicense: CC BY-SA 4.0

Title: Enable validation for Hidden elements

Body:
Hi I want to validate hidden field value in MVC 5. Below is the view side code

@Html.HiddenFor(m => m.DecalLogoFileName, new { id = "hdImageName" })
@Html.ValidationMessageFor(model => model.DecalLogoFileName)

I have many editor control for which validation is getting fire but any how this validation control is not getting fire on submit click

@Html.HiddenFor(m => m.DecalLogoFileName, new { id = "hdImageName" })
@Html.ValidationMessageFor(model => model.DecalLogoFileName)

Upload Logo

<input type='file' id="imgInp" name="image" />

Body:
Basically jQuery validate ignores hidden fields,display:none and any element with has invisible parent what you can do is override default behavior by applying

$("#yourformid").data("validator").settings.ignore = "";

OR

$.validator.setDefaults({ ignore: [] });

This should not in document.ready

Above line of code will validate all hidden fields in form which you have passed in some of the cases it's not quite good in some case you just want to validate only hidden field which has a particular class XYZ then do it like below

$.validator.setDefaults({ ignore: ':hidden:not(.XYZ)' });,

Above line of code set a validator as a way to ignore all hiddenfields but validate hiddenfield whose class is XYZ

UPDATE

Validate Fields with particular class even if it's hidden.

$(document).ready(function() {
  $.validator.setDefaults({
    ignore: ":hidden:not('.Validateclass')" // validate all hidden fields with specified class
  });
  $('form').valid();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<form id="form">
  <input class="Validateclass" name="hoge1" type="hidden" data-val-required="The field is required." data-val="true" required />
  <span data-valmsg-for="hoge1" data-valmsg-replace="true"></span>
  <input name="hoge2" type="hidden" data-val-required="The field is required." data-val="true" required/>
  <span data-valmsg-for="hoge2" data-valmsg-replace="true"></span>
  <input type="submit" />
</form>


问:
Twitter Bootstrap v4 and jQuery 3.2.1
I'm trying to migrate to the new version of bootstrap and jQuery.

Dropdown in example not working and console outputs error:

```<code>> Syntax error, unrecognized expression: #
</code>```

This is my code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

  </button>
  Navbar

        Home (current)

        Features

        Pricing

          Dropdown link

          Action
          Another action
          Something else here

```

jquery doesn't add class "show" to parent li and doesn't change aria-expanded attribute.

Seems like jquery v3.2.1 not compatible with botstrap v4, but i saw examples which uses this versions.

Please, help me to resolve this problem.

答:
You did not include Popper.js in your markup.

The javascript part of Bootstrap 4 has been built on top of jQuery and Popper.js. As the documentation points it out: "jQuery must come first, then Popper.js, and then our JavaScript plugins". Including Popper.js will eliminate your error.

Additionally, it is also suggested that these

```

Title: Twitter Bootstrap v4 and jQuery 3.2.1

Body:
I'm trying to migrate to the new version of bootstrap and jQuery.

Dropdown in example not working and console outputs error:

> Syntax error, unrecognized expression: #

This is my code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

  </button>
  Navbar

        Home (current)

        Features

        Pricing

          Dropdown link

          Action
          Another action
          Something else here

jquery doesn't add class "show" to parent li and doesn't change aria-expanded attribute.

Seems like jquery v3.2.1 not compatible with botstrap v4, but i saw examples which uses this versions.

Please, help me to resolve this problem.

Body:
You did not include Popper.js in your markup.

The javascript part of Bootstrap 4 has been built on top of jQuery and Popper.js. As the documentation points it out: "jQuery must come first, then Popper.js, and then our JavaScript plugins". Including Popper.js will eliminate your error.

Additionally, it is also suggested that these <script> tags should go to near to the end of the pages, right before the closing </body> tag.

So your markup should look like this:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="#">Navbar</a>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown link
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>
  </div>
</nav>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>


问:
Very slow cursor SQL Server
I don't know why this is so slow

```<code>DECLARE kursor CURSOR FOR
    SELECT mediatime, ShortDate, MediaDateID, TimeID
    FROM DateTimeMCross

DECLARE @mediatime INT, @ShortDate DATE, @MediaDateID INT, @TimeID INT, @tmpDate DATE

SET @mediatime = 0;

OPEN kursor

FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID

WHILE @@FETCH_STATUS = 0
BEGIN
    /*SET @tmpDate = (select DATEADD(day,-1,@shortDate))*/
    IF @mediatime >= 2400
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = 2/*(SELECT     YEAR(@tmpDate) * 10000 + MONTH(@tmpDate) * 100 + DAY(@tmpDate))*/
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END
    ELSE IF @mediatime < 2400 AND @mediatime >= 0
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = @MediaDateID
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END

    FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID
END

CLOSE kursor
DEALLOCATE kursor
</code>```

I make before one statement with cursor and it was fast and this is really really slow.

I thought at the beginning it was caused by DATEADD() and other function but no. After comment out it is as slow as before

答:
This reaaaaaally doesn't need to be a cursor at all. Seems like you want a simple UPDATE:

```<code>UPDATE DateTimeMCross
SET newMediaDateID = CASE
                        WHEN mediatime >= 2400 THEN 2
                        ELSE MediaDateID
                     END
;
</code>```

Title: Very slow cursor SQL Server

Body:
I don't know why this is so slow

DECLARE kursor CURSOR FOR
    SELECT mediatime, ShortDate, MediaDateID, TimeID
    FROM DateTimeMCross

DECLARE @mediatime INT, @ShortDate DATE, @MediaDateID INT, @TimeID INT, @tmpDate DATE

SET @mediatime = 0;

OPEN kursor

FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID

WHILE @@FETCH_STATUS = 0
BEGIN
    /*SET @tmpDate = (select DATEADD(day,-1,@shortDate))*/
    IF @mediatime >= 2400
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = 2/*(SELECT     YEAR(@tmpDate) * 10000 + MONTH(@tmpDate) * 100 + DAY(@tmpDate))*/
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END
    ELSE IF @mediatime < 2400 AND @mediatime >= 0
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = @MediaDateID
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END

    FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID
END

CLOSE kursor
DEALLOCATE kursor

I make before one statement with cursor and it was fast and this is really really slow.

I thought at the beginning it was caused by DATEADD() and other function but no. After comment out it is as slow as before

Body:
This reaaaaaally doesn't need to be a cursor at all. Seems like you want a simple UPDATE:

UPDATE DateTimeMCross
SET newMediaDateID = CASE
                        WHEN mediatime >= 2400 THEN 2
                        ELSE MediaDateID
                     END
;


问:
Jquery autocomplete on dynamically created inputs
I am still learning javascript and Jquery. I am creating simple autocomplete with jQuery:

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

答:
As a ID is unique you should not assign a ID twice. Use a class for this instead. So your code would look something like this:

JS:

```<code>$(function() {
    $(".nazov").autocomplete({
    minLength: 2,
    source: 'private/search.php',

    select: function(event, ui) {
        document.getElementByClass("pocet").value = ui.item.pocet;
    }
  });
});
</code>```

HTML:

```<code><label for="nazov">Názov: </label>
<input class="nazov">
<input class="pocet">
</code>```

Hope this helps

Body:
As a ID is unique you should not assign a ID twice. Use a class for this instead. So your code would look something like this:

JS:

$(function() {
    $(".nazov").autocomplete({
    minLength: 2,
    source: 'private/search.php',

    select: function(event, ui) {
        document.getElementByClass("pocet").value = ui.item.pocet;
    }
  });
});

HTML:

<label for="nazov">Názov: </label>
<input class="nazov">
<input class="pocet">

Hope this helps


问:
iOS 11 custom titleView size; autolayout seems to be ignored
I have a uinavigationbar as part of a navigationcontroller that I need to be 70 pixels high. Pre-iOS11 there are various solutions and I implemented one.

During the iOS 11 beta, I tried various ways of using autolayout to size the titleView. According to the WWDC talk, it should recognize width+height constraints within the titleview and accommodate them. It does not appear to do so.

It looks like it conflicts with the built in UILayoutGuide

```<code>(
    "<NSLayoutConstraint:0x60000008c760 UILayoutGuide:0x6000001acbe0'TitleView(0x7fe600c0a710)'.height == 44   (active)>",
    "<NSLayoutConstraint:0x61400008c6c0 EasyRelease.CustomTitleView:0x7fe606008e70.top >= UILayoutGuide:0x6000001acbe0'TitleView(0x7fe600c0a710)'.top   (active)>",
    "<NSLayoutConstraint:0x61400008c800 EasyRelease.CustomTitleView:0x7fe606008e70.centerY == UILayoutGuide:0x6000001acbe0'TitleView(0x7fe600c0a710)'.centerY   (active)>",
    "<NSLayoutConstraint:0x61400008bbd0 EasyRelease.CustomTitleView:0x7fe606008e70.height == 70   (active)>"
)
</code>```

What gives? Is this feature not implemented correctly in iOS11, or am I missing something? Are there any known workarounds for adjusting titleview+uinavigationbar height?

edit: The way my code works, is I have added width + height constraints to the titleView. Is there anything else I should do? From the WWDC presentation this looked sufficient.

答:
This could work, it put a view above the NavigationBar.
You should note that your image should be 70 pixels height.
13 is a magic number for 70 pixels image, because it appears centered in the navigation bar.</p>

```<code>-(void)updateNavBarBackground{
    [[self.navigationController.navigationBar viewWithTag:1] removeFromSuperview];
    UIImage * image = [ UIImage imageNamed:@"NavBarImage"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.center = CGPointMake(self.navigationController.navigationBar.frame.size.width  / 2,
                               self.navigationController.navigationBar.frame.size.height / 2 - 13);

    imageView.tag = 1;
    [self.navigationController.navigationBar addSubview : imageView];
}
</code>```

Body:
I have a uinavigationbar as part of a navigationcontroller that I need to be 70 pixels high. Pre-iOS11 there are various solutions and I implemented one.

During the iOS 11 beta, I tried various ways of using autolayout to size the titleView. According to the WWDC talk, it should recognize width+height constraints within the titleview and accommodate them. It does not appear to do so.

It looks like it conflicts with the built in UILayoutGuide

(
    "<NSLayoutConstraint:0x60000008c760 UILayoutGuide:0x6000001acbe0'TitleView(0x7fe600c0a710)'.height == 44   (active)>",
    "<NSLayoutConstraint:0x61400008c6c0 EasyRelease.CustomTitleView:0x7fe606008e70.top >= UILayoutGuide:0x6000001acbe0'TitleView(0x7fe600c0a710)'.top   (active)>",
    "<NSLayoutConstraint:0x61400008c800 EasyRelease.CustomTitleView:0x7fe606008e70.centerY == UILayoutGuide:0x6000001acbe0'TitleView(0x7fe600c0a710)'.centerY   (active)>",
    "<NSLayoutConstraint:0x61400008bbd0 EasyRelease.CustomTitleView:0x7fe606008e70.height == 70   (active)>"
)

What gives? Is this feature not implemented correctly in iOS11, or am I missing something? Are there any known workarounds for adjusting titleview+uinavigationbar height?

edit: The way my code works, is I have added width + height constraints to the titleView. Is there anything else I should do? From the WWDC presentation this looked sufficient.

Body:
This could work, it put a view above the NavigationBar.
You should note that your image should be 70 pixels height.
13 is a magic number for 70 pixels image, because it appears centered in the navigation bar.

-(void)updateNavBarBackground{
    [[self.navigationController.navigationBar viewWithTag:1] removeFromSuperview];
    UIImage * image = [ UIImage imageNamed:@"NavBarImage"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.center = CGPointMake(self.navigationController.navigationBar.frame.size.width  / 2,
                               self.navigationController.navigationBar.frame.size.height / 2 - 13);

    imageView.tag = 1;
    [self.navigationController.navigationBar addSubview : imageView];
}


问:
spring-cloud-config in docker-compose https certificate not found
I am writing spring cloud application my config service point to my repository. In my development machine everything is working properly but when I create the docker with the help of docker-compose, my virtual machines give the following errors:

```<code>2017-02-28T03:14:10.847459300Z
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141) ~[na:1.8.0_91]
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126) ~[na:1.8.0_91]
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) ~[na:1.8.0_91]
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382) ~[na:1.8.0_91]
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[na:1.8.0_91]
at sun.security.validator.Validator.validate(Validator.java:260) ~[na:1.8.0_91]
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) ~[na:1.8.0_91]
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) ~[na:1.8.0_91]
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) ~[na:1.8.0_91]
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491) ~[na:1.8.0_91]
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216) ~[na:1.8.0_91]
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979) ~[na:1.8.0_91]
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[na:1.8.0_91]
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441) ~[na:1.8.0_91]
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338) ~[na:1.8.0_91]
at org.eclipse.jgit.transport.http.JDKHttpConnection.getResponseCode(JDKHttpConnection.java:98) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.util.HttpSupport.response(HttpSupport.java:196) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.TransportHttp.connect(TransportHttp.java:489) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.TransportHttp.openFetch(TransportHttp.java:311) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:136) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1201) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:128) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:203) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:136) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.cloneToBasedir(JGitEnvironmentRepository.java:399) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.copyRepository(JGitEnvironmentRepository.java:373) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.createGitClient(JGitEnvironmentRepository.java:358) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.refresh(JGitEnvironmentRepository.java:177) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.getLocations(JGitEnvironmentRepository.java:155) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository.getLocations(MultipleJGitEnvironmentRepository.java:132) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.AbstractScmEnvironmentRepository.findOne(AbstractScmEnvironmentRepository.java:42) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository.findOne(MultipleJGitEnvironmentRepository.java:170) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.CompositeEnvironmentRepository.findOne(CompositeEnvironmentRepository.java:45) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]

at org.springframework.cloud.config.server.environment.EnvironmentEncryptorEnvironmentRepository.findOne(EnvironmentEncryptorEnvironmentRepository.java:53) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.EnvironmentController.labelled(EnvironmentController.java:112) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) ~[spring-boot-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108) ~[spring-boot-actuator-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.cloud.sleuth.instrument.web.TraceFilter.doFilter(TraceFilter.java:145) ~[spring-cloud-sleuth-core-1.2.0.BUILD-SNAPSHOT.jar!/:1.2.0.BUILD-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) ~[spring-boot-actuator-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
</code>```

I assume that I my config cannot access the https certificates. How to compose the image with yaml to tell the docker about the ssl certificates?

答:
First, you’ll want to create a directory where you can hold the docker compose yaml file and the ssl certificates.

```<code>├── docker-compose.yml
└── ssl
    ├── cert.key
    └── cert.pem
</code>```

In the docker-compose.yml mount the volumes inside the container something like this and copy the cert:

```<code>version: '2'

services:
  image: hub:application-service
    volumes:
      - ./ssl:/etc/ssl
</code>```

Body:
I am writing spring cloud application my config service point to my repository. In my development machine everything is working properly but when I create the docker with the help of docker-compose, my virtual machines give the following errors:

2017-02-28T03:14:10.847459300Z
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141) ~[na:1.8.0_91]
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126) ~[na:1.8.0_91]
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) ~[na:1.8.0_91]
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382) ~[na:1.8.0_91]
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[na:1.8.0_91]
at sun.security.validator.Validator.validate(Validator.java:260) ~[na:1.8.0_91]
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) ~[na:1.8.0_91]
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) ~[na:1.8.0_91]
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) ~[na:1.8.0_91]
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491) ~[na:1.8.0_91]
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216) ~[na:1.8.0_91]
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979) ~[na:1.8.0_91]
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403) ~[na:1.8.0_91]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[na:1.8.0_91]
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441) ~[na:1.8.0_91]
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338) ~[na:1.8.0_91]
at org.eclipse.jgit.transport.http.JDKHttpConnection.getResponseCode(JDKHttpConnection.java:98) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.util.HttpSupport.response(HttpSupport.java:196) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.TransportHttp.connect(TransportHttp.java:489) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.TransportHttp.openFetch(TransportHttp.java:311) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:136) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1201) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:128) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:203) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:136) ~[org.eclipse.jgit-4.6.0.201612231935-r.jar!/:4.6.0.201612231935-r]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.cloneToBasedir(JGitEnvironmentRepository.java:399) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.copyRepository(JGitEnvironmentRepository.java:373) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.createGitClient(JGitEnvironmentRepository.java:358) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.refresh(JGitEnvironmentRepository.java:177) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.getLocations(JGitEnvironmentRepository.java:155) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository.getLocations(MultipleJGitEnvironmentRepository.java:132) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.AbstractScmEnvironmentRepository.findOne(AbstractScmEnvironmentRepository.java:42) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository.findOne(MultipleJGitEnvironmentRepository.java:170) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.CompositeEnvironmentRepository.findOne(CompositeEnvironmentRepository.java:45) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]

at org.springframework.cloud.config.server.environment.EnvironmentEncryptorEnvironmentRepository.findOne(EnvironmentEncryptorEnvironmentRepository.java:53) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at org.springframework.cloud.config.server.environment.EnvironmentController.labelled(EnvironmentController.java:112) ~[spring-cloud-config-server-1.3.0.BUILD-SNAPSHOT.jar!/:1.3.0.BUILD-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) ~[spring-boot-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108) ~[spring-boot-actuator-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.cloud.sleuth.instrument.web.TraceFilter.doFilter(TraceFilter.java:145) ~[spring-cloud-sleuth-core-1.2.0.BUILD-SNAPSHOT.jar!/:1.2.0.BUILD-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) ~[spring-boot-actuator-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.6.RELEASE.jar!/:4.3.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar!/:8.5.11]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]

I assume that I my config cannot access the https certificates. How to compose the image with yaml to tell the docker about the ssl certificates?

Body:
First, you’ll want to create a directory where you can hold the docker compose yaml file and the ssl certificates.

├── docker-compose.yml
└── ssl
    ├── cert.key
    └── cert.pem

In the docker-compose.yml mount the volumes inside the container something like this and copy the cert:

version: '2'

services:
  image: hub:application-service
    volumes:
      - ./ssl:/etc/ssl


问:
Kotlin Coroutines with timeout
I'm currently writing a test-function which should run a block or (when a certain timeout is reached) throws an exception.

I was trying this with Coroutines in Kotlin but ended up with a mixture of Coroutines and CompletableFuture:

```<code>fun <T> runBlockWithTimeout(maxTimeout: Long, block: () -> T ): T {
    val future = CompletableFuture<T>()

    // runs the coroutine
    launch { block() }

    return future.get(maxTimeout, TimeUnit.MILLISECONDS)
}
</code>```

This works, but I'm not sure if this is the intended way to solve that problem in kotlin.

I also tried other approaches:

```<code>runBlocking {
    withTimeout(maxTimeout) {
        block()
    }
}
</code>```

But this seems not to work as soon as the block calls e.g. Thread.sleep(...)

So is the CompletableFuture approach the way to go or is there a better one?

update 1
What I want to achieve:

Async Integration-Test code (like receiving data from RabbitMq) should be tested somehow like this:

```<code>var rabbitResults: List = ... // are filled async via RabbitListeners
...
waitMax(1000).toSucceed {
    assertThat(rabbitResults).hasSize(1)
}
waitMax(1000).toSucceed {
    assertThat(nextQueue).hasSize(3)
}
...
</code>```

答:
withTimeout { ... } is designed to cancel the ongoing operation on timeout, which is only possible if the operation in question is cancellable.

The reason it works with future.get(timeout, unit) is because it only waits with timeout. It does not actually cancel or abort in any way your background operation which still continues to execute after timeout had elapsed.

If you want to mimick similar behavior with coroutines, then you should wait with timeout, like this:

```<code>val d = async { block() } // run the block code in background
withTimeout(timeout, unit) { d.await() } // wait with timeout
</code>```

It works properly because await is a cancellable function which you can verify by reading its API documentation.

However, if you want to actually cancel the ongoing operation on timeout, then then you should implement your code in asyncronous and cancellable way. Cancellation is cooperative, so, to start, the underlying library that you are using in your code has to provide asynchronous API that supports cancellation of ongoing operation.

You can read more about cancellation and timeouts in the corresponding section of the coroutines guide and watch the KotlinConf's Deep Dive into Coroutines on how to integrate coroutines with asynchronous libraries.

Title: Kotlin Coroutines with timeout

Body:
I'm currently writing a test-function which should run a block or (when a certain timeout is reached) throws an exception.

I was trying this with Coroutines in Kotlin but ended up with a mixture of Coroutines and CompletableFuture:

fun <T> runBlockWithTimeout(maxTimeout: Long, block: () -> T ): T {
    val future = CompletableFuture<T>()

    // runs the coroutine
    launch { block() }

    return future.get(maxTimeout, TimeUnit.MILLISECONDS)
}

This works, but I'm not sure if this is the intended way to solve that problem in kotlin.

I also tried other approaches:

runBlocking {
    withTimeout(maxTimeout) {
        block()
    }
}

But this seems not to work as soon as the block calls e.g. Thread.sleep(...)

So is the CompletableFuture approach the way to go or is there a better one?

update 1
What I want to achieve:

Async Integration-Test code (like receiving data from RabbitMq) should be tested somehow like this:

var rabbitResults: List = ... // are filled async via RabbitListeners
...
waitMax(1000).toSucceed {
    assertThat(rabbitResults).hasSize(1)
}
waitMax(1000).toSucceed {
    assertThat(nextQueue).hasSize(3)
}
...

Body:
withTimeout { ... } is designed to cancel the ongoing operation on timeout, which is only possible if the operation in question is cancellable.

The reason it works with future.get(timeout, unit) is because it only waits with timeout. It does not actually cancel or abort in any way your background operation which still continues to execute after timeout had elapsed.

If you want to mimick similar behavior with coroutines, then you should wait with timeout, like this:

val d = async { block() } // run the block code in background
withTimeout(timeout, unit) { d.await() } // wait with timeout

It works properly because await is a cancellable function which you can verify by reading its API documentation.

However, if you want to actually cancel the ongoing operation on timeout, then then you should implement your code in asyncronous and cancellable way. Cancellation is cooperative, so, to start, the underlying library that you are using in your code has to provide asynchronous API that supports cancellation of ongoing operation.

You can read more about cancellation and timeouts in the corresponding section of the coroutines guide and watch the KotlinConf's Deep Dive into Coroutines on how to integrate coroutines with asynchronous libraries.


问:
Combining CPU-bound and IO-bound work in async method
There is such application:

```<code>    static void Main(string[] args)
    {
        HandleRequests(10).Wait();
        HandleRequests(50).Wait();
        HandleRequests(100).Wait();
        HandleRequests(1000).Wait();

        Console.ReadKey();
    }

    private static async Task IoBoundWork()
    {
        await Task.Delay(100);
    }

    private static void CpuBoundWork()
    {
        Thread.Sleep(100);
    }

    private static async Task HandleRequest()
    {
        CpuBoundWork();
        await IoBoundWork();
    }

    private static async Task HandleRequests(int numberOfRequests)
    {
        var sw = Stopwatch.StartNew();

        var tasks = new List<Task>();

        for (int i = 0; i < numberOfRequests; i++)
        {
            tasks.Add(HandleRequest());
        }

        await Task.WhenAll(tasks.ToArray());

        sw.Stop();

        Console.WriteLine(sw.Elapsed);
    }
</code>```

Below the output of this app:

From my perspective having CPU-bound and IO-bound parts in one method it is quite regular situation, e.g. parsing/archiving/serialization of some object and saving that to the disk, so it should probably work well. However in the implementation above it works very slow. Could you please help me to understand why?

If we wrap the body of CpuBoundWork() in Task it significantly improve performance:

```<code>    private static async Task CpuBoundWork()
    {
        await Task.Run(() => Thread.Sleep(100));
    }

    private static async Task HandleRequest()
    {
        await CpuBoundWork();
        await IoBoundWork();
    }
</code>```

Why it works so slow without Task.Run? Why we can see performance boost after adding Task.Run? Should we always use such approach in similar methods?

答:
```<code>for (int i = 0; i < numberOfRequests; i++)
    {
        tasks.Add(HandleRequest());
    }
</code>```

The returned task is created at the first await in the HandleRequest(). So you are executing all CPU bound code on one thread: the for loop thread. complete serialization, no parallelism at all.

When you wrap the CPU part in a task you are actually submitting the CPU part as Tasks, so they are executed in parallel.

Body:
There is such application:

    static void Main(string[] args)
    {
        HandleRequests(10).Wait();
        HandleRequests(50).Wait();
        HandleRequests(100).Wait();
        HandleRequests(1000).Wait();

        Console.ReadKey();
    }

    private static async Task IoBoundWork()
    {
        await Task.Delay(100);
    }

    private static void CpuBoundWork()
    {
        Thread.Sleep(100);
    }

    private static async Task HandleRequest()
    {
        CpuBoundWork();
        await IoBoundWork();
    }

    private static async Task HandleRequests(int numberOfRequests)
    {
        var sw = Stopwatch.StartNew();

        var tasks = new List<Task>();

        for (int i = 0; i < numberOfRequests; i++)
        {
            tasks.Add(HandleRequest());
        }

        await Task.WhenAll(tasks.ToArray());

        sw.Stop();

        Console.WriteLine(sw.Elapsed);
    }

Below the output of this app:

From my perspective having CPU-bound and IO-bound parts in one method it is quite regular situation, e.g. parsing/archiving/serialization of some object and saving that to the disk, so it should probably work well. However in the implementation above it works very slow. Could you please help me to understand why?

If we wrap the body of CpuBoundWork() in Task it significantly improve performance:

    private static async Task CpuBoundWork()
    {
        await Task.Run(() => Thread.Sleep(100));
    }

    private static async Task HandleRequest()
    {
        await CpuBoundWork();
        await IoBoundWork();
    }

Why it works so slow without Task.Run? Why we can see performance boost after adding Task.Run? Should we always use such approach in similar methods?

Body:
for (int i = 0; i < numberOfRequests; i++)
    {
        tasks.Add(HandleRequest());
    }

The returned task is created at the first await in the HandleRequest(). So you are executing all CPU bound code on one thread: the for loop thread. complete serialization, no parallelism at all.

When you wrap the CPU part in a task you are actually submitting the CPU part as Tasks, so they are executed in parallel.


答:
You've indicated that your method ought to be asynchronous, by having it return a Task, but you've not actually made it (entirely) asynchronous.  You're implementation of the method does a bunch of expensive, long running, work synchronously, and then returns to the caller and does some other work asynchronously.

Your callers of the method, however, assume that it's actually asynchronous (in entirety) and that it doesn't do expensive work synchronously.  They assume that they can call the method multiple times, have it return immediately, and then continue on, but since your implementation doesn't return immediately, and instead does a bunch of expensive work before returning, that code doesn't work properly (specifically, it's not able to start the next operation until the previous one returns, so that synchronous work isn't being done in parallel).

Note that your "fix" isn't quite idiomatic.  You're using the async over sync anti-pattern.  Rather than making CpuBoundWork async and having it return a Task, despite being a CPU bound operation, it should remain as is an HandleRequest should handle indicating that the CPU bound work should be done asynchronously in another thread by calling Task.Run:

```<code>private static async Task HandleRequest()
{
    await Task.Run(() => CpuBoundWork());
    await IoBoundWork();
}
</code>```

Title: Combining CPU-bound and IO-bound work in async method

Body:
You've indicated that your method ought to be asynchronous, by having it return a Task, but you've not actually made it (entirely) asynchronous.  You're implementation of the method does a bunch of expensive, long running, work synchronously, and then returns to the caller and does some other work asynchronously.

Your callers of the method, however, assume that it's actually asynchronous (in entirety) and that it doesn't do expensive work synchronously.  They assume that they can call the method multiple times, have it return immediately, and then continue on, but since your implementation doesn't return immediately, and instead does a bunch of expensive work before returning, that code doesn't work properly (specifically, it's not able to start the next operation until the previous one returns, so that synchronous work isn't being done in parallel).

Note that your "fix" isn't quite idiomatic.  You're using the async over sync anti-pattern.  Rather than making CpuBoundWork async and having it return a Task, despite being a CPU bound operation, it should remain as is an HandleRequest should handle indicating that the CPU bound work should be done asynchronously in another thread by calling Task.Run:

private static async Task HandleRequest()
{
    await Task.Run(() => CpuBoundWork());
    await IoBoundWork();
}


问:
Mapbox toggle all layers off except one
I am new to Mapbox and javascript. I'm attempting to slightly modify a Mapbox GL code example, found here, which allows for the toggling on/off of multiple layers.

I have four layers, and I would like the user to toggle these layers on and off, but when the map initially displays, I only want one layer toggled on. I am able to have three of the layers turned off when the page loads (here is one as an example):

```<code> map.addSource("gnat-4zdrvs", {
     type: 'vector',
       url: 'mapbox://jesselangdon.bbtex1ps'
 });
 map.addLayer({
     "id": "gnat",
     "type": "line",
     "source": "gnat-4zdrvs",
     "source-layer": "gnat-4zdrvs",
     "minzoom": 8,
         "filter": [
             "==",
             "$type",
             "LineString"
        ],
        "layout": {
            "visibility": "none",
            "line-cap": "round",
            "line-join": "round"
        },
        "paint": {
            "line-width": 2,
            "line-color": {
                "base": 1,
                "type": "interval",
                "property": "C_Sin",
                "stops": [
                    [1,"hsl(189, 81%, 79%)"],
                    [1.02,"hsl(189, 91%, 65%)"],
                    [1.04, "hsl(189, 81%, 53%)"],
                    [1.06,"hsl(189, 83%, 43%)"],
                    [1.08,"hsl(189, 89%, 34%)"],
                    [1.1,"hsl(189, 90%, 28%)"],
                    [1.3,"hsl(189, 96%, 21%)"]
                ],
                "default": "hsl(0, 0%, 50%)"
            }
        }
   })
</code>```

However, my limited knowledge of Javascript is keeping from figuring out how to set up the menu of clickable links so that only the "visible" layer is in a toggled "On" state.

Here's the code snippet which controls the toggle menu:

```<code>var toggleableLayerIds = [ 'conductivity', 'confinement', 'gnat', 'solar' ];

for (var i = 0; i < toggleableLayerIds.length; i++) {
    var id = toggleableLayerIds[i];

    var link = document.createElement('a');
    link.href = '#';
    link.className = 'active';
    link.textContent = id;

    link.onclick = function (e) {
        var clickedLayer = this.textContent;
        e.preventDefault();
        e.stopPropagation();

        var visibility = map.getLayoutProperty(clickedLayer, 'visibility');

        if (visibility === 'visible') {
            map.setLayoutProperty(clickedLayer, 'visibility', 'none');
            this.className = '';
        } else {
            this.className = 'active';
            map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
        }
    };

    var layers = document.getElementById('menu');
    layers.appendChild(link);
}
</code>```

The map is viewable here. Notice that all four layers in the toggle menu are blue (meaning they are in an "On" position, when in fact the only layer that is "on" is solar).  Any help, advice, or criticism is welcome... thanks!

答:
You are setting the class to active unconditionally on creation which will always make the link blue even if the layer is not visible. Try something like this. </p>

```<code>    if(map.getLayoutProperty(id, 'visibility') === 'visible')
    {
     link.className = 'active';
    }
</code>```

<p>Though this will need to be done inside the onload function otherwise the property will be undefined. </p>

Title: Mapbox toggle all layers off except one

Body:
I am new to Mapbox and javascript. I'm attempting to slightly modify a Mapbox GL code example, found here, which allows for the toggling on/off of multiple layers.

I have four layers, and I would like the user to toggle these layers on and off, but when the map initially displays, I only want one layer toggled on. I am able to have three of the layers turned off when the page loads (here is one as an example):

 map.addSource("gnat-4zdrvs", {
     type: 'vector',
       url: 'mapbox://jesselangdon.bbtex1ps'
 });
 map.addLayer({
     "id": "gnat",
     "type": "line",
     "source": "gnat-4zdrvs",
     "source-layer": "gnat-4zdrvs",
     "minzoom": 8,
         "filter": [
             "==",
             "$type",
             "LineString"
        ],
        "layout": {
            "visibility": "none",
            "line-cap": "round",
            "line-join": "round"
        },
        "paint": {
            "line-width": 2,
            "line-color": {
                "base": 1,
                "type": "interval",
                "property": "C_Sin",
                "stops": [
                    [1,"hsl(189, 81%, 79%)"],
                    [1.02,"hsl(189, 91%, 65%)"],
                    [1.04, "hsl(189, 81%, 53%)"],
                    [1.06,"hsl(189, 83%, 43%)"],
                    [1.08,"hsl(189, 89%, 34%)"],
                    [1.1,"hsl(189, 90%, 28%)"],
                    [1.3,"hsl(189, 96%, 21%)"]
                ],
                "default": "hsl(0, 0%, 50%)"
            }
        }
   })

However, my limited knowledge of Javascript is keeping from figuring out how to set up the menu of clickable links so that only the "visible" layer is in a toggled "On" state.

Here's the code snippet which controls the toggle menu:

var toggleableLayerIds = [ 'conductivity', 'confinement', 'gnat', 'solar' ];

for (var i = 0; i < toggleableLayerIds.length; i++) {
    var id = toggleableLayerIds[i];

    var link = document.createElement('a');
    link.href = '#';
    link.className = 'active';
    link.textContent = id;

    link.onclick = function (e) {
        var clickedLayer = this.textContent;
        e.preventDefault();
        e.stopPropagation();

        var visibility = map.getLayoutProperty(clickedLayer, 'visibility');

        if (visibility === 'visible') {
            map.setLayoutProperty(clickedLayer, 'visibility', 'none');
            this.className = '';
        } else {
            this.className = 'active';
            map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
        }
    };

    var layers = document.getElementById('menu');
    layers.appendChild(link);
}

The map is viewable here. Notice that all four layers in the toggle menu are blue (meaning they are in an "On" position, when in fact the only layer that is "on" is solar).  Any help, advice, or criticism is welcome... thanks!

Body:
You are setting the class to active unconditionally on creation which will always make the link blue even if the layer is not visible. Try something like this.

    if(map.getLayoutProperty(id, 'visibility') === 'visible')
    {
     link.className = 'active';
    }

Though this will need to be done inside the onload function otherwise the property will be undefined.


问:
How to use Webpack for Bootstrap?
I am using webpack to bundle some boostrap and other css files into one, the following is the webpack.config.js file
var htmlWebPack = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

```<code>module.exports = {
    entry: "./app/main.ts",
    output: {
        path: __dirname + '/dist',
        filename: "bundle.js"
    },
    resolve: {
    extensions: ['.js','.ts']
  },
    module: {
        loaders: [
          {
              test: /\.tsx?$/,
              loader: 'awesome-typescript-loader'
          },
          {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      },
      {
             test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
           loader: 'url-loader' }
        ]
    },
    plugins: [
    new htmlWebPack({
        template: './index.html',

    }),
      new ExtractTextPlugin("minified-style.css"),
    ]

};
</code>```

and i have referenced my bootstrap folder in the main.ts file like this

```<code>require('../Content/bootstrap/bootstrap.min.css');
require('../Content/bootstrap/bootstrap-theme.min.css');
</code>```

but when i run webpack, i am getting the error something like this

D:\project\angularControls\angularControls\node_modules\loader-runner\lib\loadLoader.js:35

throw new Error("Module '" + loader.path + "' is not a loader (must have           normal or pitch function)");

^ Error: Module
  'D:\project\angularControls\angularControls\node_modules\url\url.js'

is not a loader (must have normal or pitch function)

not sure what is going wrong.

答:
Webpack has come a long way in terms of flexibility and power. Though i had the same question some time back, didn't take much time to setup a module to use bootstrap with webpack. Feel free to visit the code in GitHub Repo.

Hope it helps someone.

Title: How to use Webpack for Bootstrap?

Body:
I am using webpack to bundle some boostrap and other css files into one, the following is the webpack.config.js file
var htmlWebPack = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: "./app/main.ts",
    output: {
        path: __dirname + '/dist',
        filename: "bundle.js"
    },
    resolve: {
    extensions: ['.js','.ts']
  },
    module: {
        loaders: [
          {
              test: /\.tsx?$/,
              loader: 'awesome-typescript-loader'
          },
          {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      },
      {
             test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
           loader: 'url-loader' }
        ]
    },
    plugins: [
    new htmlWebPack({
        template: './index.html',

    }),
      new ExtractTextPlugin("minified-style.css"),
    ]

};

and i have referenced my bootstrap folder in the main.ts file like this

require('../Content/bootstrap/bootstrap.min.css');
require('../Content/bootstrap/bootstrap-theme.min.css');

but when i run webpack, i am getting the error something like this

D:\project\angularControls\angularControls\node_modules\loader-runner\lib\loadLoader.js:35

throw new Error("Module '" + loader.path + "' is not a loader (must have           normal or pitch function)");

^ Error: Module
  'D:\project\angularControls\angularControls\node_modules\url\url.js'

is not a loader (must have normal or pitch function)

not sure what is going wrong.