问:
Background outside CSS Bottom Border
first question here so please be kind! I am designing a website and I've been asked to frame pictures in sine-like borders. So far I've gotten around to it by creating a container div with 3 divs: the first for the downward bend, the second is just straight (I'm considering the idea of removing it later on) and the third one does the upward bend.
Here's a screenshot of the current state
So this is the the current code:

.border {
  overflow: hidden;
  align-items: center;
  height: auto;
  width: 100%;
  display: flex;
}

.bord1 {
  margin-top: 4vh;
  height: 4vh;
  flex: 1;
  border-top: solid 5px;
  border-color: #e4ae03 rgba(0, 0, 0, 0) transparent transparent;
  border-radius: 100% 0 0 0;
  z-index: 999;
}

.bord2 {
  margin-top: 4vh;
  flex: 1;
  display: inline;
  height: 4vh;
  border-top: 5px solid #e4ae03;
}

.bord3 {
  margin-top: -4vh;
  flex: 1;
  height: 4vh;
  display: block;
  border-bottom: 5px solid;
  border-color: transparent transparent #e4ae03 transparent;
  border-radius: 0 0 100% 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">
  <div class="bord1 top top-bord"></div>
  <div class="bord2 top top-bord"></div>
  <div class="bord3 bottom"></div>
</div></code>```

I'm really trying to figure out how to get the last segment white, as it's created by rounding the bottom right corner, so the white background would have to be "outside" the div.

I know this might be a stupid question, but here it is! Thanks!

*Edit: Sorry everyone, here is an image of what I'm trying to do]2

答:
Ok, in the end I was able to fix the layout using a system of inner divs, here is how I handled it:

.container {
  line-height: 1.5rem;
  margin-top: -5vh;
  padding: 0px 0px 0px;
  padding-top: 5vh;
  padding-bottom: 0px;
  z-index: 0;
  color: #b3b5b3;
  background: -webkit-linear-gradient(left, #1b2716, #000000 80%);
  background: -o-linear-gradient(left, #1b2716, #000000 80%);
  background: -moz-linear-gradient(left, #1b2716, #000000 80%);
  background: linear-gradient(left, #1b2716, #000000 80%);
  min-height: 75vh;
}
.top {
  box-shadow: inset 0 6px 0 0px #243c51;
}

.bottom {
  box-shadow: 0 6px 0 0px #243c51;
}
.border{
  overflow: hidden;
  align-items: center;
  height: auto;
  width: 100%;
  display: flex;
}

.bord1{
  margin-top: 4vh;
  height: 4vh;
  flex:1;
  border-top: solid 5px;
  border-color:#e4ae03 rgba(0,0,0,0) transparent transparent;
  border-radius: 100% 0 0 0;
  z-index: 999;
}

.bord1-bot{
  background: white;
}

.bord2 {
  margin-top: 4vh;
  flex: 1;
  display: inline;
  height: 4vh;
  border-top: 5px solid #e4ae03;
}

.bord2-bot {
  background: white;
  margin-bottom: 4vh;
  flex: 1;
  display: inline;
  height: 4vh;
  border-bottom: 5px solid #e4ae03;
}

.bord3{
  flex: 1;
  height: 4vh;
  display: block;
  border-bottom: 5px solid;
  border-color: transparent transparent #e4ae03 transparent;
  border-radius: 0 0 100% 0;
}

.bord3-top {
  margin-top: 0vh;
  background: black;
}
.bord3-bot {
  margin-top: 0vh;
  background: white;
}
.bord3-bottom {
  background: white;
}
.bord3-layer-top{
  flex:1;
  height: 8.5vh;
  display: block;
  background-color: white;
}

.bord3-layer-bot{
  flex:1;
  height: 8.5vh;
  display: block;
}
.bord1-layer-top{
  flex:1;
  height: 8.5vh;
  display: block;
  background-color: white;
}

.bot-bord {
  background: -webkit-linear-gradient(left, #1b2716, #000000 240%);
}

.text-con {
  padding: 2vw;
  z-index: 2;
}
.image-within {
  display: block;
  background: yellow;
  height: 200px;
  z-index: 10;
}
.top-bord {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="border">
  <div class="bord1 top top-bord"></div>
  <div class="bord2 top top-bord"></div>
  <div class="bord3-layer-top">
  <div class="bord3 bottom bord3-top"></div>
</div>
</div>
<div class="image-within">
</div>
<div class="border">
  <div class="bord1-layer-top"><div class="bord1 top bot-bord"></div></div>
  <div class="bord2-bot bottom"></div>
  <div class="bord3-layer-bot">
  <div class="bord3 bottom bord3-bot"></div>
</div>
</div>
</div></code>```

The CSS is really messy at the moment, so I'll have to clean it up a bit and work on keeping all the items constantly aligned, but it's looking pretty good right now! Thanks LegendaryJLD!

Title: Background outside CSS Bottom Border

Body:
first question here so please be kind! I am designing a website and I've been asked to frame pictures in sine-like borders. So far I've gotten around to it by creating a container div with 3 divs: the first for the downward bend, the second is just straight (I'm considering the idea of removing it later on) and the third one does the upward bend.
Here's a screenshot of the current state
So this is the the current code:

.border {
  overflow: hidden;
  align-items: center;
  height: auto;
  width: 100%;
  display: flex;
}

.bord1 {
  margin-top: 4vh;
  height: 4vh;
  flex: 1;
  border-top: solid 5px;
  border-color: #e4ae03 rgba(0, 0, 0, 0) transparent transparent;
  border-radius: 100% 0 0 0;
  z-index: 999;
}

.bord2 {
  margin-top: 4vh;
  flex: 1;
  display: inline;
  height: 4vh;
  border-top: 5px solid #e4ae03;
}

.bord3 {
  margin-top: -4vh;
  flex: 1;
  height: 4vh;
  display: block;
  border-bottom: 5px solid;
  border-color: transparent transparent #e4ae03 transparent;
  border-radius: 0 0 100% 0;
}

I'm really trying to figure out how to get the last segment white, as it's created by rounding the bottom right corner, so the white background would have to be "outside" the div.

I know this might be a stupid question, but here it is! Thanks!

*Edit: Sorry everyone, here is an image of what I'm trying to do]2

Body:
Ok, in the end I was able to fix the layout using a system of inner divs, here is how I handled it:

.container {
  line-height: 1.5rem;
  margin-top: -5vh;
  padding: 0px 0px 0px;
  padding-top: 5vh;
  padding-bottom: 0px;
  z-index: 0;
  color: #b3b5b3;
  background: -webkit-linear-gradient(left, #1b2716, #000000 80%);
  background: -o-linear-gradient(left, #1b2716, #000000 80%);
  background: -moz-linear-gradient(left, #1b2716, #000000 80%);
  background: linear-gradient(left, #1b2716, #000000 80%);
  min-height: 75vh;
}
.top {
  box-shadow: inset 0 6px 0 0px #243c51;
}

.bottom {
  box-shadow: 0 6px 0 0px #243c51;
}
.border{
  overflow: hidden;
  align-items: center;
  height: auto;
  width: 100%;
  display: flex;
}

.bord1{
  margin-top: 4vh;
  height: 4vh;
  flex:1;
  border-top: solid 5px;
  border-color:#e4ae03 rgba(0,0,0,0) transparent transparent;
  border-radius: 100% 0 0 0;
  z-index: 999;
}

.bord1-bot{
  background: white;
}

.bord2 {
  margin-top: 4vh;
  flex: 1;
  display: inline;
  height: 4vh;
  border-top: 5px solid #e4ae03;
}

.bord2-bot {
  background: white;
  margin-bottom: 4vh;
  flex: 1;
  display: inline;
  height: 4vh;
  border-bottom: 5px solid #e4ae03;
}

.bord3{
  flex: 1;
  height: 4vh;
  display: block;
  border-bottom: 5px solid;
  border-color: transparent transparent #e4ae03 transparent;
  border-radius: 0 0 100% 0;
}

.bord3-top {
  margin-top: 0vh;
  background: black;
}
.bord3-bot {
  margin-top: 0vh;
  background: white;
}
.bord3-bottom {
  background: white;
}
.bord3-layer-top{
  flex:1;
  height: 8.5vh;
  display: block;
  background-color: white;
}

.bord3-layer-bot{
  flex:1;
  height: 8.5vh;
  display: block;
}
.bord1-layer-top{
  flex:1;
  height: 8.5vh;
  display: block;
  background-color: white;
}

.bot-bord {
  background: -webkit-linear-gradient(left, #1b2716, #000000 240%);
}

.text-con {
  padding: 2vw;
  z-index: 2;
}
.image-within {
  display: block;
  background: yellow;
  height: 200px;
  z-index: 10;
}
.top-bord {
  background: white;
}

<div class="container">
<div class="border">
  <div class="bord1 top top-bord"></div>
  <div class="bord2 top top-bord"></div>
  <div class="bord3-layer-top">
  <div class="bord3 bottom bord3-top"></div>
</div>
</div>
<div class="image-within">
</div>
<div class="border">
  <div class="bord1-layer-top"><div class="bord1 top bot-bord"></div></div>
  <div class="bord2-bot bottom"></div>
  <div class="bord3-layer-bot">
  <div class="bord3 bottom bord3-bot"></div>
</div>
</div>
</div>

The CSS is really messy at the moment, so I'll have to clean it up a bit and work on keeping all the items constantly aligned, but it's looking pretty good right now! Thanks LegendaryJLD!


来源: stackexchange

问:
Convolve2d just by using Numpy
I am studying image-processing using NumPy and facing a problem with filtering with convolution.

I would like to convolve a gray-scale image. (convolve a 2d Array with a smaller 2d Array)

Does anyone have an idea to refine my method?

I know that SciPy supports convolve2d but I want to make a convolve2d only by using NumPy.

What I have done

First, I made a 2d array the submatrices.

```<code>a = np.arange(25).reshape(5,5) # original matrix

submatrices = np.array([
     [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
     [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
     [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
</code>```

the submatrices seems complicated but what I am doing is shown in the following drawing.

Next, I multiplied each submatrices with a filter.

```<code>conv_filter = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])
multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
</code>```

and summed them.

```<code>np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)
#array([[ 6,  7,  8],
#       [11, 12, 13],
#       [16, 17, 18]])
</code>```

Thus this procedure can be called my convolve2d.

```<code>def my_convolve2d(a, conv_filter):
    submatrices = np.array([
         [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
         [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
         [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
    multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
    return np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)
</code>```

However, I find this my_convolve2d troublesome for 3 reasons.

Generation of the submatrices is too awkward that is difficult to read and can only be used when the filter is 3*3

The size of the variant submatrices seems to be too big, since it is approximately 9 folds bigger than the original matrix.

The summing seems a little non intuitive. Simply said, ugly.

Thank you for reading this far.

Kind of update. I wrote a conv3d for myself. I will leave this as a public domain.

```<code>def convolve3d(img, kernel):
    # calc the size of the array of submatrices
    sub_shape = tuple(np.subtract(img.shape, kernel.shape) + 1)

    # alias for the function
    strd = np.lib.stride_tricks.as_strided

    # make an array of submatrices
    submatrices = strd(img,kernel.shape + sub_shape,img.strides * 2)

    # sum the submatrices and kernel
    convolved_matrix = np.einsum('hij,hijklm->klm', kernel, submatrices)

    return convolved_matrix
</code>```

答:
Cleaned up using as_strided and @Crispin 's einsum trick from above. Enforces the filter size into the expanded shape.  Should even allow non-square inputs if the indices are compatible.

```<code>def conv2d(a, f):
    s = f.shape + tuple(np.subtract(a.shape, f.shape) + 1)
    strd = numpy.lib.stride_tricks.as_strided
    subM = strd(a, shape = s, strides = a.strides * 2)
    return np.einsum('ij,ijkl->kl', f, subM)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Convolve2d just by using Numpy

Body:
I am studying image-processing using NumPy and facing a problem with filtering with convolution.

I would like to convolve a gray-scale image. (convolve a 2d Array with a smaller 2d Array)

Does anyone have an idea to refine my method?

I know that SciPy supports convolve2d but I want to make a convolve2d only by using NumPy.

What I have done

First, I made a 2d array the submatrices.

a = np.arange(25).reshape(5,5) # original matrix

submatrices = np.array([
     [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
     [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
     [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])

the submatrices seems complicated but what I am doing is shown in the following drawing.

Next, I multiplied each submatrices with a filter.

conv_filter = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])
multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)

and summed them.

np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)
#array([[ 6,  7,  8],
#       [11, 12, 13],
#       [16, 17, 18]])

Thus this procedure can be called my convolve2d.

def my_convolve2d(a, conv_filter):
    submatrices = np.array([
         [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
         [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
         [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
    multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
    return np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)

However, I find this my_convolve2d troublesome for 3 reasons.

Generation of the submatrices is too awkward that is difficult to read and can only be used when the filter is 3*3

The size of the variant submatrices seems to be too big, since it is approximately 9 folds bigger than the original matrix.

The summing seems a little non intuitive. Simply said, ugly.

Thank you for reading this far.

Kind of update. I wrote a conv3d for myself. I will leave this as a public domain.

def convolve3d(img, kernel):
    # calc the size of the array of submatrices
    sub_shape = tuple(np.subtract(img.shape, kernel.shape) + 1)

    # alias for the function
    strd = np.lib.stride_tricks.as_strided

    # make an array of submatrices
    submatrices = strd(img,kernel.shape + sub_shape,img.strides * 2)

    # sum the submatrices and kernel
    convolved_matrix = np.einsum('hij,hijklm->klm', kernel, submatrices)

    return convolved_matrix

Body:
Cleaned up using as_strided and @Crispin 's einsum trick from above. Enforces the filter size into the expanded shape.  Should even allow non-square inputs if the indices are compatible.

def conv2d(a, f):
    s = f.shape + tuple(np.subtract(a.shape, f.shape) + 1)
    strd = numpy.lib.stride_tricks.as_strided
    subM = strd(a, shape = s, strides = a.strides * 2)
    return np.einsum('ij,ijkl->kl', f, subM)

ContentLicense: CC BY-SA 3.0


问:
Detect progress of Async file(s) upload in AngularJS
I am trying to upload my file(s) on server once opened. I have a function in my service and calling that service to upload my file(s). This is my service function.

```<code>function post(file) {
var file = file;
if (angular.isDefined(file)) {
  return Upload.upload({
    url: filesConfig.uploadFile,
    data: {
      file: file
    }
  }).then(function (response) {
      return response;
    },
    function (error) {
      return error;
    },
    function (evt) {
      var progress = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progress + '% ' + evt.config.data.file.name);
    });
}

 }
</code>```

In last evt arg function I am getting progress in variable. I am calling this post function from controller like this.

```<code> angular.element(document.querySelector('#fileinput')).on('change', function () {
for (var i = 0; i < this.files.length; i++) {
  vm.filess.push(this.files[i]);
  fileUpload.post(vm.filess[i]).then(function (response) {
    console.log(response);
  });
}
 });
</code>```

Now I want to detect progress of each file in my controller, to show progress bar in UI. How to detect progress?

答:
Quickest and somehow dirtiest solution is below.

In controller:

```<code>angular.element(document.querySelector('#fileinput')).on('change', function() {
  for (var i = 0; i < this.files.length; i++) {
    var item = {
      file: this.files[i]
    };

    vm.filess.push(item);

    fileUpload.post(item).then(function (response) {
      console.log(response);
    });
  }
});
</code>```

In service:

```<code>function post(item) {
  var file = item.file;

  if (angular.isDefined(file)) {
    return Upload.upload({
      url: filesConfig.uploadFile,
      data: {
        file: file
      }
    }).then(function (response) {
        return response;
      },
      function (error) {
        return error;
      },
      function (evt) {
        item.progress = parseInt(100.0 * evt.loaded / evt.total);
      });
  }
}
</code>```

Doing that, you're wrapping your file within an item object, keeping file as property on that object. In your service, you're directly modifying the reference for your item.

On view, you just need to loop through vm.filess and you can access the dynamically property progress added.

Is not the best solution, I think that's the quickest I can think of with your setup.

Body:
I am trying to upload my file(s) on server once opened. I have a function in my service and calling that service to upload my file(s). This is my service function.

function post(file) {
var file = file;
if (angular.isDefined(file)) {
  return Upload.upload({
    url: filesConfig.uploadFile,
    data: {
      file: file
    }
  }).then(function (response) {
      return response;
    },
    function (error) {
      return error;
    },
    function (evt) {
      var progress = parseInt(100.0 * evt.loaded / evt.total);
      console.log('progress: ' + progress + '% ' + evt.config.data.file.name);
    });
}

 }

In last evt arg function I am getting progress in variable. I am calling this post function from controller like this.

 angular.element(document.querySelector('#fileinput')).on('change', function () {
for (var i = 0; i < this.files.length; i++) {
  vm.filess.push(this.files[i]);
  fileUpload.post(vm.filess[i]).then(function (response) {
    console.log(response);
  });
}
 });

Now I want to detect progress of each file in my controller, to show progress bar in UI. How to detect progress?

Body:
Quickest and somehow dirtiest solution is below.

In controller:

angular.element(document.querySelector('#fileinput')).on('change', function() {
  for (var i = 0; i < this.files.length; i++) {
    var item = {
      file: this.files[i]
    };

    vm.filess.push(item);

    fileUpload.post(item).then(function (response) {
      console.log(response);
    });
  }
});

In service:

function post(item) {
  var file = item.file;

  if (angular.isDefined(file)) {
    return Upload.upload({
      url: filesConfig.uploadFile,
      data: {
        file: file
      }
    }).then(function (response) {
        return response;
      },
      function (error) {
        return error;
      },
      function (evt) {
        item.progress = parseInt(100.0 * evt.loaded / evt.total);
      });
  }
}

Doing that, you're wrapping your file within an item object, keeping file as property on that object. In your service, you're directly modifying the reference for your item.

On view, you just need to loop through vm.filess and you can access the dynamically property progress added.

Is not the best solution, I think that's the quickest I can think of with your setup.


问:
JMeter Selenium plugin Kernel32 exception
i have been trying to setup Selenium plugins for JMeter for a day already and i can't figure out how to solve this exception. I have tried replacing selenium jar's, switching versions and still i get this one.

JMeter version: 2.13
Selenium libs: 2.46.0

```<code>Uncaught exception:  java.lang.NoClassDefFoundError: org/openqa/selenium/os/Kernel32
at org.openqa.selenium.os.ProcessUtils.killWinProcess(ProcessUtils.java:133)
at org.openqa.selenium.os.ProcessUtils.killProcess(ProcessUtils.java:81)
at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.destroyHarder(UnixProcess.java:248)
at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.access$200(UnixProcess.java:200)
at org.openqa.selenium.os.UnixProcess.destroy(UnixProcess.java:124)
at org.openqa.selenium.os.CommandLine.destroy(CommandLine.java:153)
at org.openqa.selenium.firefox.FirefoxBinary.quit(FirefoxBinary.java:259)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.quit(NewProfileExtensionConnection.java:202)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.quit(FirefoxDriver.java:376)
at org.openqa.selenium.firefox.FirefoxDriver.stopClient(FirefoxDriver.java:322)
at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:477)
at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.quitBrowser(WebDriverConfig.java:269)
at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.threadFinished(WebDriverConfig.java:244)
at org.apache.jmeter.threads.JMeterThread$ThreadListenerTraverser.addNode(JMeterThread.java:612)
at org.apache.jorphan.collections.HashTree.traverseInto(HashTree.java:998)
at org.apache.jorphan.collections.HashTree.traverse(HashTree.java:980)
at org.apache.jmeter.threads.JMeterThread.threadFinished(JMeterThread.java:584)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:315)
at java.lang.Thread.run(Unknown Source)
</code>```

答:
The Error comes when the following issues are met:

In the Lib folder, multiple jars with different versions are present.

platform.jar is not present in lib folder

jna.jar are not present is not present in lib folder.

To solve the issue:
1. Install platform.jar and jna.jar in the lib folder and delete all the jar files with the same name.

Body:
i have been trying to setup Selenium plugins for JMeter for a day already and i can't figure out how to solve this exception. I have tried replacing selenium jar's, switching versions and still i get this one.

JMeter version: 2.13
Selenium libs: 2.46.0

Uncaught exception:  java.lang.NoClassDefFoundError: org/openqa/selenium/os/Kernel32
at org.openqa.selenium.os.ProcessUtils.killWinProcess(ProcessUtils.java:133)
at org.openqa.selenium.os.ProcessUtils.killProcess(ProcessUtils.java:81)
at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.destroyHarder(UnixProcess.java:248)
at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.access$200(UnixProcess.java:200)
at org.openqa.selenium.os.UnixProcess.destroy(UnixProcess.java:124)
at org.openqa.selenium.os.CommandLine.destroy(CommandLine.java:153)
at org.openqa.selenium.firefox.FirefoxBinary.quit(FirefoxBinary.java:259)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.quit(NewProfileExtensionConnection.java:202)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.quit(FirefoxDriver.java:376)
at org.openqa.selenium.firefox.FirefoxDriver.stopClient(FirefoxDriver.java:322)
at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:477)
at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.quitBrowser(WebDriverConfig.java:269)
at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.threadFinished(WebDriverConfig.java:244)
at org.apache.jmeter.threads.JMeterThread$ThreadListenerTraverser.addNode(JMeterThread.java:612)
at org.apache.jorphan.collections.HashTree.traverseInto(HashTree.java:998)
at org.apache.jorphan.collections.HashTree.traverse(HashTree.java:980)
at org.apache.jmeter.threads.JMeterThread.threadFinished(JMeterThread.java:584)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:315)
at java.lang.Thread.run(Unknown Source)


问:
How to merge many directory in one directory by keeping th order?
I need to to copy numpy files in directory A to diretory B, by keeping their order on time. </p>

```<code>import os
import shutil
DestFolder = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4'
SrcFolder  = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4_1'
os.chdir(SrcFolder)
list_files_Without_Sort=os.listdir(os.getcwd())
list_files_Sorted=sorted((list_files_Without_Sort),key=os.path.getmtime)
for root, dirs, files in os.walk(list_files_Sorted, topdown=True):
    for name in files:
        SourceFolder = os.path.join(root,name)
        shutil.copy2(SourceFolder, DestFolder)
</code>```

<p>It gives me this error: </p>

```<code>    names = listdir(top)

TypeError: coercing to Unicode: need string or buffer, list found
</code>```

答:
os.walk takes a string but you're passing a list object. You can walk the directory without sorting (I don't see why you need to order independent copy ops):

```<code>import os
import shutil

destfolder = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4'
srcfolder  = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4_1'
for root, dirs, files in os.walk(srcfolder, topdown=True):
    for name in files:
        src = os.path.join(root, name)
        shutil.copy2(src, destfolder)
</code>```

Body:
I need to to copy numpy files in directory A to diretory B, by keeping their order on time.

import os
import shutil
DestFolder = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4'
SrcFolder  = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4_1'
os.chdir(SrcFolder)
list_files_Without_Sort=os.listdir(os.getcwd())
list_files_Sorted=sorted((list_files_Without_Sort),key=os.path.getmtime)
for root, dirs, files in os.walk(list_files_Sorted, topdown=True):
    for name in files:
        SourceFolder = os.path.join(root,name)
        shutil.copy2(SourceFolder, DestFolder)

It gives me this error:

    names = listdir(top)

TypeError: coercing to Unicode: need string or buffer, list found

Body:
os.walk takes a string but you're passing a list object. You can walk the directory without sorting (I don't see why you need to order independent copy ops):

import os
import shutil

destfolder = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4'
srcfolder  = 'D:\\Traces_Copie\\Simulations\\Traces4\\Trace4_1'
for root, dirs, files in os.walk(srcfolder, topdown=True):
    for name in files:
        src = os.path.join(root, name)
        shutil.copy2(src, destfolder)


问:
Summernote image upload not working in codeigniter
I have integrated summernote in my website (built with Codeigniter) and for texts it is working fine. But for image upload, there arises the following problem.

Summernote reads the image as base64. Now this works perfectly fine for small images, but once images are large, the image finally does not render due to the huge string created by the base64 in the database.

So I am trying to save the image in my server and then use the link of that image.

Following are the codes:
Script for summernote:

```<code><script type="text/javascript">
$(document).ready(function() {
  $('#summernote').summernote({
    height: 300,
    onImageUpload: function(files) {
            sendFile(files[0]);
        }
  });
  function sendFile(file) {
        data = new FormData();
        data.append("files", file);
        upload_url = "<?php echo base_url(); ?>" + "general/upload_image";
        $.ajax({
            data: data,
            type: "POST",
            url: upload_url,
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                 $(this).summernote("insertImage", url);

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

the php upload_image function:

```<code>public function upload_image()
{
    if ($_FILES['file']['name']) {
        if (!$_FILES['file']['error']) {
            $name = md5(rand(100, 200));
            $ext = explode('.', $_FILES['file']['name']);
            $filename = $name . '.' . $ext[1];
            $destination = 'http://sitename.com/dist/img/blogimg/' . $filename; //change this directory
            $location = $_FILES["file"]["tmp_name"];
            move_uploaded_file($location, $destination);
            echo 'http://sitename.com/dist/img/blogimg/' . $filename;//change this URL
        }
        else
        {
            echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
        }
    }
}
</code>```

now, when I click on insert image in summernote or drag and drop an image multiple instances of the following error is shown in the console:

```<code>>Uncaught TypeError: Cannot read property 'nodeType' of undefined
</code>```

This is what I want to achieve,
N.B. This editor is for a blog.
1. User clicks on insert image and uploads an image from his computer.
2. the image is shown in the editor (but not uploaded to server at this step).
3. When user clicks on submit button, then the image should be saved as an image file in a predefined folder.
4. When the page renders the it should have

```<code><img src="mysite.com/path_to_image">
</code>```

now it is something like

```<code><img src="data:image/jpeg;base64,/9j/4AAQSkZJR....">)
</code>```

Please note, I tried using onImageUpload within callbacks but the result was nothing was actually happening, neither the image was geting uploaded to the editor nor to the folder in the server.

Where am I going wrong....?? Please help me fix this...

答:
if your summernote version after 0.7

following this

```<code>$('#summernote').summernote({
                height: 400,
                callbacks: {
                    onImageUpload: function(files, editor, welEditable) {
                        sendFile(files[0]);
                    }
                }});
</code>```

Body:
if your summernote version after 0.7

following this

$('#summernote').summernote({
                height: 400,
                callbacks: {
                    onImageUpload: function(files, editor, welEditable) {
                        sendFile(files[0]);
                    }
                }});


问:
Child div should be as high as parent div
I need a child div to be as high as its parent, but I do not know the parent's height. It can change.
Setting "height: 100%" does not work, as the div will take the height of the entire page.

This is the layout of the divs:

```<code><div id="deelnemersballoon">
    <div class="balloonarrow"></div>

    <div class="balloonborder">

        <div class="ballooncontent">
            <div id="aantaldeelnemers">1</div>
            <div id="deelnemertekst">deelnemer werd toegevoegd.</div>
            <div class="clear">
                <button>Add something</button>
            </div>
        </div>

    </div>

</div>
</code>```

.balloonarrow should be as high as #deelnemersballoon

答:
I never had much luck with height: 100%; even when playing by the rules. What does .balloonarrow do? If you're just trying to snap a graphic to the bottom of the div, you can try position: absolute; and bottom: 0px;, as long as #deelnemersballoon is set to position: relative;.

If you're just looking to make a solid/patterned visual contained by .balloonarrow, you're better off making a stretch image: create an image 3px or 4px tall, make it the background of #deelnemersballoon, and set it to repeat-y. Quick and dirty way to make a 100% height sidebar.

Hope this helps, can't tell much more without seeing your css.

ContentLicense: CC BY-SA 2.5

Body:
I need a child div to be as high as its parent, but I do not know the parent's height. It can change.
Setting "height: 100%" does not work, as the div will take the height of the entire page.

This is the layout of the divs:

1

deelnemer werd toegevoegd.

                <button>Add something</button>

.balloonarrow should be as high as #deelnemersballoon


问:
After cropping and writing in png file the size of some images has changed,why?
My images are in mat file after I cropped them with a particular size 256x256, the size was correct before  writing in png file. I saved them in png format. Now, I wanted to process them and realized that the sizes are not same, what is the reason? And how can I solve it? Thanks

This the code:

```<code>[m1,m2] = size(II);

i1_start = floor((m1)/2)-floor(n/2); % or round instead of floor; using neither gives warning
i1_stop = i1_start + n;

i2_start = floor((m2)/2)-floor(n/2);
i2_stop = i2_start + n;

B = II(i1_start+1:i1_stop, i2_start+1:i2_stop);

figure ,imshow(B,[]);
</code>```

and this is the code for png conversion:

```<code> outfile = sprintf(png_filename)
data=uint8(data);
imwrite(data,outfile,'png','BitDepth' ,8);
</code>```

答:
Use imwrite function</p>

```<code>A = rand(50);
imwrite(A,'myGray.png')
</code>```

Body:
My images are in mat file after I cropped them with a particular size 256x256, the size was correct before  writing in png file. I saved them in png format. Now, I wanted to process them and realized that the sizes are not same, what is the reason? And how can I solve it? Thanks

This the code:

[m1,m2] = size(II);

i1_start = floor((m1)/2)-floor(n/2); % or round instead of floor; using neither gives warning
i1_stop = i1_start + n;

i2_start = floor((m2)/2)-floor(n/2);
i2_stop = i2_start + n;

B = II(i1_start+1:i1_stop, i2_start+1:i2_stop);

figure ,imshow(B,[]);

and this is the code for png conversion:

 outfile = sprintf(png_filename)
data=uint8(data);
imwrite(data,outfile,'png','BitDepth' ,8);

Body:
Use imwrite function

A = rand(50);
imwrite(A,'myGray.png')


问:
How to write sub queries with LINQ
I'm trying to write a similar query with LINQ

```<code>select DISTINCT(m.MatchID),
    (select TeamName
     from tbl_TournamentTeams
     where TeamID = m.Team1),
    (select TeamName
     from tbl_TournamentTeams
     where TeamID = m.Team2)
     from tbl_TournamentTeams t, tbl_Match m
     where t.TournamentID = m.TournamentID
</code>```

SQL tbl_TournamentTeams table design,

```<code>Create Table tbl_TournamentTeams(
TeamID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
TeamName varchar(30) NOT NULL
);
</code>```

SQL tbl_Match table design,

```<code>Create Table tbl_Match(
MatchID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
Team1 int Foreign key references tbl_TournamentTeams(TeamID),
Team2 int Foreign key references tbl_TournamentTeams(TeamID),
StartTime DateTime not null,
MatchBetAmount int not null
);
</code>```

Please let me know will i be able to write a similar query with LINQ. Thanks

I want to get TeamName for every match from the linq query, currently i'm just able to fetch the teamId for a match. Please let me know how to get the TeamName details as well with the below query,

```<code> var res = dbEntity.tbl_Match.Join(dbEntity.tbl_TournamentTeams,
                                            m => m.TournamentID,
                                            t => t.TournamentID,
                                            (m, t) => new
                                            {
                                                MatchID = m.MatchID,
                                                MatchTeam1 = m.Team1,
                                                MatchTeam2 = m.Team2,
                                                TournamentID =t.TournamentID

                                                // How to print the team name details as well here, where currently i'm just able to fetch the teamID
                                            });
</code>```

答:
I assume team1 and team2 doesn't contains null values    </p>

```<code> dbEntity.tbl_Match.Select(m => new{
     m.Id,
    Team1Name=dbEntity.TournamentTeams.SingleOrDefault(t => t.id=m.Team1).Name,
    Team2Name =dbEntity.TournamentTeams.SingleOrDefault(t => t.id=m.Team2).Name
     })
</code>```

Title: How to write sub queries with LINQ

Body:
I'm trying to write a similar query with LINQ

select DISTINCT(m.MatchID),
    (select TeamName
     from tbl_TournamentTeams
     where TeamID = m.Team1),
    (select TeamName
     from tbl_TournamentTeams
     where TeamID = m.Team2)
     from tbl_TournamentTeams t, tbl_Match m
     where t.TournamentID = m.TournamentID

SQL tbl_TournamentTeams table design,

Create Table tbl_TournamentTeams(
TeamID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
TeamName varchar(30) NOT NULL
);

SQL tbl_Match table design,

Create Table tbl_Match(
MatchID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
Team1 int Foreign key references tbl_TournamentTeams(TeamID),
Team2 int Foreign key references tbl_TournamentTeams(TeamID),
StartTime DateTime not null,
MatchBetAmount int not null
);

Please let me know will i be able to write a similar query with LINQ. Thanks

I want to get TeamName for every match from the linq query, currently i'm just able to fetch the teamId for a match. Please let me know how to get the TeamName details as well with the below query,

 var res = dbEntity.tbl_Match.Join(dbEntity.tbl_TournamentTeams,
                                            m => m.TournamentID,
                                            t => t.TournamentID,
                                            (m, t) => new
                                            {
                                                MatchID = m.MatchID,
                                                MatchTeam1 = m.Team1,
                                                MatchTeam2 = m.Team2,
                                                TournamentID =t.TournamentID

                                                // How to print the team name details as well here, where currently i'm just able to fetch the teamID
                                            });

Body:
I assume team1 and team2 doesn't contains null values

 dbEntity.tbl_Match.Select(m => new{
     m.Id,
    Team1Name=dbEntity.TournamentTeams.SingleOrDefault(t => t.id=m.Team1).Name,
    Team2Name =dbEntity.TournamentTeams.SingleOrDefault(t => t.id=m.Team2).Name
     })


问:
Searching Up the Scope vs Accessing the DOM - Speed Performance
I am learning javaScript and there are still many doubts. I've already tried to search this one but maybe I am using the wrong words. I am always delaying this but since the size of the project I am working on is becoming larger than I expected I need to be clarified.

I am aware that are costs in terms of speed in both searching up the scope and accessing the Dom. But I don't know which one is slower than the other.

Is it faster...

a) to go up the scope chain to grab the variable with the jQuery object, but go to the Dom just once

or

b) Not go up the scope chain, but go to the Dom again

```<code>var $el = $("#el");

//$el is used on this scope (and so, the question makes some sense:))

$el (...)

// some or lot's of code

function a() {

   // some or lot's of code

   function b(){

      // some or lot's of code

      function c() {

         a) $el (...)
         b) var $el = $("#el");
            $el (...)

      }

  }

}
</code>```

答:
Option A is faster. (Declaring the variable on top)

When you need $("#el") more then once store it as a variable. Using the DOM multiple times is slow.

Greg Franko explains a few best practices here. See slide 10-13 for your question.

Body:
I am learning javaScript and there are still many doubts. I've already tried to search this one but maybe I am using the wrong words. I am always delaying this but since the size of the project I am working on is becoming larger than I expected I need to be clarified.

I am aware that are costs in terms of speed in both searching up the scope and accessing the Dom. But I don't know which one is slower than the other.

Is it faster...

a) to go up the scope chain to grab the variable with the jQuery object, but go to the Dom just once

or

b) Not go up the scope chain, but go to the Dom again

var $el = $("#el");

//$el is used on this scope (and so, the question makes some sense:))

$el (...)

// some or lot's of code

function a() {

   // some or lot's of code

   function b(){

      // some or lot's of code

      function c() {

         a) $el (...)
         b) var $el = $("#el");
            $el (...)

      }

  }

}


问:
Is SNMP++ worth using
I have implemented a small program which uses Net-SNMP to get network related information. It uses asynchronous mode to query multiple hosts.

Since Net-SNMPv3 does not support multi-threading, is it beneficial to shift to SNMP++?
I have a lot of hosts or routers in the network where I need to monitor the traps and general network information of ~2000 routers.

Will using SNMP++ be much faster that Net-SNMP as it uses multi-threading?

答:
I guess you are implementing in C++ and maybe need to, but I you can use snmp4j it has the possibility to use multi-threading. Even if you have to wrap the code to using Java.
Are at the same issue, where 1-2000 units need both SNMP Get / Walks and due to slow units, there needs to be multiple threads fetching data in parallel.</p>

Title: Is SNMP++ worth using


问:
Assingning Refrences in Java
```<code>class A{}
class B extends A{}
class C extends A{}

public class Test {
     public static void main(String [] args){
    A a = new A();
    A b = new B();
    A c = new C();

    a = b;
    b = c;
    }
}
</code>```

Here how can we assign child reference to parent one ? and also b and c are different object types then how we can assign one to another ?

答:
Because of polymorphism and inheritance. When you say that;

```<code>class Manager extends Worker{}
</code>```

Actually you say, all Manager is a Worker. But Manager is more spesific type than Worker. For this reason we use the extends keyword for inheritance. Every Manager is a Worker but more detailed Worker.

```<code>Worker o1 = new Worker();
Worker o2 = new Manager();
o1 = o2;
</code>```

In first line, o1 is a worker Object (general type).
Second line is an example of upcasting. This line say that:  o2 is a manager object but o2's interface is worker's interface.
In third line, because every manager is a worker, you can assign a manager object to a worker type reference.

Title: Assingning Refrences in Java

Body:
class A{}
class B extends A{}
class C extends A{}

public class Test {
     public static void main(String [] args){
    A a = new A();
    A b = new B();
    A c = new C();

    a = b;
    b = c;
    }
}

Here how can we assign child reference to parent one ? and also b and c are different object types then how we can assign one to another ?

Body:
Because of polymorphism and inheritance. When you say that;

class Manager extends Worker{}

Actually you say, all Manager is a Worker. But Manager is more spesific type than Worker. For this reason we use the extends keyword for inheritance. Every Manager is a Worker but more detailed Worker.

Worker o1 = new Worker();
Worker o2 = new Manager();
o1 = o2;

In first line, o1 is a worker Object (general type).
Second line is an example of upcasting. This line say that:  o2 is a manager object but o2's interface is worker's interface.
In third line, because every manager is a worker, you can assign a manager object to a worker type reference.


问:
Form Submit using Angularjs to SpringMVC Controller using $http.post
How to send multiple data  from jsp to Springmvc controller to change password.
I wants to change password using angular js.
How to solve this?

Alert message showing properly but cannot call controller using post method.

My js code

```<code>myangu.controller('account', function($scope, $http) {

    var submitvalue = $scope.detailspassword = function() {

        alert($scope.confirmpassword + "" + $scope.newpassword + ""
                + $scope.existedpassword);

    };
    var submitvalue = function(request) {

    };
    var error = function(reason) {
        alert("failure message: " + JSON.stringify({
            reason : reason
        }));

        $scope.errormessage = "Something Wrong.Cannot Change Your Password";

    };

    $http.post('/java/updatepassword').then(submitvalue, error);

});
</code>```

SpringMvc controller

```<code>@RequestMapping(value = "/updatepassword", method = RequestMethod.POST,produces="application/json")
    public @ResponseBody String updatepassword(@RequestBody Users users) throws JSONException,NullPointerException,JsonGenerationException{

        System.out.println("Updatedpassword"+users.getPassword());

        return uservice.updatepassword(users);
    }
</code>```

Jsp page

```<code><div class="divTablebody">
    <div  ng-controller="account">
        <%-- <form:form action="/java/changepassword"  method="POST" > --%>
        <div>{{errormessage}}</div>
        <div class="divTableRow">

            <div class="divTableCell">Existed password:</div>
            <div class="divTableCell">
                <input type="password" placeholder="Existed Password"
                    id="Existedpw" ng-model="existedpassword">
            </div>
        </div>
        <div class="divTableRow">
            <div class="divTableCell">New password:</div>
            <div class="divTableCell">
                <input type="password" placeholder="New Password" id="newpw"
                    ng-model="newpassword">
            </div>
        </div>
        <div class="divTableRow">
            <div class="divTableCell">Password Confirmation:</div>
            <div class="divTableCell">
                <input type="password" placeholder="Confirm Password "
                    id="confirmpw" ng-model="confirmpassword">
            </div>
        </div>
        <div class="divTableRow">
            <div class="divTableCell">Save</div>
            <div class="divTableCell">
                <input type="submit" id="pwsubmit" ng-click="detailspassword()" name="Submit">
            </div>
        </div>
</code>```

答:
You need to pass the data in post call as second parameter.

```<code>var objPassword = {
       existedpassword : $scope.existedpassword
       newpassword : $scope.newpassword
       newpassword : $scope.confirmpassword
}

$http.post('/java/updatepassword',objPassword).then(submitvalue, error);
</code>```

For more Angular#POST

EDIT :

```<code>myangu.controller('account', ['$scope', '$http', function ($scope, $http) {
    $scope.detailspassword = function () {
        alert($scope.confirmpassword + "" + $scope.newpassword + "" + $scope.existedpassword);
        var formData = { cpass: $scope.confirmpassword, newpass: $scope.newpassword, oldpass: $scope.existedpassword };

        var error = function (responce) {
            $scope.errormessage = "Unsuccessful";
        };
        $http.post('/java/updatepassword',formData).then(submitvalue, error);
    };
}]);
</code>```

Body:
How to send multiple data  from jsp to Springmvc controller to change password.
I wants to change password using angular js.
How to solve this?

Alert message showing properly but cannot call controller using post method.

My js code

myangu.controller('account', function($scope, $http) {

    var submitvalue = $scope.detailspassword = function() {

        alert($scope.confirmpassword + "" + $scope.newpassword + ""
                + $scope.existedpassword);

    };
    var submitvalue = function(request) {

    };
    var error = function(reason) {
        alert("failure message: " + JSON.stringify({
            reason : reason
        }));

        $scope.errormessage = "Something Wrong.Cannot Change Your Password";

    };

    $http.post('/java/updatepassword').then(submitvalue, error);

});

SpringMvc controller

@RequestMapping(value = "/updatepassword", method = RequestMethod.POST,produces="application/json")
    public @ResponseBody String updatepassword(@RequestBody Users users) throws JSONException,NullPointerException,JsonGenerationException{

        System.out.println("Updatedpassword"+users.getPassword());

        return uservice.updatepassword(users);
    }

Jsp page

        <%-- <form:form action="/java/changepassword"  method="POST" > --%>

{{errormessage}}

Existed password:

                <input type="password" placeholder="Existed Password"
                    id="Existedpw" ng-model="existedpassword">

New password:

                <input type="password" placeholder="New Password" id="newpw"
                    ng-model="newpassword">

Password Confirmation:

                <input type="password" placeholder="Confirm Password "
                    id="confirmpw" ng-model="confirmpassword">

Save

                <input type="submit" id="pwsubmit" ng-click="detailspassword()" name="Submit">

Body:
You need to pass the data in post call as second parameter.

var objPassword = {
       existedpassword : $scope.existedpassword
       newpassword : $scope.newpassword
       newpassword : $scope.confirmpassword
}

$http.post('/java/updatepassword',objPassword).then(submitvalue, error);

For more Angular#POST

EDIT :

myangu.controller('account', ['$scope', '$http', function ($scope, $http) {
    $scope.detailspassword = function () {
        alert($scope.confirmpassword + "" + $scope.newpassword + "" + $scope.existedpassword);
        var formData = { cpass: $scope.confirmpassword, newpass: $scope.newpassword, oldpass: $scope.existedpassword };

        var error = function (responce) {
            $scope.errormessage = "Unsuccessful";
        };
        $http.post('/java/updatepassword',formData).then(submitvalue, error);
    };
}]);


问:
How to get values of two columns only when both column values are present using bash script
1

2

3   5

4   6

9

I have two columns, if 2nd column contain no values then skip the row  else I want result like two column values only  when both column values are present

sample output

3 5

4 6

答:
For bash only you could try:</p>

```<code>while read -r -a nums
do
  (( ${#nums[*]} == 2 )) && echo "${nums[@]}"
done<input_file
</code>```

Body:
For bash only you could try:

while read -r -a nums
do
  (( ${#nums[*]} == 2 )) && echo "${nums[@]}"
done<input_file


问:
What's the difference between == and : in swift extension where condition
I have a question in swift extension:

```<code>protocol Racer {
    var speed: Double { get }
}
extension Sequence where Iterator.Element == Racer {
    func fastest() -> Iterator.Element? {
        return self.max(by: { (a: Iterator.Element, b: Iterator.Element) -> Bool in
            return a.speed < b.speed
        })
    }
}

extension Sequence where Iterator.Element: Racer {
    func bla() -> Void {

    }
}
</code>```

I am wondering what's the difference between them. In fact, an array of type [Racer] doesn't have bla() function.

Edit 1： There's still a question, assuming we have a struct conform to Racer

```<code>struct Human: Racer {
    var speed: Double
}
</code>```

If we have an Array<Racer>:

```<code>let me = Human(speed: 99999)
let you = Human(speed: 99998)
let arr: [Racer] = [me, you]
// Threre's no problem, we can do this
arr.fastest()

// but
let arr2: [Human] = [me, you]
// this Array won't have the `fastest` function
arr2.fastest() ------> Error!
</code>```

So, I have to extension both == and : at the same time for the same function?

答:
When using : you are writing an extension for a type that conforms to a particular protocol or inherits a specified class.

When using = you are writing an extension for a specific type, in your case Racer.

You can read more in the docs here.

Edit:

One difference is that when you are using = the type must match, this means that the element type for the array must be Racer.
This is why Array[Human] doesn't get the extension method, because the type isn't Racer is actually Human.

You don't need 2 methods, you can change the first one to use : instead of  =. Conforming to Racer protocol is enough, it doesn't need to be of Racer type.

Body:
I have a question in swift extension:

protocol Racer {
    var speed: Double { get }
}
extension Sequence where Iterator.Element == Racer {
    func fastest() -> Iterator.Element? {
        return self.max(by: { (a: Iterator.Element, b: Iterator.Element) -> Bool in
            return a.speed  Void {

    }
}

I am wondering what's the difference between them. In fact, an array of type [Racer] doesn't have bla() function.

Edit 1： There's still a question, assuming we have a struct conform to Racer

struct Human: Racer {
    var speed: Double
}

If we have an Array<Racer>:

let me = Human(speed: 99999)
let you = Human(speed: 99998)
let arr: [Racer] = [me, you]
// Threre's no problem, we can do this
arr.fastest()

// but
let arr2: [Human] = [me, you]
// this Array won't have the `fastest` function
arr2.fastest() ------> Error!

So, I have to extension both == and : at the same time for the same function?


答:
While your question is very unclear, perhaps I can answer it with a general rule of thumb:

The DOM is slowwwww. If you can avoid traversing it, do so. If you search the DOM to find a specfic node, store that reference in a variable to avoid having to search through the DOM again.

Title: Searching Up the Scope vs Accessing the DOM - Speed Performance


问:
remove some elements if no children
i need to remove some elements if no children...

this will work...

```<code>$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});
</code>```

but it will look for all elements... i need to limit to some elements.. so i made this..

```<code>elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})
</code>```

but it doesn't work..

答:
If I understood correctly what you asked, you should rty :

```<code>if($("some selection").children() === undefined){
//do something
}
</code>```

or as a function :

```<code>function rmIfNoChild(jQobj){
    if(jQobj.children() === undefined){
      //do something
    }
}
</code>```

Title: remove some elements if no children

Body:
i need to remove some elements if no children...

this will work...

$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});

but it will look for all elements... i need to limit to some elements.. so i made this..

elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})

but it doesn't work..

Body:
If I understood correctly what you asked, you should rty :

if($("some selection").children() === undefined){
//do something
}

or as a function :

function rmIfNoChild(jQobj){
    if(jQobj.children() === undefined){
      //do something
    }
}


问:
Excel 2016 on MAC missing pictures after save
I have an application created on Excel file with macros. It needs to be compatible with all Excel versions starting from 2007, both PC and MAC.

I have problem with pictures on MAC 2016. Whenever I save file, close it and reopen again I can't see pictures on the sheet which was active one during saving. Do anyone know what the problem is and how to deal with it?

My end users are not experienced enough and they get panicked if they can't see proper buttons...

My solution is to change active sheet using Workbook_BeforeSave event, but on MAC 2016 version I can't get back, because Workbook_AfterSave event doesn't work at all. As you can imagine it is not very convenient for end user to change active sheet when you just want to save your work.

I will be very grateful for any suggestion.

答:
I'm not sure whether it helps, But you can give a try

Try using Workbook_BeforeClose event.

or else try to acheive the same using your code like switching to the sheet whatever you need

Sheets("activesheet").Select


问:
How to address a workbook in vba for Mac?
I´m trying to run a macro that works perfectly on a PC, but when trying to run the same macro on Mac I get the error "1004"; which says that the file can´t be found.
I´m writing the address like this way:

```<code>Workbooks.Open("\Macintosh HD\Usuarios\carlosstephan\Dropbox\SCEN Const.\GastosyPagosSCEN.xlsm")
</code>```

Does someone knows how to write it correct?.

I already tried with "/" instead of "\", and it doesn´t works either.

The same error pops-up with this "with":

```<code>With Sheets("Gastos")

    .Range(“A8”, .Cells(.Rows.Count, .Columns.Count)).Clear

End With
</code>```

Where is the mistake?.

答:
It depends on your version of Mac. I always have problems with getting VBA to run on Mac and Office 2016 has been a step backwards.

See
http://www.rondebruin.nl/mac/mac017.htm

```<code>in 2011 it return a path like this :
Macintosh HD:Users:rdb:Desktop:YourFolder:
And in 2016  a path like this :
/Users/RDB/Desktop/YourFolder/
Reason is that in 2016 you must use the posix path in VBA codes
</code>```

Body:
I´m trying to run a macro that works perfectly on a PC, but when trying to run the same macro on Mac I get the error "1004"; which says that the file can´t be found.
I´m writing the address like this way:

Workbooks.Open("\Macintosh HD\Usuarios\carlosstephan\Dropbox\SCEN Const.\GastosyPagosSCEN.xlsm")

Does someone knows how to write it correct?.

I already tried with "/" instead of "\", and it doesn´t works either.

The same error pops-up with this "with":

With Sheets("Gastos")

    .Range(“A8”, .Cells(.Rows.Count, .Columns.Count)).Clear

End With

Where is the mistake?.

Body:
It depends on your version of Mac. I always have problems with getting VBA to run on Mac and Office 2016 has been a step backwards.

See
http://www.rondebruin.nl/mac/mac017.htm

in 2011 it return a path like this :
Macintosh HD:Users:rdb:Desktop:YourFolder:
And in 2016  a path like this :
/Users/RDB/Desktop/YourFolder/
Reason is that in 2016 you must use the posix path in VBA codes


问:
How to loop through columns and calculate averages?
data series

I want to find the average for each segment of ten values down a column. (See data series picture)
Continuously all the way to the bottom of the data set. The data set can vary in length, and the code has to be "generic" of sorts.

Based on other code segments I have tried to do this:

```<code>Sub tenthavg()

Dim currentIndex As Long
Dim myArray() As Variant
Dim rng As Range

ReDim myArray(1 To 10)

Range("b1", Range("b1").End(xlDown)).Select
Set myArray = Selection
currentIndex = 1

Do Until currentIndex + 1 > UBound(myArray)
    ActiveSheet.Cells(currentIndex, "T") = AverageOfSubArray(myArray, currentIndex, 10)
    currentIndex = currentIndex + 1
Loop

End Sub

'=================================================================

Function AverageOfSubArray(myArray As Variant, startIndex As Long,   elementCount As Long) As Double
Dim runningTotal As Double
Dim i As Long

For i = startIndex To (startIndex + elementCount - 1)
    runningTotal = runningTotal + val(myArray(i))
Next i
AverageOfSubArray = runningTotal / elementCount
End Function
</code>```

Unfortunately I can't make it work. Am I approaching this the right way?

If so, what am I doing wrong?

答:
IMHO it's not quite the successful approach ... instead of Selecting EndDown and other concepts borrowed from interactive working make use of VBA's own mechanisms.

A "generic" approch takes Range start address, batch size and offsets where to put the result as arguments ...

```<code>Sub AvgX(MyR As Range, S As Integer, ORow As Integer, OCol As Integer)
' MyR = start of range
' S   = batch size
' OCol, ORow = Offsets to place result in relation to last batch value
Dim Idx As Integer, Jdx As Integer, RSum As Variant

    Idx = 1
    RSum = 0
    Do
        For Jdx = 1 To S
            RSum = RSum + MyR(Idx, 1)
            Idx = Idx + 1
            If MyR(Idx, 1) = "" Then Exit Do
        Next Jdx
        MyR(Idx - 1, 1).Offset(ORow, OCol) = RSum / (Jdx - 1)
        RSum = 0
    Loop
End Sub
</code>```

and is called by

```<code>Sub Test()
    AvgX [C4], 10, 0, 1
End Sub
</code>```

to give you this result ...

Body:
data series

I want to find the average for each segment of ten values down a column. (See data series picture)
Continuously all the way to the bottom of the data set. The data set can vary in length, and the code has to be "generic" of sorts.

Based on other code segments I have tried to do this:

Sub tenthavg()

Dim currentIndex As Long
Dim myArray() As Variant
Dim rng As Range

ReDim myArray(1 To 10)

Range("b1", Range("b1").End(xlDown)).Select
Set myArray = Selection
currentIndex = 1

Do Until currentIndex + 1 > UBound(myArray)
    ActiveSheet.Cells(currentIndex, "T") = AverageOfSubArray(myArray, currentIndex, 10)
    currentIndex = currentIndex + 1
Loop

End Sub

'=================================================================

Function AverageOfSubArray(myArray As Variant, startIndex As Long,   elementCount As Long) As Double
Dim runningTotal As Double
Dim i As Long

For i = startIndex To (startIndex + elementCount - 1)
    runningTotal = runningTotal + val(myArray(i))
Next i
AverageOfSubArray = runningTotal / elementCount
End Function

Unfortunately I can't make it work. Am I approaching this the right way?

If so, what am I doing wrong?

Body:
IMHO it's not quite the successful approach ... instead of Selecting EndDown and other concepts borrowed from interactive working make use of VBA's own mechanisms.

A "generic" approch takes Range start address, batch size and offsets where to put the result as arguments ...

Sub AvgX(MyR As Range, S As Integer, ORow As Integer, OCol As Integer)
' MyR = start of range
' S   = batch size
' OCol, ORow = Offsets to place result in relation to last batch value
Dim Idx As Integer, Jdx As Integer, RSum As Variant

    Idx = 1
    RSum = 0
    Do
        For Jdx = 1 To S
            RSum = RSum + MyR(Idx, 1)
            Idx = Idx + 1
            If MyR(Idx, 1) = "" Then Exit Do
        Next Jdx
        MyR(Idx - 1, 1).Offset(ORow, OCol) = RSum / (Jdx - 1)
        RSum = 0
    Loop
End Sub

and is called by

Sub Test()
    AvgX [C4], 10, 0, 1
End Sub

to give you this result ...


问:
Sharing Style with DataTrigger depending on bound value
I have searched but not yet found any way on how to do this. I'm also relatively new to XAML and binding.

I have many TextBlocks in which the text is bound to a property and have a StringFormat:

```<code><TextBlock Text="{Binding PropA, StringFormat=Running {0}"/>
<TextBlock Text="{Binding Height, StringFormat=Sub: \{0\}"/>
<TextBlock Text="{Binding Depth, StringFormat=Indie: \{0\}"/>
<TextBlock Text="{Binding Color, StringFormat=State: \{0\}"/>
</code>```

Now I want to apply a style depending on the value of the bound variable (so the real text being displayed is irrelevant). Currently I have to apply a
</Style>

<TextBlock Text="{Binding PropA, StringFormat=Running {0}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Height, StringFormat=Sub: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Depth, StringFormat=Indie: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Color, StringFormat=State: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
```

答:
You can use attached property to pass something common (e.g. bool value) into style:

```<code>public class TextBlockBehavior
{
    public static bool GetMyProperty(DependencyObject obj) => (bool)obj.GetValue(MyPropertyProperty);
    public static void SetMyProperty(DependencyObject obj, bool value) => obj.SetValue(MyPropertyProperty, value);

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(bool), typeof(TextBlockBehavior), new PropertyMetadata(false));
}
</code>```

Then each TextBlock can set value of it from different sources:

```<code><TextBlock Text="{Binding PropA, StringFormat=Running \{0\}}"
           local:TextBlockBehavior.MyProperty="{Binding PropA ...}"
           Style="{StaticResource Highlight_Non_Zero}" />
</code>```

Note: you have to use converter or another property in ViewModel to make properties of various type (in your case PropA, Color, Depth, etc.) setting  value of bool MyProperty.

And then in style you can use it:

```<code><Style x:Key="Highlight_Non_Zero" TargetType="TextBlock">
    <Setter Property="TextBlock.Background" Value="Orange" />
    <Style.Triggers>
        <Trigger Property="local:TextBlockBehavior.MyProperty" Value="True">
            <Setter Property="TextBlock.Background" Value="Transparent" />
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

Given solution suits well if style triggers doing many things. In your case (to change background) it would be easier to simply make converter (or use another property in ViewModel, colors are ok to return, see e.g. this) for each type to produce wanted background brush/color (e.g. ColorToBackground):

```<code><TextBlock Text="{Binding PropA, StringFormat=Running \{0\}}"
           Background="{Binding PropA, Converter=local:SomeTypeToBackground}" />
</code>```

Body:
I have searched but not yet found any way on how to do this. I'm also relatively new to XAML and binding.

I have many TextBlocks in which the text is bound to a property and have a StringFormat:

<TextBlock Text="{Binding PropA, StringFormat=Running {0}"/>
<TextBlock Text="{Binding Height, StringFormat=Sub: \{0\}"/>
<TextBlock Text="{Binding Depth, StringFormat=Indie: \{0\}"/>
<TextBlock Text="{Binding Color, StringFormat=State: \{0\}"/>

Now I want to apply a style depending on the value of the bound variable (so the real text being displayed is irrelevant). Currently I have to apply a
</Style>

<TextBlock Text="{Binding PropA, StringFormat=Running {0}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Height, StringFormat=Sub: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Depth, StringFormat=Indie: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>
<TextBlock Text="{Binding Color, StringFormat=State: \{0\}" Style="{StaticResource Highlight_Non_Zero}"/>

Body:
You can use attached property to pass something common (e.g. bool value) into style:

public class TextBlockBehavior
{
    public static bool GetMyProperty(DependencyObject obj) => (bool)obj.GetValue(MyPropertyProperty);
    public static void SetMyProperty(DependencyObject obj, bool value) => obj.SetValue(MyPropertyProperty, value);

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(bool), typeof(TextBlockBehavior), new PropertyMetadata(false));
}

Then each TextBlock can set value of it from different sources:

<TextBlock Text="{Binding PropA, StringFormat=Running \{0\}}"
           local:TextBlockBehavior.MyProperty="{Binding PropA ...}"
           Style="{StaticResource Highlight_Non_Zero}" />

Note: you have to use converter or another property in ViewModel to make properties of various type (in your case PropA, Color, Depth, etc.) setting  value of bool MyProperty.

And then in style you can use it:

<Style x:Key="Highlight_Non_Zero" TargetType="TextBlock">
    <Setter Property="TextBlock.Background" Value="Orange" />
    <Style.Triggers>
        <Trigger Property="local:TextBlockBehavior.MyProperty" Value="True">
            <Setter Property="TextBlock.Background" Value="Transparent" />
        </Trigger>
    </Style.Triggers>
</Style>

Given solution suits well if style triggers doing many things. In your case (to change background) it would be easier to simply make converter (or use another property in ViewModel, colors are ok to return, see e.g. this) for each type to produce wanted background brush/color (e.g. ColorToBackground):

<TextBlock Text="{Binding PropA, StringFormat=Running \{0\}}"
           Background="{Binding PropA, Converter=local:SomeTypeToBackground}" />


问:
Get a date range covering 2 business weeks starting with current monday
I am having trouble adjusting a week range in PHP.

I have it working to show the current work week starting on monday.

So for this week it shows 11/29/2010 - 12/03/2010.

I need to modify this to start from the current work week's monday and show and end date of two fridays from the monday.

So for example currently it would show a start date of 11/29/2010 and and end date of 12/10/2010.

Here is my code

```<code><?
$timestamp = time();
echo date("m/d/Y", strtotime("this monday", $timestamp));
echo " - ";
echo date("m/d/Y", strtotime("Next Friday", $timestamp));
?>
</code>```

How do I add +7 to "Next Friday"

thx

答:
You cannot use this monday to construct date time,

as it went pass Monday, it return next Monday

here is my suggestion

```<code><?
$current_wkday = date('N', time());
switch ($current_wkday)
{
  /* assuming on sunday, get next monday */
  case 0:  $this_monday = strtotime('+1 day'); break;
  case 1:  $this_monday = time(); break;
  default: $this_monday = strtotime('-'.($current_wkday-1).'day'); break;
}

echo date("m/d/Y", $this_monday); /* 11days = 7+(5-1) */
echo " - ";
echo date("m/d/Y", $this_monday+(86400*11));
?>
</code>```

Body:
I am having trouble adjusting a week range in PHP.

I have it working to show the current work week starting on monday.

So for this week it shows 11/29/2010 - 12/03/2010.

I need to modify this to start from the current work week's monday and show and end date of two fridays from the monday.

So for example currently it would show a start date of 11/29/2010 and and end date of 12/10/2010.

Here is my code

<?
$timestamp = time();
echo date("m/d/Y", strtotime("this monday", $timestamp));
echo " - ";
echo date("m/d/Y", strtotime("Next Friday", $timestamp));
?>

How do I add +7 to "Next Friday"

thx

Body:
You cannot use this monday to construct date time,

as it went pass Monday, it return next Monday

here is my suggestion

<?
$current_wkday = date('N', time());
switch ($current_wkday)
{
  /* assuming on sunday, get next monday */
  case 0:  $this_monday = strtotime('+1 day'); break;
  case 1:  $this_monday = time(); break;
  default: $this_monday = strtotime('-'.($current_wkday-1).'day'); break;
}

echo date("m/d/Y", $this_monday); /* 11days = 7+(5-1) */
echo " - ";
echo date("m/d/Y", $this_monday+(86400*11));
?>


问:
Make cell clickable in asp gridview
I need the complete cell clickable. I tried few solutions but they couldn't make cell clickable, the text is clickable only.

```<code>protected void gvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow )
    {
        e.Row.Cells[0].Attributes["style"] = "cursor:pointer";
        e.Row.Cells[0].Text = "<a href='/Pages/ProjectEdit.aspx?ID="+ ((Label)e.Row.FindControl("lblID")).Text+"'>" + ((Label)e.Row.FindControl("lblID")).Text + "</a>";
    }
}
</code>```

..............................

```<code><Columns>
    <asp:TemplateField ItemStyle-CssClass="ItemClass" ItemStyle-Width="8%" HeaderText="Project ID">
        <ItemTemplate>
            <asp:Label style="cursor:pointer;" ID="lblID" runat="server" Text='<%# Eval("id")%>' ></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
</code>```

I need this hyper link on the complete cell not just on the text.

答:
You can give the cell an onclick attribute in the same way you did with the style.

```<code>e.Row.Cells[0].Attributes["onclick"] = "location.href='/Pages/ProjectEdit.aspx?ID='";
</code>```

Or wrap the link around a div with full width and height (better for SEO)

```<code>e.Row.Cells[0].Text = "<a href=\"/Pages/ProjectEdit.aspx?ID=\"><div style=\"width: 100%; height: 100%;\">CLickMe</div></a>";
</code>```

Title: Make cell clickable in asp gridview

Body:
I need the complete cell clickable. I tried few solutions but they couldn't make cell clickable, the text is clickable only.

protected void gvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow )
    {
        e.Row.Cells[0].Attributes["style"] = "cursor:pointer";
        e.Row.Cells[0].Text = "" + ((Label)e.Row.FindControl("lblID")).Text + "";
    }
}

..............................

<Columns>
    <asp:TemplateField ItemStyle-CssClass="ItemClass" ItemStyle-Width="8%" HeaderText="Project ID">
        <ItemTemplate>
            <asp:Label style="cursor:pointer;" ID="lblID" runat="server" Text='<%# Eval("id")%>' ></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>

I need this hyper link on the complete cell not just on the text.

Body:
You can give the cell an onclick attribute in the same way you did with the style.

e.Row.Cells[0].Attributes["onclick"] = "location.href='/Pages/ProjectEdit.aspx?ID='";

Or wrap the link around a div with full width and height (better for SEO)

e.Row.Cells[0].Text = "<a href=\"/Pages/ProjectEdit.aspx?ID=\"><div style=\"width: 100%; height: 100%;\">CLickMe</div></a>";


问:
Sliding Menu Bar is Working- But Not Well
I've been having a lot of trouble with this menu.  I have it working but the method I'm using is both buggy and inefficient.  Take a look at the jsfiddle, on first hover the pop-up menu does not have any animation.  However, on second hover and every hover after that the desired animation works.  Even if I get it to work on first hover it will still not be well made because when the user tries to access any of the items on the drop down the mouse out event is triggered and the menu begins to slide up.  Here's the Jquery I am using:

```<code>$(function(){
$('.dropdown').hover(function(){
    $('.dropdown-menu').stop().slideDown(250);
});
$('.dropdown').mouseout(function(){
    $('.dropdown-menu').stop().slideUp(250);
});
</code>```

I tried making the mouse out apply to the drop down menu as well by using:

```<code>$('.dropdown','.dropdown-menu').mouseout(function(){
</code>```

That just made it worse.  I am looking for a more efficient and user-friendly way to make my menu bar have the desired animations.

https://jsfiddle.net/ghcywu6L/

答:
I think you didn't know about the mouseover thingy. It actually exists. Check out the code. It should be fine now.

$(function() {
  $('.dropdown').mouseover(function() {
    $('.dropdown-menu').stop().slideDown(250);
  });
  $('.dropdown').mouseout(function() {
    $('.dropdown-menu').stop().slideUp(250);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
}

/* Top nav syling */

.navbar-default {
  background-color: rgb(54, 135, 2);
  font-size: 120%;
}

/*Main display styling */

.jumbotron {
  height: 400px;
  background: url("../images/bg.jpg");
  background-size: cover;
  background-position: 50% 50%;
  width: 96%;
  border-bottom: 5px solid rgb(79, 201, 2);
  border-top: 5px solid rgb(79, 201, 2);
  border-radius: 5px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

/*Navbar font coloring */

.nav.navbar-nav li a {
  color: white;
}

/* Centers content vertically */

.vert-center {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

/*Styles partially transparent background within jumbotron class */

.transparent {
  background: rgba(190, 200, 216, .5);
  display: inline-block;
  padding-left: 20px;
  padding-right: 20px;
  border-radius: 5px;
  border-left: 4px solid rgb(79, 201, 2);
  border-right: 4px solid rgb(79, 201, 2);
  width: 60%;
}

/*Padding around desc within jumbotron */

#heading-desc {
  padding-top: 15px;
  padding-bottom: 15px;
}

/*Padding around title within jumbotron */

#heading-title {
  padding-top: 15px;
}

/* Bootstrap menu created using bootstrapdesigntools.com */

#custom-bootstrap-menu.navbar-default .navbar-brand {
  color: rgba(255, 255, 255, 1);
}

#custom-bootstrap-menu.navbar-default {
  font-size: 16px;
  background-color: rgba(54, 135, 2, 1);
  background: -webkit-linear-gradient(top, rgba(47, 196, 116, 1) 0%, rgba(54, 135, 2, 1) 100%);
  background: linear-gradient(to bottom, rgba(47, 196, 116, 1) 0%, rgba(54, 135, 2, 1) 100%);
  border-width: 1px;
  border-radius: 4px;
}

#custom-bootstrap-menu.navbar-default .navbar-nav>li>a {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(248, 248, 248, 0);
}

#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(90, 224, 4, 1);
}

#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(68, 168, 5, 1);
}

