问:
Video display in html
I am learning html, css, javascript for creating a simple website for learning purpose. I am able to display a video saved in my drive using video element in html page. I also want to display the title of the video, total length of the video, total views of the video in the same video. Please help me which part I need to concentrate more also where I can get information to learn these and able to display all the things I need in each video.

My html code:

* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

 #navBar {
   float: left;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang = "en">
  <head>
  <title>Videos</title>
      <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="videos.css">
  </head>

<body>
   <header>
  <nav>
  <h1> Main logo </h1>
   <ul id="nav">
    <li>Home</li>
    <li>Videos</li>

 </ul>
 </nav>
 </header>
 <div class="divider"></div>
 <div id="navBar">

<ul>
 <li>education videos </li>
 <li>film videos</li>
 <li>other videos </li>
</ul>

 </div>
<video title="abcd" controls width="250" height="160">
<source  src="videoplayback.mp4" />
</video>
<video title="abcd" controls width="250" height="160">
<source src="videoplayback (1).mp4" />
</video>

<video title="abcd" controls width="250" height="160">
<source src="1 Ton.mp4" />
</video>

    <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

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

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

答:
What you want:

...to display the title of the video, total length of the video, total views of the video...

display the title of the video

video length

total views of the video

1:

If by "title of video", you mean filename, try this:

```<code>Array.from(document.querySelectorAll("video")).forEach(video=>{
    const title = (video.src || video.children[0].src).replace(/.*\//g, "").replace(/\.[a-zA-Z0-9_-]+/, "").replace(/-|_/g, " ");
    video.insertAdjacentHTML("beforeBegin", title);
});
</code>```

2:

```<code>Array.from(document.querySelectorAll("video")).forEach(video=>video.addEventListener('loadedmetadata', function() {
    const duration = videoPlayer.duration;
    video.insertAdjacentHTML("afterEnd", Math.floor(video.duration / (60 * 60)) + ":" + Math.floor(video.duration / 60) + ":" + video.duration % 60)
}));
</code>```

3:

See this answer.

DEMO:

Array.from(document.querySelectorAll("video")).forEach(video=>{
    const title = (video.src || video.children[0].src).replace(/.*\//g, "").replace(/\.[a-zA-Z0-9_-]+/, "").replace(/-|_/g, " ");
    video.insertAdjacentHTML("beforeBegin", title);
});
Array.from(document.querySelectorAll("video")).forEach(video=>video.addEventListener('loadedmetadata', function() {
    const duration = videoPlayer.duration;
    video.insertAdjacentHTML("afterEnd", Math.floor(video.duration / (60 * 60)) + ":" + Math.floor(video.duration / 60) + ":" + video.duration % 60)
}));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

 #navBar {
   float: left;
 }</code>```

<!DOCTYPE HTML>

  <title>Videos</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="videos.css">

 Main logo

Home

Videos

education videos

film videos

other videos

<video title="abcd" controls width="250" height="160">
<source  src="videoplayback.mp4" />
</video>
<video title="abcd" controls width="250" height="160">
<source src="videoplayback (1).mp4" />
</video>

<video title="abcd" controls width="250" height="160">
<source src="1 Ton.mp4" />
</video>

```

Title: Video display in html

Body:
I am learning html, css, javascript for creating a simple website for learning purpose. I am able to display a video saved in my drive using video element in html page. I also want to display the title of the video, total length of the video, total views of the video in the same video. Please help me which part I need to concentrate more also where I can get information to learn these and able to display all the things I need in each video.

My html code:

* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

 #navBar {
   float: left;
 }

<!DOCTYPE HTML>

  <title>Videos</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="videos.css">

 Main logo

Home

Videos

education videos

film videos

other videos

<video title="abcd" controls width="250" height="160">
<source  src="videoplayback.mp4" />
</video>
<video title="abcd" controls width="250" height="160">
<source src="videoplayback (1).mp4" />
</video>

<video title="abcd" controls width="250" height="160">
<source src="1 Ton.mp4" />
</video>

Body:
What you want:

...to display the title of the video, total length of the video, total views of the video...

display the title of the video

video length

total views of the video

1:

If by "title of video", you mean filename, try this:

Array.from(document.querySelectorAll("video")).forEach(video=>{
    const title = (video.src || video.children[0].src).replace(/.*\//g, "").replace(/\.[a-zA-Z0-9_-]+/, "").replace(/-|_/g, " ");
    video.insertAdjacentHTML("beforeBegin", title);
});

2:

Array.from(document.querySelectorAll("video")).forEach(video=>video.addEventListener('loadedmetadata', function() {
    const duration = videoPlayer.duration;
    video.insertAdjacentHTML("afterEnd", Math.floor(video.duration / (60 * 60)) + ":" + Math.floor(video.duration / 60) + ":" + video.duration % 60)
}));

3:

See this answer.

DEMO:

Array.from(document.querySelectorAll("video")).forEach(video=>{
    const title = (video.src || video.children[0].src).replace(/.*\//g, "").replace(/\.[a-zA-Z0-9_-]+/, "").replace(/-|_/g, " ");
    video.insertAdjacentHTML("beforeBegin", title);
});
Array.from(document.querySelectorAll("video")).forEach(video=>video.addEventListener('loadedmetadata', function() {
    const duration = videoPlayer.duration;
    video.insertAdjacentHTML("afterEnd", Math.floor(video.duration / (60 * 60)) + ":" + Math.floor(video.duration / 60) + ":" + video.duration % 60)
}));

* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

 #navBar {
   float: left;
 }

<!DOCTYPE HTML>
<html lang = "en">
  <head>
  <title>Videos</title>
      <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="videos.css">
  </head>

<body>
   <header>
  <nav>
  <h1> Main logo </h1>
   <ul id="nav">
    <li><a class="homeblack" href="index.html">Home</a></li>
    <li><a class="homered" href="videos.html">Videos</a></li>

 </ul>
 </nav>
 </header>
 <div class="divider"></div>
 <div id="navBar">

<ul>
 <li><a href="#">education videos </a></li>
 <li><a href="#">film videos</a></li>
 <li><a href="#">other videos </a></li>
</ul>

 </div>
<video title="abcd" controls width="250" height="160">
<source  src="videoplayback.mp4" />
</video>
<video title="abcd" controls width="250" height="160">
<source src="videoplayback (1).mp4" />
</video>

<video title="abcd" controls width="250" height="160">
<source src="1 Ton.mp4" />
</video>

    <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

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

  </body>
</html>


来源: stackexchange

问:
How to recursively build a list using a callback and iterating through the children?
I'm unsure on how to build this list (which is a string) and then returning as one complete string.
I've worked past my last issue but I think this one is realy bugging me. buildItem() should iterate through item, and then recursively build a list while getting the totalCost from another callback. I know it works asynchronously...

```<code>buildItem(data, function(html){
    $('#nestable ol').append(html);
});
</code>```

Should append the 'final' html string that's created from being appended throughout the file.

```<code>function buildItem(item, callback) {
    getTotalCost(item, function(totalCost) {
        var html = "<li class='dd-item' data-id='" + item.id + "' data-email='" + item.email + "' data-title='" + item.corporateTitle + "' data-name='" + item.firstName + " " + item.lastName + "' id='" + item.id + "'>";
        if (item.children && item.children.length > 0) {
            html += "<ol class='dd-list'>";
            $.each(item.children, function (index, sub) {
                buildItem(item, function(subHtml){
                    html += subHtml;
                })
            })
            html += "</ol>";
        }
        html += "</li>";
        callback(html);
    });
}
</code>```

I know that

```<code>buildItem(item, function(subHtml){
    html += subHtml;
})
</code>```

shouldn't work since javascript is asynchronous. I'm just not sure on how to return from a recursive function? If I were to do something like

```<code>buildItem(item, function(subHtml){
    callback(subHtml);
})
</code>```

You'll get duplicate values because you'll have the starting value and it's children, but since you're also calling it back you'll get the children outside of the starting value. So it'll look like

```<code>1
     a
     b
     c
     d
     e
a
b
c
d
e
</code>```

So what's the best way to approach a solution? I was thinking of making another function, hypothetically a buildChild(sub) that returned html, but the same issue with asynchronous is going to come up where the return will be undefined. I've read some of the threads where you can handle asynchronous values with callbacks, but I'm not sure on how to do it with recursion here.

getTotalCost is another callback function that shouldn't mean much, I removed the line by accident but I just need the totalCost from a database.

```<code>function getTotalCost(item, callback) {
    $.ajax({
        dataType: "json",
        url: "/retrieveData.do?item=" + item.email,
        success: function(data) {
            var totalCost = 0;
            for (var i = 0; i < data.length; i++) {
                totalCost += parseFloat(data[i].cost);
            }
            callback(totalCost);
        }
    });
}
</code>```

答:
You can simplify this with promises and async functions:

```<code>async function getTotalCost(item) {
  const data = await Promise.resolve($.ajax({
    dataType: "json",
    url: "/retrieveData.do?item=" + item.email
  }));
  return data.reduce((acc, next) => acc + next.cost, 0);
}

async function buildItem(item) {
  const totalCost = await getTotalCost(item);
  let html = `<li class="dd-item" data-id="${item.id}" data-email="${item.email}" data-title="${item.corporateTitle}" data-name="${item.firstName} ${item.lastName}" id="${item.id}">`;
  if (item.children && item.children.length > 0) {
    html += '<ol class="dd-list">';
    for (const childItem of item.children) {
      html += await buildItem(childItem);
    }
    html += "</ol>";
  }
  html += "</li>";
  return html;
}
</code>```

Unfortunately, async functions aren't supported by all browsers yet, so you'll have to use Babel to transpile your code.

I also added some new ES6 features: arrow functions, const and template literals.

ContentLicense: CC BY-SA 3.0

Body:
I'm unsure on how to build this list (which is a string) and then returning as one complete string.
I've worked past my last issue but I think this one is realy bugging me. buildItem() should iterate through item, and then recursively build a list while getting the totalCost from another callback. I know it works asynchronously...

buildItem(data, function(html){
    $('#nestable ol').append(html);
});

Should append the 'final' html string that's created from being appended throughout the file.

function buildItem(item, callback) {
    getTotalCost(item, function(totalCost) {
        var html = "
";
        if (item.children && item.children.length > 0) {
            html += "
";
            $.each(item.children, function (index, sub) {
                buildItem(item, function(subHtml){
                    html += subHtml;
                })
            })
            html += "
";
        }
        html += "
";
        callback(html);
    });
}

I know that

buildItem(item, function(subHtml){
    html += subHtml;
})

shouldn't work since javascript is asynchronous. I'm just not sure on how to return from a recursive function? If I were to do something like

buildItem(item, function(subHtml){
    callback(subHtml);
})

You'll get duplicate values because you'll have the starting value and it's children, but since you're also calling it back you'll get the children outside of the starting value. So it'll look like

1
     a
     b
     c
     d
     e
a
b
c
d
e

So what's the best way to approach a solution? I was thinking of making another function, hypothetically a buildChild(sub) that returned html, but the same issue with asynchronous is going to come up where the return will be undefined. I've read some of the threads where you can handle asynchronous values with callbacks, but I'm not sure on how to do it with recursion here.

getTotalCost is another callback function that shouldn't mean much, I removed the line by accident but I just need the totalCost from a database.

function getTotalCost(item, callback) {
    $.ajax({
        dataType: "json",
        url: "/retrieveData.do?item=" + item.email,
        success: function(data) {
            var totalCost = 0;
            for (var i = 0; i < data.length; i++) {
                totalCost += parseFloat(data[i].cost);
            }
            callback(totalCost);
        }
    });
}

Body:
You can simplify this with promises and async functions:

async function getTotalCost(item) {
  const data = await Promise.resolve($.ajax({
    dataType: "json",
    url: "/retrieveData.do?item=" + item.email
  }));
  return data.reduce((acc, next) => acc + next.cost, 0);
}

async function buildItem(item) {
  const totalCost = await getTotalCost(item);
  let html = `<li class="dd-item" data-id="${item.id}" data-email="${item.email}" data-title="${item.corporateTitle}" data-name="${item.firstName} ${item.lastName}" id="${item.id}">`;
  if (item.children && item.children.length > 0) {
    html += '<ol class="dd-list">';
    for (const childItem of item.children) {
      html += await buildItem(childItem);
    }
    html += "</ol>";
  }
  html += "</li>";
  return html;
}

Unfortunately, async functions aren't supported by all browsers yet, so you'll have to use Babel to transpile your code.

I also added some new ES6 features: arrow functions, const and template literals.


问:
Azure Application Insights - Summarize by part of timestamp
How can I summarize records by year, month,day and hour only?</p>

答:
In Application Insights Analytics:

By hour:

```<code>requests
 | summarize count() by bin(timestamp, 1h)
</code>```

By day:

```<code>requests
 | summarize count() by bin(timestamp, 1d)
</code>```

By month

```<code>requests
  | summarize count()  by bin(datepart("Month", timestamp), 1)
</code>```

By year

```<code>requests
  | summarize count()  by bin(datepart("Year", timestamp), 1)
</code>```

Body:
In Application Insights Analytics:

By hour:

requests
 | summarize count() by bin(timestamp, 1h)

By day:

requests
 | summarize count() by bin(timestamp, 1d)

By month

requests
  | summarize count()  by bin(datepart("Month", timestamp), 1)

By year

requests
  | summarize count()  by bin(datepart("Year", timestamp), 1)


问:
Hive union all efficiency and best practice
I have a hive efficiency question. I have 2 massive queries that need to be filtered, joined with mapping tables, and unioned. All the joins are identical for both tables. Would it be more efficient to union them before applying the joins to the combined table or to apply the joins to each massive query individually then union the results? Does it make a difference?

I tried the second way and the query ran for 24 hours before I killed it. I feel like I did everything I could to optimize it except potentially rearrange the union statement. On the one hand, I feel like it should not matter because the number or rows being joined by the mapping table is the same and since everything is palatalized, it should take roughly the same amount of time. On the other hand, maybe by doing the union first, it should guarantee that the two big queries are given full system resources before the joins are run. Then again, that might mean that there are only 2 jobs running at a time so the system is not being fully used or something.

I simply do not know enough about how hive and it's multi-threading works. Anybody have any ideas?

答:
There is no such best practice. Both approaches are applicable. Subqueries in UNION ALL are running as parallel jobs. So join before union will work as parallel tasks with smaller datasets, tez can optimize execution and common joined tables will be read only once in single mapper stage for each table.
Also you can avoid joins for some subqueries for example if their keys are not applicable for join.

Join with union-ed bigger dataset also may work with very high parallelism depending on your settings (bytes per reducer for example), optimizer also may rewrite query plan. So I suggest you to check both methods, measure speed, study plan and check if you can change something. Change, measure, study plan... repeat

Few more suggestions:
Try to limit datasets before joining them. If your join multiplies rows then analytics and aggregation may work slower on bigger datasets and first approach may be preferable if you can apply analytics/aggregation before union.


问:
CSS background-image transitions effects not working as expected
Ok, so I'm working on this swipe effect on hover using div and background image. background image uses outer div max-width and inner div with padding-bottom percentage to maintain aspect ratio.

There are a few things here I don't understand.

I was very surprised that my %200 background position only pushed the image over a few pixels, in the end, a massive 7100% was required to fully move the image over so the repeated image was fully visible.

When I set the padding-bottom to anything over 54%, the transition and everything stops working.

This '7100%' seems to produce the right effect in chrome, firefox, and opera, but not safari.

My fiddle, thoughts?
https://jsfiddle.net/riegersn/a3mnr9um

```<code>.container {
      max-width: 480px;
    }

.project {
  margin-bottom: 15px;
  cursor: pointer;
  overflow: hidden;
  width: 100%;
  background-position: center center;
  background-repeat: repeat-x;
  background-size: contain;
  transition: all 0.2s ease-out;
  padding-bottom: 54%;
  &:hover {
    background-position: 7100% 50%;
  }
}
</code>```

答:
The setup

I've modified your fiddle for demonstration purposes. The image proportions and relevant CSS properties are the same. So let's first have a look at what we get from our setup:

.container {
  max-width: 480px;
  background: orange;
}

.project {
  width: 100%;
  background-image: url("https://i.stack.imgur.com/Wurh4.png");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  padding-bottom: 54%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="project">
  </div>
</div></code>```

```<code>Image width:      504px
Image height:     276px
Container width:  480px
Container height: 259.2px // FireFox 53
</code>```

Because of background-size: contain our background-image has the following dimensions:

```<code>BG image height:  259.2px
BG image width:   473.3217...px
</code>```

The height is equal to the container height (this is simply how contain works in this scenario). The width is then calculated as follows: (259.2 / 276) * 504.

```<code>Difference D:     480px - 473.3217...px = 6.6782...px
</code>```

This is the gap you can discover in the above snippet. Because of the background-position-x: center you see ~3px on the left and another ~3px gap on the right.

How background-position and percentages work

In short: a background-position-x: 50% centers the center of the background-image to the center of the container. So a background-position-x: 100% will simply align the the right side of the image to the right side of the container.

.container {
  width: 700px;
  height: 300px;
  background: orange;
  background-image: url("https://i.stack.imgur.com/Wurh4.png");
  background-position: 90% 50%;
  background-repeat: no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
</div></code>```

The above calculated difference D is exactly what the 100% in background-position-x: 100% would be represented in px.

7100% is not random

```<code>Difference D:     6.6782...px
Factor F:         480px / D = 71.8749...
</code>```

To move our background-image completely out of the viewing range we would have to set background-position-x: 7174%. Questions 1 should now be answered. If you skipped everything up to here, the short answer is: a value of 100% has a very special meaning when it comes to the background-position property.

When I set the padding-bottom to anything over 54%, the transition and everything stops working.

Yes, because then the width of the background-image gets bigger than the width of the container.

Body:
Ok, so I'm working on this swipe effect on hover using div and background image. background image uses outer div max-width and inner div with padding-bottom percentage to maintain aspect ratio.

There are a few things here I don't understand.

I was very surprised that my %200 background position only pushed the image over a few pixels, in the end, a massive 7100% was required to fully move the image over so the repeated image was fully visible.

When I set the padding-bottom to anything over 54%, the transition and everything stops working.

This '7100%' seems to produce the right effect in chrome, firefox, and opera, but not safari.

My fiddle, thoughts?
https://jsfiddle.net/riegersn/a3mnr9um

.container {
      max-width: 480px;
    }

.project {
  margin-bottom: 15px;
  cursor: pointer;
  overflow: hidden;
  width: 100%;
  background-position: center center;
  background-repeat: repeat-x;
  background-size: contain;
  transition: all 0.2s ease-out;
  padding-bottom: 54%;
  &:hover {
    background-position: 7100% 50%;
  }
}

Body:
The setup

I've modified your fiddle for demonstration purposes. The image proportions and relevant CSS properties are the same. So let's first have a look at what we get from our setup:

.container {
  max-width: 480px;
  background: orange;
}

.project {
  width: 100%;
  background-image: url("https://i.stack.imgur.com/Wurh4.png");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  padding-bottom: 54%;
}

<div class="container">
  <div class="project">
  </div>
</div>

Image width:      504px
Image height:     276px
Container width:  480px
Container height: 259.2px // FireFox 53

Because of background-size: contain our background-image has the following dimensions:

BG image height:  259.2px
BG image width:   473.3217...px

The height is equal to the container height (this is simply how contain works in this scenario). The width is then calculated as follows: (259.2 / 276) * 504.

Difference D:     480px - 473.3217...px = 6.6782...px

This is the gap you can discover in the above snippet. Because of the background-position-x: center you see ~3px on the left and another ~3px gap on the right.

How background-position and percentages work

In short: a background-position-x: 50% centers the center of the background-image to the center of the container. So a background-position-x: 100% will simply align the the right side of the image to the right side of the container.

.container {
  width: 700px;
  height: 300px;
  background: orange;
  background-image: url("https://i.stack.imgur.com/Wurh4.png");
  background-position: 90% 50%;
  background-repeat: no-repeat;
}

<div class="container">
</div>

The above calculated difference D is exactly what the 100% in background-position-x: 100% would be represented in px.

7100% is not random

Difference D:     6.6782...px
Factor F:         480px / D = 71.8749...

To move our background-image completely out of the viewing range we would have to set background-position-x: 7174%. Questions 1 should now be answered. If you skipped everything up to here, the short answer is: a value of 100% has a very special meaning when it comes to the background-position property.

When I set the padding-bottom to anything over 54%, the transition and everything stops working.

Yes, because then the width of the background-image gets bigger than the width of the container.


问:
Clickonce downloading the deploy files via HTTP and not HTTPS
I am working on a project to deploy a project via clickonce.  The website where these files are housed will only accept HTTPS traffic and if you attempt to connect via HTTP, our siteminder agent will redirect you to a HTTPS login form.  We cannot disable the siteminder agent or enable HTTP for security reasons.
In the application file, I have a codebase that references an absolute path to the manifest and it is via HTTPS

```<code>  <dependency>
    <dependentAssembly dependencyType="install" codebase="https://psaportal.ilab.test.com/testprinting/Application_Files/testprint_1_0_0_1/testprint.exe.manifest" size="10147">
      <assemblyIdentity name="testprint.exe" version="1.0.0.1" publicKeyToken="9a078649ee05e0e7" language="neutral" processorArchitecture="msil" type="win32" />
      <hash>
        <dsig:Transforms>
          <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
        </dsig:Transforms>
        <dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <dsig:DigestValue>2nch1T0SmlAycmePobtg9F1qF7c=</dsig:DigestValue>
      </hash>
    </dependentAssembly>
  </dependency>
</code>```

In running wireshark and decoding the SSL traffic (I am using the server’s private key in wireshark to decrypt the SSL traffic).  I see the request to the application’s manifest file is via HTTPS (This is a good thing).  But when the clickonce tries to download the testprint.exe.deploy and the other respective files, it is always via HTTP and the siteminder jumps in and redirects the requests which kills the clickonce install with errors.

I have tried to specific an absolute codebase reference in the manifest file, but then I start getting entrypoint errors when the manifest is downloaded by the Clickonce installer.

The current dependency section from the manifest file looks like the following:

```<code>  <dependency>
    <dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="testprint.exe" size="107008">
      <assemblyIdentity name="testprint" version="1.0.0.1" language="neutral" processorArchitecture="msil" />
      <hash>
        <dsig:Transforms>
          <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
        </dsig:Transforms>
        <dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <dsig:DigestValue>dm2nJsu/5UyaEXSDmnISwfnE9MM=</dsig:DigestValue>
      </hash>
    </dependentAssembly>
  </dependency>
</code>```

I have verified that the website where the application, manifest and deploy files are all under the same URL and the SSL certificate is a valid certificate.

We have tried about every combination of generating application and manifest files as we a dream up and are looking for other solutions.

The application is using .NET 3.5 and we have tried building the application and manifest files via VS2008, VS2010 and mage with no success.

Does anyone know how to get all of the deploy files to always download via HTTPS?

答: From your description, it sounds like a certificate or web server configuration issue.  Have you tried the guidance in Serve and Client Configuration Issues in ClickOnce Deployments?</p>

ContentLicense: CC BY-SA 2.5

Body:
I am working on a project to deploy a project via clickonce.  The website where these files are housed will only accept HTTPS traffic and if you attempt to connect via HTTP, our siteminder agent will redirect you to a HTTPS login form.  We cannot disable the siteminder agent or enable HTTP for security reasons.
In the application file, I have a codebase that references an absolute path to the manifest and it is via HTTPS

  <dependency>
    <dependentAssembly dependencyType="install" codebase="https://psaportal.ilab.test.com/testprinting/Application_Files/testprint_1_0_0_1/testprint.exe.manifest" size="10147">
      <assemblyIdentity name="testprint.exe" version="1.0.0.1" publicKeyToken="9a078649ee05e0e7" language="neutral" processorArchitecture="msil" type="win32" />
      <hash>
        <dsig:Transforms>
          <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
        </dsig:Transforms>
        <dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <dsig:DigestValue>2nch1T0SmlAycmePobtg9F1qF7c=</dsig:DigestValue>
      </hash>
    </dependentAssembly>
  </dependency>

In running wireshark and decoding the SSL traffic (I am using the server’s private key in wireshark to decrypt the SSL traffic).  I see the request to the application’s manifest file is via HTTPS (This is a good thing).  But when the clickonce tries to download the testprint.exe.deploy and the other respective files, it is always via HTTP and the siteminder jumps in and redirects the requests which kills the clickonce install with errors.

I have tried to specific an absolute codebase reference in the manifest file, but then I start getting entrypoint errors when the manifest is downloaded by the Clickonce installer.

The current dependency section from the manifest file looks like the following:

  <dependency>
    <dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="testprint.exe" size="107008">
      <assemblyIdentity name="testprint" version="1.0.0.1" language="neutral" processorArchitecture="msil" />
      <hash>
        <dsig:Transforms>
          <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
        </dsig:Transforms>
        <dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <dsig:DigestValue>dm2nJsu/5UyaEXSDmnISwfnE9MM=</dsig:DigestValue>
      </hash>
    </dependentAssembly>
  </dependency>

I have verified that the website where the application, manifest and deploy files are all under the same URL and the SSL certificate is a valid certificate.

We have tried about every combination of generating application and manifest files as we a dream up and are looking for other solutions.

The application is using .NET 3.5 and we have tried building the application and manifest files via VS2008, VS2010 and mage with no success.

Does anyone know how to get all of the deploy files to always download via HTTPS?


问:
React material-ui Stepper orientation Uncaught TypeError: Cannot read property 'props' of null
My Stepper component should render in a vertical or horizontal layout depending on screen size. For that reason I'm using a prop "verticalLayout". If I render it in vertical mode (verticalLayout = {true}) everything seems to be working just fine. As soon as I render in horizontal mode (verticalLayout = {false}) it stops working with the Uncaught TypeError: Cannot read property 'props' of null

My search didn't yield any answers and I tried everything I could think of (replacing this with a let variable, refactoring the code to check if this && this.props ... etc.) but only deleting all the references to  in the vertical Layout gets rid of the error. I'm at a loss and would greatly appreciate your help. Here is my code:

```<code>import React, {Component} from 'react';

import {
  Step,
  Stepper,
  StepLabel,
  StepContent,
} from 'material-ui/Stepper';

export default class MyReactiveStepperComponent extends Component {
  render() {
    console.info(this.props.verticalLayout)
    return (
      <div>
        <Stepper activeStep={this.props.activeStep} orientation={this.props.verticalLayout ? "vertical" : "horizontal"}>
          <Step>
            <StepLabel>Step 1</StepLabel>
            { console.warn(this.props) && this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
          <Step>
            <StepLabel>Step 2</StepLabel>
            { this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
          <Step>
            <StepLabel>Step 3</StepLabel>
            { this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
          <Step>
            <StepLabel>Step 4</StepLabel>
            { this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
        </Stepper>
        { !this.props.verticalLayout && <div> { this.props.children } </div> }
      </div>
    );
  }
}
</code>```

答:
Maybe not the answer you are looking for, but there is an open discussion on the Github page about it:

Stepper: Allow null children #6004

In a pinch, you might consider writing a renderStepChildren() function that dynamically adds the StepContent. Something like this (untested):

```<code>renderStepChildren = (verticalLayout) => {
  const children = [];

  children.push(<StepLabel key={0}>...</StepLabel>);
  if (verticalLayout) {
    children.push(<StepContent key={1}>...</StepContent>);
  }

  return children;
};
</code>```

Then, in your render() method:

```<code><Step>
  {this.renderStepChildren(this.props.verticalLayout)}
</Step>
</code>```

Body:
My Stepper component should render in a vertical or horizontal layout depending on screen size. For that reason I'm using a prop "verticalLayout". If I render it in vertical mode (verticalLayout = {true}) everything seems to be working just fine. As soon as I render in horizontal mode (verticalLayout = {false}) it stops working with the Uncaught TypeError: Cannot read property 'props' of null

My search didn't yield any answers and I tried everything I could think of (replacing this with a let variable, refactoring the code to check if this && this.props ... etc.) but only deleting all the references to  in the vertical Layout gets rid of the error. I'm at a loss and would greatly appreciate your help. Here is my code:

import React, {Component} from 'react';

import {
  Step,
  Stepper,
  StepLabel,
  StepContent,
} from 'material-ui/Stepper';

export default class MyReactiveStepperComponent extends Component {
  render() {
    console.info(this.props.verticalLayout)
    return (

        <Stepper activeStep={this.props.activeStep} orientation={this.props.verticalLayout ? "vertical" : "horizontal"}>
          <Step>
            <StepLabel>Step 1</StepLabel>
            { console.warn(this.props) && this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
          <Step>
            <StepLabel>Step 2</StepLabel>
            { this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
          <Step>
            <StepLabel>Step 3</StepLabel>
            { this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
          <Step>
            <StepLabel>Step 4</StepLabel>
            { this.props.verticalLayout &&
            <StepContent>
              {this.props.children}
            </StepContent>
            }
          </Step>
        </Stepper>
        { !this.props.verticalLayout &&
 { this.props.children }
 }

    );
  }
}

Body:
Maybe not the answer you are looking for, but there is an open discussion on the Github page about it:

Stepper: Allow null children #6004

In a pinch, you might consider writing a renderStepChildren() function that dynamically adds the StepContent. Something like this (untested):

renderStepChildren = (verticalLayout) => {
  const children = [];

  children.push(<StepLabel key={0}>...</StepLabel>);
  if (verticalLayout) {
    children.push(<StepContent key={1}>...</StepContent>);
  }

  return children;
};

Then, in your render() method:

<Step>
  {this.renderStepChildren(this.props.verticalLayout)}
</Step>


问:
How do I change text within
 tags with Javascript?

I need some help on editing elements which are in HTML with JavaScript. Is it possible to change the "text" with javascript? I've tried using document.getElementById but I don't think I'm doing it correctly.

答:
Get the elemet with a query like you would use in css:

```<code>var element = document.querySelector('div.header');
</code>```

Change the content using the textContent property:

```<code>element.textContent = "New Content;"
</code>```

Adding image to content:

```<code>document.querySelector('div.header').innerHTML = "<img src='smiley.gif' alt='Smiley face' height='42' width='42'>";
</code>```

Title: How do I change text within <div> tags with Javascript?

Body:
Get the elemet with a query like you would use in css:

var element = document.querySelector('div.header');

Change the content using the textContent property:

element.textContent = "New Content;"

Adding image to content:

document.querySelector('div.header').innerHTML = "<img src='smiley.gif' alt='Smiley face' height='42' width='42'>";


问:
How to structure REGEX in C#
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

```<code>var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);
</code>```

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.

答:
I believe you can't merge both patterns into one, so you would have to perform two diferent regex operations, one to split the states into a list, and a subsequent one for the validation of each item within it.

I'd rather go for something "simpler" such as

```<code>var states = input.Split('|').Select(s => new string(s.Where(char.IsLetter).ToArray()))
                 .Where(s => !string.IsNullOrWhiteSpace(s));
</code>```

Title: How to structure REGEX in C#

Body:
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.

Body:
I believe you can't merge both patterns into one, so you would have to perform two diferent regex operations, one to split the states into a list, and a subsequent one for the validation of each item within it.

I'd rather go for something "simpler" such as

var states = input.Split('|').Select(s => new string(s.Where(char.IsLetter).ToArray()))
                 .Where(s => !string.IsNullOrWhiteSpace(s));


问:
Angular2: Prevent authenticated users from accessing specific routes
I've defined some routes in my main.ts file:

```<code>const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: '', redirectTo: 'home', terminal: true },
  { path: 'dashboard', component: DashboardComponent, canActivate: [LoggedInGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'about', component: AboutComponent }
];
</code>```

After successful login I want my authenticated users can be able to use specific routes (e.g. dashboard). And without login they cannot access dashboard but they can be able to visit about,home,login

I've managed to restrict users traversing the dashboard without login, using CanActivate.

```<code>canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    }
    this.router.navigateByUrl('/login');
    return false;
  }
</code>```

But Using those routes and the CanActivate approach after successful login, users are also able to goto routes like login, home. How can I prevent that?

N.B. I'm using angular2 RC4.

答:
You could write a guard like this:

```<code>import { Injectable } from '@angular/core';
import {
    ActivatedRouteSnapshot,
    CanActivate,
    RouterStateSnapshot
} from '@angular/router';

import { AuthService } from './your-auth.service';

@Injectable()
export class UserAccessGuard implements CanActivate {
    constructor(private authService: AuthService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return route.data['onlyGuests'] != authService.isAuthenticated();
    }
}
</code>```

And then use it in your route definition:

```<code>const routes: Routes = [
  { path: '', redirectTo: 'home' },

  // accessible only to guests
  {
      path: '',
      component: HomeComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },
  {
      path: 'login',
      component: LoginComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },

  // accessible only to authenticated users
  {
      path: 'dashboard',
      component: DashboardComponent,
      canActivate: [ UserAccessGuard ]
  }
];
</code>```

Body:
I've defined some routes in my main.ts file:

const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: '', redirectTo: 'home', terminal: true },
  { path: 'dashboard', component: DashboardComponent, canActivate: [LoggedInGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'about', component: AboutComponent }
];

After successful login I want my authenticated users can be able to use specific routes (e.g. dashboard). And without login they cannot access dashboard but they can be able to visit about,home,login

I've managed to restrict users traversing the dashboard without login, using CanActivate.

canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    }
    this.router.navigateByUrl('/login');
    return false;
  }

But Using those routes and the CanActivate approach after successful login, users are also able to goto routes like login, home. How can I prevent that?

N.B. I'm using angular2 RC4.

Body:
You could write a guard like this:

import { Injectable } from '@angular/core';
import {
    ActivatedRouteSnapshot,
    CanActivate,
    RouterStateSnapshot
} from '@angular/router';

import { AuthService } from './your-auth.service';

@Injectable()
export class UserAccessGuard implements CanActivate {
    constructor(private authService: AuthService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return route.data['onlyGuests'] != authService.isAuthenticated();
    }
}

And then use it in your route definition:

const routes: Routes = [
  { path: '', redirectTo: 'home' },

  // accessible only to guests
  {
      path: '',
      component: HomeComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },
  {
      path: 'login',
      component: LoginComponent,
      data: { onlyGuests: true },
      canActivate: [ UserAccessGuard ]
  },

  // accessible only to authenticated users
  {
      path: 'dashboard',
      component: DashboardComponent,
      canActivate: [ UserAccessGuard ]
  }
];


问:
A Universal Match Pattern ('/**') is Defined Before Other Patterns
I have a problem when trying to introduce Spring Security to my webapp. Here's my web.xml:

```<code><welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:application-context.xml
        classpath:web-context.xml
        classpath:security-context.xml
    </param-value>
</context-param>

<context-param>
    <param-name>defaultHtmlEscape</param-name>
    <param-value>true</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/admin</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<session-config>
    <session-timeout>30</session-timeout>
    <tracking-mode>COOKIE</tracking-mode>
</session-config>

<!-- Spring Security config -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

security-context.xml:

```<code><security:http auto-config='true'>
    <security:intercept-url pattern="/admin.html" />
    <security:http-basic />
</security:http>
<security:http pattern="/services/**" security="none" />
<security:authentication-manager>
    <security:authentication-provider>
        <security:user-service>
            <security:user name="admin" password="analyzer4321"
                authorities="ROLE_ADMIN" />
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>
</code>```

When I'm trying to run server I have this exception on start:

```<code>java.lang.IllegalArgumentException: A universal match pattern ('/**')
is defined before other patterns in the filter chain, causing them to be ignored.
Please check the ordering in your <security:http> namespace or
FilterChainProxy bean configuration.
</code>```

I have no idea what I'm doing wrong. Any suggestions?

答:
The first pattern Spring security takes up is from the http tag in the pattern attribute. If no pattern attribute is declared in the http tag, it defaults to <security:http pattern="/**">
the intercept-url tag attribute is allways taken up in second place ie after de http pattern tag.
If you have two or more http tags, you should allways declare the pattern attribute with values so no conflicts occur

Body:
I have a problem when trying to introduce Spring Security to my webapp. Here's my web.xml:

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:application-context.xml
        classpath:web-context.xml
        classpath:security-context.xml
    </param-value>
</context-param>

<context-param>
    <param-name>defaultHtmlEscape</param-name>
    <param-value>true</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/admin</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<session-config>
    <session-timeout>30</session-timeout>
    <tracking-mode>COOKIE</tracking-mode>
</session-config>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

security-context.xml:

<security:http auto-config='true'>
    <security:intercept-url pattern="/admin.html" />
    <security:http-basic />
</security:http>
<security:http pattern="/services/**" security="none" />
<security:authentication-manager>
    <security:authentication-provider>
        <security:user-service>
            <security:user name="admin" password="analyzer4321"
                authorities="ROLE_ADMIN" />
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>

When I'm trying to run server I have this exception on start:

java.lang.IllegalArgumentException: A universal match pattern ('/**')
is defined before other patterns in the filter chain, causing them to be ignored.
Please check the ordering in your <security:http> namespace or
FilterChainProxy bean configuration.

I have no idea what I'm doing wrong. Any suggestions?


问:
How can I remove the GMSPolyline in Swift 3
I'm making the GMSPolyline in the GoogleMap. When I want to remove the GMSPolyline by coding polyline.map = nil, but it can not working for me. I'm copy some coding in the below.

(added the marker before, I need remove the polyline only)

Thank you for your help!!!

my coding:

```<code>func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    //MARK: create the GMSPolyline
    let polyline = GMSPolyline()
    //MARK: remove the old polyline from the GoogleMap
    polyline.map = nil

    let origin = "\(mapView.myLocation!.coordinate.latitude),\(mapView.myLocation!.coordinate.longitude)"
    let destination = "\(marker.position.latitude),\(marker.position.longitude)"

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"

    Alamofire.request(url).responseJSON { response in

        let json = JSON(data: response.data!)
        let routes = json["routes"].arrayValue

        //MARK: print route using Polyline
        for route in routes
        {
            let routeOverviewPolyline = route["overview_polyline"].dictionary
            let points = routeOverviewPolyline?["points"]?.stringValue
            let path = GMSPath(fromEncodedPath: points!)
            polyline = GMSPolyline(path: path)
            polyline.strokeWidth = 4
            polyline.strokeColor = UIColor.yellow
            polyline.isTappable = true
            polyline.map = self.mapView
        }
    }
    return false
}
</code>```

答:
you should clear the map before adding new polyline on the map.

clear() function of GMSMapView

```<code>/**

Clears all markup that has been added to the map, including markers, polylines and ground overlays.
This will not clear the visible location dot or reset the current mapType.

*/
</code>```

Try this

```<code>func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    //MARK: create the GMSPolyline
    let polyline = GMSPolyline()
    //MARK: remove the old polyline from the GoogleMap
    mapView.clear()
    //TODO:- Redraw all marker here.
    let origin = "\(mapView.myLocation!.coordinate.latitude),\(mapView.myLocation!.coordinate.longitude)"
    let destination = "\(marker.position.latitude),\(marker.position.longitude)"

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"

    Alamofire.request(url).responseJSON { response in

        let json = JSON(data: response.data!)
        let routes = json["routes"].arrayValue

        //MARK: print route using Polyline
        for route in routes
        {
            let routeOverviewPolyline = route["overview_polyline"].dictionary
            let points = routeOverviewPolyline?["points"]?.stringValue
            let path = GMSPath(fromEncodedPath: points!)
            polyline = GMSPolyline(path: path)
            polyline.strokeWidth = 4
            polyline.strokeColor = UIColor.yellow
            polyline.isTappable = true
            polyline.map = self.mapView
        }
    }
    return false
}
</code>```

Body:
I'm making the GMSPolyline in the GoogleMap. When I want to remove the GMSPolyline by coding polyline.map = nil, but it can not working for me. I'm copy some coding in the below.

(added the marker before, I need remove the polyline only)

Thank you for your help!!!

my coding:

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    //MARK: create the GMSPolyline
    let polyline = GMSPolyline()
    //MARK: remove the old polyline from the GoogleMap
    polyline.map = nil

    let origin = "\(mapView.myLocation!.coordinate.latitude),\(mapView.myLocation!.coordinate.longitude)"
    let destination = "\(marker.position.latitude),\(marker.position.longitude)"

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"

    Alamofire.request(url).responseJSON { response in

        let json = JSON(data: response.data!)
        let routes = json["routes"].arrayValue

        //MARK: print route using Polyline
        for route in routes
        {
            let routeOverviewPolyline = route["overview_polyline"].dictionary
            let points = routeOverviewPolyline?["points"]?.stringValue
            let path = GMSPath(fromEncodedPath: points!)
            polyline = GMSPolyline(path: path)
            polyline.strokeWidth = 4
            polyline.strokeColor = UIColor.yellow
            polyline.isTappable = true
            polyline.map = self.mapView
        }
    }
    return false
}

Body:
you should clear the map before adding new polyline on the map.

clear() function of GMSMapView

/**

Clears all markup that has been added to the map, including markers, polylines and ground overlays.
This will not clear the visible location dot or reset the current mapType.

*/

Try this

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    //MARK: create the GMSPolyline
    let polyline = GMSPolyline()
    //MARK: remove the old polyline from the GoogleMap
    mapView.clear()
    //TODO:- Redraw all marker here.
    let origin = "\(mapView.myLocation!.coordinate.latitude),\(mapView.myLocation!.coordinate.longitude)"
    let destination = "\(marker.position.latitude),\(marker.position.longitude)"

    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"

    Alamofire.request(url).responseJSON { response in

        let json = JSON(data: response.data!)
        let routes = json["routes"].arrayValue

        //MARK: print route using Polyline
        for route in routes
        {
            let routeOverviewPolyline = route["overview_polyline"].dictionary
            let points = routeOverviewPolyline?["points"]?.stringValue
            let path = GMSPath(fromEncodedPath: points!)
            polyline = GMSPolyline(path: path)
            polyline.strokeWidth = 4
            polyline.strokeColor = UIColor.yellow
            polyline.isTappable = true
            polyline.map = self.mapView
        }
    }
    return false
}


问:
How to find repeating sequence of Integers in an array of Integers in java?
For example if input is:

2 0 6 3 1 6 3 1 6 3 1

then output should be 6 3 1.Need to find the first repetition cycle.

```<code>class FindDuplicate
{
void printRepeating(int arr[], int size)
{
    int i;
    System.out.println("The repeating elements are : ");

    for (i = 0; i < size; i++)
    {
        if (arr[Math.abs(arr[i])] >= 0)
            arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
        else
            System.out.print(Math.abs(arr[i]) + " ");
    }
}

public static void main(String[] args)
{
    FindDuplicate duplicate = new FindDuplicate();
    int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
    int arr_size = arr.length;
    duplicate.printRepeating(arr, arr_size);
}
}
</code>```

答:
Loop through those array elements and cache your elements until you have the same value for example

```<code>List list = Arrays.asList(1,2,3);
if(list.contains(element))
 //code to check here