#custom-bootstrap-menu.navbar-default .navbar-toggle {
  border-color: #44a805;
}

/*Styling of icons */

.size {
  font-size: 60px;
  padding-top: 15px;
}

/*Outline surrounding three columns including icons */

.outline {
  border-left: 2px solid rgb(79, 201, 2);
  border-right: 2px solid rgb(79, 201, 2);
}

.navbar-bottom {
  background-color: rgba(222, 223, 224, 1);
  background: -webkit-linear-gradient(top, rgba(249, 249, 249, 1) 0%, rgba(222, 223, 224, 1) 100%);
  background: linear-gradient(to bottom, rgba(249, 249, 249, 1) 0%, rgba(222, 223, 224, 1) 100%);
  margin: 0;
  padding-top: 2px;
  margin-top: 90px;
}

.btn-format {
  display: block;
  width: 40%;
  left: 50%;
  height: 6%;
  border-radius: 3px;
  margin-top: 3px;
}

.horizontal-center {
  margin: 0 auto;
  width: 100px;
}

}
.footer-heading {
  font-size: 150px;
  margin-top: 2px;
  margin-bottom: 7px;
}
footer-title-pad {
  padding-top: 2px;
}
#custom-bootstrap-menu.navbar-default .navbar-brand {
  color: rgba(255, 255, 255, 1);
}
#custom-bootstrap-menu.navbar-default {
  font-size: 15px;
  background-color: rgba(47, 196, 116, 1);
  background: -webkit-linear-gradient(top, rgba(54, 135, 2, 1) 0%, rgba(47, 196, 116, 1) 100%);
  background: linear-gradient(to bottom, rgba(54, 135, 2, 1) 0%, rgba(47, 196, 116, 1) 100%);
  border-width: 1px;
  border-radius: 4px;
}
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(248, 248, 248, 0);
}
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(68, 229, 74, 1);
}