</code>```

you will need get size of your list and based on that check exactly this amount of items if they match if yes then output if not clear cache and start cache from the begging.

Body:
For example if input is:

2 0 6 3 1 6 3 1 6 3 1

then output should be 6 3 1.Need to find the first repetition cycle.

class FindDuplicate
{
void printRepeating(int arr[], int size)
{
    int i;
    System.out.println("The repeating elements are : ");

    for (i = 0; i < size; i++)
    {
        if (arr[Math.abs(arr[i])] >= 0)
            arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
        else
            System.out.print(Math.abs(arr[i]) + " ");
    }
}

public static void main(String[] args)
{
    FindDuplicate duplicate = new FindDuplicate();
    int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
    int arr_size = arr.length;
    duplicate.printRepeating(arr, arr_size);
}
}

Body:
Loop through those array elements and cache your elements until you have the same value for example

List list = Arrays.asList(1,2,3);
if(list.contains(element))
 //code to check here

you will need get size of your list and based on that check exactly this amount of items if they match if yes then output if not clear cache and start cache from the begging.


问:
Error in declaring unordered_map which maps string to a template
```<code>template<typename T>
struct hash;

template<typename T> class WUG{
    public:
        WUG(){
            unordered_map<string,typename T,hash> vertexmap; //Problem
        }
};
</code>```

I am getting some error in this code which really doesn't say anything to me. How should I declare it properly?

The error message I'm having is:

    [Error] template argument 2 is invalid

[Error] template argument 5 is invalid

答:
You have using namespace std; that imports all the names from the std namesapce including std::hash, fix:

```<code>struct MyHash;

template <typename T>
class WUG {
public:
  WUG() {
    unordered_map<string, T, MyHash> vertexmap; //Problem
  }
};
</code>```

or with the standard hash:

```<code>template <typename T>
class WUG {
public:
  WUG() {
    unordered_map<string, T> vertexmap; //Problem
  }
};
</code>```

Body:
template<typename T>
struct hash;

template<typename T> class WUG{
    public:
        WUG(){
            unordered_map<string,typename T,hash> vertexmap; //Problem
        }
};

I am getting some error in this code which really doesn't say anything to me. How should I declare it properly?

The error message I'm having is:

    [Error] template argument 2 is invalid

[Error] template argument 5 is invalid

Body:
You have using namespace std; that imports all the names from the std namesapce including std::hash, fix:

struct MyHash;

template <typename T>
class WUG {
public:
  WUG() {
    unordered_map<string, T, MyHash> vertexmap; //Problem
  }
};

or with the standard hash:

template <typename T>
class WUG {
public:
  WUG() {
    unordered_map<string, T> vertexmap; //Problem
  }
};


问:
Creating a Custom Sorter for CollectionView.CustomSort in Powershell

I am kinda' new to Powershell and have searched the ends of the earth for a solution, but I can't seem to find anything. I hope it's still doable.

I am trying to sort a CollectionView by date that's in string format. In my custom sorter, I  want to convert the date strings (M/dd/yyyy) into Date objects and have the Comparer sort it by date. My CollectionView is filled like this:

$stuff = [System.Collections.ObjectModel.ObservableCollection[System.Object]](ImportClixml -Path $path)
$view = [System.Windows.Data.CollectionView]([System.Windows.Data.CollectionViewSource]::GetDefaultView($stuff))
```