/*Styles active tab of top menu bar */
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(57, 145, 3, 1));
  background: -webkit-linear-gradient(top, rgba(54, 135, 2, 1) 0%, rgba(57, 145, 3, 1) 100%);
  background: linear-gradient(to bottom, rgba(54, 135, 2, 1) 0%, rgba(57, 145, 3, 1) 100%);
}
#custom-bootstrap-menu.navbar-default .navbar-toggle {
  border-color: #42a503;
}
#custom-bootstrap-menu.navbar-default .navbar-toggle:hover,
#custom-bootstrap-menu.navbar-default .navbar-toggle:focus {
  background-color: #42a503;
}
#custom-bootstrap-menu.navbar-default .navbar-toggle .icon-bar {
  background-color: #42a503;
}
#custom-bootstrap-menu.navbar-default .navbar-toggle:hover .icon-bar,
#custom-bootstrap-menu.navbar-default .navbar-toggle:focus .icon-bar {
  background-color: #2fc474;
}
.navbar-bottom button {
  margin: auto;
}
.footer-bottom {
  margin-bottom: 7px;
}
.footer-top {
  margin-top: 2px;
}

/*Upper outline on bottom navigation bar*/
.outline-above {
  border-top: 1px solid rgb(79, 201, 2);
}

/*Spacing between buttons in footer, error- needs more efficient  class */
#button-margin-top1 {
  margin-top: 8px;
}
#button-margin-top2 {
  margin-top: 8px;
}
#button-margin-top3 {
  margin-top: 8px;
}