<p>The <code>XML</code> data is filled with <code>Properties</code> that are <code>String</code> and <code>Boolean</code> values. the Date value I am trying to sort is a <code>String</code>. The <code>CollectionView</code> is the bound to a <code>DataGrid</code> like so: <code>$myDataGrid.ItemsSource = $myCollectionView</code>
Can I just make a function that sorts and just point to it somehow?</p>

<pre class="lang-sh prettyprint-override"><code>function customSorter{ #Do Stuff }
$myCollectionView.CustomSort = customSorter
</code>```

The CustomSort property takes in a System.Collections.IComparer object. I'm not sure how to approach this. I would prefer to just keep it all in powershell 4 and not import C# code or something like that. Any help is appreciated.

答:
You can format your string dates into a datetime object

For example, yyyy-MM-dd format will be easy to sort.

If you want to convert your string dates you can use :

```<code>$timeinfo = '6/06/2017'
$template = 'M/dd/yyyy'
$newDate = Get-Date([DateTime]::ParseExact($timeinfo, $template, $null)) -Format "yyyy-MM-dd"
</code>```

Result is : 2017-06-06

Body:
I am kinda' new to Powershell and have searched the ends of the earth for a solution, but I can't seem to find anything. I hope it's still doable.

I am trying to sort a CollectionView by date that's in string format. In my custom sorter, I  want to convert the date strings (M/dd/yyyy) into Date objects and have the Comparer sort it by date. My CollectionView is filled like this:

$stuff = [System.Collections.ObjectModel.ObservableCollection[System.Object]](ImportClixml -Path $path)
$view = [System.Windows.Data.CollectionView]([System.Windows.Data.CollectionViewSource]::GetDefaultView($stuff))

The XML data is filled with Properties that are String and Boolean values. the Date value I am trying to sort is a String. The CollectionView is the bound to a DataGrid like so: $myDataGrid.ItemsSource = $myCollectionView
Can I just make a function that sorts and just point to it somehow?

function customSorter{ #Do Stuff }
$myCollectionView.CustomSort = customSorter

The CustomSort property takes in a System.Collections.IComparer object. I'm not sure how to approach this. I would prefer to just keep it all in powershell 4 and not import C# code or something like that. Any help is appreciated.

Body:
You can format your string dates into a datetime object

For example, yyyy-MM-dd format will be easy to sort.

If you want to convert your string dates you can use :

$timeinfo = '6/06/2017'
$template = 'M/dd/yyyy'
$newDate = Get-Date([DateTime]::ParseExact($timeinfo, $template, $null)) -Format "yyyy-MM-dd"

Result is : 2017-06-06


问:
Connecting to Postgres Database via Python
I am trying to connect to my database via Python 2.7 with this code:

```<code>import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"
</code>```

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.

答:
Seems like there are something wrong with your postgres.

Try and see postgres log.
Location of postgres log by default :
tail -f /var/log/postgresql/<>/main/postgresql.log
something like this.

Also don't forget to check firewall. Maybe someone disable it by accident.

Body:
I am trying to connect to my database via Python 2.7 with this code:

import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.


问:
Firefox display=block problem
I have a the following HTML

```<code> <a id="rptQuestions_ctl01_hlQuestion" onclick="rptQuestions_ctl01_pnlAnswer.style.display = rptQuestions_ctl01_pnlAnswer.style.display == 'none'? 'block' : 'none';" href="javascript:">Header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">

            My Text to display

</div>
</code>```

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

```<code>        <a id="rptQuestions_ctl01_hlQuestion" onclick="jasvascript:document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='block';" href="#">My header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">
My Text

</div>
</code>```

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?

答:
```<code><a id="rptQuestions_ctl01_hlQuestion" onclick="javascript:document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display = document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display == 'none'? 'block' : 'none';return false" href="#">Header Link</a>

        <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">

        My Text to display
</code>```

Title: Firefox display=block problem

Body:
I have a the following HTML

 Header Link

            My Text to display

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

        My header Link

My Text

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?


问:
uib-carousel causing inifinite loop
I am using the following markup in my html:

```<code><div style="height: 305px">
  <div uib-carousel active="false" interval="50000" no-wrap="true">
    <div uib-slide ng-repeat="slide in shoes track by slide._id" index="slide._id">
      <img ng-src="{{slide.image}}" style="margin:auto;">
      <div class="carousel-caption">
        <h4>Slide {{slide._id}}</h4>
        <p>{{slide.text}}</p>
      </div>
    </div>
  </div>
</div>
</code>```

Every time I run navigate to this view, I get an infinite loop. It seems (from the console logs I have) that the controller is loading again and again. When I comment out these lines, the rest of the page loads just fine. Is there any reason uib-carousel would cause a reload like this? Am I implementing this correctly? Here is my controller code:

```<code>myApp.controller( 'myShoesController', [ '$http', '$location', function( $http, $location ) {

var vm = this;
vm.shoes = [];

console.log( 'myShoesController connected' );

vm.myShoes = function() {
  console.log( 'running vm.myShoes' );
    $http ({
      method:'GET',
      url:'/shoes'
    }).then(function success( response ) {
      vm.shoes = response.data;
      console.log( 'response from shoes', response );
    }).catch(function(err) {
      console.log('error returning shoes:', err);
    });
  };

  vm.myShoes();
}]);
</code>```

Here are my main app.js file with routes (what I originally thought might be the cause, but seem fine):

```<code>var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);

/// Routes ///
myApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

  $locationProvider.hashPrefix('');

  $routeProvider
    .when('/home', {
      templateUrl: '/views/home.html',
      controller: "LoginController as lc"
    })
    .when('/register', {
      templateUrl: '/views/register.html',
      controller: "LoginController as lc"
    })
    .when('/user', {
      templateUrl: '/views/user.html',
      controller: "UserController as uc"
    })
    .when( '/addItem', {
      templateUrl: '/views/addItem.html',
      controller: "addItemController as aic"
    })
    .when( '/myShoes', {
      templateUrl: '/views/myShoes.html',
      controller: "myShoesController as msc"
    })
    .when( '/selectShoes', {
      templateUrl: '/views/selectShoes.html',
      controller: "selectShoesController as ssc"
    })
    .otherwise({
      redirectTo: 'home'
    });

}]);
</code>```

And my dependencies:

```<code><script type="text/javascript" src="/vendors/angular.min.js"></script>
<script type="text/javascript" src="/vendors/ui-bootstrap-tpls.js" charset="utf-8"></script>
<script type="text/javascript" src="/vendors/ui-bootstrap.js" charset="utf-8"></script>
<script type="text/javascript" src="/vendors/angular-route.min.js"></script>
</code>```

I am using angular 1.6

答:
I'm not sure what your data looks like, but after creating a plunker and playing around, it looks like your problem might be the index="slide._id". I found that if there is not an index value of 0 in one of your slides, and if the indexes are not sequential, then the carousel goes haywire.

I think it's safe to say that array rules apply to the index attribute. That is to say, that the values must start at zero and be sequential, just like an array accessor.

It might be better to just use $index for the index attribute, or make sure your data has ID's that are sequential and that start at 0.

```<code><div style="height: 305px">
  <div uib-carousel="" active="false" interval="5000" no-wrap="true">
    <div uib-slide="" ng-repeat="slide in shoes track by $index" index="$index">
      <img ng-src="{{slide.image}}" style="margin:auto;" />
      <div class="carousel-caption">
        <h4>Slide {{slide._id}}</h4>
        <p>{{slide.text}}</p>
      </div>
    </div>
  </div>