/*dropdown menu background color */
.dropdown-menu {
  background-color: rgba(47, 196, 116, 1);
  background: -webkit-linear-gradient(top, rgba(67, 171, 3, .93) 0%, rgba(47, 196, 116, .93) 100%);
  background: linear-gradient(to bottom, rgba(67, 171, 3, .93) 0%, rgba(47, 196, 116, .93) 100%);
}

/*Dropdown menu on hover instead of click unless screen has been resized */
@media (min-width: 979px) {
  ul.nav li.dropdown:hover>ul.dropdown-menu {
    display: block;
  }
}
#custom-bootstrap-menu.navbar-default .dropdown-menu>li>a:hover,
#custom-bootstrap-menu.navbar-default .dropdown-menu>li>a:focus {
  background-color: rgba(68, 229, 74, 1);
}

/*Changes dropdown menu icon on screen resize */
.navbar-toggle,
.icon-bar {
  background-color: rgba(44, 226, 50, 1);
}
.dropdown>a {
  display: block;
}
.div-outliner {
  border: 1px solid black;
}
.col-lg-8 {
  background: url("../images/bg.jpg");
  height: 300px;
  background-position: 0 50%;
}</code>```

<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link href="css/custom.css" rel="stylesheet">

Brand Logo
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-menubuilder">Toggle navigation
            </button>

Home

            Products

Option 1

Option 2

Option 3

Option 4

About Us

Contact Us

```

Body:
I've been having a lot of trouble with this menu.  I have it working but the method I'm using is both buggy and inefficient.  Take a look at the jsfiddle, on first hover the pop-up menu does not have any animation.  However, on second hover and every hover after that the desired animation works.  Even if I get it to work on first hover it will still not be well made because when the user tries to access any of the items on the drop down the mouse out event is triggered and the menu begins to slide up.  Here's the Jquery I am using:

$(function(){
$('.dropdown').hover(function(){
    $('.dropdown-menu').stop().slideDown(250);
});
$('.dropdown').mouseout(function(){
    $('.dropdown-menu').stop().slideUp(250);
});

I tried making the mouse out apply to the drop down menu as well by using:

$('.dropdown','.dropdown-menu').mouseout(function(){

That just made it worse.  I am looking for a more efficient and user-friendly way to make my menu bar have the desired animations.

https://jsfiddle.net/ghcywu6L/

Body:
I think you didn't know about the mouseover thingy. It actually exists. Check out the code. It should be fine now.

$(function() {
  $('.dropdown').mouseover(function() {
    $('.dropdown-menu').stop().slideDown(250);
  });
  $('.dropdown').mouseout(function() {
    $('.dropdown-menu').stop().slideUp(250);
  });
});

* {
  margin: 0;
  padding: 0;
}

/* Top nav syling */

.navbar-default {
  background-color: rgb(54, 135, 2);
  font-size: 120%;
}

/*Main display styling */

.jumbotron {
  height: 400px;
  background: url("../images/bg.jpg");
  background-size: cover;
  background-position: 50% 50%;
  width: 96%;
  border-bottom: 5px solid rgb(79, 201, 2);
  border-top: 5px solid rgb(79, 201, 2);
  border-radius: 5px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

/*Navbar font coloring */

.nav.navbar-nav li a {
  color: white;
}

/* Centers content vertically */

.vert-center {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

/*Styles partially transparent background within jumbotron class */

.transparent {
  background: rgba(190, 200, 216, .5);
  display: inline-block;
  padding-left: 20px;
  padding-right: 20px;
  border-radius: 5px;
  border-left: 4px solid rgb(79, 201, 2);
  border-right: 4px solid rgb(79, 201, 2);
  width: 60%;
}

/*Padding around desc within jumbotron */

#heading-desc {
  padding-top: 15px;
  padding-bottom: 15px;
}

/*Padding around title within jumbotron */

#heading-title {
  padding-top: 15px;
}

/* Bootstrap menu created using bootstrapdesigntools.com */

#custom-bootstrap-menu.navbar-default .navbar-brand {
  color: rgba(255, 255, 255, 1);
}

#custom-bootstrap-menu.navbar-default {
  font-size: 16px;
  background-color: rgba(54, 135, 2, 1);
  background: -webkit-linear-gradient(top, rgba(47, 196, 116, 1) 0%, rgba(54, 135, 2, 1) 100%);
  background: linear-gradient(to bottom, rgba(47, 196, 116, 1) 0%, rgba(54, 135, 2, 1) 100%);
  border-width: 1px;
  border-radius: 4px;
}

#custom-bootstrap-menu.navbar-default .navbar-nav>li>a {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(248, 248, 248, 0);
}

#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(90, 224, 4, 1);
}