</div>
</code>```

https://plnkr.co/edit/wMtj7tt8M3AN3e7RMMfk?p=preview

Title: uib-carousel causing inifinite loop

Body:
I am using the following markup in my html:

Slide {{slide._id}}

{{slide.text}}

Every time I run navigate to this view, I get an infinite loop. It seems (from the console logs I have) that the controller is loading again and again. When I comment out these lines, the rest of the page loads just fine. Is there any reason uib-carousel would cause a reload like this? Am I implementing this correctly? Here is my controller code:

myApp.controller( 'myShoesController', [ '$http', '$location', function( $http, $location ) {

var vm = this;
vm.shoes = [];

console.log( 'myShoesController connected' );

vm.myShoes = function() {
  console.log( 'running vm.myShoes' );
    $http ({
      method:'GET',
      url:'/shoes'
    }).then(function success( response ) {
      vm.shoes = response.data;
      console.log( 'response from shoes', response );
    }).catch(function(err) {
      console.log('error returning shoes:', err);
    });
  };

  vm.myShoes();
}]);

Here are my main app.js file with routes (what I originally thought might be the cause, but seem fine):

var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);

/// Routes ///
myApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

  $locationProvider.hashPrefix('');

  $routeProvider
    .when('/home', {
      templateUrl: '/views/home.html',
      controller: "LoginController as lc"
    })
    .when('/register', {
      templateUrl: '/views/register.html',
      controller: "LoginController as lc"
    })
    .when('/user', {
      templateUrl: '/views/user.html',
      controller: "UserController as uc"
    })
    .when( '/addItem', {
      templateUrl: '/views/addItem.html',
      controller: "addItemController as aic"
    })
    .when( '/myShoes', {
      templateUrl: '/views/myShoes.html',
      controller: "myShoesController as msc"
    })
    .when( '/selectShoes', {
      templateUrl: '/views/selectShoes.html',
      controller: "selectShoesController as ssc"
    })
    .otherwise({
      redirectTo: 'home'
    });

}]);

And my dependencies:

I am using angular 1.6

Body:
I'm not sure what your data looks like, but after creating a plunker and playing around, it looks like your problem might be the index="slide._id". I found that if there is not an index value of 0 in one of your slides, and if the indexes are not sequential, then the carousel goes haywire.

I think it's safe to say that array rules apply to the index attribute. That is to say, that the values must start at zero and be sequential, just like an array accessor.

It might be better to just use $index for the index attribute, or make sure your data has ID's that are sequential and that start at 0.

<div style="height: 305px">
  <div uib-carousel="" active="false" interval="5000" no-wrap="true">
    <div uib-slide="" ng-repeat="slide in shoes track by $index" index="$index">
      <img ng-src="{{slide.image}}" style="margin:auto;" />
      <div class="carousel-caption">
        <h4>Slide {{slide._id}}</h4>
        <p>{{slide.text}}</p>
      </div>
    </div>
  </div>
</div>

https://plnkr.co/edit/wMtj7tt8M3AN3e7RMMfk?p=preview


问:
What is the difference between commands and container_commands configuration keys in Beanstalk?
When we setup Elastic Beanstalk extensions in .ebextensions

I wonder what is the difference between commands and container_commands in Beanstalk configuration file keys.

My command is like this

```<code>container_commands:
  04_insert_app:
    command: "cat .ebextensions/insertapp_job.txt > /etc/cron.d/insertapp_job && chmod 644 /etc/cron.d/insertapp_job"
    leader_only: true
</code>```

container_commands works fine.

commands: has error .ebextensions/insertapp_job.txt not found

答:
As an addition to @Tiro and @t10508hn answer I just want to clarify that both commands and container_commands are executed on the host machine.

To execute commands within the docker container use the Dockerfile.

This was a point of confusion when I was had to execute a couple of commands with leader_only and assumed that container_commands were actually executed within the container.

ContentLicense: CC BY-SA 4.0

Body:
When we setup Elastic Beanstalk extensions in .ebextensions

I wonder what is the difference between commands and container_commands in Beanstalk configuration file keys.

My command is like this

container_commands:
  04_insert_app:
    command: "cat .ebextensions/insertapp_job.txt > /etc/cron.d/insertapp_job && chmod 644 /etc/cron.d/insertapp_job"
    leader_only: true

container_commands works fine.

commands: has error .ebextensions/insertapp_job.txt not found


问:
Android record in FLAC file
How can I make a record with a microphone in FLAC file?
I have tried this:

```<code>import javaFlacEncoder.FLAC_FileEncoder;

FLAC_FileEncoder flacEncoder = new FLAC_FileEncoder();
File outputFile = new File(dir + "/flac1.flac");
flacEncoder.encode(file, outputFile);
</code>```

Error:

```<code>E/AndroidRuntime(5891): java.lang.VerifyError: javaFlacEncoder/FLAC_FileEncoder
</code>```

Whether it is possible to record sound in format Wav using Java 1.6 and android 4.0.3?

答:
From what earlier comments here were alluding to:

From this link Android appears only support AMR, PCM and GSM codecs. If you need .flac (often google's services favorite) I suggest using the lossless PCM (supports .wav) formats and using FFMPEG, SOX or some other audio converter service to then make them .flac.

(all codecs implemented in Android 3.1x (level 12) so this should apply to your version)

Title: Android record in FLAC file

Body:
How can I make a record with a microphone in FLAC file?
I have tried this:

import javaFlacEncoder.FLAC_FileEncoder;

FLAC_FileEncoder flacEncoder = new FLAC_FileEncoder();
File outputFile = new File(dir + "/flac1.flac");
flacEncoder.encode(file, outputFile);

Error:

E/AndroidRuntime(5891): java.lang.VerifyError: javaFlacEncoder/FLAC_FileEncoder

Whether it is possible to record sound in format Wav using Java 1.6 and android 4.0.3?


问:
How Netty ChannelFuture notify does not cause dead lock
I've read Netty Guide, it does not explain much on ChannelFuture. I am confused why It won't cause a deadlock.

1.It teaches me to start up a server like this.

```<code>ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup);
        sb.channel(NioServerSocketChannel.class);
        sb.localAddress(new InetSocketAddress(port));
        sb.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new BigGameMessageDecoder(msgRegistry));
                        ch.pipeline().addLast(BIG_MSG_ENCODER);
                    if (isDebug) {
                        ch.pipeline().addLast(MSG_LOGGER);
                    }

                    ch.pipeline().addLast(new GameMessageHandler<>(msgRegistry,
                            sessionFactory.createGameSession(), event, false));
                }

        });

        ChannelFuture cf = sb.bind().sync();
        logger.error("start server at port: {}", port);
        if (sync) {
            cf.channel().closeFuture().sync();
        }