#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(68, 168, 5, 1);
}

#custom-bootstrap-menu.navbar-default .navbar-toggle {
  border-color: #44a805;
}

/*Styling of icons */

.size {
  font-size: 60px;
  padding-top: 15px;
}

/*Outline surrounding three columns including icons */

.outline {
  border-left: 2px solid rgb(79, 201, 2);
  border-right: 2px solid rgb(79, 201, 2);
}

.navbar-bottom {
  background-color: rgba(222, 223, 224, 1);
  background: -webkit-linear-gradient(top, rgba(249, 249, 249, 1) 0%, rgba(222, 223, 224, 1) 100%);
  background: linear-gradient(to bottom, rgba(249, 249, 249, 1) 0%, rgba(222, 223, 224, 1) 100%);
  margin: 0;
  padding-top: 2px;
  margin-top: 90px;
}

.btn-format {
  display: block;
  width: 40%;
  left: 50%;
  height: 6%;
  border-radius: 3px;
  margin-top: 3px;
}

.horizontal-center {
  margin: 0 auto;
  width: 100px;
}

}
.footer-heading {
  font-size: 150px;
  margin-top: 2px;
  margin-bottom: 7px;
}
footer-title-pad {
  padding-top: 2px;
}
#custom-bootstrap-menu.navbar-default .navbar-brand {
  color: rgba(255, 255, 255, 1);
}
#custom-bootstrap-menu.navbar-default {
  font-size: 15px;
  background-color: rgba(47, 196, 116, 1);
  background: -webkit-linear-gradient(top, rgba(54, 135, 2, 1) 0%, rgba(47, 196, 116, 1) 100%);
  background: linear-gradient(to bottom, rgba(54, 135, 2, 1) 0%, rgba(47, 196, 116, 1) 100%);
  border-width: 1px;
  border-radius: 4px;
}
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(248, 248, 248, 0);
}
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>li>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(68, 229, 74, 1);
}

/*Styles active tab of top menu bar */
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:hover,
#custom-bootstrap-menu.navbar-default .navbar-nav>.active>a:focus {
  color: rgba(255, 255, 255, 1);
  background-color: rgba(57, 145, 3, 1));
  background: -webkit-linear-gradient(top, rgba(54, 135, 2, 1) 0%, rgba(57, 145, 3, 1) 100%);
  background: linear-gradient(to bottom, rgba(54, 135, 2, 1) 0%, rgba(57, 145, 3, 1) 100%);
}
#custom-bootstrap-menu.navbar-default .navbar-toggle {
  border-color: #42a503;
}
#custom-bootstrap-menu.navbar-default .navbar-toggle:hover,
#custom-bootstrap-menu.navbar-default .navbar-toggle:focus {
  background-color: #42a503;
}
#custom-bootstrap-menu.navbar-default .navbar-toggle .icon-bar {
  background-color: #42a503;
}
#custom-bootstrap-menu.navbar-default .navbar-toggle:hover .icon-bar,
#custom-bootstrap-menu.navbar-default .navbar-toggle:focus .icon-bar {
  background-color: #2fc474;
}
.navbar-bottom button {
  margin: auto;
}
.footer-bottom {
  margin-bottom: 7px;
}
.footer-top {
  margin-top: 2px;
}