</code>```

In line:

```<code>ChannelFuture cf = sb.bind().sync();
</code>```

sb.bind() returns a ChannelFuture and sync() will wait until this future isDone.

I read DefaultChannelGroupFuture code, it shows me to sync() calls await() indeed.
And await() lock itself, wait for other's notify.

And in ChannelFuture's function setSuccess it tries to get that lock again. So my question is if sync() gets the lock first then waits and then ChannelFuture tries to notify but it can not get the lock. Will it cause a deadlock?

If don't, how can ChannelFuture notify other listeners?

Other books told me DO NOT USE sync() or await() in ChannelHandler because It may cause deadlock. Why? What's the difference between Question 1 and 3?

```<code>public DefaultChannelGroupFuture sync() throws InterruptedException {
    super.sync();
    return this;
}

  public Promise<V> sync() throws InterruptedException {
    await();
    rethrowIfFailed();
    return this;
}

  public Promise<V> await() throws InterruptedException {
    if (isDone()) {
        return this;
    }

    if (Thread.interrupted()) {
        throw new InterruptedException(toString());
    }

    synchronized (this) {
        while (!isDone()) {
            checkDeadLock();
            incWaiters();
            try {
                wait();
            } finally {`enter code here`
                decWaiters();
            }
        }
    }
    return this;
}

  public Promise<V> setSuccess(V result) {
    if (setSuccess0(result)) {
        notifyListeners();
        return this;
    }
    throw new IllegalStateException("complete already: " + this);
}

  private boolean setSuccess0(V result) {
    if (isDone()) {
        return false;
    }

    synchronized (this) {
        // Allow only once.
        if (isDone()) {
            return false;
        }
        if (result == null) {
            this.result = SUCCESS;
        } else {
            this.result = result;
        }
        if (hasWaiters()) {
            notifyAll();
        }
    }
    return true;
}
</code>```

答:
In your above code:

```<code>public Promise<V> await() throws InterruptedException {
if (isDone()) {
    return this;
}

if (Thread.interrupted()) {
    throw new InterruptedException(toString());
}

synchronized (this) {
    while (!isDone()) {
        checkDeadLock();
        incWaiters();
        try {
            wait();
        } finally {`enter code here`
            decWaiters();
        }
    }
}
return this;
</code>```

The sync method code checkDeadLock(); will check current thread is not internal thread which is used to deal io event,if not ,the deadlock will occur while the bind operation will dispatch to the same thread that wait for the lock.And then,the wait(); will release the lock of this and wait for some thread acquire the lock and notify it.When the IO thread call the setSuccess,it can acquire the lock,because no one hold the lock.

Body:
I've read Netty Guide, it does not explain much on ChannelFuture. I am confused why It won't cause a deadlock.

1.It teaches me to start up a server like this.

ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup);
        sb.channel(NioServerSocketChannel.class);
        sb.localAddress(new InetSocketAddress(port));
        sb.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new BigGameMessageDecoder(msgRegistry));
                        ch.pipeline().addLast(BIG_MSG_ENCODER);
                    if (isDebug) {
                        ch.pipeline().addLast(MSG_LOGGER);
                    }

                    ch.pipeline().addLast(new GameMessageHandler<>(msgRegistry,
                            sessionFactory.createGameSession(), event, false));
                }

        });

        ChannelFuture cf = sb.bind().sync();
        logger.error("start server at port: {}", port);
        if (sync) {
            cf.channel().closeFuture().sync();
        }

In line:

ChannelFuture cf = sb.bind().sync();

sb.bind() returns a ChannelFuture and sync() will wait until this future isDone.

I read DefaultChannelGroupFuture code, it shows me to sync() calls await() indeed.
And await() lock itself, wait for other's notify.

And in ChannelFuture's function setSuccess it tries to get that lock again. So my question is if sync() gets the lock first then waits and then ChannelFuture tries to notify but it can not get the lock. Will it cause a deadlock?

If don't, how can ChannelFuture notify other listeners?

Other books told me DO NOT USE sync() or await() in ChannelHandler because It may cause deadlock. Why? What's the difference between Question 1 and 3?

public DefaultChannelGroupFuture sync() throws InterruptedException {
    super.sync();
    return this;
}

  public Promise<V> sync() throws InterruptedException {
    await();
    rethrowIfFailed();
    return this;
}

  public Promise<V> await() throws InterruptedException {
    if (isDone()) {
        return this;
    }

    if (Thread.interrupted()) {
        throw new InterruptedException(toString());
    }

    synchronized (this) {
        while (!isDone()) {
            checkDeadLock();
            incWaiters();
            try {
                wait();
            } finally {`enter code here`
                decWaiters();
            }
        }
    }
    return this;
}

  public Promise<V> setSuccess(V result) {
    if (setSuccess0(result)) {
        notifyListeners();
        return this;
    }
    throw new IllegalStateException("complete already: " + this);
}

  private boolean setSuccess0(V result) {
    if (isDone()) {
        return false;
    }

    synchronized (this) {
        // Allow only once.
        if (isDone()) {
            return false;
        }
        if (result == null) {
            this.result = SUCCESS;
        } else {
            this.result = result;
        }
        if (hasWaiters()) {
            notifyAll();
        }
    }
    return true;
}

Body:
In your above code:

public Promise<V> await() throws InterruptedException {
if (isDone()) {
    return this;
}

if (Thread.interrupted()) {
    throw new InterruptedException(toString());
}

synchronized (this) {
    while (!isDone()) {
        checkDeadLock();
        incWaiters();
        try {
            wait();
        } finally {`enter code here`
            decWaiters();
        }
    }
}
return this;

The sync method code checkDeadLock(); will check current thread is not internal thread which is used to deal io event,if not ,the deadlock will occur while the bind operation will dispatch to the same thread that wait for the lock.And then,the wait(); will release the lock of this and wait for some thread acquire the lock and notify it.When the IO thread call the setSuccess,it can acquire the lock,because no one hold the lock.


问:
Is it possible to use a table in an array statement?
I'm trying to reference a table in an array to eventually use in process in a data step. Here is the code:

```<code>proc sql;
create table claims.iterations
    as select Allowed_Claims, Px1
    from simulation
    order by Allowed_Claims, Px1;
quit;
data simulation_iterations;
    array Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);
    array ****** ;
    do i = 1 to 24;
    do j = 1 to Members{i}-1;
        Px2 = rand('Uniform',0,1);
        if Px2 > 0.5 then Px2=Px2;
        output;
        end;
    output;
    end;
run;
</code>```

is it possible to do so? Although it isn't shown, I want to use the table as in an attempt to linearly interpolate for the values in the "Members" array.

Edit:

I want to interpolate for Allowed_Claims based on a randomly generated value (from 0 to 1). The condensed table that I'm basing my linearly interpolation off of is listed below.

```<code>Allowed_Claims  Px1
25.224545313    0.0008129708
34.767797696    0.0014747668
35.367278291    0.0015210493
42.616660238    0.0021191153
52.495185148    0.0030343735
52.652599162    0.0030497846
53.26904904     0.0031103676
57.183442582    0.0035034118
</code>```

For example, let's call this Process A, if Px2 = rand('Uniform',0,1) yields .0010, I want it to interpolate between the Allowed_Claims values where Px1 = 0.0008129708 and Px1 = 0.0014747668.

The role of the array is that it dictates how many iterations of Process A I want. The array is

```<code>Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);
</code>```

So when the loop starts, it will perform 5 iterations of Process A, thereby producing 5 interpolated "allowed_claims" values. I want the average of these five claims.

Then, the loop will continue and perform 6 iterations of Process A and produce 6 interpolated "allowed_claims" values. Again, I want the average of these 6 claims.

I want the output table to look like:

`

```<code>Member[i]    Average_Expected_Claims
   5              (average of 5 interpolated claims)
   6              (average of 6 interpolated claims)
   8              (average of 8 interpolated claims)
</code>```

答:
No, it's not possible to do that, but there is the concept of hash tables, which would be one appropriate solution to accomplish the same kind of lookup.

Arrays in SAS are basically variable name lists, they're not actual data types in the sense they would be in C# or such.

Body:
I'm trying to reference a table in an array to eventually use in process in a data step. Here is the code:

proc sql;
create table claims.iterations
    as select Allowed_Claims, Px1
    from simulation
    order by Allowed_Claims, Px1;
quit;
data simulation_iterations;
    array Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);
    array ****** ;
    do i = 1 to 24;
    do j = 1 to Members{i}-1;
        Px2 = rand('Uniform',0,1);
        if Px2 > 0.5 then Px2=Px2;
        output;
        end;
    output;
    end;
run;

is it possible to do so? Although it isn't shown, I want to use the table as in an attempt to linearly interpolate for the values in the "Members" array.

Edit:

I want to interpolate for Allowed_Claims based on a randomly generated value (from 0 to 1). The condensed table that I'm basing my linearly interpolation off of is listed below.

Allowed_Claims  Px1
25.224545313    0.0008129708
34.767797696    0.0014747668
35.367278291    0.0015210493
42.616660238    0.0021191153
52.495185148    0.0030343735
52.652599162    0.0030497846
53.26904904     0.0031103676
57.183442582    0.0035034118

For example, let's call this Process A, if Px2 = rand('Uniform',0,1) yields .0010, I want it to interpolate between the Allowed_Claims values where Px1 = 0.0008129708 and Px1 = 0.0014747668.

The role of the array is that it dictates how many iterations of Process A I want. The array is

Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);

So when the loop starts, it will perform 5 iterations of Process A, thereby producing 5 interpolated "allowed_claims" values. I want the average of these five claims.

Then, the loop will continue and perform 6 iterations of Process A and produce 6 interpolated "allowed_claims" values. Again, I want the average of these 6 claims.

I want the output table to look like:

`

Member[i]    Average_Expected_Claims
   5              (average of 5 interpolated claims)
   6              (average of 6 interpolated claims)
   8              (average of 8 interpolated claims)