/*Upper outline on bottom navigation bar*/
.outline-above {
  border-top: 1px solid rgb(79, 201, 2);
}

/*Spacing between buttons in footer, error- needs more efficient  class */
#button-margin-top1 {
  margin-top: 8px;
}
#button-margin-top2 {
  margin-top: 8px;
}
#button-margin-top3 {
  margin-top: 8px;
}

/*dropdown menu background color */
.dropdown-menu {
  background-color: rgba(47, 196, 116, 1);
  background: -webkit-linear-gradient(top, rgba(67, 171, 3, .93) 0%, rgba(47, 196, 116, .93) 100%);
  background: linear-gradient(to bottom, rgba(67, 171, 3, .93) 0%, rgba(47, 196, 116, .93) 100%);
}

/*Dropdown menu on hover instead of click unless screen has been resized */
@media (min-width: 979px) {
  ul.nav li.dropdown:hover>ul.dropdown-menu {
    display: block;
  }
}
#custom-bootstrap-menu.navbar-default .dropdown-menu>li>a:hover,
#custom-bootstrap-menu.navbar-default .dropdown-menu>li>a:focus {
  background-color: rgba(68, 229, 74, 1);
}

/*Changes dropdown menu icon on screen resize */
.navbar-toggle,
.icon-bar {
  background-color: rgba(44, 226, 50, 1);
}
.dropdown>a {
  display: block;
}
.div-outliner {
  border: 1px solid black;
}
.col-lg-8 {
  background: url("../images/bg.jpg");
  height: 300px;
  background-position: 0 50%;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link href="css/custom.css" rel="stylesheet">
  <script type="text/javascript" src="scripts/dropdown.js"></script>
</head>

<body>
  <div id="custom-bootstrap-menu" class="navbar navbar-default " role="navigation">
    <div class="container-fluid">
      <div class="navbar-header"><a class="navbar-brand" href="#">Brand Logo</a>
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-menubuilder"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
            </button>
      </div>
      <div class="collapse navbar-collapse navbar-menubuilder">
        <ul class="nav navbar-nav navbar-left">
          <li class="active"><a href="#">Home</a>
          </li>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle slideDown" data-toggle="dropdown">Products<span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#">Option 1</a></li>
              <li class="divider"></li>
              <li><a href="#">Option 2</a></li>
              <li class="divider"></li>
              <li><a href="#">Option 3</a></li>
              <li class="divider"></li>
              <li><a href="#">Option 4</a></li>
            </ul>
          </li>
          <li><a href="/about-us">About Us</a>
          </li>
          <li><a href="/contact">Contact Us</a>
          </li>
        </ul>
      </div>
    </div>
  </div>

</body>

</html>


问:
CNTK Transfer Learning with LSTM: appending pretrained network to another network
I have a pretrained Seq-to-Seq slot tagger network as which in its simplest form is follows:

```<code>Network_1 = Sequential ([
    Embedding(emb_dim)
    Recurrence(LSTM(LSTM_dim))
    Dense(num_labels)
])
</code>```

I would like to use the output of this as initial layers in another network. Basically I would like to concatenate the embeddings from the network_1 (pretrained) to an embedding layer in the network_2 as follows:

```<code>Network_2 = Sequential ([
    Concat_embeddings ( Embedding(emb_dim), Network_1_embed() )
    Recurrence(LSTM(LSTM_dim))
    (Label('encoded_h'), Label('encoded_c'))
])

def Network_1_embed():
    loaded_model = load_model(path_to_network_1_saved_model);
    cloned_model = loaded_model.clone(CloneMethod.freeze);
    return cloned_model

def Concat_embeddings(emb1, emb2):
    X=Placeholder();
    return splice(emb1(X), emb2(X))
</code>```

This is giving me the following error
ValueError: Times: The 1 leading dimensions of the right operand with shape '[50360]' do not match the left operand's trailing dimensions with shape '[293]'

For reference, we get [293] since emb_dim=256, and num_network_1_labels=37, while [50360] is the vocabulary size of the network_2 input. The Network_1 also had the same vocabulary mapping when being trained, so it can take the same input, and output a 37 dimensional vector for each token.
How do I make this work?
Thanks

答:
I think your problem is that you are using the entire Network_1 as the embedding, instead of just its embedding layer.

One way would be to define embed separately and train it through Network_1:

```<code>embed = Embedding(emb_dim)
Network_1 = Sequential ([
    embed,
    Recurrence(LSTM(LSTM_dim)),
    Dense(num_labels)
])
</code>```

Then train Network_1, but save embed:

```<code>embed.save(EMBED_PATH)
</code>```

Explanation: Since Network_1 just invokes embed, they share parameters, so that training Network_1 will train embed's parameters. Saving embed then gives you the embedding layer trained by Network_1. Quite straight-forward, actually.

Then, to train your second model (in a second script), load embed from disk and just use it:

```<code>Network_1_embed = load_model(EMBED_PATH)
Network_2 = Sequential ([
    ( Embedding(emb_dim), Network_1_embed() ),
    splice,
    Recurrence(LSTM(LSTM_dim)),
    (Label('encoded_h'), Label('encoded_c'))
])
</code>```

Note the use of a function tuple as the first item passed to Sequential(). The tuple means to apply both functions to the same input, and generates two outputs, which are then the input to the subsequent function, splice.

To keep embed constant, clone it with Freeze option as you already did in your example.

(I am not in front of a computer with the latest CNTK and cannot test this, so it is possible that I made a mistake.)

Body:
I have a pretrained Seq-to-Seq slot tagger network as which in its simplest form is follows:

Network_1 = Sequential ([
    Embedding(emb_dim)
    Recurrence(LSTM(LSTM_dim))
    Dense(num_labels)
])

I would like to use the output of this as initial layers in another network. Basically I would like to concatenate the embeddings from the network_1 (pretrained) to an embedding layer in the network_2 as follows:

Network_2 = Sequential ([
    Concat_embeddings ( Embedding(emb_dim), Network_1_embed() )
    Recurrence(LSTM(LSTM_dim))
    (Label('encoded_h'), Label('encoded_c'))
])

def Network_1_embed():
    loaded_model = load_model(path_to_network_1_saved_model);
    cloned_model = loaded_model.clone(CloneMethod.freeze);
    return cloned_model

def Concat_embeddings(emb1, emb2):
    X=Placeholder();
    return splice(emb1(X), emb2(X))

This is giving me the following error
ValueError: Times: The 1 leading dimensions of the right operand with shape '[50360]' do not match the left operand's trailing dimensions with shape '[293]'

For reference, we get [293] since emb_dim=256, and num_network_1_labels=37, while [50360] is the vocabulary size of the network_2 input. The Network_1 also had the same vocabulary mapping when being trained, so it can take the same input, and output a 37 dimensional vector for each token.
How do I make this work?
Thanks

Body:
I think your problem is that you are using the entire Network_1 as the embedding, instead of just its embedding layer.

One way would be to define embed separately and train it through Network_1:

embed = Embedding(emb_dim)
Network_1 = Sequential ([
    embed,
    Recurrence(LSTM(LSTM_dim)),
    Dense(num_labels)
])

Then train Network_1, but save embed:

embed.save(EMBED_PATH)

Explanation: Since Network_1 just invokes embed, they share parameters, so that training Network_1 will train embed's parameters. Saving embed then gives you the embedding layer trained by Network_1. Quite straight-forward, actually.

Then, to train your second model (in a second script), load embed from disk and just use it:

Network_1_embed = load_model(EMBED_PATH)
Network_2 = Sequential ([
    ( Embedding(emb_dim), Network_1_embed() ),
    splice,
    Recurrence(LSTM(LSTM_dim)),
    (Label('encoded_h'), Label('encoded_c'))
])

Note the use of a function tuple as the first item passed to Sequential(). The tuple means to apply both functions to the same input, and generates two outputs, which are then the input to the subsequent function, splice.

To keep embed constant, clone it with Freeze option as you already did in your example.

(I am not in front of a computer with the latest CNTK and cannot test this, so it is possible that I made a mistake.)